import React, { useState, Suspense } from "react";
import { Routes, Route, useNavigate, useLocation } from "react-router-dom";
import { Header } from "@/components/Header";
import { Sidebar } from "@/components/Sidebar";
import { Footer } from "@/components/Footer";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { LocaleProvider } from "@/i18n/LocaleContext";
import { AdBlockDetect } from "@/components/AdBlockDetect";
import { AdDiagnostics } from "@/components/AdDiagnostics";
import { FloatingSiteSwitcher } from "@/components/FloatingSiteSwitcher";
import { AdSlot } from "@/components/AdSlot";
import { cn } from "@/lib/utils";
import { OfflineIndicator } from "@/components/PWAComponents";
import { Menu } from "lucide-react";
import { submitSingleUrl } from "@/lib/indexnow";

const IndexNowPinger: React.FC<{ path: string }> = ({ path }) => {
  React.useEffect(() => {
    const fullUrl = `https://calccompare.com${path}`;
    const storageKey = `indexnow_pinged_${path}`;
    const lastPing = localStorage.getItem(storageKey);
    const now = Date.now();
    const oneDay = 24 * 60 * 60 * 1000;

    if (!lastPing || now - Number(lastPing) > oneDay) {
      submitSingleUrl(fullUrl).then(({ success }) => {
        if (success) {
          localStorage.setItem(storageKey, String(now));
        }
      }).catch(() => {});
    }
  }, [path]);
  return null;
};


import { FrenchHeader } from "@/components/fr/FrenchHeader";
import { FrenchFooter } from "@/components/fr/FrenchFooter";
import { GermanHeader } from "@/components/de/GermanHeader";
import { GermanFooter } from "@/components/de/GermanFooter";
import { ArabicHeader } from "@/components/ar/ArabicHeader";
import { ArabicFooter } from "@/components/ar/ArabicFooter";
import { SpanishHeader } from "@/components/es/SpanishHeader";
import { SpanishFooter } from "@/components/es/SpanishFooter";
import { PaypalHeader } from "@/components/paypal/PaypalHeader";
import { PaypalFooter } from "@/components/paypal/PaypalFooter";
import { SalaryFooter } from "@/components/salary/SalaryFooter";
import { DepopHeader } from "@/components/depop/DepopHeader";
import { DepopFooter } from "@/components/depop/DepopFooter";
import { AstrologyHeader } from "@/components/astrology/AstrologyHeader";
import { AstrologyFooter } from "@/components/astrology/AstrologyFooter";
import { TaxHeader } from "@/components/tax/TaxHeader";
import { TaxFooter } from "@/components/tax/TaxFooter";

const SubdomainsModal = React.lazy(() => import("@/components/SubdomainsModal").then(m => ({ default: m.SubdomainsModal })));
const AppRoutes = React.lazy(() => import("./RouterConfig").then(m => ({ default: m.AppRoutes })));

