/* Pitch-only router. Handles the 7 public surfaces.
 * Product CTAs (onboarding, dashboard) open a "Request demo" modal instead.
 */
const { useState: useStateAPP, useEffect: useEffectAPP } = React;

function readSurfaceFromURL() {
  try {
    const q = new URLSearchParams(window.location.search);
    const s = q.get('surface');
    const allowed = ['landing','features','cafes','restaurants','bars','bakeries','groups'];
    return allowed.includes(s) ? s : 'landing';
  } catch (e) { return 'landing'; }
}

function readThemeFromURL() {
  try {
    const q = new URLSearchParams(window.location.search);
    const t = q.get('theme');
    if (t === 'light' || t === 'dark') return t;
  } catch (e) {}
  return (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
}

function ContactModal({ onClose, context }) {
  const [sent, setSent] = useStateAPP(false);
  useEffectAPP(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <React.Fragment>
      <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,.55)', zIndex:9996 }}/>
      <div role="dialog" aria-modal="true" style={{
        position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)', zIndex:9997,
        background:'var(--bg)', color:'var(--ink)', border:'1px solid var(--line)', borderRadius:18,
        boxShadow:'var(--shadow-lg)', width:'calc(100vw - 40px)', maxWidth: 480, padding:0,
      }}>
        <div style={{ padding:'28px 28px 8px' }}>
          <h2 className="serif" style={{ margin:0, fontSize:28, fontWeight:400, letterSpacing:'-0.01em' }}>
            {sent ? 'Thanks — we\'ll be in touch.' : 'Request a demo'}
          </h2>
          <p style={{ margin:'8px 0 0', color:'var(--muted)', fontSize:14, lineHeight:1.5 }}>
            {sent ? 'We\'ll follow up within one business day.' : 'Leave your email and a team member will reach out to schedule a walkthrough.'}
          </p>
        </div>
        {!sent && (
          <form onSubmit={(e) => { e.preventDefault(); setSent(true); }} style={{ padding:'16px 28px 24px', display:'grid', gap:12 }}>
            <input required type="text" placeholder="Your name" style={{ padding:'12px 14px', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:10, fontSize:14, color:'var(--ink)' }}/>
            <input required type="email" placeholder="Email" style={{ padding:'12px 14px', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:10, fontSize:14, color:'var(--ink)' }}/>
            <input type="text" placeholder="Venue name (optional)" style={{ padding:'12px 14px', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:10, fontSize:14, color:'var(--ink)' }}/>
            {context && <div style={{ fontSize:12, color:'var(--muted)' }}>Context: {context}</div>}
            <div style={{ display:'flex', gap:10, marginTop:4 }}>
              <button type="submit" className="btn btn-primary" style={{ padding:'12px 20px', fontSize:14.5, fontWeight:600, flex:1, justifyContent:'center' }}>Send request</button>
              <button type="button" onClick={onClose} className="btn btn-ghost" style={{ padding:'12px 20px', fontSize:14.5 }}>Cancel</button>
            </div>
          </form>
        )}
        {sent && (
          <div style={{ padding:'16px 28px 24px' }}>
            <button onClick={onClose} className="btn btn-primary" style={{ padding:'12px 20px', fontSize:14.5, fontWeight:600, width:'100%', justifyContent:'center' }}>Close</button>
          </div>
        )}
      </div>
    </React.Fragment>
  );
}

function PitchApp() {
  const [surface, setSurface] = useStateAPP(readSurfaceFromURL());
  const [theme, setTheme] = useStateAPP(readThemeFromURL());
  const [contact, setContact] = useStateAPP(null);

  useEffectAPP(() => {
    const root = document.documentElement;
    if (theme === 'dark') root.classList.add('dark'); else root.classList.remove('dark');
  }, [theme]);

  useEffectAPP(() => {
    const onPop = () => setSurface(readSurfaceFromURL());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const go = (target, opts) => {
    const pitchSurfaces = ['landing','features','cafes','restaurants','bars','bakeries','groups'];
    if (pitchSurfaces.includes(target)) {
      setSurface(target);
      const url = new URL(window.location.href);
      url.searchParams.set('surface', target);
      window.history.pushState({}, '', url.toString());
      const scroller = document.querySelector('[data-screen-label]');
      if (scroller) scroller.scrollTop = 0;
      return;
    }
    // product surfaces → contact modal
    const labelMap = {
      onboarding: 'Start free trial',
      dashboard: 'Sign in',
      register: 'Register demo',
      menu: 'Menu studio demo',
      reservations: 'Reservations demo',
      orders: 'Kitchen display demo',
      analytics: 'Analytics demo',
      team: 'Team demo',
      live: 'Live site demo',
      websitebuilder: 'Website builder demo',
      inventory: 'Inventory demo',
      payments: 'Payments demo',
      settings: 'Settings demo',
    };
    setContact(labelMap[target] || target);
  };

  const registry = {
    landing: window.Landing,
    features: window.Features,
    cafes: window.SolutionCafes,
    restaurants: window.SolutionRestaurants,
    bars: window.SolutionBars,
    bakeries: window.SolutionBakeries,
    groups: window.SolutionGroups,
  };

  const Current = registry[surface] || registry.landing;
  if (!Current) {
    return (
      <div style={{ height:'100%', display:'grid', placeItems:'center', background:'var(--bg)', color:'var(--ink)' }}>
        <div style={{ textAlign:'center' }}>
          <div className="serif" style={{ fontSize:28, letterSpacing:'-0.03em' }}>Loading…</div>
          <div style={{ marginTop:8, fontSize:13, color:'var(--muted)' }}>Preparing Vividish</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height:'100%' }}>
      <Current go={go} theme={theme} setTheme={setTheme}/>
      {contact && <ContactModal onClose={() => setContact(null)} context={contact}/>}
    </div>
  );
}

function boot() {
  const root = document.getElementById('root');
  if (!root) return;
  if (!window.Landing || !window.Features || !window.SolutionCafes) {
    setTimeout(boot, 80);
    return;
  }
  ReactDOM.createRoot(root).render(<PitchApp/>);
}
boot();
