import Script from 'next/script'

/** Contenu exécuté avant hydratation (thème + fond, évite flash clair). */
export const THEME_INIT_SCRIPT = `
(function () {
  try {
    var raw = localStorage.getItem("ultimail-mail-settings");
    if (!raw) return;
    var parsed = JSON.parse(raw);
    var state = parsed.state || parsed;
    var mode = state.themeMode || "system";
    var resolved =
      mode === "system"
        ? window.matchMedia("(prefers-color-scheme: dark)").matches
          ? "dark"
          : "light"
        : mode;
    document.documentElement.classList.toggle("dark", resolved === "dark");
    var bgId = state.backgroundId;
    if (bgId && bgId !== "none") {
      var legacy = {
        mountains: "photo-mountains",
        ocean: "gradient-ocean",
        forest: "photo-nature",
        abstract: "gradient-blossom"
      };
      var id = legacy[bgId] || bgId;
      var layers = {
        "gradient-aurora": 'url("/mail-backgrounds/gradient-aurora.svg") center/cover no-repeat',
        "gradient-sunset": 'url("/mail-backgrounds/gradient-sunset.svg") center/cover no-repeat',
        "gradient-ocean": 'url("/mail-backgrounds/gradient-ocean.svg") center/cover no-repeat',
        "gradient-blossom": 'url("/mail-backgrounds/gradient-blossom.svg") center/cover no-repeat',
        "photo-mountains": 'url("https://picsum.photos/seed/ultimail-mountains/1920/1080") center/cover no-repeat',
        "photo-ocean": 'url("https://picsum.photos/seed/ultimail-ocean/1920/1080") center/cover no-repeat',
        "photo-city": 'url("https://picsum.photos/seed/ultimail-city/1920/1080") center/cover no-repeat',
        "photo-nature": 'url("https://picsum.photos/seed/ultimail-nature/1920/1080") center/cover no-repeat'
      };
      var fallbacks = {
        "gradient-aurora": "#667eea",
        "gradient-sunset": "#e44d26",
        "gradient-ocean": "#203a43",
        "gradient-blossom": "#ffecd2",
        "photo-mountains": "#5c6b73",
        "photo-ocean": "#1a5276",
        "photo-city": "#2c3e50",
        "photo-nature": "#2d5016"
      };
      if (layers[id]) {
        document.documentElement.dataset.mailBackground = id;
        document.documentElement.style.setProperty("--mail-bg-layer", layers[id]);
        document.documentElement.style.setProperty(
          "--mail-bg-fallback",
          fallbacks[id] || "#202124"
        );
      }
    }
  } catch (e) {}
})();
`.trim()

/** Script bloquant injecté par Next.js dans le <head> (compatible React 19). */
export function ThemeInitScript() {
  return (
    <Script id="ultimail-theme-init" strategy="beforeInteractive">
      {THEME_INIT_SCRIPT}
    </Script>
  )
}
