import React, { useState, useEffect } from 'react';
import { auth } from './services/firebase';
import type { User } from 'firebase/auth';
import { onIdTokenChanged } from 'firebase/auth';
import AuthPage from './components/AuthPage';
import Dashboard from './components/Dashboard';
import { Spinner } from './components/icons/Spinner';
import VerifyEmailPage from './components/pages/VerifyEmailPage';
import { ThemeProvider } from './contexts/ThemeContext';
import ThemeTransition from './components/ThemeTransition';
import { LocaleProvider } from './contexts/LocaleContext';

const App: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // This listener is the core of the authentication system.
    // We use onIdTokenChanged instead of onAuthStateChanged because it's more comprehensive.
    // It triggers not only on sign-in/sign-out but also when the user's ID token
    // is refreshed. This is crucial for scenarios like an email change, where the
    // user's session remains active but their token is updated with new claims.
    // This prevents the user from being logged out after verifying a new email.
    const unsubscribe = onIdTokenChanged(auth, (currentUser) => {
      setUser(currentUser);
      setLoading(false);
    });

    // Cleanup subscription on unmount
    return () => unsubscribe();
  }, []);

  // This effect ensures the user's auth state is kept fresh.
  useEffect(() => {
    const handleFocus = () => {
      // If there's a logged-in user when the window is refocused, reload their data.
      // This is a robust way to pick up auth changes made in other tabs, such as
      // verifying a new email address, ensuring the UI is always up-to-date.
      if (auth.currentUser) {
        auth.currentUser.reload().catch((error) => {
          // It's possible for the reload to fail if the user's session is
          // truly expired or invalid. We'll log this for debugging, but
          // the onIdTokenChanged listener will handle logging them out gracefully.
          console.warn("Failed to reload user data:", error.message);
        });
      }
    };

    // Add the listener when the component mounts.
    window.addEventListener('focus', handleFocus);

    // Remove the listener when the component unmounts.
    return () => {
      window.removeEventListener('focus', handleFocus);
    };
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-brand-light dark:bg-brand-dark">
        <Spinner className="w-12 h-12 text-brand-primary" />
      </div>
    );
  }

  // WORKAROUND: To unblock development, we bypass email verification for the admin account.
  // The root cause is likely a Firebase project configuration issue (e.g., authorized domains, quotas).
  // This should be removed once the Firebase configuration is fixed.
  const isAdmin = user && user.email === 'ragow49@gmail.com';
  const isVerified = user && (user.emailVerified || isAdmin);

  return (
    <LocaleProvider>
      <ThemeProvider>
        <ThemeTransition />
        <main className="min-h-screen font-sans antialiased text-brand-dark dark:text-brand-light">
          {!user ? (
            <AuthPage />
          ) : !isVerified ? (
            // If there's a user but they are not verified (and not the admin), show the verification page.
            <VerifyEmailPage user={user} />
          ) : (
            // If there's a user and they ARE verified (or they are the admin), show the dashboard.
            <Dashboard user={user} />
          )}
        </main>
      </ThemeProvider>
    </LocaleProvider>
  );
};

export default App;
