// Tweaks — lets user change accent color, noise intensity, cursor style

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E8A0A0",
  "grain": 0.045,
  "cursorMode": "pink",
  "showFloatingTiles": true
}/*EDITMODE-END*/;

function Tweaks() {
  const [on, setOn] = React.useState(false);
  const [vals, setVals] = React.useState(TWEAK_DEFAULTS);

  React.useEffect(() => {
    const h = (e) => {
      if (e.data?.type === "__activate_edit_mode") setOn(true);
      if (e.data?.type === "__deactivate_edit_mode") setOn(false);
    };
    window.addEventListener("message", h);
    // announce availability AFTER listener mounts
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", h);
  }, []);

  React.useEffect(() => {
    document.documentElement.style.setProperty("--pink", vals.accent);
    const grain = document.querySelector(".film-grain");
    if (grain) grain.style.opacity = vals.grain;
  }, [vals]);

  const update = (k, v) => {
    const next = { ...vals, [k]: v };
    setVals(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  return (
    <div className={`tweak-panel ${on ? "on" : ""}`}>
      <div className="flex items-center justify-between mb-4">
        <span className="font-display text-[12px] tracking-[0.2em] uppercase text-[#f0ece8]">Tweaks</span>
        <span className="text-[9px] tracking-[0.2em] uppercase text-[rgba(232,160,160,0.6)]">Palm · Home</span>
      </div>
      <div className="tweak-row">
        <label>Accent</label>
        <div className="flex gap-2">
          {["#E8A0A0","#D3B98E","#8BAAA0","#E8D1A0","#C47A7A"].map(c => (
            <button key={c} onClick={() => update("accent", c)} className="w-6 h-6 rounded-full border border-white/10" style={{ background: c, outline: vals.accent === c ? "1px solid #fff" : "none", outlineOffset: 2 }}></button>
          ))}
        </div>
      </div>
      <div className="tweak-row">
        <label>Grain</label>
        <input type="range" min="0" max="0.12" step="0.005" value={vals.grain} onChange={(e) => update("grain", parseFloat(e.target.value))} />
      </div>
      <div className="tweak-row">
        <label>Cursor</label>
        <select value={vals.cursorMode} onChange={(e) => update("cursorMode", e.target.value)}>
          <option value="pink">Pink ring</option>
          <option value="dot">Dot only</option>
          <option value="native">Native</option>
        </select>
      </div>
      <div className="mt-4 pt-3 border-t border-white/[0.06] text-[10px] tracking-[0.2em] uppercase text-white/30">Toggle with Tweaks in toolbar</div>
    </div>
  );
}

// Apply cursor mode
(function() {
  const mo = new MutationObserver(() => {
    const mode = window.__tweaks?.cursorMode;
  });
})();

window.Tweaks = Tweaks;
