// Tweaks panel: theme/accent/animation switcher wired to body dataset + localStorage.

function TweaksPanel() {
  const [visible, setVisible] = useState(false);
  const [tweaks, setTweaks] = useState(() => {
    try {
      const saved = localStorage.getItem('dashboard-tweaks');
      if (saved) return { ...(window.__TWEAKS__ || {}), ...JSON.parse(saved) };
    } catch (e) {}
    return window.__TWEAKS__ || { theme: 'luminous', accent: 'green', animation: 'max', grain: true, ambient: true };
  });

  // Apply tweaks to DOM
  useEffect(() => {
    document.body.dataset.theme = tweaks.theme;
    document.body.dataset.accent = tweaks.accent;
    document.body.dataset.animation = tweaks.animation;
    document.body.dataset.grain = tweaks.grain ? 'on' : 'off';
    document.body.dataset.ambient = tweaks.ambient ? 'on' : 'off';
    try { localStorage.setItem('dashboard-tweaks', JSON.stringify(tweaks)); } catch (e) {}
  }, [tweaks]);

  // Edit-mode protocol
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const update = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };

  if (!visible) return null;

  const themes = [
    { id: 'luminous', label: 'luminous' },
    { id: 'editorial', label: 'editorial' },
    { id: 'terminal', label: 'terminal' },
  ];
  const accents = [
    { id: 'green', label: 'green', color: '#7FD4A3' },
    { id: 'amber', label: 'amber', color: '#E8A94A' },
    { id: 'lime', label: 'lime', color: '#C6F24A' },
    { id: 'magenta', label: 'magenta', color: '#E84A9B' },
    { id: 'cyan', label: 'cyan', color: '#4ADCE8' },
  ];

  return (
    <div className="tweaks-panel fade-up">
      <div className="flex items-center justify-between mb-3">
        <div className="text-[11px] tracking-[0.25em] uppercase font-medium" style={{ color: 'var(--text-0)' }}>Tweaks</div>
        <button onClick={() => setVisible(false)} style={{ color: 'var(--text-2)' }}><XIcon size={14} /></button>
      </div>

      <div className="mb-3">
        <div className="text-[10px] tracking-[0.25em] uppercase mb-2" style={{ color: 'var(--text-2)' }}>theme</div>
        <div className="flex gap-1 flex-wrap">
          {themes.map(t => (
            <button key={t.id} onClick={() => update({ theme: t.id })} className="tweak-chip" data-active={tweaks.theme === t.id}>
              {t.label}
            </button>
          ))}
        </div>
      </div>

      <div className="mb-3">
        <div className="text-[10px] tracking-[0.25em] uppercase mb-2" style={{ color: 'var(--text-2)' }}>accent</div>
        <div className="flex gap-1 flex-wrap">
          {accents.map(a => (
            <button key={a.id} onClick={() => update({ accent: a.id })} className="tweak-chip flex items-center gap-1.5" data-active={tweaks.accent === a.id}>
              <span className="w-2 h-2 rounded-full inline-block" style={{ background: a.color }} />
              {a.label}
            </button>
          ))}
        </div>
      </div>

      <div className="mb-3">
        <div className="text-[10px] tracking-[0.25em] uppercase mb-2" style={{ color: 'var(--text-2)' }}>animation</div>
        <div className="flex gap-1">
          {['max', 'mid', 'low'].map(a => (
            <button key={a} onClick={() => update({ animation: a })} className="tweak-chip" data-active={tweaks.animation === a}>
              {a}
            </button>
          ))}
        </div>
      </div>

      <div className="flex gap-4 text-[11px]" style={{ color: 'var(--text-1)' }}>
        <label className="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" checked={tweaks.grain} onChange={(e) => update({ grain: e.target.checked })} />
          grain
        </label>
        <label className="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" checked={tweaks.ambient} onChange={(e) => update({ ambient: e.target.checked })} />
          ambient
        </label>
      </div>
    </div>
  );
}

window.TweaksPanel = TweaksPanel;
