// Main app — mounts the chosen direction + tweaks panel
// Listens for edit-mode messages from parent.

function App() {
  const [tweaks, setTweaks] = React.useState(window.GABI_TWEAKS || { direction: 'editorial', typographyVariant: 'default' });
  const [editMode, setEditMode] = React.useState(false);

  const setTweak = (key, value) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: value };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
      return next;
    });
    // Scroll to top on direction switch
    if (key === 'direction') window.scrollTo({ top: 0, behavior: 'smooth' });
  };

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

  const DirectionComp = {
    editorial: window.EditorialDirection,
    brutalism: window.BrutalismDirection,
    quietlight: window.QuietLightDirection,
  }[tweaks.direction] || window.EditorialDirection;

  return (
    <>
      <DirectionComp key={tweaks.direction} typographyVariant={tweaks.typographyVariant} />
      {editMode && <TweaksPanel tweaks={tweaks} setTweak={setTweak} />}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
