/* global React, Segmented */
// ============================================================================
// shell.jsx — the v2 app shell (_spec-app-v2.md): five tabs for the boys
// (Today · Plan · Progress · Life · Me) and a Family tab for parents.
// Routing is the URL hash: #today, #plan/month, #progress/benchmarks, …
// Every screen gets the same props: { memberDb, isAdmin, go, sub }.
//   memberDb — the boy being viewed (a boy: always himself; a parent: the switch)
//   go(tab, sub) — navigate, e.g. go('progress', 'ladders')
//   sub — the sub-view from the hash ('month', 'benchmarks', …) or ''
// ============================================================================
(() => {
  const { useState, useEffect } = React;

  const BOY_TABS = [
    { id: 'today', label: 'Today', icon: 'home', screen: 'IdagScreen' },
    { id: 'plan', label: 'Plan', icon: 'calendar', screen: 'PlanScreen' },
    { id: 'progress', label: 'Progress', icon: 'ladder', screen: 'ProgressScreen' },
    { id: 'life', label: 'Life', icon: 'book', screen: 'LifeScreen' },
    { id: 'me', label: 'Me', icon: 'user', screen: 'MeScreen' },
  ];
  const FAMILY_TAB = { id: 'family', label: 'Family', icon: 'users', screen: 'ParentsScreen' };

  function parseHash() {
    const h = (location.hash || '').replace(/^#/, '');
    const [tab, sub] = h.split('/');
    return { tab: tab || 'today', sub: sub || '' };
  }

  function Icon({ name }) {
    const c = { fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' };
    const p = {
      home: <><path d="M3 11l9-8 9 8" /><path d="M5 10v10h14V10" /></>,
      calendar: <><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M3 9h18M8 3v4M16 3v4" /></>,
      ladder: <><path d="M7 3v18M17 3v18M7 7h10M7 12h10M7 17h10" /></>,
      book: <><path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z" /><path d="M4 19V5" /></>,
      user: <><circle cx="12" cy="8" r="4" /><path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6" /></>,
      users: <><circle cx="9" cy="8" r="3.5" /><path d="M2.5 20c1-3.5 3.8-5 6.5-5s5.5 1.5 6.5 5" /><circle cx="17" cy="9" r="2.5" /><path d="M16 14.5c2.6 0 4.6 1.3 5.5 4" /></>,
    }[name];
    return <svg viewBox="0 0 24 24" width="22" height="22" {...c}>{p}</svg>;
  }

  function Missing({ name }) {
    return <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-muted)', fontFamily: 'var(--font-sans)' }}>{name} is loading…</div>;
  }

  function V2Shell({ session }) {
    const A = window.PlanAPI;
    const who = A.me();
    const [kid, setKid] = useState(who.defaultKid);
    const [route, setRoute] = useState(parseHash());
    const [ready, setReady] = useState(false);
    useEffect(() => {
      const f = () => { setRoute(parseHash()); window.scrollTo(0, 0); };
      window.addEventListener('hashchange', f);
      A.loadContent().then(() => setReady(true)).catch(e => { console.error(e); setReady(true); });
      return () => window.removeEventListener('hashchange', f);
    }, []);
    const tabs = who.isAdmin ? [...BOY_TABS.slice(0, 4), FAMILY_TAB, BOY_TABS[4]] : BOY_TABS;
    const tab = tabs.find(t => t.id === route.tab) || tabs[0];
    const go = (t, sub) => { location.hash = sub ? `${t}/${sub}` : t; };
    const Screen = window[tab.screen];
    const kidName = (who.kids.find(k => k.db_id === kid) || {}).name;

    return (
      <div style={{ minHeight: '100vh', background: 'var(--bg)', color: 'var(--fg)', fontFamily: 'var(--font-sans)' }}>
        <header style={{
          position: 'sticky', top: 0, zIndex: 20, background: 'rgba(252,252,253,0.92)', backdropFilter: 'blur(10px)',
          borderBottom: '1px solid var(--border)', padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-subtle)' }}>
            {tab.label}{!who.isAdmin && kidName ? ` · ${kidName}` : ''}
          </div>
          <div style={{ flex: 1 }} />
          {who.isAdmin && who.kids.length > 1 && tab.id !== 'family' && (
            <Segmented size="sm" options={who.kids.map(k => ({ value: k.db_id, label: k.name }))} value={kid} onChange={setKid} />
          )}
          {window.MOCK_MODE && <span style={{ fontSize: 10, color: 'var(--warning)', fontFamily: 'var(--font-mono)' }}>MOCK</span>}
        </header>

        <main style={{ paddingBottom: 88 }}>
          {!ready ? <Missing name="The plan" />
            : Screen ? <Screen key={tab.id + kid} memberDb={kid} isAdmin={who.isAdmin} go={go} sub={route.sub} session={session} />
            : <Missing name={tab.label} />}
        </main>

        <nav aria-label="Main" style={{
          position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 30, display: 'flex',
          background: 'rgba(252,252,253,0.96)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--border)',
          paddingBottom: 'env(safe-area-inset-bottom)',
        }}>
          {tabs.map(t => {
            const on = t.id === tab.id;
            return (
              <button key={t.id} onClick={() => go(t.id)} style={{
                flex: 1, border: 'none', background: 'none', padding: '8px 0 6px', cursor: 'pointer',
                color: on ? 'var(--signal)' : 'var(--fg-subtle)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: on ? 600 : 400,
              }}>
                <Icon name={t.icon} />{t.label}
              </button>
            );
          })}
        </nav>
      </div>
    );
  }

  window.V2Shell = V2Shell;
})();
