
import React from 'react';
import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { useTranslation } from 'react-i18next';
import { useEffect } from 'react';
import { Toaster } from 'sonner';
import { AuthProvider } from '@/context/AuthContext';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/config';
import { useAuth } from '@/context/AuthContext';

import Index from '@/pages/Index';
import Home from '@/pages/Home';
import About from '@/pages/About';
import Faq from '@/pages/Faq';
import Contact from '@/pages/Contact';
import Privacy from '@/pages/Privacy';
import Terms from '@/pages/Terms';
import Profile from '@/pages/Profile';
import ExtensionView from '@/pages/ExtensionView';
import MyExtensionsPage from '@/pages/MyExtensionsPage';
import Tutorials from '@/pages/Tutorials';
import TutorialDetail from '@/pages/TutorialDetail';
import Billing from '@/pages/Billing';
import PaymentSuccess from '@/pages/PaymentSuccess';
import PaymentFailed from '@/pages/PaymentFailed';
import UseCases from '@/pages/UseCases';
import Timeline from '@/pages/Timeline';
import NotFound from '@/pages/NotFound';
import Pricing from '@/pages/Pricing';

import AdminRoute from '@/components/AdminRoute';
import AdminDashboard from '@/pages/admin/AdminDashboard';
import AdminUsers from '@/pages/admin/AdminUsers';
import AdminExtensions from '@/pages/admin/AdminExtensions';
import AdminSettings from '@/pages/admin/AdminSettings';

import CookieConsent from '@/components/CookieConsent';
import Analytics from '@/components/Analytics';

const ScrollToTop = () => {
  const { pathname } = useLocation();
  
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);
  
  return null;
};

const SEO = () => {
  const { pathname } = useLocation();
  const { t } = useTranslation();
  const baseUrl = 'https://chromify.app';
  const canonicalUrl = `${baseUrl}${pathname}`;
  
  const getMetaTags = () => {
    const defaultTags = {
      title: t('heroTitle'),
      description: t('heroSubtitle'),
      keywords: 'chrome extension, ai extension, no-code extension'
    };

    const routeSpecificTags = {
      '/': defaultTags,
      '/about': {
        title: t('about') + ' - ' + t('heroTitle'),
        description: t('heroSubtitle'),
        keywords: 'chrome extension, ai development, extension generator'
      },
    };

    return routeSpecificTags[pathname] || defaultTags;
  };

  const metaTags = getMetaTags();

  return (
    <Helmet>
      <title>{metaTags.title}</title>
      <meta name="description" content={metaTags.description} />
      <meta name="keywords" content={metaTags.keywords} />
      <link rel="canonical" href={canonicalUrl} />
      
      <meta property="og:title" content={metaTags.title} />
      <meta property="og:description" content={metaTags.description} />
      <meta property="og:url" content={canonicalUrl} />
      <meta property="og:type" content="website" />
      <meta property="og:image" content={`${baseUrl}/logo.svg`} />
      
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:title" content={metaTags.title} />
      <meta name="twitter:description" content={metaTags.description} />
      <meta name="twitter:image" content={`${baseUrl}/logo.svg`} />
      
      <meta name="robots" content="index, follow" />
    </Helmet>
  );
};

const ProtectedRoute = ({ element }: { element: React.ReactNode }) => {
  const { user } = useAuth();
  
  if (!user) {
    return <Navigate to="/" replace />;
  }
  
  return <>{element}</>;
};

const IndexRedirect = () => {
  const { user } = useAuth();
  
  if (user) {
    return <Index />;
  }
  
  return <Home />;
};

const AppRoutes = () => {
  const { i18n } = useTranslation();
  
  useEffect(() => {
    document.documentElement.lang = i18n.language;
    const isRTL = i18n.language === 'ar';
    document.documentElement.dir = isRTL ? 'rtl' : 'ltr';
    
    const event = new Event('languageChanged');
    document.dispatchEvent(event);
  }, [i18n.language]);
  
  return (
    <>
      <SEO />
      <ScrollToTop />
      <Routes>
        <Route path="/" element={<IndexRedirect />} />
        <Route path="/home" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/faq" element={<Faq />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="/privacy" element={<Privacy />} />
        <Route path="/terms" element={<Terms />} />
        <Route path="/profile" element={<ProtectedRoute element={<Profile />} />} />
        <Route path="/extension/:id" element={<ProtectedRoute element={<ExtensionView />} />} />
        <Route path="/my-extensions" element={<ProtectedRoute element={<MyExtensionsPage />} />} />
        <Route path="/tutorials" element={<Tutorials />} />
        <Route path="/tutorials/:id" element={<TutorialDetail />} />
        <Route path="/tutorial/:id" element={<TutorialDetail />} />
        <Route path="/billing" element={<ProtectedRoute element={<Billing />} />} />
        <Route path="/pricing" element={<Pricing />} />
        <Route path="/payment/success" element={<ProtectedRoute element={<PaymentSuccess />} />} />
        <Route path="/payment/failed" element={<ProtectedRoute element={<PaymentFailed />} />} />
        <Route path="/use-cases" element={<UseCases />} />
        <Route path="/timeline" element={<Timeline />} />
        
        <Route path="/admin" element={<AdminRoute><AdminDashboard /></AdminRoute>} />
        <Route path="/admin/users" element={<AdminRoute><AdminUsers /></AdminRoute>} />
        <Route path="/admin/extensions" element={<AdminRoute><AdminExtensions /></AdminRoute>} />
        <Route path="/admin/settings" element={<AdminRoute><AdminSettings /></AdminRoute>} />
        
        <Route path="*" element={<NotFound />} />
      </Routes>
      
      <Toaster position="top-right" richColors closeButton />
      <CookieConsent />
      <Analytics />
    </>
  );
};

const App = () => {
  return (
    <BrowserRouter>
      <I18nextProvider i18n={i18n}>
        <AuthProvider>
          <AppRoutes />
        </AuthProvider>
      </I18nextProvider>
    </BrowserRouter>
  );
};

export default App;
