// Auth session storage — localStorage wrapper for tokens
window.AuthStorage = {
  // Get stored auth data
  getAuth() {
    try {
      const stored = localStorage.getItem('sleepagotchi_auth');
      const parsed = stored ? JSON.parse(stored) : null;
      console.log('[AuthStorage] getAuth:', { exists: !!parsed, expiresAt: parsed?.expiresAt });
      return parsed;
    } catch (err) {
      console.error('[AuthStorage] Error reading auth from storage:', err);
      return null;
    }
  },

  // Save auth data — also writes JWT to cookie
  setAuth(accessToken, refreshToken, expiresAt) {
    try {
      console.log('[AuthStorage] setAuth called with:', {
        hasAccessToken: !!accessToken,
        hasRefreshToken: !!refreshToken,
        expiresAt: expiresAt,
        expiresAtType: typeof expiresAt
      });

      // Validate inputs
      if (!accessToken || !refreshToken || !expiresAt) {
        console.error('[AuthStorage] Invalid auth data, missing required fields', {
          accessToken: !!accessToken,
          refreshToken: !!refreshToken,
          expiresAt
        });
        throw new Error('Invalid auth data');
      }

      const auth = { accessToken, refreshToken, expiresAt };

      // Store in localStorage
      const stored = JSON.stringify(auth);
      localStorage.setItem('sleepagotchi_auth', stored);
      console.log('[AuthStorage] Stored in localStorage:', {
        expiresAt: expiresAt,
        stored: stored.substring(0, 100) + '...'
      });

      // Verify localStorage was actually saved
      const verified = localStorage.getItem('sleepagotchi_auth');
      if (verified) {
        console.log('[AuthStorage] ✓ localStorage verified');
      } else {
        console.error('[AuthStorage] ✗ localStorage FAILED to save!');
      }

      // Also set JWT cookie for server-side access
      const expiryDate = new Date(expiresAt);
      const nowMs = Date.now();
      const expiryMs = expiryDate.getTime();
      const diffMs = expiryMs - nowMs;
      const maxAge = Math.max(0, Math.floor(diffMs / 1000));

      console.log('[AuthStorage] Cookie calculation:', {
        expiresAt: expiresAt,
        expiryDate: expiryDate.toISOString(),
        nowMs: nowMs,
        expiryMs: expiryMs,
        diffMs: diffMs,
        maxAge: maxAge
      });

      const secure = location.protocol === 'https:' ? '; Secure' : '';
      const cookieValue = `sleepagotchi_jwt=${accessToken}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;

      // Set cookie with explicit expiration
      document.cookie = cookieValue;
      console.log('[AuthStorage] Set JWT cookie with maxAge:', maxAge);

      // Verify cookie was set
      if (document.cookie.includes('sleepagotchi_jwt')) {
        console.log('[AuthStorage] ✓ Cookie verified');
      } else {
        console.warn('[AuthStorage] ⚠ Cookie may not have been set');
      }

      return auth;
    } catch (err) {
      console.error('[AuthStorage] Error setting auth:', err);
      throw err;
    }
  },

  // Get access token
  getAccessToken() {
    const auth = this.getAuth();
    return auth?.accessToken || null;
  },

  // Get refresh token
  getRefreshToken() {
    const auth = this.getAuth();
    return auth?.refreshToken || null;
  },

  // Check if token is expired
  isTokenExpired() {
    const auth = this.getAuth();
    if (!auth?.expiresAt) {
      console.log('[AuthStorage] No expiresAt, token considered expired');
      return true;
    }

    const now = new Date().getTime();
    const expiry = new Date(auth.expiresAt).getTime();
    const isExpired = now >= expiry;

    console.log('[AuthStorage] isTokenExpired check:', {
      now: new Date(now).toISOString(),
      expiresAt: new Date(expiry).toISOString(),
      isExpired,
      msUntilExpiry: expiry - now
    });

    return isExpired;
  },

  // Check if token expires soon (within 5 minutes)
  isTokenExpiringSoon() {
    const auth = this.getAuth();
    if (!auth?.expiresAt) {
      console.log('[AuthStorage] No expiresAt, token expiring soon');
      return true;
    }

    const now = new Date().getTime();
    const expiry = new Date(auth.expiresAt).getTime();
    const expiresIn = expiry - now;
    const expiresSoon = expiresIn < 5 * 60 * 1000; // 5 minutes

    console.log('[AuthStorage] isTokenExpiringSoon check:', {
      expiresIn: Math.round(expiresIn / 1000) + 's',
      expiresSoon
    });

    return expiresSoon;
  },

  // Clear auth data
  clearAuth() {
    console.log('[AuthStorage] Clearing auth...');
    localStorage.removeItem('sleepagotchi_auth');
    document.cookie = 'sleepagotchi_jwt=; path=/; max-age=0; SameSite=Lax';
  },

  // Get full auth object
  getFullAuth() {
    return this.getAuth();
  }
};

window.AuthStorage.getAuth();
