// Cookie names
export const ACCESS_TOKEN_COOKIE = 'access_token';
export const USER_DATA_COOKIE = 'mbhs_user_data';
export const REFRESH_TOKEN_COOKIE = 'mbhs_refresh_token';

// User data type
export interface UserData {
  id: string;
  role: string;
  name: string;
  email: string;
  subscription_type?: 'individual' | 'group' | string;
  has_active_subscription?: boolean;
  force_password_change?: boolean;
  is_managed?: boolean;
}

// access_token is now set as HttpOnly cookie by the backend.
// Client-side JS cannot read or write HttpOnly cookies — the browser sends them automatically.

/**
 * Set refresh token cookie (client-side only)
 */
export function setRefreshTokenCookie(token: string): void {
  if (typeof window === 'undefined') return;

  const maxAge = 60 * 60 * 24 * 7; // 7 days (matches refresh token validity)
  const secure = window.location.protocol === 'https:' ? '; Secure' : '';
  document.cookie = `${REFRESH_TOKEN_COOKIE}=${token}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;
}

/**
 * Get refresh token from cookie (client-side only)
 */
export function getRefreshTokenCookie(): string | null {
  if (typeof window === 'undefined') return null;

  const match = document.cookie.match(new RegExp(`(^| )${REFRESH_TOKEN_COOKIE}=([^;]+)`));
  return match ? match[2] : null;
}

/**
 * Delete refresh token cookie (client-side only)
 */
export function deleteRefreshTokenCookie(): void {
  if (typeof window === 'undefined') return;

  document.cookie = `${REFRESH_TOKEN_COOKIE}=; path=/; max-age=0`;
}

/**
 * Set user data cookie (client-side only)
 */
export function setUserDataCookie(user: UserData): void {
  if (typeof window === 'undefined') return;

  const encoded = btoa(JSON.stringify(user));
  const maxAge = 60 * 60 * 24 * 7; // 7 days
  const secure = window.location.protocol === 'https:' ? '; Secure' : '';
  document.cookie = `${USER_DATA_COOKIE}=${encoded}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;
}

/**
 * Get user data from cookie (client-side only)
 */
export function getUserDataCookie(): UserData | null {
  if (typeof window === 'undefined') return null;

  const match = document.cookie.match(new RegExp(`(^| )${USER_DATA_COOKIE}=([^;]+)`));
  if (!match) return null;

  try {
    return JSON.parse(atob(match[2])) as UserData;
  } catch {
    return null;
  }
}

/**
 * Delete user data cookie (client-side only)
 */
export function deleteUserDataCookie(): void {
  if (typeof window === 'undefined') return;

  document.cookie = `${USER_DATA_COOKIE}=; path=/; max-age=0`;
}

/**
 * Clear auth cookies without redirecting — for silent session-expiry cleanup
 * (e.g., landing page shouldn't force-redirect visitors to /login).
 */
export function clearAuthCookies(): void {
  if (typeof window === 'undefined') return;

  deleteUserDataCookie();
  deleteRefreshTokenCookie();
  localStorage.removeItem('has_active_subscription');
  localStorage.removeItem('subscription_type');
}

/**
 * Logout - clears all auth cookies and redirects to login
 */
export function logout(): void {
  if (typeof window === 'undefined') return;

  // access_token (HttpOnly) is cleared by backend on /v1/logout — cannot be deleted client-side
  deleteUserDataCookie();
  deleteRefreshTokenCookie();
  localStorage.removeItem('has_active_subscription');
  localStorage.removeItem('subscription_type');

  // Preserve locale when redirecting to login
  const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
  const pathAfterBase = basePath
    ? window.location.pathname.replace(basePath, '')
    : window.location.pathname;
  const segments = pathAfterBase.split('/').filter(Boolean);
  const locale = (segments[0] && /^[a-z]{2}$/.test(segments[0])) ? segments[0] : 'en';
  window.location.href = `${basePath}/${locale}/login`;
}

/**
 * Check if user is authenticated (client-side only)
 */
export function isAuthenticated(): boolean {
  // access_token is HttpOnly — invisible to JS; check user data cookie presence instead
  return !!getUserDataCookie();
}
