// Tweaks.jsx — design-system edit-mode panel
const { useState: useStateT, useEffect: useEffectT } = React;

function Tweaks({ state, setState, defaults }) {
  const [active, setActive] = useStateT(false);

  useEffectT(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setActive(true);
      if (e.data.type === '__deactivate_edit_mode') setActive(false);
    };
    window.addEventListener('message', onMsg);
    // announce only AFTER listener is registered
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const update = (key, val) => {
    const next = { ...state, [key]: val };
    setState(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  };

  const group = (label, options, key) => (
    <div className="tweak-row">
      <label>{label}</label>
      <div className="options">
        {options.map(o => (
          <button
            key={o.val}
            className={state[key] === o.val ? 'active' : ''}
            onClick={() => update(key, o.val)}
          >{o.label}</button>
        ))}
      </div>
    </div>
  );

  return (
    <div className={`tweaks-panel ${active ? 'is-open' : ''}`}>
      <h6>Tweaks</h6>

      {group('Hero mode', [
        { val: 'dark', label: 'Dark' },
        { val: 'purple', label: 'Purple' },
        { val: 'light', label: 'Light' },
      ], 'heroMode')}

      {group('Cursor', [
        { val: true, label: 'Custom' },
        { val: false, label: 'Default' },
      ], 'customCursor')}

      {group('Type voice', [
        { val: 'serif', label: 'Serif' },
        { val: 'sans', label: 'Sans' },
      ], 'typeVoice')}

      <div className="tweak-row">
        <label>Marquee speed · {state.marqueeSpeed}s</label>
        <input
          type="range"
          min="15" max="80" step="5"
          value={state.marqueeSpeed}
          onChange={(e) => update('marqueeSpeed', Number(e.target.value))}
        />
      </div>

      {group('Accent', [
        { val: 'gold', label: 'Gold' },
        { val: 'none', label: 'None' },
      ], 'accent')}
    </div>
  );
}

window.Tweaks = Tweaks;
