const { useState: useStateTw, useEffect: useEffectTw } = React;

function TweaksPanel({ state, setState }) {
  const [visible, setVisible] = useStateTw(false);

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

  const set = (version) => {
    setState(s => ({ ...s, version }));
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { version } }, '*');
  };

  const opts = [
    ['listino',   'Listino'],
    ['manifesto', 'Manifesto'],
    ['quaderno',  'Quaderno'],
  ];

  return (
    <div className={`tweaks ${visible ? 'is-visible' : ''}`}>
      <div className="tweaks__title">Direction</div>
      <div className="tweaks__opts">
        {opts.map(([k, l]) => (
          <button
            key={k}
            className={`tweaks__opt ${state.version === k ? 'is-active' : ''}`}
            onClick={() => set(k)}
          >{l}</button>
        ))}
      </div>
    </div>
  );
}

window.TweaksPanel = TweaksPanel;
