// ============================================================================
// USA Trip Companion v2 — App shell with nav stack + Tab bar
// ============================================================================

const { useState: aS, useEffect: aE, useCallback: aC, useMemo: aM } = React;

function App() {
  const pq = usePhotoQuest();
  // Navigation stack — array of route objects
  const [stack, setStack] = aS([{ screen: 'home' }]);
  const [tabRoot, setTabRoot] = aS('home'); // which tab is selected
  const [lightbox, setLightbox] = aS(null);

  // Restore last tab from localStorage
  aE(() => {
    try {
      const saved = localStorage.getItem('v2:lastTab');
      if (saved && ['home', 'map', 'team', 'more'].includes(saved)) {
        setTabRoot(saved);
        setStack([{ screen: saved }]);
      }
    } catch {}
  }, []);

  // Heartbeat — keep v2:lastActive current while app is visible
  aE(() => {
    const tick = () => {
      if (!document.hidden) {
        try { localStorage.setItem('v2:lastActive', String(Date.now())); } catch {}
      }
    };
    tick();
    const id = setInterval(tick, 60_000);
    return () => clearInterval(id);
  }, []);

  // Return-to-home after 10 min idle (visibilitychange + pageshow)
  aE(() => {
    const IDLE_MS = 10 * 60 * 1000;
    const onResume = () => {
      if (document.hidden) return;
      try {
        const last = parseInt(localStorage.getItem('v2:lastActive') || '0', 10);
        if (Date.now() - last > IDLE_MS) {
          setStack([{ screen: 'home' }]);
          setTabRoot('home');
          localStorage.setItem('v2:lastTab', 'home');
        }
      } catch {}
    };
    document.addEventListener('visibilitychange', onResume);
    window.addEventListener('pageshow', onResume);
    return () => {
      document.removeEventListener('visibilitychange', onResume);
      window.removeEventListener('pageshow', onResume);
    };
  }, []);

  const nav = aM(() => ({
    push: (route) => setStack((s) => [...s, route]),
    back: () => setStack((s) => s.length > 1 ? s.slice(0, -1) : [{ screen: 'more' }]),
    reset: (route) => setStack([route]),
  }), []);

  const goTab = aC((tab) => {
    setTabRoot(tab);
    localStorage.setItem('v2:lastTab', tab);
    const rootRoute = {
      home: { screen: 'home' },
      map: { screen: 'map' },
      team: { screen: 'team' },
      more: { screen: 'more' },
    }[tab];
    setStack([rootRoute]);
  }, []);

  // Lightbox helper — exposed globally
  aE(() => {
    window.__lightbox = (images, i = 0) => setLightbox({ images, i });
  }, []);

  const current = stack[stack.length - 1];
  const openLightbox = aC((images, i = 0) => setLightbox({ images, i }), []);

  // Which tab is logically active based on current screen
  const activeTab = aM(() => {
    if (current.screen === 'home') return 'home';
    if (current.screen === 'map') return 'map';
    if (current.screen === 'team') return 'team';
    if (['checklist', 'flights', 'hotels', 'docs', 'challenges', 'more'].includes(current.screen)) return 'more';
    return tabRoot;
  }, [current.screen, tabRoot]);

  // Render the current screen
  let body;
  switch (current.screen) {
    case 'home':       body = <HomeScreen openLightbox={openLightbox} />; break;
    case 'map':        body = <MapScreen initialDay={current.initialDay} initialPointId={current.initialPointId} />; break;
    case 'place':      body = <PlaceScreen pointId={current.pointId} initialTab={current.tab || 'overview'} />; break;
    case 'weather':    body = <WeatherScreen />; break;
    case 'team':       body = <TeamScreen />; break;
    case 'challenges': body = <ChallengesScreen />; break;
    case 'checklist':  body = <ChecklistScreen />; break;
    case 'flights':    body = <FlightsScreen />; break;
    case 'hotels':     body = <HotelsScreen />; break;
    case 'docs':       body = <DocsScreen />; break;
    case 'tips':       body = <TipsScreen pointId={current.pointId} />; break;
    case 'slang':      body = <SlangScreen pointId={current.pointId} />; break;
    case 'more':       body = <MoreScreen />; break;
    default:           body = <HomeScreen openLightbox={openLightbox} />;
  }

  const showTabBar = ['home', 'map', 'team', 'more', 'checklist', 'flights', 'hotels', 'docs', 'challenges', 'weather'].includes(current.screen);

  return (
    <NavContext.Provider value={nav}>
      {/* Screen */}
      <div key={stack.length + ':' + current.screen} style={{ flex: 1, minHeight: 0, position: 'relative', display: 'flex', flexDirection: 'column' }}>
        {body}
      </div>

      {/* Tab bar */}
      {showTabBar && <NowNextBar />}
      {showTabBar && (
        <nav className="tab-bar">
          <button className={`tab ${activeTab === 'home' ? 'active' : ''}`} onClick={() => goTab('home')}>
            <Icon name="home" /><span>Today</span>
          </button>
          <button className={`tab ${activeTab === 'map' ? 'active' : ''}`} onClick={() => goTab('map')}>
            <Icon name="map" /><span>Map</span>
          </button>
          <button className={`tab`} style={{ position: 'relative' }} onClick={() => nav.push({ screen: 'challenges' })}>
            <Icon name="camera" /><span>Capture</span>
            {(() => { const s = pq.getDaySummary(pq.getTodayDayId()); return s && s.filled < 20 && s.filled > 0 ? <span className="tab-badge">{s.filled}/20</span> : null; })()}
          </button>
          <button className={`tab ${activeTab === 'team' ? 'active' : ''}`} onClick={() => goTab('team')}>
            <Icon name="team" /><span>Team</span>
          </button>
          <button className={`tab ${activeTab === 'more' ? 'active' : ''}`} onClick={() => goTab('more')}>
            <Icon name="more" /><span>More</span>
          </button>
        </nav>
      )}

      {/* Lightbox */}
      {lightbox && <Lightbox images={lightbox.images} startIndex={lightbox.i} onClose={() => setLightbox(null)} />}
    </NavContext.Provider>
  );
}

