// Top-level app + router. Hash-based routes so refresh keeps state.
const initialCtx = {
  eventCode: null,
  first: '', last: '', email: '', birthday: '', phone: '',
  careers: [],
  guardianName: '', guardianEmail: '', guardianPhone: '',
  typedSig: '', drawnSig: '', guardianTypedSig: '',
  confirmNum: null, signedAt: null,
};

function App() {
  const [route, setRoute] = React.useState(() => {
    const h = window.location.hash.slice(1);
    return h ? parseRoute(h) : { name: 'landing' };
  });
  const [ctx, setCtxState] = React.useState(initialCtx);

  React.useEffect(() => {
    const onHash = () => setRoute(parseRoute(window.location.hash.slice(1)));
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const setCtx = (patch) => setCtxState(c => ({ ...c, ...(typeof patch === 'function' ? patch(c) : patch) }));

  const go = (name, params = {}) => {
    if (params.eventCode) setCtx({ eventCode: params.eventCode });
    const newRoute = { name, step: params.step ?? (name === 'signup' ? (route.name === 'signup' ? route.step : 0) : 0) };
    setRoute(newRoute);
    window.location.hash = serializeRoute(newRoute);
    // Scroll the screen container to top on route change
    setTimeout(() => {
      const el = document.querySelector('[data-screen]');
      if (el) el.scrollTop = 0;
    }, 0);
  };

  return (
    <div data-screen-label={'Screen · ' + route.name.toUpperCase()} data-screen style={{ height: '100%', width: '100%' }}>
      {route.name === 'landing' && <Landing go={go} />}
      {route.name === 'signup' && <Signup ctx={ctx} setCtx={setCtx} go={go} step={route.step || 0} />}
      {route.name === 'admin' && <AdminGate go={go}><Admin go={go} /></AdminGate>}
    </div>
  );
}

const KNOWN_ROUTES = ['landing', 'signup', 'admin'];
function parseRoute(h) {
  const [name, step] = h.split('/');
  return { name: KNOWN_ROUTES.includes(name) ? name : 'landing', step: step ? +step : 0 };
}
function serializeRoute(r) {
  return r.name + (r.name === 'signup' ? `/${r.step || 0}` : '');
}

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