// Tweaks panel — in-design controls, toggled by host toolbar.

function useEditModeBridge() {
  const [active, setActive] = React.useState(false);
  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setActive(true);
      if (d.type === "__deactivate_edit_mode") setActive(false);
    };
    window.addEventListener("message", onMsg);
    // announce availability AFTER listener is live
    window.parent && window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);
  const persist = (edits) => {
    window.parent && window.parent.postMessage({ type: "__edit_mode_set_keys", edits }, "*");
  };
  return { active, persist };
}

function TweakRow({ label, children }) {
  return (
    <div className="flex items-center justify-between gap-3 py-2.5">
      <span className="mono text-[10px] uppercase tracking-[0.16em] t-mute">{label}</span>
      <div className="flex items-center gap-2">{children}</div>
    </div>
  );
}

function SwatchBtn({ color, active, onClick }) {
  return (
    <button
      onClick={onClick}
      className="w-6 h-6 rounded-full transition"
      style={{
        background: color,
        boxShadow: active ? `0 0 0 2px var(--bg), 0 0 0 3px ${color}` : "0 0 0 1px rgba(14,21,19,0.15)",
      }}
      aria-label={color}
    />
  );
}

function TweaksPanel({ values, onChange }) {
  const accents = [
    { label: "Esmeralda", v: "#22E0A1" },
    { label: "Cyan", v: "#22D3EE" },
    { label: "Violeta", v: "#A78BFA" },
    { label: "Ámbar", v: "#F59E0B" },
    { label: "Rosa", v: "#F472B6" },
    { label: "Blanco", v: "#E8EDEE" },
  ];
  const speeds = [1400, 2200, 3200, 5000];
  return (
    <div className="fixed z-50 right-5 bottom-5 w-[300px] glass-strong rounded-2xl p-4 shadow-2xl" style={{ boxShadow: "0 20px 60px rgba(0,0,0,0.6)" }}>
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          <span className="w-2 h-2 rounded-full pulse" style={{ background: "var(--accent)" }} />
          <span className="serif text-[18px]">Tweaks</span>
        </div>
        <span className="mono text-[10px] t-dim uppercase tracking-[0.18em]">live</span>
      </div>
      <div className="accent-rule mb-2" />

      <TweakRow label="Acento">
        <div className="flex gap-1.5">
          {accents.map(a => <SwatchBtn key={a.v} color={a.v} active={values.accent === a.v} onClick={() => onChange({ accent: a.v })} />)}
        </div>
      </TweakRow>

      <TweakRow label="Rotación título">
        <div className="flex gap-1">
          {speeds.map(s => (
            <button key={s} onClick={() => onChange({ titleRotationMs: s })}
              className="mono text-[10px] px-2 py-1 rounded-md hairline transition"
              style={{
                background: values.titleRotationMs === s ? "var(--accent)" : "var(--surface-1)",
                color: values.titleRotationMs === s ? "#FFFFFF" : "var(--text-mute)",
                borderColor: values.titleRotationMs === s ? "transparent" : "var(--border)",
              }}>
              {s/1000}s
            </button>
          ))}
        </div>
      </TweakRow>

      <TweakRow label="Densidad bento">
        {["compact","roomy"].map(d => (
          <button key={d} onClick={() => onChange({ bentoDensity: d })}
            className="mono text-[10px] px-2 py-1 rounded-md hairline"
            style={{
              background: values.bentoDensity === d ? "var(--accent)" : "var(--surface-1)",
              color: values.bentoDensity === d ? "#FFFFFF" : "var(--text-mute)",
              borderColor: values.bentoDensity === d ? "transparent" : "var(--border)",
            }}>
            {d}
          </button>
        ))}
      </TweakRow>

      <TweakRow label="Sparkline KPI">
        <button onClick={() => onChange({ showSparkline: !values.showSparkline })}
          className="mono text-[10px] px-2 py-1 rounded-md hairline"
          style={{
            background: values.showSparkline ? "var(--accent)" : "var(--surface-1)",
            color: values.showSparkline ? "#FFFFFF" : "var(--text-mute)",
            borderColor: values.showSparkline ? "transparent" : "var(--border)",
          }}>
          {values.showSparkline ? "visible" : "oculto"}
        </button>
      </TweakRow>

      <div className="mono text-[9px] t-dim uppercase tracking-[0.18em] mt-3 pt-2 hairline-t">
        cambios persistentes · escritos a disco
      </div>
    </div>
  );
}

function applyTweakVars(values) {
  const root = document.documentElement;
  root.style.setProperty("--accent", values.accent);
  // derive softs
  const hex = values.accent.replace("#","");
  const r = parseInt(hex.slice(0,2), 16);
  const g = parseInt(hex.slice(2,4), 16);
  const b = parseInt(hex.slice(4,6), 16);
  root.style.setProperty("--accent-soft", `rgba(${r},${g},${b},0.12)`);
  root.style.setProperty("--accent-line", `rgba(${r},${g},${b},0.35)`);
}

Object.assign(window, { useEditModeBridge, TweaksPanel, applyTweakVars });
