import { StrictMode, useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.tsx';
import LoginPage from './pages/LoginPage.tsx';
import SuperAdminPanel from './pages/SuperAdminPanel.tsx';
import ResetPasswordPage from './pages/ResetPasswordPage.tsx';
import OnboardingPage from './pages/OnboardingPage.tsx';
import { supabase } from './lib/supabase.ts';
import type { AuthSession } from './types.ts';
import { LanguageProvider } from './lib/i18n.tsx';

function RouterShell() {
  const [session, setSession] = useState<AuthSession | null>(null);
  const [booting, setBooting] = useState(true);

  // Check if we are on the admin subdomain, an admin Vercel URL, or admin path/hash
  const isAdminRoute = window.location.hostname.includes('admin') || 
                        window.location.pathname.startsWith('/admin') ||
                        window.location.hash.startsWith('#/admin');

  const isResetRoute = window.location.pathname.startsWith('/reset-password') || 
                       window.location.hash.includes('type=recovery') ||
                       window.location.hash.includes('type=invite');

  const isOnboardingRoute = window.location.pathname.startsWith('/onboard');

  useEffect(() => {
    // Restore session from Supabase on mount
    supabase.auth.getSession().then(async ({ data: { session: sbSession } }) => {
      if (sbSession?.user) {
        await resolveSession(sbSession.user);
      }
      setBooting(false);
    });

    // Listen for auth state changes (login / logout)
    const { data: listener } = supabase.auth.onAuthStateChange(async (event, sbSession) => {
      if (event === 'SIGNED_IN') {
        localStorage.removeItem('cafe_console_locked');
      }
      
      if (!sbSession?.user) {
        setSession(null);
        return;
      }
      await resolveSession(sbSession.user);
    });

    // Prevent accidental reload when offline
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (!navigator.onLine) {
        e.preventDefault();
        e.returnValue = ''; // Triggers the browser's native confirmation prompt
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      listener.subscription.unsubscribe();
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);

  async function resolveSession(user: { id: string; email?: string }) {
    const SUPER_ADMIN_EMAIL = import.meta.env.VITE_SUPER_ADMIN_EMAIL as string;

    if (user.email === SUPER_ADMIN_EMAIL) {
      if (!isAdminRoute) {
        await supabase.auth.signOut();
        setSession(null);
        return;
      }
      setSession({ role: 'superadmin', businessId: null, businessName: null, businessType: 'Super Admin', businessPhone: null, email: user.email! });
      return;
    }

    if (isAdminRoute) {
      await supabase.auth.signOut();
      setSession(null);
      return;
    }

    const { data: biz, error } = await supabase
      .from('businesses')
      .select('id, business_name, business_type, phone, status, supabase_user_id, staff_user_id')
      .or(`supabase_user_id.eq.${user.id},staff_user_id.eq.${user.id}`)
      .single();

    if (error && (error.message.includes('FetchError') || error.message.includes('Failed to fetch') || !navigator.onLine)) {
      // Offline / Network Error: Try to load from cache
      const cached = localStorage.getItem('cafe_session_cache');
      if (cached) {
        setSession(JSON.parse(cached));
      }
      // If we have no cache but we are offline, just return! 
      // This prevents destroying the currently active React state session.
      return;
    }

    if (biz && biz.status === 'active') {
      // If the user's ID matches the owner's ID, or if no staff account has even been created yet, they are the manager.
      const role: 'manager' | 'staff' = (biz.supabase_user_id === user.id || !biz.staff_user_id || biz.staff_user_id !== user.id) ? 'manager' : 'staff';
      const sessionData = { role, businessId: biz.id, businessName: biz.business_name, businessType: biz.business_type || 'Cafe', businessPhone: biz.phone, email: user.email! };
      localStorage.setItem('cafe_session_cache', JSON.stringify(sessionData));
      setSession(sessionData);
    } else if (error && !biz) {
       const cached = localStorage.getItem('cafe_session_cache');
       if (cached) {
         setSession(JSON.parse(cached));
         return;
       }
       // If no cache and some other error occurred, don't blindly log out if offline
       if (!navigator.onLine) return;
       
       await supabase.auth.signOut();
       setSession(null);
       localStorage.removeItem('cafe_session_cache');
    } else {
      await supabase.auth.signOut();
      setSession(null);
      localStorage.removeItem('cafe_session_cache');
    }
  }

  async function handleSignOut() {
    await supabase.auth.signOut();
    localStorage.removeItem('cafe_console_locked');
    setSession(null);
  }

  if (booting) {
    return (
      <div style={{
        minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: '#2D1B18', flexDirection: 'column', gap: '16px',
      }}>
        <div style={{ width: '48px', height: '48px', border: '3px solid rgba(250,247,242,0.15)', borderTopColor: '#D84315', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
        <div style={{ color: 'rgba(250,247,242,0.4)', fontSize: '14px' }}>Loading Café Portal…</div>
      </div>
    );
  }

  if (isResetRoute) {
    return <ResetPasswordPage />;
  }

  if (isOnboardingRoute) {
    return <OnboardingPage />;
  }

  if (!session) {
    return <LoginPage onLogin={setSession} isAdminRoute={isAdminRoute} />;
  }

  if (session.role === 'superadmin') {
    return <SuperAdminPanel onSignOut={handleSignOut} />;
  }

  return (
    <App
      businessId={session.businessId!}
      businessName={session.businessName!}
      businessType={session.businessType || ''}
      businessPhone={session.businessPhone || ''}
      userEmail={session.email}
      userRole={session.role}
      onSignOut={handleSignOut}
    />
  );
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <LanguageProvider>
      <RouterShell />
    </LanguageProvider>
  </StrictMode>
);
