// ─── Gunzaru app shell — multi-frame canvas with sync navigation ───

const {
  IOSDevice,
  TweaksPanel, useTweaks, TweakSection, TweakRadio,
  OnboardingScreen, DiscoveryScreen, EventDetailScreen,
  ChatScreen, CreateEventScreen, CheckinScreen,
  PaymentScreen, PackagesScreen, ProfileScreen, MyEventsScreen,
} = window;

// Color theme presets (primary)
const PRIMARY_PRESETS = {
  ocean: { l: 'oklch(38% 0.085 215)', d: 'oklch(72% 0.12 215)' },
  reef:  { l: 'oklch(45% 0.10 175)',  d: 'oklch(72% 0.13 175)' },
  ink:   { l: 'oklch(28% 0.04 250)',  d: 'oklch(80% 0.04 250)' },
  amber: { l: 'oklch(55% 0.13 65)',   d: 'oklch(78% 0.13 65)' },
};
const ACCENT_PRESETS = {
  coral:  { l: 'oklch(72% 0.16 38)',  d: 'oklch(78% 0.15 42)' },
  citrus: { l: 'oklch(75% 0.16 90)',  d: 'oklch(80% 0.15 90)' },
  reef:   { l: 'oklch(65% 0.14 175)', d: 'oklch(75% 0.13 175)' },
};
const RADIUS_PRESETS = {
  sharp: { sm: 6, md: 10, lg: 16, card: 14 },
  soft:  { sm: 12, md: 18, lg: 26, card: 22 },
  pill:  { sm: 18, md: 26, lg: 34, card: 30 },
};

function applyTheme(t) {
  const root = document.documentElement;
  root.dataset.theme = t.theme;
  const p = PRIMARY_PRESETS[t.primary] || PRIMARY_PRESETS.ocean;
  const a = ACCENT_PRESETS[t.accent] || ACCENT_PRESETS.coral;
  const r = RADIUS_PRESETS[t.radius] || RADIUS_PRESETS.soft;
  const isDark = t.theme === 'dark';
  root.style.setProperty('--primary', isDark ? p.d : p.l);
  root.style.setProperty('--accent', isDark ? a.d : a.l);
  root.style.setProperty('--radius-sm', r.sm + 'px');
  root.style.setProperty('--radius', r.md + 'px');
  root.style.setProperty('--radius-lg', r.lg + 'px');
  root.style.setProperty('--radius-card', r.card + 'px');
}

// All screens registered with a label
const SCREEN_LIST = [
  { id: 'onboarding', label: '01 · Welcome' },
  { id: 'discovery', label: '02 · Discover' },
  { id: 'detail', label: '03 · Event Detail' },
  { id: 'chat', label: '04 · Event Chat' },
  { id: 'create', label: '05 · Create Event' },
  { id: 'checkin', label: '06 · Check-In' },
  { id: 'packages', label: '07 · Packages' },
  { id: 'payment', label: '08 · Card Scan & Pay' },
  { id: 'my', label: '09 · My Events' },
  { id: 'profile', label: '10 · Profile' },
];

