// theme.jsx — Shared theme app for module pages (cashflow, commerce, crm, analista)
// Reads palette + dark from localStorage so the choice persists between pages.
// Mounts a Tweaks panel in its own root.

(function() {
  const STORAGE = "afianco_theme";

  function loadTheme() {
    try {
      const raw = localStorage.getItem(STORAGE);
      if (!raw) return null;
      return JSON.parse(raw);
    } catch (e) { return null; }
  }
  function saveTheme(t) {
    try { localStorage.setItem(STORAGE, JSON.stringify(t)); } catch (e) {}
  }

  // Apply immediately to avoid flash
  let stored = loadTheme();
  // LEGACY_CORAL_MIGRATION: indigo is the new default brand, migrate any
  // previously persisted coral or emerald choices on first load.
  if (stored && (stored.palette === "coral" || stored.palette === "emerald") && !localStorage.getItem("afianco_palette_indigo_migrated")) {
    stored = { ...stored, palette: "indigo" };
    try { localStorage.setItem("afianco_palette_indigo_migrated", "1"); } catch (e) {}
    saveTheme(stored);
  }
  const initial = stored || { palette: "indigo", dark: false };
  document.documentElement.setAttribute("data-palette", initial.palette);
  document.documentElement.setAttribute("data-theme", initial.dark ? "dark" : "light");

  // Wait for React + DOM, then mount the panel
  function mount() {
    if (!window.React || !window.ReactDOM || !window.TweaksPanel) {
      setTimeout(mount, 50);
      return;
    }
    const { useState, useEffect } = React;

    function ThemeApp() {
      const [palette, setPalette] = useState(initial.palette);
      const [dark, setDark] = useState(initial.dark);

      useEffect(() => {
        document.documentElement.setAttribute("data-palette", palette);
        document.documentElement.setAttribute("data-theme", dark ? "dark" : "light");
        saveTheme({ palette, dark });
      }, [palette, dark]);

      return (
        <TweaksPanel title="Personalizza">
          <TweakSection label="Brand color" />
          <TweakRadio
            label="Palette"
            value={palette}
            options={[
              { value: "emerald", label: "Emerald" },
              { value: "indigo",  label: "Indigo" },
              { value: "coral",   label: "Coral" },
              { value: "slate",   label: "Slate" },
            ]}
            onChange={setPalette}
          />
          <TweakSection label="Tema" />
          <TweakToggle
            label="Dark mode"
            value={dark}
            onChange={setDark}
          />
        </TweaksPanel>
      );
    }

    // Mount in a dedicated container so it doesn't fight the page's main React root.
    let host = document.getElementById("__theme_host");
    if (!host) {
      host = document.createElement("div");
      host.id = "__theme_host";
      document.body.appendChild(host);
    }
    ReactDOM.createRoot(host).render(<ThemeApp />);
  }
  mount();
})();
