/* global React, ReactDOM, RIcons, RHome, RRound, RScreens, RJournal, RChat, RNightWatch, RPaywall, ROnboarding, ONBOARD_DEFAULTS, CHAT_SESSIONS */
// App shell — Felt Rounds: rounds + journal/tracker + Night Watch upsell.

const { useState: useStateA, useEffect: useEffectA } = React;
const { HomeScreen, BottomNav, PushNotif } = RHome;
const { RoundScreen, RoundChatScreen } = RRound;
const { JournalScreen, LogEntrySheet, PatternsScreen } = RJournal;
const { CareChatScreen, ChatSidebar } = RChat;
const { ScheduleScreen, BundleScreen, BundleConfirmScreen, ModeScreen } = RScreens;
const {
  NWContextScreen, NWPackageScreen, NWQuickArm, NWActivatingScreen, NWActiveScreen,
  NightWatchTabScreen, NightWatchTabDock, NightWatchSuggestCard, NightWatchActiveBanner, DEFAULT_CONTEXT,
  AutoNWGhostCard,
} = RNightWatch;
const { PaywallSheet } = RPaywall;
const {
  OnboardHeroScreen, OnboardStep1Screen, OnboardStep2Screen,
  OnboardStep3Screen, OnboardDoneScreen,
} = ROnboarding;

// ─── Static route sets — hoisted so they're not rebuilt each render ──
const NW_ROUTES = ['nw-context', 'nw-package', 'nw-quick', 'nw-activating', 'nw-active'];
const OB_ROUTES = ['onboard-hero', 'onboard-step1', 'onboard-step2', 'onboard-step3', 'onboard-done'];
const FULL_FLOW_ROUTES = new Set(['round', 'round-chat', 'bundle', 'confirm', 'patterns', 'consult', ...NW_ROUTES, ...OB_ROUTES]);

// ─── Shared demo scenario data — used by both ScenarioLoader and MobileDemoSheet ──
const DEMO_GROUPS_STATIC = [
  { label: 'Onboarding', items: [
    { id: 'onboard-hero', label: 'Introducing Rounds', sub: 'First-time setup · hero → 3 steps' },
  ]},
  { label: 'Rounds', items: [
    { id: 'home',  label: 'Home',          sub: 'Round + upsell cards' },
    { id: 'round', label: 'Morning round', sub: 'Signed · MD seal' },
  ]},
  { label: 'Journal', items: [
    { id: 'journal', label: "Today's log", sub: '15 entries · temp flagged' },
  ]},
  { label: 'Chat', items: [
    { id: 'care-chat',  label: 'Care chat',   sub: 'Vitals · add to round' },
    { id: 'round-chat', label: 'Round chat',  sub: 'Signed report attached' },
  ]},
  { label: 'Night Watch', items: [
    { id: 'nw-tab', label: 'NW · Care tab', sub: '24/7 + Night Watch' },
  ]},
];

function StatusBar({ time = '7:32', dark = true }) {
  const c = dark ? '#fff' : '#000';
  return (
    <div className="status-bar" style={{ color: c }}>
      <div>{time}</div>
      <div className="right">
        <svg width="18" height="11" viewBox="0 0 18 11" fill="currentColor"><rect x="0" y="6.5" width="3" height="4.5" rx="0.6"/><rect x="4.5" y="4" width="3" height="7" rx="0.6"/><rect x="9" y="1.5" width="3" height="9.5" rx="0.6"/><rect x="13.5" y="0" width="3" height="11" rx="0.6"/></svg>
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none" stroke="currentColor" strokeWidth="1.1"><path d="M.5 4.5C3 2 5 1 8 1s5 1 7.5 3.5"/><path d="M3 6.5C4.5 5 6 4.5 8 4.5s3.5.5 5 2"/><circle cx="8" cy="9.2" r="1.2" fill="currentColor"/></svg>
        <svg width="26" height="12" viewBox="0 0 26 12"><rect x="0.5" y="0.5" width="22" height="11" rx="3" fill="none" stroke="currentColor" strokeOpacity="0.4"/><rect x="2" y="2" width="18" height="8" rx="1.5" fill="currentColor"/><rect x="23.2" y="3.5" width="1.8" height="5" rx="0.7" fill="currentColor" opacity="0.5"/></svg>
      </div>
    </div>
  );
}

