"use client";
import "./globals.css";
import "@/styles/cmdk.css";
import Providers from "@/components/Providers";
import ProgressBar from "@/components/ProgressBar";
import { PostHogPageView } from "@/components/PostHogPageView";
import PostHogIdentifier from "@/components/PostHogIdentifier";
import ConsentManager from "@/components/ConsentManager";
import { useAnalyticsConsent } from "@/hooks/useAnalyticsConsent";
import { useEffect, Suspense } from "react";

/**
 * Simple garde pour maintenir le company_name dans localStorage pour l'affichage UI.
 * La source de vérité est maintenant entièrement server-side via les cookies et /api/me.
 */
function OrgPersistenceGuard() {
  useEffect(() => {
    if (typeof window === "undefined") return;

    // Simple garde pour éviter que company_name soit effacé par des scripts externes
    const preserveCompanyName = () => {
      const currentName = localStorage.getItem("company_name");
      if (currentName) {
        sessionStorage.setItem("last_company_name", currentName);
      }
    };

    const restoreCompanyName = () => {
      const currentName = localStorage.getItem("company_name");
      const lastName = sessionStorage.getItem("last_company_name");
      
      if (!currentName && lastName) {
        localStorage.setItem("company_name", lastName);
      }
    };

    // Préserver le nom périodiquement
    preserveCompanyName();
    const interval = setInterval(preserveCompanyName, 5000);

    // Restaurer si nécessaire
    window.addEventListener("storage", restoreCompanyName);

    return () => {
      clearInterval(interval);
      window.removeEventListener("storage", restoreCompanyName);
    };
  }, []);

  return null;
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="fr">
      <head>
        <title>Espace Paie Odentas</title>
        <meta name="description" content="Plateforme de gestion de paie Odentas" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5, viewport-fit=cover" />
        
        {/* Favicons */}
        <link rel="icon" href="/favicon.ico" sizes="32x32" />
        <link rel="icon" href="/favicon.png" type="image/png" sizes="any" />
        <link rel="icon" href="/favicon-16x16.png" sizes="16x16" type="image/png" />
        <link rel="icon" href="/favicon-32x32.png" sizes="32x32" type="image/png" />
        
        {/* Apple Touch Icon */}
        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="default" />
        <meta name="apple-mobile-web-app-title" content="Espace Paie" />
        
        {/* Manifest PWA */}
        <link rel="manifest" href="/manifest.json" />
        
        {/* Theme color */}
        <meta name="theme-color" content="#2D7FF9" />
        <meta name="msapplication-TileColor" content="#2D7FF9" />
        
        {/* PWA */}
        <meta name="mobile-web-app-capable" content="yes" />
        <meta name="application-name" content="Espace Paie" />
      </head>
      <body>
        {/* Barre de progression pour les changements de page */}
        <ProgressBar />
        {/* Garde simple pour préserver l'affichage UI */}
        <OrgPersistenceGuard />
        <Providers>
          <Suspense fallback={null}>
            <PostHogPageView />
            <PostHogIdentifier />
          </Suspense>
          {children}
          {/* Gestion du consentement selon le contexte (B2B ou salarié) */}
          <ConsentManager policyUrl="/politique-confidentialite" />
        </Providers>
        {/* BugReporter temporairement masqué */}
      </body>
    </html>
  );
}