function App() {
  const [t, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  const [active, setActive] = React.useState('discovery');
  const [eventId, setEventId] = React.useState(EVENTS[0].id);
  const [pkg, setPkg] = React.useState('gold');

  React.useEffect(() => { applyTheme(t); }, [t]);

  // Update screen label in chrome
  React.useEffect(() => {
    const n = document.getElementById('screen-name');
    if (n) n.textContent = SCREEN_LIST.find(s => s.id === active)?.label || '—';
  }, [active]);

  const openEvent = (id) => { setEventId(id); setActive('detail'); };
  const goto = (id) => setActive(id);

  const renderScreen = () => {
    switch (active) {
      case 'onboarding': return <OnboardingScreen onDone={() => goto('discovery')} />;
      case 'discovery':  return <DiscoveryScreen onOpenEvent={openEvent} onTab={goto} onCreate={() => goto('create')} />;
      case 'detail':     return <EventDetailScreen eventId={eventId} onBack={() => goto('discovery')} onChat={() => goto('chat')} onCheckin={() => goto('checkin')} />;
      case 'chat':       return <ChatScreen eventId={eventId} onBack={() => goto('detail')} />;
      case 'create':     return <CreateEventScreen onBack={() => goto('discovery')} onPublish={() => goto('discovery')} />;
      case 'checkin':    return <CheckinScreen eventId={eventId} onBack={() => goto('detail')} />;
      case 'packages':   return <PackagesScreen onBack={() => goto('profile')} onSelect={(id) => { setPkg(id); goto('payment'); }} />;
      case 'payment':    return <PaymentScreen pkg={pkg} onBack={() => goto('packages')} onDone={() => goto('discovery')} />;
      case 'my':         return <MyEventsScreen onTab={goto} onCreate={() => goto('create')} onOpenEvent={openEvent} />;
      case 'profile':    return <ProfileScreen onTab={goto} onCreate={() => goto('create')} onPackages={() => goto('packages')} />;
      default: return null;
    }
  };

  const dark = t.theme === 'dark';

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
      {/* Sidebar — screen list */}
      <div data-screen-label="screens-nav" style={{
        width: 220, padding: '20px 12px',
        background: 'rgba(255,255,255,0.55)', backdropFilter: 'blur(12px)',
        borderRadius: 22, border: '1px solid rgba(0,0,0,0.06)',
        maxHeight: 740, overflow: 'auto',
        boxShadow: '0 10px 40px rgba(15,30,50,0.08)',
      }}>
        <div style={{
          fontFamily: 'Geist Mono', fontSize: 10, color: '#6c7787',
          letterSpacing: '0.14em', textTransform: 'uppercase',
          padding: '4px 10px 10px',
        }}>Screens</div>
        {SCREEN_LIST.map(s => (
          <button key={s.id} onClick={() => setActive(s.id)} style={{
            display: 'block', width: '100%', textAlign: 'left',
            padding: '9px 12px', borderRadius: 11, marginBottom: 2,
            border: 'none', cursor: 'pointer',
            background: active === s.id ? '#2a4a6a' : 'transparent',
            color: active === s.id ? '#fff' : '#2a3a4a',
            fontFamily: 'Geist', fontSize: 13, fontWeight: active === s.id ? 600 : 500,
            letterSpacing: '-0.01em',
            transition: 'all .15s',
          }}>{s.label}</button>
        ))}
        <div style={{ height: 1, background: 'rgba(0,0,0,0.08)', margin: '10px 6px' }}/>
        <div style={{
          fontFamily: 'Geist Mono', fontSize: 10, color: '#6c7787',
          letterSpacing: '0.14em', textTransform: 'uppercase',
          padding: '4px 10px 6px',
        }}>Quick flows</div>
        <FlowBtn label="Join an event" steps={['discovery','detail','chat']} onPlay={setActive} />
        <FlowBtn label="Subscribe to Gold" steps={['profile','packages','payment']} onPlay={setActive} />
        <FlowBtn label="Host an event" steps={['create']} onPlay={setActive} />
      </div>

      {/* Phone frame */}
      <div data-screen-label={SCREEN_LIST.find(s => s.id === active)?.label || active} style={{ position: 'relative' }}>
        <IOSDevice dark={dark} width={390} height={840}>
          {renderScreen()}
        </IOSDevice>
      </div>

      {/* Right rail — context info for current screen */}
      <ContextRail screenId={active} onJump={setActive} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio label="Mode" value={t.theme} options={[
            { value: 'light', label: 'Light' },
            { value: 'dark', label: 'Dark' },
          ]} onChange={v => setTweak('theme', v)} />
        </TweakSection>

        <TweakSection label="Brand">
          <TweakRadio label="Primary" value={t.primary} options={[
            { value: 'ocean', label: 'Ocean' },
            { value: 'reef', label: 'Reef' },
            { value: 'ink', label: 'Ink' },
            { value: 'amber', label: 'Amber' },
          ]} onChange={v => setTweak('primary', v)} />
          <TweakRadio label="Accent" value={t.accent} options={[
            { value: 'coral', label: 'Coral' },
            { value: 'citrus', label: 'Citrus' },
            { value: 'reef', label: 'Reef' },
          ]} onChange={v => setTweak('accent', v)} />
        </TweakSection>

        <TweakSection label="Shape">
          <TweakRadio label="Corners" value={t.radius} options={[
            { value: 'sharp', label: 'Sharp' },
            { value: 'soft', label: 'Soft' },
            { value: 'pill', label: 'Pill' },
          ]} onChange={v => setTweak('radius', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function FlowBtn({ label, steps, onPlay }) {
  const [playing, setPlaying] = React.useState(false);
  const play = async () => {
    if (playing) return;
    setPlaying(true);
    for (const s of steps) {
      onPlay(s);
      await new Promise(r => setTimeout(r, 900));
    }
    setPlaying(false);
  };
  return (
    <button onClick={play} style={{
      display: 'flex', alignItems: 'center', gap: 8,
      width: '100%', padding: '8px 12px', borderRadius: 11,
      border: 'none', cursor: 'pointer', textAlign: 'left',
      background: playing ? 'rgba(220,130,80,0.15)' : 'transparent',
      color: '#2a3a4a',
      fontFamily: 'Geist', fontSize: 12, fontWeight: 500,
    }}>
      <span style={{
        display: 'grid', placeItems: 'center', width: 18, height: 18,
        borderRadius: '50%', background: playing ? '#dc8250' : '#2a4a6a', color: '#fff', fontSize: 10,
      }}>▶</span>
      {label}
    </button>
  );
}

// Context rail — describes the current screen
function ContextRail({ screenId, onJump }) {
  const ctx = {
    onboarding: { title: 'Welcome', desc: 'First-time intro framing the value: stop guessing who shows up.', notes: ['Dhivehi script (ގުންޒަރު) reinforces local identity', 'Single primary CTA + secondary sign-in'] },
    discovery: { title: 'Discover', desc: 'Local feed of nearby events with personalisation hooks.', notes: ['Stat strip surfaces participation at a glance', 'Filter chips · category tiles · featured card'] },
    detail: { title: 'Event Detail', desc: 'All info + 3-state RSVP. Privacy toggle is a key trust feature.', notes: ['Going / Maybe / Can\'t go is the core mechanic', 'Hide-my-name still counts toward total'] },
    chat: { title: 'Event Chat', desc: 'Gold/Premium only · contextual to the event.', notes: ['Organiser badge for clarity', 'Pinned event banner stays at top'] },
    create: { title: 'Create Event', desc: '3-step wizard guarding Gold/Premium feature.', notes: ['Step 1: what & where', 'Step 2: when & who', 'Step 3: review & publish'] },
    checkin: { title: 'Check-In', desc: 'QR for organiser-scan or self check-in.', notes: ['Compares expected vs actual attendees', 'Builds reliability score over time'] },
    packages: { title: 'Packages', desc: 'Tiered pricing in MVR · Gold is most popular.', notes: ['Free → Basic → Gold → Premium', 'Locked features greyed + struck-through'] },
    payment: { title: 'Card Scan & Pay', desc: 'Camera-based card scan, only CVV is user-entered.', notes: ['Card number + expiry auto-filled', 'CVV never stored · BML Gateway'] },
    my: { title: 'My Events', desc: 'Going / Hosting / Past — context per tab.', notes: ['Hosting tab shows manage actions', 'Past builds attendance history'] },
    profile: { title: 'Profile', desc: 'Identity, plan, settings, achievements.', notes: ['Show-up rate is the gunzaru-specific metric', 'Plan card links to packages'] },
  }[screenId] || { title: '', desc: '', notes: [] };

  return (
    <div style={{
      width: 280, padding: 22,
      background: 'rgba(255,255,255,0.55)', backdropFilter: 'blur(12px)',
      borderRadius: 22, border: '1px solid rgba(0,0,0,0.06)',
      boxShadow: '0 10px 40px rgba(15,30,50,0.08)',
      maxHeight: 740, overflow: 'auto',
    }}>
      <div style={{ fontFamily: 'Geist Mono', fontSize: 10, color: '#6c7787', letterSpacing: '0.14em', textTransform: 'uppercase' }}>
        Currently viewing
      </div>
      <h3 style={{
        margin: '6px 0 8px',
        fontFamily: 'Bricolage Grotesque', fontSize: 22, fontWeight: 600,
        letterSpacing: '-0.025em', color: '#1a2a3a',
      }}>{ctx.title}</h3>
      <p style={{ margin: 0, fontFamily: 'Geist', fontSize: 13, color: '#445566', lineHeight: 1.5 }}>{ctx.desc}</p>

      <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid rgba(0,0,0,0.07)' }}>
        <div style={{ fontFamily: 'Geist Mono', fontSize: 9, color: '#6c7787', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 8 }}>Design notes</div>
        <ul style={{ margin: 0, paddingLeft: 18, fontFamily: 'Geist', fontSize: 12, color: '#445566', lineHeight: 1.55 }}>
          {ctx.notes.map((n, i) => <li key={i} style={{ marginBottom: 4 }}>{n}</li>)}
        </ul>
      </div>

      <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid rgba(0,0,0,0.07)' }}>
        <div style={{ fontFamily: 'Geist Mono', fontSize: 9, color: '#6c7787', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 8 }}>Try it</div>
        <div style={{ fontFamily: 'Geist', fontSize: 12, color: '#445566', lineHeight: 1.5 }}>
          The phone is fully interactive. Tap the bottom nav, RSVP, scroll the chat, send a message, run through the create-event wizard, scan the card.
        </div>
      </div>
    </div>
  );
}

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