const { useState, useEffect } = React;

function useRoute() {
  const parse = () => {
    const h = (window.location.hash || '').replace(/^#\/?/, '').toLowerCase();
    if (h.startsWith('contact')) return 'contact';
    return 'home';
  };
  const [route, setRoute] = useState(parse);
  useEffect(() => {
    const on = () => {
      setRoute(parse());
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return route;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variation": 2,
  "rain": 1.0,
  "scanlines": 1.0,
  "inverted": false,
  "accent": true,
  "crosshair": false,
  "motion": true
}/*EDITMODE-END*/;

function App() {
  const [state, setState] = useState(() => {
    try {
      const saved = localStorage.getItem('01forge_tweaks');
      if (saved) return { ...TWEAK_DEFAULTS, ...JSON.parse(saved), variation: 2 };
    } catch (e) {}
    return TWEAK_DEFAULTS;
  });
  const [panelOpen, setPanelOpen] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const route = useRoute();

  const set = (patch) => {
    setState(s => {
      const next = { ...s, ...patch };
      try { localStorage.setItem('01forge_tweaks', JSON.stringify(next)); } catch (e) {}
      try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch (e) {}
      return next;
    });
  };

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

  useEffect(() => {
    document.body.classList.toggle('inverted', state.inverted);
  }, [state.inverted]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === 'Escape' && window.location.hash) { window.location.hash = ''; return; }
      if (e.key === 'i') set({ inverted: !state.inverted });
      if (e.key === 'm') set({ motion: !state.motion });
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [state, route]);

  const Variation = V02_Terminal;

  return (
    <div className="app-root" data-variation={state.variation}>
      <div className="rain-layer" style={{ opacity: state.rain > 0 ? 0.55 : 0 }}>
        <DigitalRain intensity={state.rain} accent={state.accent} paused={!state.motion} inverted={state.inverted} />
      </div>

      <ScanlineOverlay intensity={state.scanlines} />
      {state.crosshair && <Crosshair />}

      <div className="variation-stage" key={route}>
        {route === 'contact' && <PageContact />}
        {route === 'home' && <Variation />}
      </div>

      <RetellCallOverlay />

      {/* Tweaks panel only shown when toolbar Tweaks toggle is on */}
      {panelOpen && (
        <TweaksPanel
          state={state}
          set={set}
          visible={panelOpen}
          onClose={() => setPanelOpen(false)}
        />
      )}
    </div>
  );
}

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