function ScenarioLoader({ route, setRoute, onOpenPaywall, onPing, onShowAutoNWGhost }) {
  const GROUPS = [
    ...DEMO_GROUPS_STATIC,
    { label: 'Upsell', items: [
      { id: '_paywall',     label: 'Talk to a doctor', sub: 'Paywall sheet',             action: onOpenPaywall,     dot: 'var(--accent)' },
      { id: '_paywall2',    label: 'Night Watch',      sub: 'Paywall sheet',             action: onOpenPaywall,     dot: 'var(--cat-temp)' },
      { id: 'nw-active',   label: 'NW · Active',      sub: 'Post-purchase' },
      { id: '_autonwghost', label: 'Auto NW Ghost',   sub: 'Care+ upsell · missed event', action: onShowAutoNWGhost, dot: 'rgba(125,128,230,0.8)' },
    ]},
  ];

  return (
    <div className="scenario-loader">
      <div style={{ marginBottom: 12 }}>
        <h4 style={{ margin: 0 }}>Rounds · Demo</h4>
        <div className="sl-sub" style={{ marginBottom: 0 }}>Rounds · Journal · Night Watch · Telehealth</div>
      </div>

      {GROUPS.map((g, gi) => (
        <div key={gi}>
          {gi > 0 && <hr className="sl-hr" />}
          <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--foreground-muted)', marginBottom: 6, paddingLeft: 2 }}>{g.label}</div>
          {g.items.map(s => {
            const isActive = !s.action && route === s.id;
            const dot = s.dot || (isActive ? '#e8d4a5' : 'rgba(212,212,249,0.25)');
            return (
              <button
                key={s.id}
                className={`sl-btn ${isActive ? 'on' : ''}`}
                style={{ marginBottom: 4 }}
                onClick={() => s.action ? s.action() : setRoute(s.id)}>
                <span className="sl-dot" style={{ background: dot }} />
                <span style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: isActive ? '#fff' : 'var(--foreground)' }}>{s.label}</span>
                  <span style={{ display: 'block', fontSize: 10.5, color: 'var(--foreground-muted)', marginTop: 1, lineHeight: '13px' }}>{s.sub}</span>
                </span>
              </button>
            );
          })}
        </div>
      ))}

      <hr className="sl-hr" />
      <button
        className="sl-btn"
        onClick={onPing}
        style={{ background: 'var(--primary)', color: 'var(--on-primary)', borderColor: 'transparent', fontWeight: 600 }}>
        ▶ Trigger push notif
      </button>
    </div>
  );
}

// ─── Mobile demo panel ───────────────────────────────────
// Bottom sheet version of ScenarioLoader — shown on mobile only (CSS gates it).
function MobileDemoSheet({ open, onClose, route, setRoute, onOpenPaywall, onPing, onShowAutoNWGhost }) {
  const nav = (id) => { setRoute(id); onClose(); };

  const GROUPS = [
    ...DEMO_GROUPS_STATIC,
    { label: 'Upsell', items: [
      { id: '_paywall',     label: 'Talk to a doctor', sub: 'Paywall sheet',              action: () => { onOpenPaywall();    onClose(); } },
      { id: '_paywall2',    label: 'Night Watch',      sub: 'Paywall sheet',              action: () => { onOpenPaywall();    onClose(); } },
      { id: 'nw-active',   label: 'NW · Active',      sub: 'Post-purchase' },
      { id: '_autonwghost', label: 'Auto NW Ghost',   sub: 'Care+ upsell · missed event', action: () => { onShowAutoNWGhost(); onClose(); } },
    ]},
  ];

  return (
    <>
      <div className={`scrim ${open ? 'open' : ''}`} onClick={onClose} />
      <div className={`sheet sheet--demo ${open ? 'open' : ''}`}>
        <div className="sheet-handle" />
        <div className="mobile-demo-header">
          <div>
            <div className="mobile-demo-title">Rounds · Demo</div>
            <div className="mobile-demo-sub">Rounds · Journal · Night Watch · Telehealth</div>
          </div>
          <button className="mobile-demo-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        <div className="mobile-demo-list">
          {GROUPS.map((g, gi) => (
            <div key={gi}>
              {gi > 0 && <hr className="mobile-demo-hr" />}
              <span className="mobile-demo-group-label">{g.label}</span>
              {g.items.map(s => {
                const isActive = !s.action && route === s.id;
                return (
                  <button
                    key={s.id}
                    className={`sl-btn ${isActive ? 'on' : ''}`}
                    style={{ marginBottom: 4, width: '100%' }}
                    onClick={() => s.action ? s.action() : nav(s.id)}
                  >
                    <span className="sl-dot" style={{ background: isActive ? '#e8d4a5' : 'rgba(212,212,249,0.25)' }} />
                    <span style={{ flex: 1, minWidth: 0 }}>
                      <span style={{ display: 'block', fontSize: 13, fontWeight: 600, color: isActive ? '#fff' : 'var(--foreground)' }}>{s.label}</span>
                      <span style={{ display: 'block', fontSize: 11, color: 'var(--foreground-muted)', marginTop: 1, lineHeight: '14px' }}>{s.sub}</span>
                    </span>
                  </button>
                );
              })}
            </div>
          ))}
        </div>

        <button className="mobile-demo-ping" onClick={() => { onPing(); onClose(); }}>
          ▶ Trigger push notif
        </button>
      </div>
    </>
  );
}

