/**
 * Centralized access control hook
 * Checks both authentication and demo mode to determine if user has access
 */

import { useIsAuthenticated } from '../stores';

/**
 * Check if user is in demo mode
 */
export const useIsDemoMode = (): boolean => {
  return localStorage.getItem('demo_mode') === 'true';
};

/**
 * Get demo session ID
 */
export const useDemoSessionId = (): string | null => {
  return localStorage.getItem('demo_session_id');
};

/**
 * Check if user has access (either authenticated OR in valid demo mode)
 */
export const useHasAccess = (): boolean => {
  const isAuthenticated = useIsAuthenticated();
  const isDemoMode = useIsDemoMode();
  const demoSessionId = useDemoSessionId();

  // User has access if:
  // 1. They are authenticated, OR
  // 2. They are in demo mode with a valid session ID
  return isAuthenticated || (isDemoMode && !!demoSessionId);
};

/**
 * Check if current session is demo (not a real authenticated user)
 */
export const useIsDemo = (): boolean => {
  const isAuthenticated = useIsAuthenticated();
  const isDemoMode = useIsDemoMode();
  const demoSessionId = useDemoSessionId();

  // It's a demo session if demo mode is active but user is not authenticated
  return !isAuthenticated && isDemoMode && !!demoSessionId;
};

/**
 * Get demo account type
 */
export const useDemoAccountType = (): string | null => {
  const isDemoMode = useIsDemoMode();
  if (!isDemoMode) return null;
  return localStorage.getItem('demo_account_type');
};

/**
 * Get demo session expiration
 */
export const useDemoExpiresAt = (): string | null => {
  const isDemoMode = useIsDemoMode();
  if (!isDemoMode) return null;
  return localStorage.getItem('demo_expires_at');
};

/**
 * Clear demo session data
 */
export const clearDemoSession = (): void => {
  localStorage.removeItem('demo_mode');
  localStorage.removeItem('demo_session_id');
  localStorage.removeItem('demo_account_type');
  localStorage.removeItem('demo_expires_at');
};
