/* ============================================================
   Main App — top-level routing + screen switcher
   ============================================================ */

const { useState: useApp, useEffect: useAppEffect } = React;

const SCREENS = [
  { key: 'landing',   label: '01 · Marketing landing' },
  { key: 'tract',     label: '02 · Tract detail (L1)' },
  { key: 'auth',      label: '03 · Sign in / Sign up' },
  { key: 'welcome',   label: '04 · Welcome + onboarding' },
  { key: 'dashboard', label: '05 · Dashboard (this week)' },
  { key: 'tracts',    label: '06 · Tract overview (auth)' },
  { key: 'drill',     label: '07 · Drill player (L1.4F)' },
  { key: 'map',       label: '08 · Curriculum map' },
  { key: 'moments',   label: '09 · Coach moments' },
  { key: 'ask',       label: '10 · Ask Coach Mike' },
  { key: 'park',      label: '11 · Park mode' }
];

/* ---------- Hash routing ----------
   Each screen gets a deep-linkable URL (e.g. #/dashboard). Hash routing is
   used (rather than clean paths) so the prototype needs no server-side SPA
   fallback config and never 404s on refresh on any static host. */
const SCREEN_KEYS = SCREENS.map(s => s.key);
const DEFAULT_SCREEN = 'landing';

const screenFromHash = () => {
  const k = window.location.hash.replace(/^#\/?/, '');
  return SCREEN_KEYS.includes(k) ? k : DEFAULT_SCREEN;
};

const PurchaseModal = ({ onClose, onConfirm }) => (
  <div className="modal-overlay" onClick={onClose}>
    <div className="modal" onClick={e => e.stopPropagation()}>
      <span className="eyebrow">Checkout</span>
      <h3 style={{ marginTop: 8 }}>One tract. Yours forever.</h3>
      <p style={{ color: 'var(--pm-graphite)', fontSize: 14, lineHeight: 1.55, margin: '8px 0 16px' }}>
        Confirm your purchase. You'll be sent a magic link to set up your rider.
      </p>
      <div className="line"><span>L1 · Learn to Pedal</span><span>$79.00</span></div>
      <div className="line"><span>Coach Q&A submissions</span><span>5 included</span></div>
      <div className="line"><span>Tax</span><span>$0.00</span></div>
      <div className="line total"><span>Total</span><span>$79.00</span></div>
      <div className="actions">
        <button className="btn btn-ghost sm" onClick={onClose} style={{ flex: 1 }}>Cancel</button>
        <button className="btn btn-primary" onClick={onConfirm} style={{ flex: 2 }}>
          Confirm purchase <Ico d={I.arrowRight} size={16}/>
        </button>
      </div>
      <p style={{ fontSize: 12, color: 'var(--pm-stone)', margin: '14px 0 0', textAlign: 'center' }}>
        30-day refund. If your rider isn't progressing, you didn't pay for it.
      </p>
    </div>
  </div>
);

const ScreenSwitcher = ({ value, onChange }) => (
  <div className="screen-switcher">
    <span>Prototype:</span>
    <select value={value} onChange={e => onChange(e.target.value)}>
      {SCREENS.map(s => (
        <option key={s.key} value={s.key}>{s.label}</option>
      ))}
    </select>
  </div>
);

function App() {
  const [screen, setScreen] = useApp(screenFromHash());
  const [modal, setModal] = useApp(false);

  // The URL hash is the source of truth. Sync state on back/forward or when
  // the URL is edited/shared, and normalize a missing hash to the default.
  useAppEffect(() => {
    if (!window.location.hash) window.location.replace('#/' + DEFAULT_SCREEN);
    const onHash = () => {
      setScreen(screenFromHash());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const go = (k) => {
    const next = '#/' + k;
    if (window.location.hash === next) {
      window.scrollTo({ top: 0, behavior: 'instant' });
    } else {
      window.location.hash = next; // triggers hashchange → updates screen
    }
  };

  let view;
  switch (screen) {
    case 'landing':
      view = <Landing onStart={() => go('tract')} onGo={go} />; break;
    case 'tract':
      view = <TractDetail onBuy={() => setModal(true)} onGo={go} />; break;
    case 'auth':
      view = <Auth onGo={go} onContinue={() => go('welcome')} />; break;
    case 'welcome':
      view = <Welcome onContinue={() => go('dashboard')} onGo={go} />; break;
    case 'dashboard':
      view = <Dashboard onGo={go} />; break;
    case 'tracts':
      view = <TractOverview onGo={go} />; break;
    case 'drill':
      view = <DrillPlayer onGo={go} />; break;
    case 'map':
      view = <CurriculumMap onGo={go} />; break;
    case 'moments':
      view = <CoachMoments onGo={go} />; break;
    case 'ask':
      view = <CoachQA onGo={go} />; break;
    case 'park':
      view = <ParkMode onGo={go} />; break;
    default:
      view = <Landing onStart={() => go('tract')} onGo={go} />;
  }

  return (
    <>
      {view}
      {modal && (
        <PurchaseModal
          onClose={() => setModal(false)}
          onConfirm={() => { setModal(false); go('welcome'); }}
        />
      )}
      <ScreenSwitcher value={screen} onChange={go} />
    </>
  );
}

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