import { useEffect } from 'react';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { LanguageProvider } from './contexts/LanguageContext';
import { RouterProvider, useRouter } from './contexts/RouterContext';
import { Toaster } from './components/ui/sonner';
import { Home } from './components/pages/Home';
import { About } from './components/pages/About';
import { Blog } from './components/pages/Blog';
import { Careers } from './components/pages/Careers';
import { PrivacyPolicy } from './components/pages/PrivacyPolicy';
import { TermsOfService } from './components/pages/TermsOfService';
import { FAQPage } from './components/pages/FAQPage';
import { ContactPage } from './components/pages/ContactPage';

function AppContent() {
  const { currentPage, navigateTo } = useRouter();
  const _page = window.location.hash.split('#')?.[1] ?? currentPage
  // Ensure hash scrolling works even after page is fully loaded
  useEffect(() => {
    // Wait for all images and resources to load
    if (document.readyState === 'complete') {
      handleHashScroll();
    } else {
      window.addEventListener('load', handleHashScroll);
      return () => window.removeEventListener('load', handleHashScroll);
    }
    
    function handleHashScroll() {
      const hash = window.location.hash.replace('#', '');
      if (hash) {
        setTimeout(() => {
          const element = document.getElementById(hash);
          if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'start' });
          }
        }, 100);
      }
    }
  }, [currentPage]);

  useEffect(()=> {
    navigateTo(_page)
  }, [])
  
  const renderPage = () => {
    
    switch (_page) {
      case 'home':
        return <Home />;
      case 'about':
        return <About />;
      case 'blog':
        return <Blog />;
      case 'careers':
        return <Careers />;
      case 'privacy':
        return <PrivacyPolicy />;
      case 'terms':
        return <TermsOfService />;
      case 'faq':
        return <FAQPage />;
      case 'contact':
        return <ContactPage />;
      default:
        return <Home />;
    }
  };
  
  return (
    <div className="min-h-screen flex flex-col">
      <Header />
      <main className="flex-1">
        {renderPage()}
      </main>
      <Footer />
      <Toaster />
    </div>
  );
}

export default function App() {
  return (
    <LanguageProvider>
      <RouterProvider>
        <AppContent />
      </RouterProvider>
    </LanguageProvider>
  );
}