// Tweaks panel — theme + script font switcher

const THEMES = [
  { id: 'bloom', label: 'Bloom' },
  { id: 'editorial', label: 'Editorial' },
  { id: 'dusk', label: 'Dusk' },
];
const FONTS = [
  { id: 'allura', label: 'Allura' },
  { id: 'greatvibes', label: 'Great Vibes' },
  { id: 'pinyon', label: 'Pinyon' },
];

const DEFAULT_TWEAKS = /*EDITMODE-BEGIN*/{
  "theme": "bloom",
  "font": "allura",
  "petals": true
}/*EDITMODE-END*/;

const Tweaks = () => {
  const [visible, setVisible] = React.useState(false);
  const [vals, setVals] = React.useState(DEFAULT_TWEAKS);

  React.useEffect(() => {
    document.body.setAttribute('data-theme', vals.theme);
    document.body.setAttribute('data-font', vals.font);
    document.body.setAttribute('data-petals', vals.petals ? 'on' : 'off');
  }, [vals]);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const set = (k, v) => {
    setVals(vv => {
      const nv = { ...vv, [k]: v };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
      return nv;
    });
  };

  if (!visible) return null;

  return (
    <div className="tweaks-panel">
      <h5>Tweaks</h5>
      <div className="group">
        <label>Paleta</label>
        <div className="opts">
          {THEMES.map(t => (
            <button key={t.id} className={`opt ${vals.theme === t.id ? 'active' : ''}`} onClick={() => set('theme', t.id)}>
              {t.label}
            </button>
          ))}
        </div>
      </div>
      <div className="group">
        <label>Script font</label>
        <div className="opts">
          {FONTS.map(f => (
            <button key={f.id} className={`opt ${vals.font === f.id ? 'active' : ''}`} onClick={() => set('font', f.id)}>
              {f.label}
            </button>
          ))}
        </div>
      </div>
      <div className="group">
        <label>Pétalos</label>
        <div className="opts">
          <button className={`opt ${vals.petals ? 'active' : ''}`} onClick={() => set('petals', true)}>On</button>
          <button className={`opt ${!vals.petals ? 'active' : ''}`} onClick={() => set('petals', false)}>Off</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Tweaks });