const PageSkeleton = () => (
  <div className="w-full max-w-7xl mx-auto px-4 py-8 animate-pulse space-y-8 [contain:layout]">
    <div className="rounded-3xl bg-white border border-[#E2E8F0] p-8 sm:p-12 flex flex-col items-center text-center space-y-4">
      <div className="h-6 w-48 rounded-full bg-slate-200"></div>
      <div className="h-10 sm:h-14 w-3/4 max-w-2xl rounded-2xl bg-slate-200"></div>
      <div className="h-4 w-full max-w-xl rounded-xl bg-slate-100"></div>
    </div>
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
      {[1, 2, 3, 4, 5, 6].map((i) => (
        <div key={i} className="h-48 rounded-2xl bg-white border border-[#E2E8F0] p-6 flex flex-col justify-between">
          <div className="space-y-3">
            <div className="w-10 h-10 rounded-xl bg-slate-200"></div>
            <div className="h-5 w-3/4 rounded-lg bg-slate-200"></div>
            <div className="h-3 w-full rounded bg-slate-100"></div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

export default function App() {
  const navigate = useNavigate();
  const location = useLocation();
  const [isAllSitesModalOpen, setIsAllSitesModalOpen] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // ... (rest of logic remains same)

  const handleNavigate = (path: string) => {
    if (!path) return;
    
    // Normalize path
    const targetPath = path.length > 1 && path.endsWith('/') && !path.startsWith('http') ? path.slice(0, -1) : path;
    
    // Check if it's an external link
    if (targetPath.startsWith('http')) {
      window.location.href = targetPath;
      return;
    }
    
    // SPA Navigation with immediate dir/lang synchronization
    if (targetPath.startsWith('/ar')) {
      document.documentElement.dir = 'rtl';
      document.documentElement.lang = 'ar';
    } else {
      document.documentElement.dir = 'ltr';
      if (targetPath.startsWith('/de')) document.documentElement.lang = 'de';
      else if (targetPath.startsWith('/fr')) document.documentElement.lang = 'fr';
      else if (targetPath.startsWith('/es')) document.documentElement.lang = 'es';
      else document.documentElement.lang = 'en';
    }

    if (targetPath.includes('#')) {
      const [pathname, hash] = targetPath.split('#');
      navigate(pathname || location.pathname);
      setTimeout(() => {
        const el = document.getElementById(hash);
        if (el) {
          el.scrollIntoView({ behavior: 'smooth' });
        }
      }, 50);
      return;
    }
    navigate(targetPath);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const isDe = location.pathname === "/de" || location.pathname.startsWith("/de/");
  const isAr = location.pathname === "/ar" || location.pathname.startsWith("/ar/");
  const isFr = location.pathname === "/fr" || location.pathname.startsWith("/fr/");
  const isEs = location.pathname === "/es" || location.pathname.startsWith("/es/");
  const locale: "en" | "es" | "ar" = isAr ? "ar" : isEs ? "es" : "en";

  React.useEffect(() => {
    if (typeof document !== "undefined") {
      if (isAr) {
        document.documentElement.dir = "rtl";
        document.documentElement.lang = "ar";
      } else if (isDe) {
        document.documentElement.dir = "ltr";
        document.documentElement.lang = "de";
      } else if (isFr) {
        document.documentElement.dir = "ltr";
        document.documentElement.lang = "fr";
      } else if (isEs) {
        document.documentElement.dir = "ltr";
        document.documentElement.lang = "es";
      } else {
        document.documentElement.dir = "ltr";
        document.documentElement.lang = "en";
      }
    }
  }, [isAr, isDe, isFr, isEs]);

  // Google Analytics SPA pageview tracking
  React.useEffect(() => {
    if (typeof window !== "undefined" && typeof (window as any).gtag === "function") {
      (window as any).gtag("config", "G-1HGYT9SMKG", {
        page_path: location.pathname + location.search,
      });
    }
  }, [location]);

  const isEmbedMode = location.pathname.startsWith("/embed");
  const isAdmin = location.pathname.startsWith("/admin");
  const isTaxSubsite =
    location.pathname.startsWith("/calculators/tax") ||
    location.pathname.startsWith("/calculator/property-") ||
    location.pathname.startsWith("/calculator/capital-gains") ||
    location.pathname.startsWith("/calculator/islamic-");

  const isSalarySubsite =
    location.pathname.includes("salary-calculator") ||
    location.pathname.includes("net-salary") ||
    location.pathname.includes("reverse-salary") ||
    location.pathname.includes("after-tax-salary") ||
    location.pathname.includes("salary-tax") ||
    location.pathname.includes("salary-increase") ||
    location.pathname.includes("hourly-to-salary") ||
    location.pathname.includes("salary-to-hourly") ||
    location.pathname.includes("salary-comparison") ||
    location.pathname.includes("cost-of-living") ||
    location.pathname.includes("/tax/") ||
    /^\/[a-z]{2}\/tax(\/|$)/i.test(location.pathname) ||
    /^\/[a-z]{2}\/[a-z0-9-]+\/salary-calculator(\/|$)/i.test(location.pathname) ||
    /^\/[a-z]{2}\/salary-calculator(\/|$)/i.test(location.pathname);

  const isDepopSubsite =
    location.pathname.startsWith("/depop-fees") ||
    location.pathname.startsWith("/depop-") ||
    location.pathname.includes("depop-fee");

  const isAstrologySubsite =
    location.pathname.startsWith("/sun-moon-rising") ||
    location.pathname.startsWith("/astrology") ||
    location.pathname.includes("sun-moon-rising");

  const isPaypalSubsite = 
    location.pathname.startsWith("/calculadora-paypal") ||
    location.pathname.startsWith("/calculadora-comisiones-paypal");

  const isSubsite =
    isDe ||
    isAr ||
    isFr ||
    isEs ||
    isSalarySubsite ||
    isTaxSubsite ||
    isDepopSubsite ||
    isAstrologySubsite ||
    isPaypalSubsite;

  // Admin Console: 100% Isolated, edge-to-edge layout, zero public ads, zero public headers/footers
  if (isAdmin) {
    return (
      <div className="min-h-screen bg-[#F8FAFC] text-[#0F172A] antialiased font-sans isolate">
        <ErrorBoundary>
          <Suspense fallback={
            <div className="min-h-screen flex items-center justify-center bg-white text-[#0F172A]">
              <div className="flex flex-col items-center gap-3">
                <div className="animate-spin rounded-full h-8 w-8 border-2 border-blue-500 border-t-transparent"></div>
                <span className="text-xs text-slate-500">Loading Zero Trust Admin Console...</span>
              </div>
            </div>
          }>
            <AppRoutes onNavigate={handleNavigate} />
          </Suspense>
        </ErrorBoundary>
      </div>
    );
  }

  if (isEmbedMode) {
    return (
      <LocaleProvider locale={locale}>
        <div className="min-h-screen bg-white text-[#0F172A] antialiased isolate">
          <ErrorBoundary>
            <Suspense fallback={<div className="h-64 flex items-center justify-center text-slate-500 text-xs">Loading...</div>}>
              <AppRoutes onNavigate={handleNavigate} />
            </Suspense>
          </ErrorBoundary>
        </div>
      </LocaleProvider>
    );
  }

  // Listen to global toggle-sidebar events from any localized subsite header
  React.useEffect(() => {
    const handleToggle = () => setSidebarOpen((prev) => !prev);
    window.addEventListener("toggle-sidebar", handleToggle);
    return () => window.removeEventListener("toggle-sidebar", handleToggle);
  }, []);

  // Sub-sites (Arabic, French, German, Spanish, Salary Calculator, Tax, Astrology, Depop, PayPal) - Standalone 100% isolated layout with unique branded headers and footers
  if (isSubsite) {
    let subsiteHeader: React.ReactNode = null;
    let subsiteFooter: React.ReactNode = null;

    if (isFr) {
      subsiteHeader = <FrenchHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <FrenchFooter onNavigate={handleNavigate} />;
    } else if (isDe) {
      subsiteHeader = <GermanHeader onNavigate={handleNavigate} />;
      subsiteFooter = <GermanFooter onNavigate={handleNavigate} />;
    } else if (isAr) {
      subsiteHeader = <ArabicHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <ArabicFooter onNavigate={handleNavigate} />;
    } else if (isPaypalSubsite) {
      subsiteHeader = <PaypalHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <PaypalFooter onNavigate={handleNavigate} />;
    } else if (isEs) {
      subsiteHeader = <SpanishHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <SpanishFooter onNavigate={handleNavigate} />;
    } else if (isSalarySubsite) {
      // Salary subsite pages embed SalaryHeader internally; we supply the unique SalaryFooter
      subsiteFooter = <SalaryFooter onNavigate={handleNavigate} />;
    } else if (isDepopSubsite) {
      subsiteHeader = <DepopHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <DepopFooter onNavigate={handleNavigate} />;
    } else if (isAstrologySubsite) {
      subsiteHeader = <AstrologyHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <AstrologyFooter onNavigate={handleNavigate} />;
    } else if (isTaxSubsite) {
      subsiteHeader = <TaxHeader onNavigate={handleNavigate} currentPath={location.pathname} />;
      subsiteFooter = <TaxFooter onNavigate={handleNavigate} />;
    }

    return (
      <LocaleProvider locale={locale}>
        <div className="min-h-screen flex flex-col bg-[#F8FAFC] text-[#0F172A] antialiased subsite-wrapper isolate" dir={isAr ? "rtl" : "ltr"}>
          <IndexNowPinger path={location.pathname} />
          {subsiteHeader}
          <AdBlockDetect showNotice={true} />
          <div className="flex-1 flex flex-col min-w-0 w-full isolate">
            <ErrorBoundary>
              <Suspense fallback={<PageSkeleton />}>
                <AppRoutes onNavigate={handleNavigate} />
              </Suspense>
            </ErrorBoundary>
          </div>
          {subsiteFooter}
          <OfflineIndicator />
        </div>
      </LocaleProvider>
    );
  }

  return (
    <LocaleProvider locale={locale}>
      <div className="min-h-screen flex flex-col bg-[#F8FAFC] text-[#0F172A] antialiased transition-colors isolate" dir={isAr ? "rtl" : "ltr"}>
        <IndexNowPinger path={location.pathname} />
        {/* Minimalist Top Bar with Left-Side Menu Three Lines and Centered Logo */}
        <div className="sticky top-0 z-40 bg-white/95 backdrop-blur-md border-b border-[#E2E8F0] px-4 py-2.5 grid grid-cols-3 items-center">
          {/* Left: Three Lines Menu Button */}
          <div className="flex items-center justify-start">
            <button
              type="button"
              onClick={() => setSidebarOpen((prev) => !prev)}
              className="p-2 rounded-xl text-[#0F172A] hover:bg-slate-100 transition-colors cursor-pointer flex items-center gap-2">
              <Menu className="w-5 h-5 text-blue-600" />
              <span className="text-xs font-bold text-[#0F172A] hidden sm:inline">Menu</span>
            </button>
          </div>

          {/* Center: Logo / Brand */}
          <div className="flex items-center justify-center">
            <a
              href="/"
              onClick={(e) => { e.preventDefault(); handleNavigate("/"); }}
              className="flex items-center gap-2 text-[#0F172A] font-extrabold text-sm sm:text-base tracking-tight cursor-pointer">
              <img src="/logo-64.webp" alt="CalcCompare" className="w-6 h-6 rounded-lg object-contain" />
              <span>Calc<span className="text-blue-600">Compare</span></span>
            </a>
          </div>

          {/* Right: Actions */}
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={() => setIsAllSitesModalOpen(true)}
              className="text-xs bg-[#2563EB] hover:bg-[#1D4ED8] text-white font-semibold px-3.5 py-1.5 rounded-lg transition-colors shadow-xs cursor-pointer">
              All Tools
            </button>
          </div>
        </div>

        <Sidebar 
          currentPath={location.pathname} 
          onNavigate={handleNavigate} 
          isOpen={sidebarOpen} 
          onClose={() => setSidebarOpen(false)} 
        />
        <AdBlockDetect showNotice={true} />

        {/* Content Container shifted right on desktop when sidebar is open */}
        <div className={cn("flex-1 flex flex-row transition-all duration-300", sidebarOpen ? "md:ml-64" : "md:ml-0")}>
          <div className="flex-1 flex flex-col min-w-0">
            <main id="main-content" className="flex-1 mx-auto w-full min-h-[85vh] max-w-7xl px-3 sm:px-6 lg:px-8 py-4">
              <ErrorBoundary>
                <Suspense fallback={<PageSkeleton />}>
                  <AppRoutes onNavigate={handleNavigate} />
                </Suspense>
              </ErrorBoundary>
            </main>

            <Footer onNavigate={handleNavigate} showSiteSwitcher={location.pathname === '/'} />
          </div>
        </div>
        
        {/* Floating Quick Site Switcher Widget & Full Grid View Directory Modal */}
        <FloatingSiteSwitcher 
          currentPath={location.pathname} 
          onNavigate={handleNavigate} 
          onOpenFullModal={() => setIsAllSitesModalOpen(true)} 
        />
        {isAllSitesModalOpen && (
          <Suspense fallback={null}>
            <SubdomainsModal 
              isOpen={isAllSitesModalOpen} 
              onClose={() => setIsAllSitesModalOpen(false)} 
              onNavigate={handleNavigate} 
            />
          </Suspense>
        )}

        <AdDiagnostics autoLogToConsole={true} showUI={false} />
        <OfflineIndicator />
      </div>
    </LocaleProvider>
  );
}