// ---------- MORE (hub for flights/hotels/docs/checklist/challenges) ----------
function MoreScreen() {
  const nav = useNav();
  const items = [
    { screen: 'checklist', icon: 'check', label: 'Packing', sub: 'Items to check off' },
    { screen: 'flights', icon: 'flight', label: 'Flights', sub: 'Outbound + return' },
    { screen: 'hotels', icon: 'hotel', label: 'Hotels', sub: '7 stays · 11 nights' },
    { screen: 'docs', icon: 'doc', label: 'Documents', sub: 'Booking · ESTA · policy' },
    { screen: 'challenges', icon: 'camera', label: 'Photo Quest', sub: '20 shots/day · family leaderboard' },
    { screen: 'weather', icon: 'weather', label: 'Weather', sub: '12-day forecast' },
  ];
  return (
    <div className="screen">
      <div className="screen-inner with-top">
        <div className="top-bar">
          <div />
          <div className="tb-title">More</div>
          <div />
        </div>
        <div style={{ padding: '12px 22px 18px' }}>
          <div className="mono">Trip essentials</div>
          <h2 className="display" style={{ fontSize: 34, lineHeight: 1.02, marginTop: 4, fontWeight: 400, letterSpacing: '-0.025em' }}>
            Everything else.
          </h2>
        </div>
        <div style={{ margin: '0 16px', background: 'var(--bg-elev)', border: '0.5px solid var(--line)', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--sh-xs)' }}>
          {items.map((it, i) => (
            <button key={it.screen} onClick={() => nav.push({ screen: it.screen })}
                    style={{ width: '100%', display: 'grid', gridTemplateColumns: '36px 1fr 16px', gap: 14, padding: '14px 18px', alignItems: 'center', borderTop: i > 0 ? '0.5px solid var(--line)' : 'none', textAlign: 'left' }}>
              <div style={{ color: 'var(--brand)' }}><Icon name={it.icon} size={22} /></div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{it.label}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{it.sub}</div>
              </div>
              <div style={{ color: 'var(--ink-4)' }}><Icon name="chev" size={16} /></div>
            </button>
          ))}
        </div>
        <button onClick={() => window.__lockApp && window.__lockApp()}
                style={{ margin: '20px 16px 0', width: 'calc(100% - 32px)', padding: '13px 18px', borderRadius: 14, border: '0.5px solid var(--line)', background: 'var(--bg-elev)', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 14, color: 'var(--ink-3)' }}>
          <Icon name="back" size={20} />
          <span style={{ fontSize: 15, fontWeight: 600 }}>Sign out</span>
        </button>
      </div>
    </div>
  );
}

window.App = App;
window.MoreScreen = MoreScreen;
