// shell.jsx — header + sidebar + footer for World Cup Live
function Shell({ route, onRoute, children, theme, onToggleTheme, density, competition, onChangeCompetition, clock }) {
  const ck = clock || window.WCL_CLOCK.compute('live');
  const navMain = [
    { id: 'home',     label: 'Home',        Icon: I.Home,     tip: 'Overview — countdown, every section, what\u2019s on today.' },
    { id: 'live',     label: 'Live Today',  Icon: I.Activity, tip: 'Live scores, win probability and the match timeline.' },
    { id: 'pickem',   label: 'Pick\u2019em',Icon: I.Crown,    tip: 'Predict every match — locks at kick-off, scored vs the model.' },
    { id: 'matches',  label: 'Fixtures',    Icon: I.Calendar, tip: 'Every match across the 39-day calendar.' },
    { id: 'table',    label: 'Table',       Icon: I.List,     tip: '12 groups of four — standings and who advances.' },
    { id: 'bracket',  label: 'Knockout',    Icon: I.Bracket,  tip: 'Round of 32 to the final, with model probabilities.' },
    { id: 'players',  label: 'Players',     Icon: I.Users,    tip: 'Star players + all-time legends, with Wikipedia photos.' },
    { id: 'teams',    label: 'Teams',       Icon: I.Shield,   tip: 'All 48 teams of the 2026 field, by confederation.' },
    { id: 'odds',     label: 'Odds & Model',Icon: I.Sigma,    tip: 'Trophy odds, model vs market edge, stage probabilities.' },
    { id: 'agent',    label: 'Agent',       Icon: I.Chat,     tip: 'WorldCupAI — ask anything about the tournament.' },
  ];
  const navAllTime = [
    { id: 'history',     label: 'History',     Icon: I.Book,   tip: 'The story of the World Cup, edition by edition.' },
    { id: 'tournaments', label: 'Tournaments', Icon: I.Trophy, tip: 'Index of every edition 1930 to 2034.' },
    { id: 'records',     label: 'Records',     Icon: I.Sigma,  tip: 'Overall team records, scorers, confederations.' },
    { id: 'medals',      label: 'Medals',      Icon: I.Crown,  tip: 'All-time medal table — gold, silver, bronze.' },
    { id: 'maps',        label: 'Maps',        Icon: I.Map,    tip: 'World map of every host + per-edition stadium maps.' },
  ];
  const navMore = [
    { id: 'stats',    label: 'Statistics',  Icon: I.Sigma,   tip: '2026 profile plus all-time numbers.' },
    { id: 'guide',    label: 'Guide',       Icon: I.Compass, tip: 'Primer + every edition 1930 to 2034.' },
    { id: 'faq',      label: 'FAQ',         Icon: I.Book,    tip: 'Common questions about the 2026 tournament.' },
    { id: 'sitemap',  label: 'Sitemap',     Icon: I.Map,     tip: 'Every page in the app, deep-linkable.' },
    { id: 'explainer',label: 'How it works',Icon: I.Book,    tip: 'Model, scoring, glossary, coverage.' },
  ];
  const byComp = [
    { id: 'wc_women', label: 'Women\u2019s World Cup' },
    { id: 'euros',    label: 'UEFA Euros' },
    { id: 'copa',     label: 'Copa Am\u00e9rica' },
    { id: 'afcon',    label: 'AFCON' },
    { id: 'asia',     label: 'Asian Cup' },
    { id: 'gold',     label: 'Gold Cup' },
  ];
  const years = [1930,1934,1938,1950,1954,1958,1962,1966,1970,1974,1978,1982,1986,1990,1994,1998,2002,2006,2010,2014,2018,2022,2026,2030,2034];
  const [yearsOpen, setYearsOpen] = React.useState(false);
  const [compOpen, setCompOpen] = React.useState(false);
  const isAdmin = (typeof window !== 'undefined') && window.localStorage.getItem('wcl_admin') === '1';

  function goYear(y) {
    if (y <= 2022) onRoute('tournament', { year: y, competition: 'wc_men' });
    else if (y === 2026) onRoute('wc2026');
    else onRoute('guide');
  }

  const comps = window.WCL_COMPETITIONS;
  const comp = comps[competition] || comps.wc_men;
  const B = window.WCL_BUILD;

  return (
    <div className="shell">
      <header className="hd">
        <div className="hd-ctx">
          <CompetitionSwitcher value={competition} onChange={onChangeCompetition} />
          <button className="hd-clock" onClick={() => onRoute('stats')} data-tt="Tournament clock — open statistics">
            <I.Calendar size={13} style={{ opacity: 0.7 }} />
            {ck.phase === 'pre'  && <><span className="lbl">Kick-off</span> <span className="mono">{ck.daysUntil}d</span></>}
            {ck.phase === 'live' && <><span className="lbl">{ck.dateLabel}</span> <span className="mono">Day {ck.dayN}/{ck.totalDays}</span></>}
            {ck.phase === 'post' && <><span className="lbl">2026</span> <span className="mono">Concluded</span></>}
          </button>
          {ck.phase === 'live' && <span className="hd-pulse"><span className="dot" /> LIVE · 2</span>}
        </div>
        <div className="hd-search">
          <I.Search size={14} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', opacity: 0.55 }} />
          <input className="input" style={{ paddingLeft: 32, height: 32, fontSize: 12.5 }}
                 placeholder={`Search ${comp.name.toLowerCase()}: teams, matches, players, years…`} />
          <span className="kbd">⌘K</span>
        </div>
        <div className="hd-actions">
          <button className="btn btn-ghost btn-icon" data-tt="Ask the agent" aria-label="agent" onClick={() => onRoute('agent')}>
            <I.Chat size={16} />
          </button>
          <button className="btn btn-ghost btn-icon" data-tt="FAQ" aria-label="faq" onClick={() => onRoute('faq')}><I.Book size={16} /></button>
          <button className="btn btn-ghost btn-icon" data-tt="Notifications" aria-label="notifications"><I.Bell size={16} /></button>
          <button className="btn btn-ghost btn-icon" data-tt={theme === 'light' ? 'Switch to dark' : 'Switch to light'} aria-label="theme" onClick={onToggleTheme}>
            {theme === 'light' ? <I.Moon size={16} /> : <I.Sun size={16} />}
          </button>
          <div className="avatar" data-tt="Admin sign-in" style={{ cursor: 'pointer' }} onClick={() => onRoute('admin')}>M</div>
        </div>
      </header>

      <aside className="sb">
        <div className="sb-brand">
          <div className="sb-mark" style={{ background: 'transparent', boxShadow: 'none', padding: 0 }}>
            <SoccerBall size={30} />
          </div>
          <div>
            <div className="sb-name">World Cup <span>Live</span></div>
            <div className="sb-name sub">{comp.short} · since {comp.since}</div>
          </div>
        </div>

        <div className="sb-streak">
          <span><span className="strong">Daily streak</span></span>
          <strong>6 · 🏆</strong>
        </div>

        <div className="sb-group">
          <div className="type-eyebrow" style={{ padding: '0 10px 6px' }}>WORLD CUP 2026</div>
          {navMain.map(({ id, label, Icon, tip }) => (
            <a key={id} className={'nav-item' + (route === id ? ' active' : '')} data-tooltip={tip} onClick={() => onRoute(id)}>
              <Icon size={16} /> {label}
            </a>
          ))}
        </div>

        <div className="sb-group">
          <div className="type-eyebrow" style={{ padding: '0 10px 6px' }}>ALL-TIME WORLD CUP</div>
          {navAllTime.map(({ id, label, Icon, tip }) => (
            <a key={id} className={'nav-item' + ((route === id || (id === 'records' && route === 'alltime')) ? ' active' : '')} data-tooltip={tip} onClick={() => onRoute(id)}>
              <Icon size={16} /> {label}
            </a>
          ))}
        </div>

        <div className="sb-group">
          <a className="nav-item" style={{ cursor: 'pointer' }} onClick={() => setYearsOpen(o => !o)}>
            <I.Grid size={16} /> By year
            <I.ChevDown size={13} style={{ marginLeft: 'auto', transform: yearsOpen ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-fast) var(--ease-out)' }} />
          </a>
          {yearsOpen && (
            <div className="sb-years">
              {years.map(y => (
                <button key={y} className={'sb-year' + (y > 2022 ? ' future' : '') + (y === 2026 && route === 'wc2026' ? ' active' : '')} onClick={() => goYear(y)}>{y}</button>
              ))}
            </div>
          )}
        </div>

        <div className="sb-group">
          <a className="nav-item" style={{ cursor: 'pointer' }} onClick={() => setCompOpen(o => !o)}>
            <I.Globe size={16} /> By competition
            <I.ChevDown size={13} style={{ marginLeft: 'auto', transform: compOpen ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-fast) var(--ease-out)' }} />
          </a>
          {compOpen && byComp.map(c => (
            <a key={c.id} className={'nav-item' + (competition === c.id && (route === 'history' || route === 'tournament') ? ' active' : '')}
               style={{ paddingLeft: 26 }} onClick={() => onChangeCompetition(c.id)}>
              <span style={{ width: 18, height: 18, borderRadius: 5, background: (comps[c.id]?.accent || 'var(--brand)'), color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 700, flexShrink: 0 }}>{comps[c.id]?.icon || '?'}</span> {c.label}
            </a>
          ))}
        </div>

        {isAdmin && (
          <div className="sb-group">
            <div className="type-eyebrow" style={{ padding: '0 10px 6px' }}>ADMIN</div>
            <a className={'nav-item' + (route === 'admin' ? ' active' : '')} data-tooltip="Dashboard, settings & overview." onClick={() => onRoute('admin')}><I.Grid size={16} /> Dashboard</a>
            <a className="nav-item" data-tooltip="Integrations — keys, quotas, health, tests." onClick={() => onRoute('admin')}><I.Layers size={16} /> Integrations</a>
            <a className="nav-item" data-tooltip="Data — CRUD the Supabase datasets." onClick={() => onRoute('admin')}><I.List size={16} /> Data</a>
          </div>
        )}

        <div style={{ flex: 1 }} />

        <div className="sb-group">
          {navMore.map(({ id, label, Icon, tip }) => (
            <a key={id} className={'nav-item' + (route === id ? ' active' : '')} data-tooltip={tip} onClick={() => onRoute(id)}>
              <Icon size={16} /> {label}
            </a>
          ))}
          {!isAdmin && (
            <a className={'nav-item' + (route === 'admin' ? ' active' : '')} data-tooltip="Sign-in required. Integrations, tests & data." onClick={() => onRoute('admin')}>
              <I.Settings size={16} /> Admin
            </a>
          )}
        </div>
      </aside>

      <main className="main">
        <div className="main-inner" data-density={density}>
          {children}
        </div>
      </main>

      <footer className="ft">
        <span className="ft-version">
          <span className="ft-badge">{B.version}</span>
          <span>World Cup Live</span>
          <span className="mono" data-tt={'session ref ' + B.ref}>build #{B.build}</span>
        </span>
        <span>data: <span className="mono">api-football · statsbomb · wikipedia</span></span>
        <span>model <span className="mono">v3.2 · refit 2026-06-22</span></span>
      </footer>
    </div>
  );
}

// ---------- Competition switcher ----------
function CompetitionSwitcher({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const comps = window.WCL_COMPETITIONS;
  const cur = comps[value] || comps.wc_men;
  const ref = React.useRef(null);

  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '6px 10px 6px 6px',
        background: open ? 'var(--card-hover)' : 'transparent',
        border: '1px solid ' + (open ? 'var(--border-hover)' : 'var(--border)'),
        borderRadius: 'var(--radius-md)',
        color: 'var(--foreground)',
        fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500,
        cursor: 'pointer',
        transition: 'background var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out)',
      }}>
        <span style={{
          width: 22, height: 22, borderRadius: 6,
          background: cur.accent,
          color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 11, fontWeight: 700,
        }}>{cur.icon}</span>
        <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.1 }}>
          <span style={{ fontWeight: 600 }}>{cur.short}</span>
          <span className="subtle" style={{ fontSize: 10.5, marginTop: 1, letterSpacing: '0.04em' }}>{cur.governing}</span>
        </span>
        <I.ChevDown size={12} style={{ opacity: 0.7 }} />
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', left: 0,
          minWidth: 320,
          maxHeight: 560,
          overflowY: 'auto',
          background: 'var(--popover)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--radius)',
          boxShadow: 'var(--shadow-md)',
          backdropFilter: 'blur(12px)',
          padding: 6,
          zIndex: 100,
        }}>
          <div className="eyebrow" style={{ padding: '8px 10px 4px' }}>Switch competition</div>
          {Object.values(comps).map(c => {
            const active = c.id === value;
            const last = c.editions[c.editions.length - 1];
            return (
              <button key={c.id}
                      onClick={() => { onChange(c.id); setOpen(false); }}
                      style={{
                        display: 'grid',
                        gridTemplateColumns: '24px 1fr auto',
                        gap: 10, width: '100%',
                        padding: '8px 10px',
                        background: active ? 'var(--card-hover)' : 'transparent',
                        border: 'none',
                        borderRadius: 'var(--radius-md)',
                        cursor: 'pointer',
                        textAlign: 'left',
                        color: 'inherit',
                        fontFamily: 'inherit',
                        alignItems: 'center',
                        marginBottom: 2,
                      }}
                      onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--muted)'; }}
                      onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
                <span style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: c.accent,
                  color: 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700,
                }}>{c.icon}</span>
                <span>
                  <span className="strong" style={{ fontSize: 13, fontWeight: 600 }}>{c.short}</span>
                  <span className="subtle" style={{ display: 'block', fontSize: 11, marginTop: 1 }}>
                    {c.editions.length} eds · last {last.y} · {window.WCL_TEAMS[last.winner]?.name || last.winner}
                  </span>
                </span>
                {active && <I.Check size={14} style={{ color: 'var(--pitch)' }} />}
              </button>
            );
          })}

          {/* Every Men's WC edition since 1930 */}
          <div style={{ borderTop: '1px solid var(--border)', margin: '8px -6px 0', padding: '8px 16px 4px' }}>
            <div className="eyebrow">Every Men’s World Cup · 1930 → 2022</div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 4, padding: '6px 10px 10px' }}>
            {(window.WCL_HISTORY || []).map(h => (
              <button key={h.y} onClick={() => { setOpen(false); window.__wclGoTournament && window.__wclGoTournament(h.y); }} style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                padding: '8px 4px',
                background: 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--radius-sm)',
                cursor: 'pointer',
                color: 'inherit', fontFamily: 'inherit',
                fontSize: 11,
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--border-hover)'; e.currentTarget.style.background = 'var(--card-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'var(--surface)'; }}>
                <span className="mono strong" style={{ fontSize: 11, color: 'var(--foreground)' }}>{h.y}</span>
                <Flag code={h.winner} />
                <span className="subtle" style={{ fontSize: 9, letterSpacing: '0.04em' }}>{h.host.slice(0, 8)}</span>
              </button>
            ))}
          </div>
          <div style={{ borderTop: '1px solid var(--border)', margin: '6px -6px -6px', padding: '8px 16px 8px', background: 'var(--surface)', borderRadius: '0 0 var(--radius) var(--radius)' }}>
            <div className="subtle" style={{ fontSize: 11 }}>
              Switching to a non-WC competition swaps history, archive, and tournament pages. Live coverage stays on Men\u2019s WC 2026.
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Shell, CompetitionSwitcher });
