// ============================================================
//  Design Switcher — color scheme, typography, section density
//  Header-integrated. Persists selection in localStorage.
// ============================================================
const { useState: useStateDS, useEffect: useEffectDS, useRef: useRefDS } = React;

const DS_SCHEMES = {
  warm: {
    label: "Solar Warm",
    hint: "CI · harmonisch",
    vars: {
      // Solar Warm CI Manual v1.0 — Stille / Sein / Strahlen / Weite
      // Funktionale Aliasse für bestehende Komponenten
      "--paper": "#FFF1D4",      // Stille · Honiglicht · Grund 60%
      "--cream": "#FFF6DF",      // Stille-soft · Sandmilch
      "--cream-deep": "#FFEAC2", // Stille-warm · Sandlicht
      "--ink": "#12224B",        // Sein · Sri-Yantra-Indigo
      "--accent": "#F48A28",     // Strahlen · Fiery Orange
      "--accent-deep": "#C8561D",// Sunset · CTA
      "--accent-warm": "#F4B940",// Gold · Highlight
      "--accent-earth": "#C8DDEA",// Weite · Himmelweite (max 5%)
      // Direkte CI-Tokens (für neue Komponenten)
      "--stille": "#FFF1D4",
      "--sein": "#12224B",
      "--strahlen": "#F48A28",
      "--weite": "#C8DDEA",
      "--sunset": "#C8561D",
      "--gold": "#F4B940",
    },
  },
  dawn: {
    label: "Morning Dawn",
    hint: "Weicher · pastelliger",
    vars: {
      "--paper": "#FAF4EA",
      "--cream": "#F2E8D6",
      "--cream-deep": "#E8D3B4",
      "--ink": "#3A2E24",
      "--accent": "#E8B873",
      "--accent-deep": "#B67438",
      "--accent-warm": "#D88960",
      "--accent-earth": "#6A7758",
    },
  },
  deep: {
    label: "Deep Forest",
    hint: "Geerdet · dunkler",
    vars: {
      "--paper": "#EFE9DC",
      "--cream": "#E5DCC5",
      "--cream-deep": "#D6C9A8",
      "--ink": "#1F2620",
      "--accent": "#C69050",
      "--accent-deep": "#8A5A26",
      "--accent-warm": "#B4613E",
      "--accent-earth": "#4A5540",
    },
  },
  ivory: {
    label: "Ivory",
    hint: "Minimal · heller",
    vars: {
      "--paper": "#FBF8F1",
      "--cream": "#F3EDDD",
      "--cream-deep": "#E8DEC3",
      "--ink": "#221E18",
      "--accent": "#CFA25B",
      "--accent-deep": "#9B6326",
      "--accent-warm": "#BD7246",
      "--accent-earth": "#60694F",
    },
  },
};

const DS_TYPO = {
  sourceSerifHelvetica: {
    label: "Cormorant + DM Sans",
    hint: "CI · Serif für Sein, Sans für Sagen",
    serif:
      "'Cormorant Garamond', 'Platin Pro', 'Iowan Old Style', Garamond, Georgia, serif",
    sans: "'DM Sans', ui-sans-serif, system-ui, -apple-system, sans-serif",
    mono: "'JetBrains Mono', 'IBM Plex Mono', ui-monospace, monospace",
  },
  cormorantInter: {
    label: "Cormorant + Inter",
    hint: "Warm · feminin",
    serif: "'Cormorant Garamond', Georgia, serif",
    sans: "'Inter', system-ui, sans-serif",
    mono: "'JetBrains Mono', monospace",
  },
  libreHelvetica: {
    label: "Libre Caslon + Helvetica",
    hint: "Klassisch",
    serif: "'Libre Caslon Text', 'Libre Caslon', Georgia, serif",
    sans: "'Helvetica Neue', Helvetica, Arial, sans-serif",
    mono: "'JetBrains Mono', monospace",
  },
  playfairInter: {
    label: "Playfair + Inter",
    hint: "Statement · kontrastreich",
    serif: "'Playfair Display', Georgia, serif",
    sans: "'Inter', system-ui, sans-serif",
    mono: "'JetBrains Mono', monospace",
  },
};

const DS_DENSITY = {
  airy: { label: "Luftig", hint: "Viel Weißraum", pyDesktop: "8rem", pyMobile: "4.5rem" },
  calm: { label: "Ruhig", hint: "Ausgewogen", pyDesktop: "6rem", pyMobile: "3.75rem" },
  compact: { label: "Kompakt", hint: "Dichter", pyDesktop: "4.5rem", pyMobile: "3rem" },
};

const DS_DEFAULTS = { scheme: "warm", typo: "sourceSerifHelvetica", density: "airy" };
// Storage-Key bumpen — invalidert alte localStorage-Werte aus pre-CI Versionen.
const DS_STORAGE = "tt-design-prefs-v2-solar";

function dsApply(state) {
  const root = document.documentElement;
  const scheme = DS_SCHEMES[state.scheme] || DS_SCHEMES.warm;
  Object.entries(scheme.vars).forEach(([k, v]) => root.style.setProperty(k, v));

  const typo = DS_TYPO[state.typo] || DS_TYPO.sourceSerifHelvetica;
  root.style.setProperty("--font-serif", typo.serif);
  root.style.setProperty("--font-sans", typo.sans);
  root.style.setProperty("--font-mono", typo.mono);

  const dens = DS_DENSITY[state.density] || DS_DENSITY.airy;
  const isMobile = window.matchMedia("(max-width: 768px)").matches;
  root.style.setProperty("--section-py", isMobile ? dens.pyMobile : dens.pyDesktop);
}

