// Cortex — app shell: top bar + nav (left on desktop, top tabs on mobile) +
// page router. Desktop layout is pixel-identical to the original design;
// mobile layout activates below 720px viewport width via useIsMobile().

function CortexTopbar({ env, lastBuild, version, asof }) {
  const isMobile = useIsMobile();
  // Real wall clock, updated every minute. Avoids the previous hardcoded
  // "STO 14:42 · NYSE 08:42" which was theatre, not data.
  const [now, setNow] = React.useState(() => new Date());
  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 60_000);
    return () => clearInterval(t);
  }, []);
  const fmt = (tz) => new Intl.DateTimeFormat('en-GB', {
    timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false,
  }).format(now);

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: isMobile ? '10px 14px' : '12px 24px',
      borderBottom: `1px solid ${CX.line}`, background: CX.bg,
      flex: '0 0 auto', minWidth: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 16, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
          <div style={{ width: 9, height: 9, background: CX.accent }} />
          <Mono style={{ fontSize: 12, color: CX.text, letterSpacing: '0.16em' }}>CORTEX</Mono>
          {!isMobile && (
            <Mono style={{ fontSize: 11, color: CX.faint, letterSpacing: '0.12em' }}>/ {version || '0.1.0'}</Mono>
          )}
        </div>
        {!isMobile && (
          <>
            <div style={{ width: 1, height: 18, background: CX.line }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: CX.accent, boxShadow: `0 0 8px ${CX.accent}` }} />
              <Mono style={{ fontSize: 11, color: CX.dim, letterSpacing: '0.08em' }}>
                {env} · data refreshed {lastBuild}{asof ? ` · asof ${asof}` : ''}
              </Mono>
            </div>
          </>
        )}
      </div>
      {/* On mobile, drop the dual-clock to keep the bar compact. The single
          live-dot indicator stays attached to the wordmark via the brand block. */}
      {!isMobile ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <Mono style={{ fontSize: 11, color: CX.faint, letterSpacing: '0.06em' }}>
            STO {fmt('Europe/Stockholm')} · NYSE {fmt('America/New_York')}
          </Mono>
        </div>
      ) : (
        <Mono style={{ fontSize: 10, color: CX.faint, letterSpacing: '0.06em', flexShrink: 0 }}>
          {fmt('Europe/Stockholm')} CET
        </Mono>
      )}
    </div>
  );
}

function CortexNav({ active, setActive, counts }) {
  const isMobile = useIsMobile();
  counts = counts || {};
  const items = [
    { id: 'queue',     label: 'Research Queue',   short: 'Queue',    shortcut: '1', count: counts.queue ?? null },
    { id: 'tearsheet', label: 'Tear Sheet',       short: 'Tear',     shortcut: '2', count: null },
    { id: 'similar',   label: 'Similar To…',      short: 'Similar',  shortcut: '3', count: null },
    { id: 'backtest',  label: 'Backtest Results', short: 'Backtest', shortcut: '4', count: counts.backtest ?? null },
    { id: 'predictions', label: 'Model Rankings', short: 'Models',   shortcut: '5', count: counts.predictions ?? null },
    { id: 'watchlist', label: 'Watchlist & Notes',short: 'Watch',    shortcut: '6', count: counts.watchlist ?? null },
  ];

  // ── Mobile: horizontal tab strip across the top of the content area.
  // Scrolls horizontally if the labels overflow. No keyboard-shortcut chips,
  // no DATA SCOPE footer — neither has a use on touch devices.
  if (isMobile) {
    return (
      <div style={{
        display: 'flex',
        overflowX: 'auto',
        overflowY: 'hidden',
        borderBottom: `1px solid ${CX.line}`,
        background: CX.bg,
        flex: '0 0 auto',
        WebkitOverflowScrolling: 'touch',
        scrollbarWidth: 'none',
      }}>
        {items.map(i => {
          const on = active === i.id;
          return (
            <button key={i.id} onClick={() => setActive(i.id)}
              style={{
                appearance: 'none', border: 'none',
                padding: '12px 14px',
                flexShrink: 0,
                display: 'flex', alignItems: 'center', gap: 6,
                background: on ? CX.accentVery : 'transparent',
                color: on ? CX.textHi : CX.text,
                cursor: 'pointer',
                borderBottom: `2px solid ${on ? CX.accent : 'transparent'}`,
                transition: 'background .12s, border-color .12s, color .12s',
              }}>
              <span style={{ fontFamily: CX.display, fontSize: 13, whiteSpace: 'nowrap' }}>{i.short}</span>
              {i.count != null && i.count !== '' && (
                <Mono style={{ fontSize: 10, color: on ? CX.accent : CX.faint, letterSpacing: '0.04em' }}>{i.count}</Mono>
              )}
            </button>
          );
        })}
      </div>
    );
  }

  // ── Desktop: original 220px left sidebar. Unchanged.
  return (
    <div style={{
      width: 220, flex: '0 0 220px', borderRight: `1px solid ${CX.line}`,
      background: CX.bg, display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '24px 20px 12px' }}>
        <Mono style={{ fontSize: 10, color: CX.faint, letterSpacing: '0.18em' }}>PAGES</Mono>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {items.map(i => {
          const on = active === i.id;
          return (
            <button key={i.id} onClick={() => setActive(i.id)}
              style={{
                appearance: 'none', border: 'none', textAlign: 'left',
                padding: '10px 20px',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                background: on ? CX.accentVery : 'transparent',
                cursor: 'pointer',
                borderLeft: `2px solid ${on ? CX.accent : 'transparent'}`,
                transition: 'background .12s, border-color .12s',
              }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <Mono style={{ fontSize: 10, color: on ? CX.accent : CX.faint, letterSpacing: '0.08em' }}>{i.shortcut}</Mono>
                <span style={{ fontFamily: CX.display, fontSize: 13, color: on ? CX.textHi : CX.text }}>{i.label}</span>
              </div>
              {i.count && (
                <Mono style={{ fontSize: 10, color: on ? CX.accent : CX.faint, letterSpacing: '0.04em' }}>{i.count}</Mono>
              )}
            </button>
          );
        })}
      </div>

      <div style={{ flex: 1 }} />
      <div style={{ padding: '20px 20px 16px', borderTop: `1px solid ${CX.line}` }}>
        <Mono style={{ fontSize: 10, color: CX.faint, letterSpacing: '0.18em' }}>DATA SCOPE</Mono>
        {(() => {
          const meta = (window.CORTEX_DATA && window.CORTEX_DATA.META) || {};
          const ph = window.CORTEX_DATA?.PRICE_HISTORY || {};
          const rows = (window.CORTEX_DATA?.ROWS) || [];
          const rowsByModel = (window.CORTEX_DATA?.PREDICTIONS || {}).rows_by_model || {};
          const fields = [
            ['as-of',     meta.asof || '—',                       CX.text],
            ['queue',     `${rows.length} bucketed`,              CX.text],
            ['prices to', (ph.dates && ph.dates[ph.dates.length - 1]) || '—', CX.text],
            ['models',    `${Object.keys(rowsByModel).length} live`, CX.text],
          ];
          return (
            <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {fields.map(([k, v, c], i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Mono style={{ fontSize: 11, color: CX.dim }}>{k}</Mono>
                  <Mono style={{ fontSize: 11, color: c }}>{v}</Mono>
                </div>
              ))}
            </div>
          );
        })()}
      </div>
    </div>
  );
}

window.CortexTopbar = CortexTopbar;
window.CortexNav = CortexNav;
