'use client'

/** Contenu exécuté avant hydratation (thème + fond, évite flash clair). */
export const THEME_INIT_SCRIPT = `
(function () {
  try {
    var path = window.location.pathname || "";
    var isDrive =
      path === "/drive" ||
      path.indexOf("/drive/") === 0 ||
      path === "/demo/drive" ||
      path.indexOf("/demo/drive/") === 0;
    var isMail =
      path === "/mail" ||
      path.indexOf("/mail/") === 0 ||
      path === "/demo/mail" ||
      path.indexOf("/demo/mail/") === 0;
    var splashApp = null;
    if (path === "/mail" || path.indexOf("/mail/") === 0) splashApp = "mail";
    else if (isDrive) splashApp = "drive";
    else if (path === "/agenda" || path.indexOf("/agenda/") === 0) splashApp = "agenda";
    else if (path === "/contacts" || path.indexOf("/contacts/") === 0) splashApp = "contacts";

    var splashSeen = false;
    if (splashApp) {
      splashSeen = localStorage.getItem("ultisuite-splash-seen-v1-" + splashApp) === "1";
      if (!splashSeen && splashApp === "mail") {
        splashSeen = localStorage.getItem("ultimail-splash-seen-v1") === "1";
      }
    } else {
      splashSeen = true;
    }

    if (path === "/" || path.indexOf("/demo/") === 0) {
      splashSeen = true;
    }

    if (isDrive) {
      document.documentElement.dataset.routeScope = "drive";
      delete document.documentElement.dataset.mailBackground;
      document.documentElement.style.removeProperty("--mail-bg-layer");
      document.documentElement.style.removeProperty("--mail-bg-fallback");
    } else {
      delete document.documentElement.dataset.routeScope;
    }

    document.documentElement.dataset.splashApp = splashApp || "";
    document.documentElement.dataset.splashSeen = splashSeen ? "1" : "0";

    var mode = "system";
    var bgId = null;

    function readPersistedThemeMode(raw) {
      if (!raw) return null;
      try {
        var parsed = JSON.parse(raw);
        var state = parsed.state || parsed;
        return state.themeMode || null;
      } catch (e) {
        return null;
      }
    }

    var clientRaw = localStorage.getItem("ultisuite-client-theme");
    mode = readPersistedThemeMode(clientRaw) || "system";
    if (!readPersistedThemeMode(clientRaw)) {
      var legacyMail = readPersistedThemeMode(localStorage.getItem("ultimail-mail-settings"));
      var legacyDemo = readPersistedThemeMode(localStorage.getItem("ultimail-demo-theme"));
      mode = legacyMail || legacyDemo || "system";
    }

    if (isMail) {
      var mailSettingsRaw = localStorage.getItem("ultimail-mail-settings");
      if (mailSettingsRaw) {
        try {
          var mailParsed = JSON.parse(mailSettingsRaw);
          var mailState = mailParsed.state || mailParsed;
          bgId = mailState.backgroundId;
        } catch (e) {}
      }
    }

    var resolved =
      mode === "system"
        ? window.matchMedia("(prefers-color-scheme: dark)").matches
          ? "dark"
          : "light"
        : mode;
    document.documentElement.classList.toggle("dark", resolved === "dark");
    if (isMail && 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()

/** Run theme / route bootstrap (mobile client mount — no blocking script in HTML). */
export function runThemeInit() {
  try {
    // eslint-disable-next-line no-new-func
    new Function(THEME_INIT_SCRIPT)()
  } catch {
    /* best effort */
  }
}

/**
 * Script bloquant dans <head>. SSR rend script exécutable ; côté client type
 * inerte pour éviter l'avertissement React 19 (le script a déjà tourné).
 */
export function ThemeInitScript() {
  const isServer = typeof window === 'undefined'

  return (
    <script
      id="ultimail-theme-init"
      suppressHydrationWarning
      {...(isServer
        ? { dangerouslySetInnerHTML: { __html: THEME_INIT_SCRIPT } }
        : {
            type: 'application/json' as const,
            dangerouslySetInnerHTML: { __html: THEME_INIT_SCRIPT },
          })}
    />
  )
}