function useDesignPrefs() {
  const [state, setState] = useStateDS(() => {
    try {
      const raw = localStorage.getItem(DS_STORAGE);
      if (raw) return { ...DS_DEFAULTS, ...JSON.parse(raw) };
    } catch (e) {}
    return DS_DEFAULTS;
  });

  useEffectDS(() => {
    dsApply(state);
    try { localStorage.setItem(DS_STORAGE, JSON.stringify(state)); } catch (e) {}
  }, [state]);

  useEffectDS(() => {
    const onResize = () => dsApply(state);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [state]);

  return [state, setState];
}

function DesignSwitcher({ prefs, setPrefs, variant = "desktop" }) {
  const [open, setOpen] = useStateDS(false);
  const panelRef = useRefDS(null);
  const btnRef = useRefDS(null);

  useEffectDS(() => {
    if (!open) return;
    const onDocClick = (e) => {
      if (panelRef.current?.contains(e.target)) return;
      if (btnRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const reset = () => setPrefs(DS_DEFAULTS);

  const groups = [
    { key: "scheme",  title: "Farbschema",    opts: DS_SCHEMES },
    { key: "typo",    title: "Typografie",    opts: DS_TYPO },
    { key: "density", title: "Layout-Dichte", opts: DS_DENSITY },
  ];

  const btnBase = "font-mono text-[11px] tracking-[0.20em] uppercase transition-colors flex items-center gap-2";
  const isInline = variant === "inline";

  return (
    <div className="relative">
      <button
        ref={btnRef}
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        aria-label={`Design ändern (${variant})`}
        data-design-switcher={variant}
        className={
          isInline
            ? `${btnBase} w-full justify-between border border-[color:var(--ink)]/25 px-5 py-3 text-[color:var(--ink)] hover:border-[color:var(--ink)]`
            : `${btnBase} px-3 py-2 text-[color:var(--ink)]/70 hover:text-[color:var(--ink)]`
        }
      >
        <span className="flex items-center gap-2">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden>
            <circle cx="7" cy="7" r="5.5" stroke="currentColor" strokeWidth="1.2" />
            <path d="M7 1.5v11M1.5 7h11" stroke="currentColor" strokeWidth="1.2" opacity="0.55" />
          </svg>
          Design
        </span>
        <span aria-hidden className="text-[10px] opacity-70">{open ? "▲" : "▼"}</span>
      </button>

      {open && (
        <>
          {!isInline && (
            <div className="lg:hidden fixed inset-0 bg-[color:var(--ink)]/30 z-[55]" onClick={() => setOpen(false)} />
          )}
          <div
            ref={panelRef}
            role="dialog"
            aria-label="Design-Einstellungen"
            className={
              isInline
                ? "block w-full mt-3 bg-[color:var(--paper)] border border-[color:var(--ink)]/15"
                : "absolute right-0 mt-3 w-[340px] max-w-[90vw] bg-[color:var(--paper)] border border-[color:var(--ink)]/15 shadow-2xl z-[65]"
            }
            style={!isInline ? { boxShadow: "0 30px 80px -20px rgba(0,0,0,0.28)" } : undefined}
          >
            <div className="flex items-center justify-between px-5 py-4 border-b border-[color:var(--ink)]/15">
              <div className="font-mono text-[11px] tracking-[0.22em] uppercase text-[color:var(--ink)]">
                Design-Optionen
              </div>
              <button
                onClick={reset}
                className="font-mono text-[10px] tracking-[0.18em] uppercase text-[color:var(--ink)]/55 hover:text-[color:var(--accent-deep)]"
              >
                Zurücksetzen
              </button>
            </div>

            <div className="p-5 space-y-6 max-h-[70vh] overflow-y-auto">
              {groups.map((g) => (
                <div key={g.key}>
                  <div className="font-mono text-[10px] tracking-[0.22em] uppercase text-[color:var(--ink)]/55 mb-3">
                    {g.title}
                  </div>
                  <div className="grid gap-2">
                    {Object.entries(g.opts).map(([val, v]) => {
                      const active = prefs[g.key] === val;
                      const swatches = g.key === "scheme" ? [
                        v.vars["--paper"], v.vars["--cream-deep"], v.vars["--accent"], v.vars["--accent-deep"], v.vars["--ink"],
                      ] : null;
                      return (
                        <button
                          key={val}
                          onClick={() => setPrefs({ ...prefs, [g.key]: val })}
                          className={`text-left px-4 py-3 border transition-colors ${
                            active
                              ? "border-[color:var(--ink)] bg-[color:var(--cream)]"
                              : "border-[color:var(--ink)]/15 hover:border-[color:var(--ink)]/40"
                          }`}
                        >
                          <div className="flex items-start justify-between gap-3">
                            <div className="flex-1 min-w-0">
                              <div className="font-serif text-[15px] text-[color:var(--ink)] leading-tight">
                                {v.label}
                              </div>
                              {v.hint && (
                                <div className="font-mono text-[9px] tracking-[0.14em] uppercase text-[color:var(--ink)]/55 mt-1">
                                  {v.hint}
                                </div>
                              )}
                            </div>
                            <div className={`mt-1 w-2 h-2 rounded-full shrink-0 ${active ? "bg-[color:var(--accent-deep)]" : "bg-[color:var(--ink)]/20"}`} />
                          </div>
                          {swatches && (
                            <div className="flex gap-1 mt-3">
                              {swatches.map((c, i) => (
                                <span key={i} className="block w-5 h-5 border border-[color:var(--ink)]/10" style={{ background: c }} />
                              ))}
                            </div>
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { useDesignPrefs, DesignSwitcher, DS_SCHEMES, DS_TYPO, DS_DENSITY });
