// Dashboard — status hero + alert list / history, all fed by the live backend.
// The hero never lies (zero-info anxiety, Brief §3): three honest states —
//   loading  → CONNECTING…            (gray dot, no claims)
//   offline  → FEED UNREACHABLE       (yellow dot — an app-health warning)
//   live     → clean / severity summary + WATCHING N · LAST SCAN
// There is no sample data and no demo toggle anymore: what you see is the feed.
function Dashboard({
  t, lang, setLang, selected, setSelected, feed,
  theme, setTheme, session, me, refreshMe, onConnect, onLogout,
}) {
  const { STACK_ITEMS } = window.EchoWatchData;
  const { relativeTime } = window.EchoWatchI18n;
  const [tab, setTab] = React.useState('alerts'); // 'alerts' | 'history'
  const [settingsOpen, setSettingsOpen] = React.useState(false);

  const loading = feed === undefined;
  const live = !!(feed && Array.isArray(feed.alerts));
  const alertsSrc = live ? feed.alerts : [];
  const historyItems = live ? (feed.history || []) : [];
  const lastScanIso = live ? feed.lastScanAt : null;

  const nameOf = (id) => (STACK_ITEMS.find(s => s.id === id) || {}).name || id;
  const visible = alertsSrc.filter(a => selected.length === 0 || selected.includes(a.stack));
  const counts = {
    breaking: visible.filter(a => a.severity === 'breaking').length,
    advisory: visible.filter(a => a.severity === 'advisory').length,
    info: visible.filter(a => a.severity === 'info').length,
  };
  const order = { breaking: 0, advisory: 1, info: 2 };
  const sorted = [...visible].sort((a, b) => order[a.severity] - order[b.severity]);

  const topSeverity = counts.breaking ? 'breaking' : counts.advisory ? 'advisory' : counts.info ? 'info' : null;
  const heroColor = topSeverity ? window.SEV[topSeverity].color : 'var(--status-ok)';
  const countsLine = ['breaking', 'advisory', 'info']
    .filter(k => counts[k] > 0)
    .map(k => `${counts[k]} ${window.SEV[k].label}`)
    .join(' · ');
  const watchingLine = selected.length === 0
    ? t('hero.watching.all')
    : t('hero.watching', { n: selected.length });
  const scanLine = t('hero.lastScan', { t: lastScanIso ? relativeTime(t, lastScanIso) : '—' });

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-primary)', color: 'var(--text-primary)' }}>
      <header style={{ borderBottom: '1px solid var(--border-color)' }}>
        <div className="ew-header" style={{ padding: '16px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--text-primary)' }}>
            <window.EchoWatchLogo height={26} />
            <span style={{ fontSize: 9, color: 'var(--text-secondary)', letterSpacing: '0.15em' }}>V1</span>
          </div>
          <div className="ew-header-right" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <button onClick={() => setSettingsOpen(true)} style={{
              height: 30, padding: '0 12px', borderRadius: 8, border: '1px solid var(--border-color)',
              background: 'transparent', color: 'var(--text-secondary)', cursor: 'pointer',
              fontSize: 9, fontWeight: 700, letterSpacing: '0.15em', textTransform: 'uppercase',
            }}>{t('settings.title')}</button>
            <button onClick={() => setTheme(th => th === 'dark' ? 'light' : 'dark')}
              aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'} style={{
                width: 30, height: 30, borderRadius: 8, border: '1px solid var(--border-color)',
                background: 'transparent', color: 'var(--text-secondary)', cursor: 'pointer', fontSize: 12,
              }}>◐</button>
            {window.EWApi.hasApi() && (
              session ? (
                <button onClick={onLogout} title={t('disconnect')} style={{
                  height: 30, padding: '0 12px', borderRadius: 9999, border: '1px solid var(--text-primary)',
                  background: 'var(--text-primary)', color: 'var(--bg-primary)', cursor: 'pointer',
                  fontSize: 9, fontWeight: 700, letterSpacing: '0.1em',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  <span className="dot-breathe" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--status-ok)' }} />
                  {session.stake.slice(0, 10).toUpperCase()}…
                </button>
              ) : (
                <button onClick={onConnect} style={{
                  height: 30, padding: '0 14px', borderRadius: 9999, border: '1px solid var(--text-primary)',
                  background: 'transparent', color: 'var(--text-primary)', cursor: 'pointer',
                  fontSize: 9, fontWeight: 700, letterSpacing: '0.15em', textTransform: 'uppercase',
                }}>{t('connect')}</button>
              )
            )}
          </div>
        </div>
      </header>

      <main style={{ width: '100%', maxWidth: 720, margin: '0 auto', padding: '32px 20px 80px', flex: 1 }}>
        {/* status hero — three honest states */}
        <div className="ew-card fade-up" style={{ padding: '32px 24px', borderRadius: 20, textAlign: 'center', marginBottom: 32 }}>
          <span className="corner-tl" /><span className="corner-tr" /><span className="corner-bl" /><span className="corner-br" />
          {loading ? (
            <>
              <div style={{ display: 'inline-flex', width: 12, height: 12, borderRadius: '50%', background: 'var(--text-secondary)', marginBottom: 16 }} />
              <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: 'var(--text-secondary)' }}>{t('feed.loading')}</h1>
            </>
          ) : !live ? (
            <>
              <div style={{ display: 'inline-flex', width: 12, height: 12, borderRadius: '50%', background: 'var(--sev-advisory)', marginBottom: 16 }} />
              <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700 }}>{t('hero.offline.title')}</h1>
              <p style={{ margin: '8px 0 0', fontSize: 12, color: 'var(--text-secondary)', letterSpacing: '0.05em' }}>{t('hero.offline.sub')}</p>
            </>
          ) : !topSeverity ? (
            <>
              {/* Silence is the default — one breathing dot, nothing else moves. */}
              <div className="dot-breathe" style={{ display: 'inline-flex', width: 12, height: 12, borderRadius: '50%', background: 'var(--status-ok)', marginBottom: 16 }} />
              <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700 }}>{t('hero.clean.title')}</h1>
              <p style={{ margin: '8px 0 0', fontSize: 12, color: 'var(--text-secondary)', letterSpacing: '0.05em' }}>{t('hero.clean.sub')}</p>
            </>
          ) : (
            <>
              {/* No extra motion on alerts — red is already loud enough (Brief §4). */}
              <div style={{ display: 'inline-flex', width: 12, height: 12, borderRadius: '50%', background: heroColor, marginBottom: 16 }} />
              <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: heroColor }}>{t(`hero.${topSeverity}.title`)}</h1>
              <p style={{ margin: '8px 0 0', fontSize: 12, color: 'var(--text-secondary)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{countsLine}</p>
            </>
          )}
          {live && (
            <p style={{ margin: '16px 0 0', fontSize: 9, letterSpacing: '0.15em', color: 'var(--text-secondary)', opacity: 0.7, textTransform: 'uppercase' }}>
              {watchingLine} · {scanLine}
            </p>
          )}
        </div>

        {/* tabs */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid var(--border-color)' }}>
          {[['alerts', t('tab.alerts')], ['history', t('tab.history')]].map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              padding: '10px 4px', marginRight: 20, background: 'none', border: 'none', cursor: 'pointer',
              borderBottom: '2px solid', borderColor: tab === id ? 'var(--text-primary)' : 'transparent',
              color: tab === id ? 'var(--text-primary)' : 'var(--text-secondary)',
              fontSize: 12, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
            }}>{label}</button>
          ))}
        </div>

        {tab === 'alerts' ? (
          sorted.length === 0 ? (
            <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--text-secondary)', opacity: 0.6, padding: '20px 0' }}>
              {live ? t('alerts.empty') : t('feed.loading')}
            </p>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {sorted.map(a => <window.AlertCard key={a.id} t={t} alert={a} stackName={nameOf(a.stack)} />)}
            </div>
          )
        ) : (
          <window.HistoryPanel t={t} items={historyItems} />
        )}
      </main>

      <footer style={{ padding: 20, textAlign: 'center', borderTop: '1px solid var(--border-color)' }}>
        <div style={{ display: 'flex', gap: 16, justifyContent: 'center', marginBottom: 10, flexWrap: 'wrap' }}>
          {[['tos.html', 'Terms of Service'], ['privacy.html', 'Privacy Policy'], ['cookies.html', 'Cookie Policy']].map(([href, label]) => (
            <a key={href} href={href} style={{ fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-secondary)', textDecoration: 'none' }}>{label}</a>
          ))}
        </div>
        <p style={{ margin: 0, fontSize: 9, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>ECHOFORGE ECHOWATCH · {t('tagline')}</p>
      </footer>

      <window.SettingsPanel
        open={settingsOpen} onClose={() => setSettingsOpen(false)}
        t={t} lang={lang} setLang={setLang}
        selected={selected} setSelected={setSelected}
        session={session} me={me} refreshMe={refreshMe}
      />
    </div>
  );
}
window.Dashboard = Dashboard;
