import React, { useState, useEffect } from 'react';
import Header from './components/landing/Header';
import Hero from './components/landing/Hero';
import CoachHighlight from './components/landing/CoachHighlight';
import HowItWorks from './components/landing/HowItWorks';
import Features from './components/landing/Features';
import Testimonials from './components/landing/Testimonials';
import Pricing from './components/landing/Pricing';
import FAQ from './components/landing/FAQ';
import Footer from './components/landing/Footer';
import RegistrationModal from './components/modals/RegistrationModal';
import CalculatorsModal from './components/modals/CalculatorsModal';
import Dashboard from './pages/Dashboard';
import AdminPanel from './pages/AdminPanel';
import ProfessionalDashboard from './pages/ProfessionalDashboard';
import FAQPage from './pages/FAQPage';
import { LanguageProvider } from './contexts/LanguageContext';
import { UserProvider, useUser } from './contexts/UserContext'; // Import UserContext
import { Loader2 } from 'lucide-react';

const AppContent: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isToolsOpen, setIsToolsOpen] = useState(false);
  const [authMode, setAuthMode] = useState<'login' | 'register'>('register');
  const [selectedPlan, setSelectedPlan] = useState('starter');
  const [currentView, setCurrentView] = useState<'home' | 'faq'>('home');

  // Consume UserContext
  const {
    user,
    loading,
    isAdminView,
    isProfessionalView,
    isCompletingProfile,
    toggleAdminView,
    setIsProfessionalView,
    logout,
    refreshProfile
  } = useUser();

  // Effect to handle "Complete Profile" flow automatically
  useEffect(() => {
    if (isCompletingProfile) {
      setAuthMode('register');
      setIsModalOpen(true);
    }
  }, [isCompletingProfile]);

  const handleOpenRegister = (plan: string = 'starter') => {
    setSelectedPlan(plan);
    setAuthMode('register');
    setIsModalOpen(true);
  };

  const handleOpenLogin = (context?: 'user' | 'professional') => {
    if (context === 'professional') {
      localStorage.setItem('login_intent', 'professional');
    } else {
      localStorage.setItem('login_intent', 'user');
    }
    setAuthMode('login');
    setIsModalOpen(true);
  };

  const handleAuthSuccess = async () => {
    setIsModalOpen(false);
    await refreshProfile();
    // Login intent logic handled inside context or simply by state update
    localStorage.removeItem('login_intent');
  };

  // Helper function for navigating
  const handleNavigate = (view: 'home' | 'faq') => {
    setCurrentView(view);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <Loader2 className="w-8 h-8 animate-spin text-brand-600" />
      </div>
    );
  }

  // Rota Admin
  if (user && isAdminView && user.is_admin) {
    return <AdminPanel user={user} onExitAdmin={toggleAdminView} onLogout={logout} />;
  }

  // Rota Profissional
  if (user && isProfessionalView) {
    return <ProfessionalDashboard user={user} onExit={() => setIsProfessionalView(false)} onLogout={logout} />;
  }

  // Rota Dashboard Usuário
  if (user) {
    return (
      <Dashboard
        user={user}
        onLogout={logout}
        onOpenAdmin={user.is_admin ? toggleAdminView : undefined}
        onOpenPro={() => setIsProfessionalView(true)}
      />
    );
  }

  // Rota Pública (Landing Page ou FAQ Page)
  return (
    <div className="min-h-screen bg-white text-gray-900 font-sans selection:bg-brand-100 selection:text-brand-900">
      <Header
        onRegister={() => handleOpenRegister('starter')}
        onLogin={handleOpenLogin}
        onOpenTools={() => setIsToolsOpen(true)}
        onNavigate={handleNavigate}
      />

      <main>
        {currentView === 'home' ? (
          <>
            <Hero onRegister={() => handleOpenRegister('starter')} />
            <CoachHighlight onRegister={() => handleOpenRegister('starter')} />
            <HowItWorks />
            <Features />
            <Testimonials />
            <Pricing onRegister={handleOpenRegister} />
            <FAQ />
          </>
        ) : (
          <FAQPage onBack={() => handleNavigate('home')} />
        )}
      </main>

      <Footer
        onRegister={() => handleOpenRegister('starter')}
        onNavigate={handleNavigate}
      />

      <RegistrationModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        plan={selectedPlan}
        mode={authMode}
        isCompletingProfile={isCompletingProfile}
        onSuccess={handleAuthSuccess}
      />

      <CalculatorsModal
        isOpen={isToolsOpen}
        onClose={() => setIsToolsOpen(false)}
      />
    </div>
  );
};

const App: React.FC = () => {
  return (
    <UserProvider>
      <LanguageProvider>
        <AppContent />
      </LanguageProvider>
    </UserProvider>
  );
};

export default App;