// Tweaks panel — theme/accent/density/font
// Follows the host protocol: register listener first, then announce availability.

function Tweaks() {
  const [open, setOpen] = useState(false);
  const [enabled, setEnabled] = useState(false);
  const [cfg, setCfg] = useState(() => ({...(window.__TWEAKS__ || {})}));

  useEffect(() => {
    const onMsg = (e) => {
      const t = e.data && e.data.type;
      if (t === "__activate_edit_mode") { setEnabled(true); setOpen(true); }
      else if (t === "__deactivate_edit_mode") { setEnabled(false); setOpen(false); }
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type:"__edit_mode_available" }, "*"); } catch(e){}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const apply = (next) => {
    const merged = { ...cfg, ...next };
    setCfg(merged);
    const html = document.documentElement;
    if (next.theme !== undefined) { html.classList.remove("dark","light"); html.classList.add(next.theme); }
    if (next.accent !== undefined) html.setAttribute("data-accent", next.accent);
    if (next.density !== undefined) html.setAttribute("data-density", next.density);
    if (next.monoBody !== undefined) document.body.classList.toggle("mono-body", !!next.monoBody);
    try { window.parent.postMessage({ type:"__edit_mode_set_keys", edits: next }, "*"); } catch(e){}
  };

  if (!enabled) return null;

  return (
    <div className="fixed bottom-4 right-4 z-50">
      {!open ? (
        <button onClick={() => setOpen(true)} className="surface rounded-full h-10 w-10 flex items-center justify-center shadow-lg"
          style={{boxShadow:"var(--shadow-lg)"}}>
          <Icon name="settings" size={16}/>
        </button>
      ) : (
        <div className="surface rounded-xl w-[280px] overflow-hidden" style={{boxShadow:"var(--shadow-lg)"}}>
          <div className="flex items-center px-3 py-2 border-b border-soft">
            <span className="text-[12px] font-medium">Tweaks</span>
            <button className="ml-auto text-3" onClick={() => setOpen(false)}><Icon name="x" size={14}/></button>
          </div>
          <div className="p-3 flex flex-col gap-3">
            <Row label="Theme">
              <Segmented value={cfg.theme} onChange={v => apply({theme:v})} opts={[{v:"dark",l:"Dark"},{v:"light",l:"Light"}]}/>
            </Row>
            <Row label="Density">
              <Segmented value={cfg.density} onChange={v => apply({density:v})} opts={[{v:"comfortable",l:"Comfortable"},{v:"compact",l:"Compact"}]}/>
            </Row>
            <Row label="Accent">
              <div className="flex gap-1.5">
                {["teal","lime","amber","indigo"].map(a => (
                  <button key={a} onClick={() => apply({accent:a})}
                    className={`h-7 w-7 rounded-full border ${cfg.accent===a?"border-strong":"border-soft"}`}
                    style={{background: a==="teal"?"#0ea5a0":a==="lime"?"#84cc16":a==="amber"?"#f59e0b":"#6366f1"}}/>
                ))}
              </div>
            </Row>
            <Row label="Mono body font">
              <div className="toggle" data-on={cfg.monoBody ? "true" : "false"} onClick={() => apply({monoBody: !cfg.monoBody})}/>
            </Row>
          </div>
        </div>
      )}
    </div>
  );
}

function Row({label, children}) {
  return (
    <div className="flex items-center">
      <div className="text-3 text-[11.5px] flex-1">{label}</div>
      {children}
    </div>
  );
}
function Segmented({value, onChange, opts}) {
  return (
    <div className="inline-flex rounded-md p-0.5 bg-[var(--chip)]">
      {opts.map(o => (
        <button key={o.v} onClick={() => onChange(o.v)}
          className={`px-2 h-6 text-[11px] rounded ${value===o.v?"bg-[var(--bg-raised)] text-1 shadow-sm":"text-3"}`}>
          {o.l}
        </button>
      ))}
    </div>
  );
}

window.Tweaks = Tweaks;
