import { BrowserRouter as Router, Routes, Route, useLocation, useNavigate } from 'react-router-dom';
import React, { Suspense, lazy, useEffect } from 'react';
import ErrorBoundary from './utils/errorBoundary';
import Header from './components/Header';
import AnalyticsInitializer from './components/AnalyticsInitializer';
import ReferralInitializer from './components/ReferralInitializer';
import Hero from './components/Hero';
import { useConsent } from './hooks/useConsent';
import { I18nProvider } from './context/I18nContext';
import { resolveLocaleFromPath } from './i18n';

// Lazy-load heavy routes
const Trade = lazy(() => import('./pages/Trade'));
const AboutUs = lazy(() => import('./pages/AboutUs'));
const ContactUs = lazy(() => import('./pages/ContactUs'));
const Security = lazy(() => import('./pages/Security'));
const CookiePolicy = lazy(() => import('./pages/CookiePolicy'));
const ReverseSolicitation = lazy(() => import('./pages/ReverseSolicitation'));
const OtherDocuments = lazy(() => import('./pages/OtherDocuments'));
const BecomePartner = lazy(() => import('./pages/BecomePartner'));
const AccountTypes = lazy(() => import('./pages/AccountTypes'));
const Forbidden = lazy(() => import('./pages/Forbidden'));

// Lazy-load below-the-fold home components and footer
const Features = lazy(() => import('./components/Features'));
const HowToStart = lazy(() => import('./components/HowToStart'));
const About = lazy(() => import('./components/About'));
const Footer = lazy(() => import('./components/Footer'));

const LazyConsentPopup = lazy(() => import('./components/ConsentPopup'));

// Redirect helper to ensure language prefix in URL based on selected language
const LanguageRedirector = () => {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    try {
      const stored = localStorage.getItem('finprime_language');
      const raw = stored ? (JSON.parse(stored) as string) : 'en';
      const storedLang: 'en' | 'es' | 'cs' | 'ar' | 'tr' | 'fr' | 'hu' =
        raw === 'cz' ? 'cs' : (raw === 'en' || raw === 'es' || raw === 'cs' || raw === 'ar' || raw === 'tr' || raw === 'fr' || raw === 'hu' ? (raw as 'en' | 'es' | 'cs' | 'ar' | 'tr' | 'fr' | 'hu') : 'en');
      const path = location.pathname;
      const langToPrefix: Record<'en' | 'es' | 'cs' | 'ar' | 'tr' | 'fr' | 'hu', '/en' | '/es' | '/cz' | '/ar' | '/tr' | '/fr' | '/hu'> = {
        en: '/en',
        es: '/es',
        cs: '/cz',
        ar: '/ar',
        tr: '/tr',
        fr: '/fr',
        hu: '/hu',
      };
      const prefixToLang: Record<'/en' | '/es' | '/cz' | '/ar' | '/tr' | '/fr' | '/hu', 'en' | 'es' | 'cs' | 'ar' | 'tr' | 'fr' | 'hu'> = {
        '/en': 'en',
        '/es': 'es',
        '/cz': 'cs',
        '/ar': 'ar',
        '/tr': 'tr',
        '/fr': 'fr',
        '/hu': 'hu',
      };
      const knownPrefixes = ['/en', '/es', '/cz', '/ar', '/tr', '/fr', '/hu'];

      const supportedPaths = new Set([
        '/',
        '/trade',
        '/about-us',
        '/help-center',
        '/security',
        '/cookie-policy',
        '/reverse-solicitation',
        '/privacy-policy',
        '/other-documents',
        '/become-partner',
        '/account-types',
        '/forbidden',
      ]);

      const hasAnyPrefix = knownPrefixes.some(p => path === p || path.startsWith(`${p}/`));
      const currentPrefix = knownPrefixes.find(p => path === p || path.startsWith(`${p}/`)) as '/en' | '/es' | '/cz' | '/ar' | undefined;

      // If URL already specifies a language prefix, honor it and sync localStorage
      if (hasAnyPrefix && currentPrefix) {
        const urlLang = prefixToLang[currentPrefix];
        if (storedLang !== urlLang) {
          localStorage.setItem('finprime_language', JSON.stringify(urlLang));
        }
        return; // Do not rewrite user's chosen prefixed URL
      }

      // If on unprefixed known path, add the stored language prefix
      const isKnownUnprefixedPath = supportedPaths.has(path);
      if (!hasAnyPrefix && isKnownUnprefixedPath) {
        const targetPrefix = langToPrefix[storedLang] || '/en';
        const newPath = path === '/' ? targetPrefix : `${targetPrefix}${path}`;
        navigate({ pathname: newPath, search: location.search, hash: location.hash }, { replace: true });
      }
    } catch {
      // ignore parsing issues
    }
  }, [location.pathname, location.search, location.hash, navigate]);

  return null;
};

