// ROAMR — Root + tab routing + tweaks integration.
// Mutates window.TOKENS on every render via applyTokens so all child screens
// pick up fresh palette, density, cardStyle, mapStyle and audience values.

const { TOKENS: A_T } = window;

function TabBar({ active, onChange }) {
  const T = window.TOKENS;
  const tabs = [
    { k: 'explore', label: 'Explore', icon: (
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
        <circle cx="9" cy="9" r="5.5"/><path d="M12.8 12.8 L17 17"/>
      </svg>
    ) },
    { k: 'trips', label: 'Trips', icon: (
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
        <path d="M3 16 L17 16 M5 16 L5 8 L10 4 L15 8 L15 16 M9 16 L9 11 L11 11 L11 16"/>
      </svg>
    ) },
    { k: 'map', label: 'Map', icon: (
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
        <path d="M3 5 L8 3 L13 5 L17 3 L17 16 L13 18 L8 16 L3 18 Z M8 3 L8 16 M13 5 L13 18"/>
      </svg>
    ) },
    { k: 'saved', label: 'Saved', icon: (
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
        <path d="M10 17 C 2 12 2.4 5 6 4 C 8 3.5 9.5 5 10 6 C 10.5 5 12 3.5 14 4 C 17.6 5 18 12 10 17 Z"/>
      </svg>
    ) },
    { k: 'profile', label: 'You', icon: (
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
        <circle cx="10" cy="7" r="3"/><path d="M4 17 Q 10 11 16 17"/>
      </svg>
    ) },
  ];
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      background: T.modeName === 'light' ? 'rgba(255,255,255,0.92)' : 'rgba(7,9,10,0.95)',
      backdropFilter: 'blur(16px)',
      borderTop: `1px solid ${T.border}`,
      paddingBottom: 24, paddingTop: 10,
      display: 'flex', justifyContent: 'space-around',
      zIndex: 10,
    }}>
      {tabs.map(t => {
        const is = active === t.k;
        return (
          <button key={t.k} onClick={() => onChange(t.k)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            color: is ? T.signal : T.textLo, padding: '4px 12px',
          }}>
            {t.icon}
            <span style={{ fontFamily: T.fontB, fontSize: 10, letterSpacing: 0.3, fontWeight: is ? 600 : 500 }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function AppWithBridge({ tweaks }) {
  const [tab, setTab] = React.useState('explore');
  // Show splash on first mount per session — survives tweak-induced remounts.
  const [stack, setStack] = React.useState(() => window.__roamrSplashSeen ? [] : ['splash']);
  const [openRoute, setOpenRoute] = React.useState(null);
  const [openTrip, setOpenTrip] = React.useState(null);
  const [openPlace, setOpenPlace] = React.useState(null);
  const [openStay, setOpenStay] = React.useState(null);

  React.useEffect(() => {
    window.__roamrJump = (k) => {
      if (['explore', 'trips', 'map', 'saved', 'profile'].includes(k)) {
        setTab(k); setStack([]);
      } else if (k === 'detail')   { setOpenRoute(window.ROUTES[0]); setStack(['detail']); }
      else if (k === 'nav')        { setOpenRoute(window.ROUTES[0]); setStack(['nav']); }
      else if (k === 'trip')       { setOpenTrip(window.TRIPS[0]); setStack(['trip']); }
      else if (k === 'place')      { setOpenPlace(window.PLACES[0]); setStack(['place']); }
      else if (k === 'places')     { setStack(['places']); }
      else if (k === 'stays')      { setStack(['stays']); }
      else if (k === 'staydetail') { setOpenStay(window.STAYS[0]); setStack(['staydetail']); }
      else if (k === 'splash')     { window.__roamrSplashSeen = false; setStack(['splash']); }
      else                          { setStack([k]); }
    };
    return () => { window.__roamrJump = null; };
  }, []);

  const push = (s) => setStack(prev => [...prev, s]);
  const pop = () => setStack(prev => prev.slice(0, -1));
  const top = stack[stack.length - 1];

  const handleNavigate = (where) => {
    if (['explore', 'trips', 'map', 'saved', 'profile'].includes(where)) {
      setTab(where); setStack([]);
    } else if (where === 'places') { push('places'); }
    else if (where === 'stays')    { push('stays'); }
    else { push(where); }
  };
  const handleOpenRoute = (r) => { setOpenRoute(r); push('detail'); };
  const handleStartNav  = (r) => { setOpenRoute(r); push('nav'); };
  const handleOpenTrip  = (t) => { setOpenTrip(t); push('trip'); };
  const handleOpenPlace = (p) => { setOpenPlace(p); push('place'); };
  const handleOpenStay  = (s) => { setOpenStay(s); push('staydetail'); };
  const handleSplashDone = () => { window.__roamrSplashSeen = true; pop(); };

  // ── Render top of stack ──
  let current;
  if (top === 'splash')      current = <window.SplashScreen onDone={handleSplashDone} logoKey={tweaks.logo} />;
  else if (top === 'detail') current = <window.RouteDetailScreen route={openRoute} onBack={pop} onStartNav={handleStartNav} />;
  else if (top === 'nav')    current = <window.NavScreen route={openRoute} onExit={pop} />;
  else if (top === 'ai')     current = <window.AiBuilderScreen onBack={pop} onOpenRoute={handleOpenRoute} />;
  else if (top === 'gpx')    current = <window.GpxCheckScreen onBack={pop} />;
  else if (top === 'upgrade')current = <window.UpgradeScreen onBack={pop} />;
  else if (top === 'trip')   current = <window.TripScreen trip={openTrip} onBack={pop} onOpenRoute={handleOpenRoute} onOpenPlace={handleOpenPlace} onOpenStays={() => push('stays')} />;
  else if (top === 'place')  current = <window.PlaceScreen place={openPlace} onBack={pop} onAddToTrip={() => handleOpenTrip(window.TRIPS[0])} />;
  else if (top === 'stays')  current = <window.StaysSearchScreen onBack={pop} onOpenStay={handleOpenStay} />;
  else if (top === 'staydetail') current = <window.StayDetailScreen stay={openStay} onBack={pop} />;
  else if (top === 'places') current = (
    <div>
      <BackHeader onBack={pop} title="Places" />
      <window.PlacesHubScreen onOpenPlace={handleOpenPlace} />
    </div>
  );
  else if (top === 'onb')    current = <window.OnboardingScreen onDone={pop} logoKey={tweaks.logo} />;
  else {
    if (tab === 'explore') current = <window.ExploreTravelScreen
      onOpenRoute={handleOpenRoute} onOpenPlace={handleOpenPlace}
      onOpenTrip={handleOpenTrip} onOpenStay={handleOpenStay}
      onNavigate={handleNavigate} />;
    else if (tab === 'trips')   current = <window.TripsHubScreen onOpenTrip={handleOpenTrip} />;
    else if (tab === 'map')     current = <window.MapScreen onOpenRoute={handleOpenRoute} />;
    else if (tab === 'saved')   current = <window.SavedScreen onOpenRoute={handleOpenRoute} />;
    else if (tab === 'profile') current = <window.ProfileScreen onNavigate={handleNavigate} />;
  }

  const isOnb = top === 'onb';
  const isSplash = top === 'splash';
  const showTabBar = stack.length === 0;
  const showStatusBar = top !== 'nav' && !isOnb && !isSplash;

  return (
    <div style={{ width: '100%', height: '100%', background: window.TOKENS.bg, position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {showStatusBar && (
        <div style={{ flexShrink: 0 }}>
          <window.IOSStatusBar dark={window.TOKENS.modeName !== 'light'} />
        </div>
      )}
      <div style={{ flex: 1, overflow: 'auto', position: 'relative' }}>{current}</div>
      {showTabBar && <TabBar active={tab} onChange={(k) => { setTab(k); setStack([]); }} />}
    </div>
  );
}

function BackHeader({ onBack, title }) {
  const T = window.TOKENS;
  return (
    <div style={{
      padding: '12px 14px 0', display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <button onClick={onBack} style={{
        width: 36, height: 36, borderRadius: 18, padding: 0,
        background: T.card, border: `1px solid ${T.border}`,
        color: T.textHi, fontSize: 18, cursor: 'pointer',
      }}>←</button>
      <span style={{ fontFamily: T.fontD, fontSize: 16, fontWeight: 600, color: T.textHi }}>{title}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Root
// ─────────────────────────────────────────────────────────────────────────

function Root() {
  const [hoveredJump, setHoveredJump] = React.useState(null);
  const [t, setTweak] = window.useTweaks(window.TWEAK_DEFAULTS || {
    palette: 'earth', mode: 'light', logo: 'blaze',
    density: 'cozy', cardStyle: 'photo', mapStyle: 'soft', audience: 'multi',
  });

  // Mutate the live TOKENS object before any child renders — synchronous,
  // so child screens read the fresh values on this same render pass.
  window.applyTokens(t);
  const T = window.TOKENS;
  const Logo = (window.LOGOS[t.logo] || window.LOGOS.blaze).render;

  const scenarios = [
    { k: 'splash',  label: '00 · Splash' },
    { k: 'onb',     label: '00b · Onboarding' },
    { k: 'explore', label: '01 · Explore' },
    { k: 'trips',   label: '02 · Trips hub' },
    { k: 'trip',    label: '03 · Trip detail' },
    { k: 'places',  label: '04 · Places hub' },
    { k: 'place',   label: '05 · Place detail' },
    { k: 'stays',   label: '06 · Stays (Campfind)' },
    { k: 'staydetail', label: '07 · Stay detail' },
    { k: 'map',     label: '08 · Map' },
    { k: 'detail',  label: '09 · Route detail' },
    { k: 'ai',      label: '10 · AI builder' },
    { k: 'gpx',     label: '11 · GPX check' },
    { k: 'nav',     label: '12 · Navigation' },
    { k: 'upgrade', label: '13 · Upgrade' },
    { k: 'saved',   label: '14 · Saved' },
    { k: 'profile', label: '15 · Profile' },
  ];

  // Bump key when palette/mode/density/etc change so child trees fully reset.
  const themeKey = `${t.palette}-${t.mode}-${t.density}-${t.cardStyle}-${t.mapStyle}-${t.audience}-${t.logo}`;

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--page-bg)',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: '32px 24px 64px', gap: 32,
      fontFamily: T.fontB, color: T.textHi,
      transition: 'background 0.3s ease',
    }}>
      <div style={{ width: '100%', maxWidth: 1200, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', paddingBottom: 16, borderBottom: `1px solid ${T.border}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Logo T={T} height={44} />
          <div>
            <div style={{ fontFamily: T.fontM, fontSize: 11, color: T.signal, letterSpacing: 2, marginBottom: 4 }}>● ROAMR · TRAVEL-LED PROTOTYPE</div>
            <div style={{ fontFamily: T.fontD, fontSize: 28, fontWeight: 600, letterSpacing: -0.4 }}>Plan · Discover · Save · Roam</div>
          </div>
        </div>
        <nav style={{ display: 'flex', gap: 6 }}>
          {['index', 'brand', 'app', 'admin', 'landing'].map(n => (
            <a key={n} href={`${n}.html`} style={{
              fontFamily: T.fontM, fontSize: 10, padding: '6px 10px', textDecoration: 'none',
              color: n === 'app' ? '#fff' : T.textLo,
              background: n === 'app' ? T.signal : 'transparent',
              border: `1px solid ${n === 'app' ? T.signal : T.border}`,
              letterSpacing: 1.2,
            }}>{n.toUpperCase()}</a>
          ))}
        </nav>
      </div>

      <p style={{ maxWidth: 720, textAlign: 'center', color: T.textLo, fontSize: 14, lineHeight: 1.6, margin: 0 }}>
        A travel-first iteration of the Roamr app. Open <strong style={{ color: T.signal }}>Tweaks</strong> to swap palette, mode, density, card style, map style, logo direction or audience focus. Tap any photo card to drill in.
      </p>

      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <window.IOSDevice width={402} height={874} dark={t.mode !== 'light'}>
          <AppWithBridge key={themeKey} tweaks={t} />
        </window.IOSDevice>
      </div>

      <div style={{ width: '100%', maxWidth: 920 }}>
        <div style={{ fontFamily: T.fontM, fontSize: 10, color: T.textMute, letterSpacing: 1.5, marginBottom: 12 }}>§ JUMP TO SCREEN</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 6 }}>
          {scenarios.map(s => (
            <button
              key={s.k}
              onMouseEnter={() => setHoveredJump(s.k)}
              onMouseLeave={() => setHoveredJump(null)}
              onClick={() => window.__roamrJump && window.__roamrJump(s.k)}
              style={{
                background: T.card, color: T.text,
                border: `1px solid ${hoveredJump === s.k ? T.signal : T.border}`,
                padding: '10px 12px', textAlign: 'left',
                fontFamily: T.fontM, fontSize: 11, letterSpacing: 0.5, cursor: 'pointer',
                transition: 'border-color 0.15s',
                borderRadius: 6,
              }}>{s.label}</button>
          ))}
        </div>
      </div>

      <div style={{ width: '100%', maxWidth: 920, marginTop: 8, padding: 18, background: T.card, border: `1px solid ${T.border}`, fontFamily: T.fontB, fontSize: 12, color: T.textLo, lineHeight: 1.6, borderRadius: 10 }}>
        <div style={{ fontFamily: T.fontM, fontSize: 10, color: T.signal, letterSpacing: 1.5, marginBottom: 8 }}>§ NOTES FOR REVIEW</div>
        Photo placeholders (▢ captions) mark slots for real imagery. The <strong style={{ color: T.signal }}>Tweaks</strong> panel exposes 3 palettes (Earth / Signal / Coastal), dark/light, density, card style (photo / map / minimal), map style (soft / contour / satellite) and audience lead (multi / green-lane). Try <strong style={{ color: T.signal }}>Earth + Light + Photo + Soft</strong> for the premium travel feel.
      </div>

      <window.RoamrTweaksPanel t={t} setTweak={setTweak} T={T} />
    </div>
  );
}

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