/* Tweaks panel — exposed via toolbar toggle */
const { useState: tuS, useEffect: tuE } = React;

const ACCENTS = [
  { name: "Taupe doré", value: "#C9C3B0" },
  { name: "Or chaud", value: "#D4B56A" },
  { name: "Rose poudré", value: "#D8A8A2" },
  { name: "Sauge", value: "#A8B59E" },
];
const BGS = [
  { name: "Charbon", value: "#1f1f21" },
  { name: "Encre profonde", value: "#14141b" },
  { name: "Prune nuit", value: "#231820" },
  { name: "Ivoire", value: "#f3ede0" },
];

function Tweaks() {
  const defaults = window.TWEAK_DEFAULTS || { accent: "#C9C3B0", bg: "#1f1f21", heroImage: 1, scriptSize: 1, ornaments: true };
  const [show, setShow] = tuS(false);
  const [v, setV] = tuS(defaults);

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

  tuE(() => {
    const r = document.documentElement;
    r.style.setProperty("--gold", v.accent);
    const gd = shade(v.accent, -18);
    r.style.setProperty("--gold-dark", gd);
    r.style.setProperty("--border-gold", hexA(v.accent, 0.30));

    document.body.style.background = v.bg;
    r.style.setProperty("--bg", v.bg);
    // derive 2/3/4
    r.style.setProperty("--bg-2", shade(v.bg, 6));
    r.style.setProperty("--bg-3", shade(v.bg, 12));
    r.style.setProperty("--bg-4", shade(v.bg, -4));

    // If light bg, flip paper
    const isLight = luminance(v.bg) > 0.5;
    r.style.setProperty("--paper", isLight ? "#1f1f21" : "#F3EDE0");
    r.style.setProperty("--paper-soft", isLight ? "rgba(31,31,33,0.78)" : "rgba(243,237,224,0.78)");
    r.style.setProperty("--paper-dim", isLight ? "rgba(31,31,33,0.55)" : "rgba(243,237,224,0.55)");
    r.style.setProperty("--border", isLight ? "rgba(31,31,33,0.14)" : "rgba(243,237,224,0.14)");

    document.body.classList.toggle("no-ornaments", !v.ornaments);

    // script size
    r.style.setProperty("--script-scale", String(0.75 + 0.35 * v.scriptSize));
  }, [v]);

  const patch = (p) => {
    const next = { ...v, ...p };
    setV(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: p }, "*");
  };

  return (
    <div className={`tweaks ${show ? "show" : ""}`}>
      <h5>Tweaks <span style={{ color: "var(--paper-dim)", letterSpacing: ".2em", fontSize: 10 }}>KG</span></h5>

      <label className="row">Accent</label>
      <div className="swatches">
        {ACCENTS.map(a => (
          <div key={a.value}
            className={`sw ${v.accent === a.value ? "sel" : ""}`}
            style={{ background: a.value }}
            title={a.name}
            onClick={() => patch({ accent: a.value })}
          />
        ))}
      </div>

      <label className="row">Fond</label>
      <div className="swatches">
        {BGS.map(b => (
          <div key={b.value}
            className={`sw ${v.bg === b.value ? "sel" : ""}`}
            style={{ background: b.value }}
            title={b.name}
            onClick={() => patch({ bg: b.value })}
          />
        ))}
      </div>

      <label className="row">Taille du script</label>
      <input type="range" min="0" max="1.6" step="0.1" value={v.scriptSize}
        onChange={(e) => patch({ scriptSize: parseFloat(e.target.value) })} />

      <label className="row" style={{ marginTop: 16 }}>
        <div className="toggle">
          <span>Ornements</span>
          <div className={`switch ${v.ornaments ? "on" : ""}`} onClick={() => patch({ ornaments: !v.ornaments })}>
            <div className="knob" />
          </div>
        </div>
      </label>
    </div>
  );
}

function hexA(hex, a) {
  const h = hex.replace("#", "");
  const r = parseInt(h.substr(0, 2), 16), g = parseInt(h.substr(2, 2), 16), b = parseInt(h.substr(4, 2), 16);
  return `rgba(${r},${g},${b},${a})`;
}
function shade(hex, pct) {
  const h = hex.replace("#", "");
  let r = parseInt(h.substr(0, 2), 16), g = parseInt(h.substr(2, 2), 16), b = parseInt(h.substr(4, 2), 16);
  const amt = pct / 100;
  r = Math.max(0, Math.min(255, Math.round(r + 255 * amt)));
  g = Math.max(0, Math.min(255, Math.round(g + 255 * amt)));
  b = Math.max(0, Math.min(255, Math.round(b + 255 * amt)));
  return "#" + [r, g, b].map(n => n.toString(16).padStart(2, "0")).join("");
}
function luminance(hex) {
  const h = hex.replace("#", "");
  const r = parseInt(h.substr(0, 2), 16) / 255;
  const g = parseInt(h.substr(2, 2), 16) / 255;
  const b = parseInt(h.substr(4, 2), 16) / 255;
  return 0.299 * r + 0.587 * g + 0.114 * b;
}

window.Tweaks = Tweaks;