const ScrollToTop = () => {
  const location = useLocation();
  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.scrollTo({ top: 0, left: 0, behavior: 'instant' as ScrollBehavior });
    }
  }, [location.pathname, location.search, location.hash]);
  return null;
};

function App() {
  // Manage consent at the app level to gate heavy initializers
  const { showConsentPopup, handleConsentAccepted, consentData } = useConsent();
  // Render-time consent manager so we can access location (inside Router)
  const ConsentManager: React.FC = () => {
    const loc = useLocation();
    const isReverseSolicitationPage = loc.pathname === '/reverse-solicitation' || loc.pathname.endsWith('/reverse-solicitation');
    if (isReverseSolicitationPage) return null;
    return showConsentPopup ? (
      <Suspense fallback={null}>
        <LazyConsentPopup onAccept={handleConsentAccepted} />
      </Suspense>
    ) : null;
  };

  // Minimal disclaimer for Czech and Hungarian locales
  const CzechDisclaimerBanner: React.FC = () => {
    const loc = useLocation();
    const locale = resolveLocaleFromPath(loc.pathname);
    if (locale !== 'cs' && locale !== 'hu') return null;
    return (
      <div className="w-full text-gray-400 text-[10px] sm:text-xs text-center px-4 py-1">
        This language version is AI translated, and have not been verified for accuracy. Consider using official translation.
      </div>
    );
  };

  const I18nRouterProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const loc = useLocation();
    const locale = resolveLocaleFromPath(loc.pathname);
    return <I18nProvider locale={locale}>{children}</I18nProvider>;
  };

  return (
    <ErrorBoundary>
    <Router>
      <LanguageRedirector />
      <ScrollToTop />
      <I18nRouterProvider>
        {consentData ? <AnalyticsInitializer /> : null}
        <ReferralInitializer />
        <div className="min-h-screen bg-black text-white overflow-x-hidden">
          <ConsentManager />
          <Header />
          <CzechDisclaimerBanner />
          <Suspense fallback={null}>
          <Routes>
          <Route path="/" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* English-prefixed aliases */}
          <Route path="/en" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Spanish-prefixed aliases */}
          <Route path="/es" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Czech-prefixed aliases (using /cz; support /cs via redirect) */}
          <Route path="/cz" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Redirect /cs to /cz for production environments that might link /cs */}
          <Route path="/cs" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Arabic-prefixed aliases */}
          <Route path="/ar" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Turkish-prefixed aliases */}
          <Route path="/tr" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* French-prefixed aliases */}
          <Route path="/fr" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          {/* Hungarian-prefixed aliases */}
          <Route path="/hu" element={
            <>
              <Hero />
              <Suspense fallback={null}>
                <HowToStart />
                <Features />
                <About />
              </Suspense>
            </>
          } />
          <Route path="/trade" element={<Trade />} />
          <Route path="/en/trade" element={<Trade />} />
          <Route path="/es/trade" element={<Trade />} />
          <Route path="/cz/trade" element={<Trade />} />
          <Route path="/ar/trade" element={<Trade />} />
          <Route path="/tr/trade" element={<Trade />} />
          <Route path="/fr/trade" element={<Trade />} />
          <Route path="/hu/trade" element={<Trade />} />
          <Route path="/about-us" element={<AboutUs />} />
          <Route path="/en/about-us" element={<AboutUs />} />
          <Route path="/es/about-us" element={<AboutUs />} />
          <Route path="/cz/about-us" element={<AboutUs />} />
          <Route path="/ar/about-us" element={<AboutUs />} />
          <Route path="/tr/about-us" element={<AboutUs />} />
          <Route path="/fr/about-us" element={<AboutUs />} />
          <Route path="/hu/about-us" element={<AboutUs />} />
          <Route path="/help-center" element={<ContactUs />} />
          <Route path="/en/help-center" element={<ContactUs />} />
          <Route path="/es/help-center" element={<ContactUs />} />
          <Route path="/cz/help-center" element={<ContactUs />} />
          <Route path="/ar/help-center" element={<ContactUs />} />
          <Route path="/tr/help-center" element={<ContactUs />} />
          <Route path="/fr/help-center" element={<ContactUs />} />
          <Route path="/hu/help-center" element={<ContactUs />} />
          <Route path="/security" element={<Security />} />
          <Route path="/en/security" element={<Security />} />
          <Route path="/es/security" element={<Security />} />
          <Route path="/cz/security" element={<Security />} />
          <Route path="/ar/security" element={<Security />} />
          <Route path="/tr/security" element={<Security />} />
          <Route path="/fr/security" element={<Security />} />
          <Route path="/hu/security" element={<Security />} />
          <Route path="/cookie-policy" element={<CookiePolicy />} />
          <Route path="/en/cookie-policy" element={<CookiePolicy />} />
          <Route path="/es/cookie-policy" element={<CookiePolicy />} />
          <Route path="/cz/cookie-policy" element={<CookiePolicy />} />
          <Route path="/ar/cookie-policy" element={<CookiePolicy />} />
          <Route path="/tr/cookie-policy" element={<CookiePolicy />} />
          <Route path="/fr/cookie-policy" element={<CookiePolicy />} />
          <Route path="/hu/cookie-policy" element={<CookiePolicy />} />
          <Route path="/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/en/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/es/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/cz/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/ar/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/tr/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/fr/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/hu/reverse-solicitation" element={<ReverseSolicitation />} />
          <Route path="/other-documents" element={<OtherDocuments />} />
          <Route path="/en/other-documents" element={<OtherDocuments />} />
          <Route path="/es/other-documents" element={<OtherDocuments />} />
          <Route path="/cz/other-documents" element={<OtherDocuments />} />
          <Route path="/ar/other-documents" element={<OtherDocuments />} />
          <Route path="/tr/other-documents" element={<OtherDocuments />} />
          <Route path="/fr/other-documents" element={<OtherDocuments />} />
          <Route path="/hu/other-documents" element={<OtherDocuments />} />
          <Route path="/become-partner" element={<BecomePartner />} />
          <Route path="/en/become-partner" element={<BecomePartner />} />
          <Route path="/es/become-partner" element={<BecomePartner />} />
          <Route path="/cz/become-partner" element={<BecomePartner />} />
          <Route path="/ar/become-partner" element={<BecomePartner />} />
          <Route path="/tr/become-partner" element={<BecomePartner />} />
          <Route path="/fr/become-partner" element={<BecomePartner />} />
          <Route path="/hu/become-partner" element={<BecomePartner />} />
          <Route path="/account-types" element={<AccountTypes />} />
          <Route path="/en/account-types" element={<AccountTypes />} />
          <Route path="/es/account-types" element={<AccountTypes />} />
          <Route path="/cz/account-types" element={<AccountTypes />} />
          <Route path="/ar/account-types" element={<AccountTypes />} />
          <Route path="/tr/account-types" element={<AccountTypes />} />
          <Route path="/fr/account-types" element={<AccountTypes />} />
          <Route path="/hu/account-types" element={<AccountTypes />} />
          <Route path="/forbidden" element={<Forbidden />} />
          <Route path="/en/forbidden" element={<Forbidden />} />
          <Route path="/es/forbidden" element={<Forbidden />} />
          <Route path="/cz/forbidden" element={<Forbidden />} />
          <Route path="/ar/forbidden" element={<Forbidden />} />
          <Route path="/tr/forbidden" element={<Forbidden />} />
          <Route path="/fr/forbidden" element={<Forbidden />} />
          <Route path="/hu/forbidden" element={<Forbidden />} />
          </Routes>
          </Suspense>
          <Suspense fallback={null}>
            <Footer />
          </Suspense>
        </div>
      </I18nRouterProvider>
    </Router>
    </ErrorBoundary>
  );
}

export default App;