function App() {
  const [route, setRoute] = useStateA('home');
  const [sickMode, setSickMode] = useStateA(false);
  const [pushVisible, setPushVisible] = useStateA(false);
  const [logOpen, setLogOpen] = useStateA(false);
  const [chatReturnRoute, setChatReturnRoute] = useStateA('home');
  // Night Watch state
  const [nwActive, setNwActive] = useStateA(false);
  const [nwActivatedAt, setNwActivatedAt] = useStateA(null);
  const [nwContext, setNwContext] = useStateA({ ...DEFAULT_CONTEXT });
  const [nwArmedBefore, setNwArmedBefore] = useStateA(false);
  const [lastNight, setLastNight] = useStateA(null);
  const [paywallOpen, setPaywallOpen] = useStateA(false);
  const [showAutoNWGhost, setShowAutoNWGhost] = useStateA(false);
  const [onboardPrefs, setOnboardPrefs] = useStateA(() => ({ ...ONBOARD_DEFAULTS }));
  const [mobileDemoOpen, setMobileDemoOpen] = useStateA(false);
  const [chatSidebarOpen, setChatSidebarOpen] = useStateA(false);
  const [activeChatSession, setActiveChatSession] = useStateA(CHAT_SESSIONS[0]);

  // Signal the splash overlay (index.html) that React is mounted — fades it out.
  // Small delay lets the first paint land under the splash so there's no flash.
  useEffectA(() => {
    const t = setTimeout(() => window.__roundsReady && window.__roundsReady(), 350);
    return () => clearTimeout(t);
  }, []);

  useEffectA(() => {
    if (route !== 'home') setPushVisible(false);
  }, [route]);

  function triggerPush() {
    setRoute('home');
    setTimeout(() => {
      setPushVisible(true);
      setTimeout(() => setPushVisible(false), 4200);
    }, 50);
  }

  const isFullFlow = FULL_FLOW_ROUTES.has(route);

  function startNW() {
    setNwContext({ ...DEFAULT_CONTEXT });
    setRoute(nwArmedBefore ? 'nw-quick' : 'nw-context');
  }
  function activateNW() {
    window.haptics?.trigger('success');
    setNwArmedBefore(true);
    setLastNight(nwContext);
    setNwActivatedAt(Date.now());
    setNwActive(true);
    setRoute('nw-activating');
  }
  function endNW() {
    setNwActive(false);
    setRoute('home');
  }

  const [navTab, setNavTab] = useStateA('home');

  useEffectA(() => {
    if (route === 'home') setNavTab('home');
    if (route === 'journal') setNavTab('journal');
    if (route === 'care-chat') setNavTab('chat');
    if (route === 'nw-tab') setNavTab('nightwatch');
  }, [route]);

  function gotoTab(tab) {
    setNavTab(tab);
    if (tab === 'home') setRoute('home');
    if (tab === 'journal') setRoute('journal');
    if (tab === 'chat') setRoute('care-chat');
    if (tab === 'nightwatch') setRoute('nw-tab');
  }

  let screen = null;
  if (route === 'home') {
    screen = (
      <HomeScreen
        onOpenRound={() => setRoute('round')}
        onDiscussRound={() => setRoute('round-chat')}
        onOpenSchedule={() => setRoute('bundle')}
        onOpenJournal={() => setRoute('journal')}
        onLog={() => setLogOpen(true)}
        onConsult={() => setPaywallOpen(true)}
        nwSlot={nwActive
          ? <NightWatchActiveBanner onTap={() => setRoute('nw-active')} context={nwContext} />
          : showAutoNWGhost
            ? <AutoNWGhostCard onUpgrade={() => setPaywallOpen(true)} />
            : <NightWatchSuggestCard onActivate={() => setPaywallOpen(true)} />
        }
      />
    );
  } else if (route === 'round') {
    screen = (
      <RoundScreen
        onBack={() => setRoute('home')}
        onBundle={() => setRoute('bundle')}
        format={onboardPrefs.format}
        agentPersonality={onboardPrefs.agentPersonality}
      />
    );
  } else if (route === 'care-chat') {
    screen = (
      <CareChatScreen
        onAddToRound={() => setRoute('bundle')}
        sidebarOpen={chatSidebarOpen}
        setSidebarOpen={setChatSidebarOpen}
        activeSession={activeChatSession}
        setActiveSession={setActiveChatSession}
      />
    );
  } else if (route === 'nw-tab') {
    screen = (
      <NightWatchTabScreen
        nwActive={nwActive}
        onGetStarted={() => setPaywallOpen(true)}
        onOpenActive={() => setRoute('nw-active')}
      />
    );
  } else if (route === 'round-chat') {
    screen = (
      <RoundChatScreen
        onBack={() => setRoute(chatReturnRoute)}
        agentPersonality={onboardPrefs.agentPersonality}
      />
    );
  } else if (route === 'journal') {
    screen = (
      <JournalScreen
        onBack={() => setRoute('home')}
        onLog={() => setLogOpen(true)}
        onPatterns={() => setRoute('patterns')}
      />
    );
  } else if (route === 'patterns') {
    screen = (
      <PatternsScreen onBack={() => setRoute('journal')} />
    );
  } else if (route === 'schedule') {
    screen = (
      <ScheduleScreen
        onBack={() => setRoute('home')}
        onOpenToday={() => setRoute('round')}
      />
    );
  } else if (route === 'bundle') {
    screen = (
      <BundleScreen
        onBack={() => setRoute('round')}
        onConfirm={() => setRoute('confirm')}
      />
    );
  } else if (route === 'confirm') {
    screen = (
      <BundleConfirmScreen onDone={() => setRoute('home')} />
    );
  } else if (route === 'mode') {
    screen = (
      <ModeScreen
        onBack={() => setRoute('home')}
        modeOn={sickMode}
        onToggle={() => setSickMode(s => !s)}
        onOpenSick={() => setRoute('round')}
      />
    );
  } else if (route === 'nw-context') {
    screen = (
      <NWContextScreen
        onBack={() => setRoute('home')}
        onNext={() => setRoute('nw-package')}
        context={nwContext}
        setContext={setNwContext}
      />
    );
  } else if (route === 'nw-package') {
    screen = (
      <NWPackageScreen
        onBack={() => setRoute('nw-context')}
        onActivate={activateNW}
        context={nwContext}
        setContext={setNwContext}
      />
    );
  } else if (route === 'nw-quick') {
    screen = (
      <NWQuickArm
        onBack={() => setRoute('home')}
        onActivate={activateNW}
        context={nwContext}
        setContext={setNwContext}
        lastNight={lastNight}
      />
    );
  } else if (route === 'nw-activating') {
    screen = <NWActivatingScreen onDone={() => setRoute('nw-active')} />;
  } else if (route === 'nw-active') {
    screen = (
      <NWActiveScreen
        onBack={() => setRoute('home')}
        onStartVisit={() => setRoute('consult')}
        onEditContext={() => setRoute('nw-context')}
        onEnd={endNW}
        context={nwContext}
        activatedAt={nwActivatedAt}
      />
    );
  } else if (route === 'onboard-hero') {
    screen = (
      <OnboardHeroScreen
        onStart={() => setRoute('onboard-step1')}
      />
    );
  } else if (route === 'onboard-step1') {
    screen = (
      <OnboardStep1Screen
        onBack={() => setRoute('onboard-hero')}
        onNext={() => setRoute('onboard-step2')}
        prefs={onboardPrefs}
        setPrefs={setOnboardPrefs}
      />
    );
  } else if (route === 'onboard-step2') {
    screen = (
      <OnboardStep2Screen
        onBack={() => setRoute('onboard-step1')}
        onNext={() => setRoute('onboard-step3')}
        prefs={onboardPrefs}
        setPrefs={setOnboardPrefs}
      />
    );
  } else if (route === 'onboard-step3') {
    screen = (
      <OnboardStep3Screen
        onBack={() => setRoute('onboard-step2')}
        onNext={() => setRoute('onboard-done')}
        prefs={onboardPrefs}
        setPrefs={setOnboardPrefs}
      />
    );
  } else if (route === 'onboard-done') {
    screen = (
      <OnboardDoneScreen
        prefs={onboardPrefs}
        onDone={() => setRoute('home')}
      />
    );
  }

  return (
    <div className="stage">
      <ScenarioLoader
        route={route}
        setRoute={(r) => { setPaywallOpen(false); setRoute(r); }}
        onOpenPaywall={() => { setRoute('home'); setPaywallOpen(true); }}
        onPing={triggerPush}
        onShowAutoNWGhost={() => { setShowAutoNWGhost(true); setRoute('home'); }}
      />

      <div className="phone">
        <div className="island" />
        <div className="home-indicator" />

        <div className="phone-inner">
          <StatusBar />

          {/* Chat sidebar — rendered here so it spans full phone height above nav */}
          <ChatSidebar
            open={chatSidebarOpen}
            onClose={() => setChatSidebarOpen(false)}
            sessions={CHAT_SESSIONS}
            activeId={activeChatSession.id}
            onSelect={setActiveChatSession}
            onNew={() => setChatSidebarOpen(false)}
          />

          {/* Mobile demo FAB — hidden when chat sidebar is open */}
          <button
            className="demo-fab"
            style={{ display: chatSidebarOpen ? 'none' : undefined }}
            onClick={() => setMobileDemoOpen(true)}
            aria-label="Open demo panel"
          >
            <svg width="15" height="12" viewBox="0 0 15 12" fill="none" aria-hidden="true">
              <rect y="0"   width="15" height="2" rx="1" fill="currentColor"/>
              <rect y="5"   width="10" height="2" rx="1" fill="currentColor"/>
              <rect y="10"  width="15" height="2" rx="1" fill="currentColor"/>
            </svg>
            Demo
          </button>

          <MobileDemoSheet
            open={mobileDemoOpen}
            onClose={() => setMobileDemoOpen(false)}
            route={route}
            setRoute={(r) => { setPaywallOpen(false); setRoute(r); }}
            onOpenPaywall={() => { setRoute('home'); setPaywallOpen(true); }}
            onPing={triggerPush}
            onShowAutoNWGhost={() => { setShowAutoNWGhost(true); setRoute('home'); }}
          />
          <div
            className={`scroll ${isFullFlow ? 'scroll--flow' : 'scroll--withnav'}`}
            key={route}
          >
            {screen}
          </div>

          {route === 'onboard-hero' && (
            <div className="ob-fixed-footer">
              <button className="nw-cta glow" onClick={() => setRoute('onboard-step1')}>
                Start your Rounds <RIcons.ChevronRight size={18} />
              </button>
              <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--foreground-muted)', margin: '6px 0 0', lineHeight: '17px' }}>
                Included with your Owlet subscription
              </p>
            </div>
          )}

          <PushNotif
            show={pushVisible && route === 'home'}
            onTap={() => { setPushVisible(false); setRoute('round'); }}
          />

          {route === 'journal' && (
            <button className="log-fab" onClick={() => setLogOpen(true)} aria-label="Log entry">
              <RIcons.Plus size={22} />
            </button>
          )}

          {/* Log entry sheet — accessible from any screen */}
          <LogEntrySheet open={logOpen} onClose={() => setLogOpen(false)} />

          {route === 'round' && (
            <div className="round-chat-dock">
              <button
                type="button"
                className="round-chat-cta"
                onClick={() => {
                  setChatReturnRoute('round');
                  setRoute('round-chat');
                }}
              >
                <RIcons.Chat size={17} />
                Chat about this report
              </button>
            </div>
          )}

          {route === 'nw-tab' && (
            <NightWatchTabDock
              nwActive={nwActive}
              onGetStarted={() => setPaywallOpen(true)}
              onOpenActive={() => setRoute('nw-active')}
            />
          )}

          <PaywallSheet
            open={paywallOpen}
            onClose={() => setPaywallOpen(false)}
            onSelectTonight={() => { setPaywallOpen(false); startNW(); }}
            onSelectFull={() => { setPaywallOpen(false); startNW(); }}
          />

          {!isFullFlow && <div className="nav-fade" aria-hidden="true" />}
          {!isFullFlow && <BottomNav tab={navTab} onTab={gotoTab} />}
        </div>
      </div>
    </div>
  );
}

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