// Tweaks: accent color, density, hero variant. Visible only when host toggles.
const { useState: useStateTw, useEffect: useEffectTw } = React;

const ACCENTS = [
  { key: "cobalt", v: "oklch(0.55 0.2 252)", vd: "oklch(0.7 0.17 252)", soft: "oklch(0.96 0.03 252)", softD: "oklch(0.25 0.07 252)", swatch: "#2b5fdb" },
  { key: "emerald", v: "oklch(0.55 0.16 155)", vd: "oklch(0.72 0.15 155)", soft: "oklch(0.96 0.04 155)", softD: "oklch(0.24 0.06 155)", swatch: "#1f8a5b" },
  { key: "amber", v: "oklch(0.6 0.16 60)", vd: "oklch(0.78 0.14 70)", soft: "oklch(0.96 0.05 70)", softD: "oklch(0.26 0.07 65)", swatch: "#c78328" },
  { key: "magenta", v: "oklch(0.55 0.2 350)", vd: "oklch(0.72 0.17 350)", soft: "oklch(0.96 0.04 350)", softD: "oklch(0.25 0.07 350)", swatch: "#c5379a" },
];

const DENSITIES = [
  { key: "compact", topbar: 52, sidebar: 244, sans: 14 },
  { key: "normal", topbar: 60, sidebar: 264, sans: 15 },
  { key: "roomy", topbar: 68, sidebar: 280, sans: 16 },
];

function applyAccent(a) {
  const dark = document.documentElement.getAttribute("data-theme") === "dark";
  const root = document.documentElement.style;
  root.setProperty("--accent", dark ? a.vd : a.v);
  root.setProperty("--accent-soft", dark ? a.softD : a.soft);
}
function applyDensity(d) {
  const root = document.documentElement.style;
  root.setProperty("--topbar-h", d.topbar + "px");
  root.setProperty("--sidebar-w", d.sidebar + "px");
  document.body.style.fontSize = d.sans + "px";
}

function TweaksPanel() {
  const [open, setOpen] = useStateTw(false);
  const [visible, setVisible] = useStateTw(false);
  const [accent, setAccent] = useStateTw(() => localStorage.getItem("kol_accent") || "cobalt");
  const [density, setDensity] = useStateTw(() => localStorage.getItem("kol_density") || "normal");

  useEffectTw(() => {
    const a = ACCENTS.find(x => x.key === accent) || ACCENTS[0];
    applyAccent(a);
    localStorage.setItem("kol_accent", accent);
  }, [accent]);

  useEffectTw(() => {
    const d = DENSITIES.find(x => x.key === density) || DENSITIES[1];
    applyDensity(d);
    localStorage.setItem("kol_density", density);
  }, [density]);

  // re-apply accent when theme changes (because dark mode uses different L)
  useEffectTw(() => {
    const obs = new MutationObserver(() => {
      const a = ACCENTS.find(x => x.key === accent) || ACCENTS[0];
      applyAccent(a);
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, [accent]);

  useEffectTw(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") { setVisible(true); setOpen(true); }
      else if (e.data.type === "__deactivate_edit_mode") { setVisible(false); setOpen(false); }
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch (e) {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  function close() {
    setOpen(false);
    setVisible(false);
    try { window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); } catch (e) {}
  }

  if (!visible) return null;

  return (
    <>
      <button className={`tweaks-fab visible`} onClick={() => setOpen(o => !o)} title="Tweaks">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
          <circle cx="5" cy="4.5" r="1.5"></circle><circle cx="11" cy="11.5" r="1.5"></circle>
          <path d="M5 6v6M11 4v6M2 4.5h1.5M6.5 4.5H14M2 11.5h6.5M12.5 11.5H14"></path>
        </svg>
      </button>
      <div className={`tweaks-panel ${open ? "open" : ""}`}>
        <h4>
          Tweaks
          <button onClick={close} style={{ color: "var(--ink-3)", fontSize: 14 }} aria-label="Close">×</button>
        </h4>
        <div className="tweak-group">
          <label>Accent</label>
          <div className="swatch-row">
            {ACCENTS.map(a => (
              <button
                key={a.key}
                className={`swatch ${accent === a.key ? "active" : ""}`}
                style={{ background: a.swatch }}
                onClick={() => setAccent(a.key)}
                title={a.key}
              />
            ))}
          </div>
        </div>
        <div className="tweak-group">
          <label>Density</label>
          <div className="segment">
            {DENSITIES.map(d => (
              <button key={d.key} className={density === d.key ? "active" : ""} onClick={() => setDensity(d.key)}>{d.key}</button>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

window.KOL_PAGES.TweaksPanel = TweaksPanel;
