// Dashboard — status hero + alert list / history. The hero must always prove
// the system is alive: even the clean state shows what is being watched and
// when the last scan ran (zero-info anxiety, Brief §3).
// Alerts come from the live backend feed when configured; otherwise the
// bundled sample data renders with an explicit SAMPLE DATA tag — honesty
// beats a blank or a fake-live screen.
function Dashboard({
  t, lang, setLang, selected, setSelected, feed, scenario, setScenario,
  theme, setTheme, session, me, refreshMe, onConnect, onLogout,
}) {
  const { STACK_ITEMS, ALERTS, LAST_SCAN } = window.EchoWatchData;
  const { relativeTime } = window.EchoWatchI18n;
  const [tab, setTab] = React.useState('alerts'); // 'alerts' | 'history'
  const [settingsOpen, setSettingsOpen] = React.useState(false);

  const live = !!(feed && Array.isArray(feed.alerts));
  const sourceAlerts = live ? feed.alerts : ALERTS;
  const lastScanIso = live ? feed.lastScanAt : LAST_SCAN;

  const nameOf = (id) => (STACK_ITEMS.find(s => s.id === id) || {}).name || id;
  const visible = scenario === 'clean' ? [] : sourceAlerts.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={20} />
            <span style={{ fontSize: 9, color: 'var(--text-secondary)', letterSpacing: '0.15em' }}>V0.2</span>
          </div>
          <div className="ew-header-right" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            {/* Prototype-only affordance: swaps the clean / alert states without a backend. */}
            {!live && (
              <div style={{ display: 'flex', gap: 4, padding: 3, borderRadius: 8, border: '1px solid var(--border-color)' }}>
                {[['clean', 'DEMO:CLEAN'], ['alerts', 'DEMO:ALERTS']].map(([v, label]) => (
                  <button key={v} onClick={() => setScenario(v)} style={{
                    padding: '5px 10px', borderRadius: 5, border: 'none', cursor: 'pointer',
                    background: scenario === v ? 'var(--text-primary)' : 'transparent',
                    color: scenario === v ? 'var(--bg-primary)' : 'var(--text-secondary)',
                    fontSize: 9, fontWeight: 700, letterSpacing: '0.05em',
                  }}>{label}</button>
                ))}
              </div>
            )}
            <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 */}
        <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" />
          {!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>
            </>
          )}
          <p style={{ margin: '16px 0 0', fontSize: 9, letterSpacing: '0.15em', color: 'var(--text-secondary)', opacity: 0.7, textTransform: 'uppercase' }}>
            {watchingLine} · {scanLine}{!live && <> · {t('feed.sample')}</>}
          </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' }}>{t('alerts.empty')}</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} />
        )}
      </main>

      <footer style={{ padding: 20, textAlign: 'center', borderTop: '1px solid var(--border-color)' }}>
        <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;
