// Screen 4 — Dashboard / History, and the App root

const { useState: Sd, useEffect: Ed, useRef: Rd, useMemo: Md } = React;

function DashboardHome({ t, onOpenAudit, onNewAudit, onLaunchTour }) {
  const [filter, setFilter] = Sd('all');
  const [query, setQuery] = Sd('');

  const audits = window.DAEV_AUDITS || [];

  // Sentinel column: the racecond row (or fallback: first UNSAFE row) is
  // the one that'll show the ⚠ drift state. Computed once against the
  // full list so the marker doesn't move when filters change.
  const driftAudit = audits.find(a => a.fix === 'racecond')
                     || audits.find(a => a.verdict === 'UNSAFE');
  const driftAuditId = driftAudit ? driftAudit.id : null;

  const filtered = audits.filter(a => {
    if (filter === 'unsafe' && a.verdict !== 'UNSAFE') return false;
    if (filter === 'safe' && a.verdict !== 'SAFE') return false;
    if (filter === 'review' && a.verdict !== 'NEEDS_REVIEW') return false;
    if (query && !a.title.toLowerCase().includes(query.toLowerCase()) && !a.id.includes(query)) return false;
    return true;
  });

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background: t.bg0, position:'relative' }}>
      {/* Aggregate stats header */}
      <div style={{
        padding: '24px 24px 20px',
        borderBottom:`1px solid ${t.line}`,
        display:'flex', alignItems:'flex-end', gap: 32,
      }}>
        <div style={{ flex:1 }}>
          <div style={{
            fontFamily: t.font.mono, fontSize: 10,
            color: t.fg2, letterSpacing: 1, textTransform:'uppercase',
          }}>arbiter · workspace</div>
          <div style={{
            fontFamily: t.font.ui, fontSize: 26, fontWeight: 600,
            color: t.fg0, letterSpacing: -0.5, marginTop: 4,
          }}>Recent audits</div>
        </div>

        <AggStat t={t} label="audits run" value="1,247" delta="+12 today"/>
        <AggStat t={t} label="findings caught" value="312" delta="+3 today"
          tooltip="Avg latency · fast 5.8s · full 41s"/>
        <Button t={t} variant="primary" size="lg"
          onClick={onNewAudit}
          icon={<Icon name="plus" size={13} color={t.mode==='dark'?'oklch(0.14 0.01 240)':'white'}/>}>
          New audit
        </Button>
      </div>

      {/* Demo data credibility tag — converts mock-data concession into
          a "Connect your repo" conversion path. */}
      <div style={{
        padding: '8px 24px',
        background: `color-mix(in srgb, ${t.accent.base} 6%, ${t.bg0})`,
        borderBottom: `1px solid ${t.line}`,
        fontFamily: t.font.mono, fontSize: 11, color: t.fg2,
        letterSpacing: 0.4,
        display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: '50%',
          background: t.accent.base,
        }}/>
        <span style={{ color: t.accent.base, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>// demo data</span>
        <span>· Click any audit row to inspect findings</span>
        <span style={{ flex: 1 }}/>
        {onLaunchTour && (
          <button onClick={onLaunchTour}
            style={{
              background:'transparent', border:'none',
              fontFamily: t.font.mono, fontSize: 11, fontWeight: 600,
              color: t.accent.base, cursor:'pointer',
              padding: '4px 8px', letterSpacing: 0.4,
              textDecoration:'underline', textUnderlineOffset: 3,
              textDecorationStyle: 'dotted',
            }}>Take the tour</button>
        )}
        <a href="/" onClick={() => { try { window.DAEV_TRACK && window.DAEV_TRACK('connect_repo_clicked'); } catch(_){} }}
          style={{
            fontFamily: t.font.mono, fontSize: 11, fontWeight: 700,
            color: '#ffffff', textDecoration: 'none',
            background: t.accent.base,
            padding: '5px 12px',
            borderRadius: t.radius.sm,
            letterSpacing: 0.4,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
          Connect your repo
          <Icon name="arrow_r" size={11} color="#ffffff"/>
        </a>
      </div>

      {/* (Onboarding tour relocated to ResultDashboard graph pane — that's the
          moment a first-time visitor needs orientation, not the dashboard.) */}

      {/* Filter bar */}
      <div style={{
        padding: '12px 24px',
        borderBottom:`1px solid ${t.line}`,
        display:'flex', alignItems:'center', gap: 12,
      }}>
        <div style={{
          display:'flex', alignItems:'center', gap: 8,
          background: t.bg1, border:`1px solid ${t.line}`,
          borderRadius: t.radius.sm,
          padding:'6px 10px', flex: '0 0 280px',
        }}>
          <Icon name="search" size={13} color={t.fg2}/>
          <input value={query} onChange={e=>setQuery(e.target.value)}
            placeholder="search audits, handlers, audit_id…"
            style={{
              flex:1, background:'transparent', border:'none', outline:'none',
              fontFamily: t.font.mono, fontSize: 12, color: t.fg0,
            }}/>
        </div>
        <Segmented t={t} value={filter} onChange={setFilter} options={[
          { value:'all',    label:'All' },
          { value:'unsafe', label:'Unsafe' },
          { value:'review', label:'Needs review' },
          { value:'safe',   label:'Safe' },
        ]}/>
        <div style={{ flex:1 }}/>
        <div style={{
          fontFamily: t.font.mono, fontSize: 11, color: t.fg2,
        }}>{filtered.length} of {audits.length}</div>
      </div>

      {/* WHAT'S COMING strip — discoverability for Aegis (Q3) + Sentinel (Q4) */}
      <div style={{
        margin: '10px 24px 0',
        padding: '8px 14px',
        border: `1px solid ${t.accent.base}`,
        background: `color-mix(in oklch, ${t.accent.base} 6%, ${t.bg0})`,
        borderRadius: t.radius.sm,
        fontFamily: t.font.mono, fontSize: 11, color: t.fg2,
        display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap',
        letterSpacing: 0.3,
      }}>
        <span style={{
          color: t.accent.base, fontWeight: 700,
          letterSpacing: 1.2, textTransform: 'uppercase',
        }}>// COMING NEXT</span>
        <span style={{ color: t.fg3 }}>•</span>
        <span><b style={{ color: t.fg0, letterSpacing: 0.6 }}>AEGIS Q3</b> · Causal identity for every agent action</span>
        <span style={{ color: t.fg3 }}>•</span>
        <span><b style={{ color: t.fg0, letterSpacing: 0.6 }}>SENTINEL Q4</b> · Continuous post-ship drift monitoring</span>
        <span style={{ flex: 1 }}/>
        <a href="/" onClick={() => { try { window.DAEV_TRACK && window.DAEV_TRACK('whats_coming_clicked', { from: 'dashboard' }); } catch(_){} }}
          style={{
            fontFamily: t.font.mono, fontSize: 11, fontWeight: 700,
            color: t.accent.base, textDecoration: 'none',
            letterSpacing: 0.4,
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>→ Join waitlist</a>
      </div>

      {/* Table */}
      <div data-tour="audit-table" style={{ flex:1, overflow:'auto' }}>
        <table style={{
          width:'100%', borderCollapse:'collapse',
          fontFamily: t.font.ui, fontSize: 13,
        }}>
          <thead>
            <tr style={{
              borderBottom:`1px solid ${t.line}`,
              fontFamily: t.font.mono, fontSize: 10, color: t.fg2,
              letterSpacing: 1, textTransform:'uppercase',
            }}>
              {[
                { k:'verdict',  tip:'UNSAFE / SAFE / REVIEW — DAEV final verdict' },
                { k:'audit',    tip:'File path · function name' },
                { k:'audit_id', tip:'Stable identifier — share with /demo?audit={id}' },
                { k:'mode',     tip:'fast = single-pass causal trace · full = 5-agent council' },
                { k:'lang',     tip:'Source language' },
                { k:'duration', tip:'End-to-end audit time, source → signed evidence' },
                { k:'nodes',    tip:'Causal graph node count for this audit' },
                { k:'taint',    tip:'Hops = causal chain length from source to sink. — = no taint flow.' },
                { k:'llm%',     tip:'LLM-influence: how much of the verdict relied on language-model reasoning vs deterministic graph analysis. Neutral data — neither high nor low is "better".' },
                { k:'when',     tip:'Relative time of audit run' },
                { k:'sentinel', tip:'Sentinel post-deploy monitor (Q4 2026 preview) · drift / armed / n/a' },
                { k:'',         tip:'' },
              ].map(({ k, tip }) => (
                <th key={k}
                  title={tip || undefined}
                  style={{
                    textAlign:'left', padding:'10px 16px', fontWeight:500,
                    cursor: tip ? 'help' : 'default',
                    textDecoration: tip ? 'underline dotted' : 'none',
                    textDecorationColor: t.line2,
                    textUnderlineOffset: 3,
                  }}>{k === 'taint' ? 'taint' : k}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr>
                <td colSpan={12} style={{
                  padding: '60px 24px',
                  textAlign: 'center',
                  fontFamily: t.font.mono, fontSize: 12, color: t.fg2,
                  letterSpacing: 0.4,
                }}>
                  <span style={{ color: t.accent.base, fontWeight: 700, letterSpacing: 1, textTransform:'uppercase' }}>// no matches</span>
                  <span style={{ display:'block', marginTop: 6, color: t.fg3 }}>
                    No audits match this filter{query ? ` and search "${query}"` : ''}.
                  </span>
                </td>
              </tr>
            ) : (
              filtered.map(a => (
                <AuditRow key={a.id} t={t} audit={a} isDrift={a.id === driftAuditId} onOpen={() => onOpenAudit(a)}/>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AggStat({ t, label, value, delta, tooltip }) {
  return (
    <div title={tooltip || undefined} style={{ position:'relative' }}>
      <div style={{
        fontFamily: t.font.mono, fontSize: 9,
        color: t.fg2, letterSpacing: 1, textTransform:'uppercase',
        display:'inline-flex', alignItems:'center', gap: 6,
      }}>
        {label}
        {tooltip && (
          <span style={{
            display:'inline-flex', alignItems:'center', justifyContent:'center',
            width: 12, height: 12, borderRadius:'50%',
            border: `1px solid ${t.line2}`,
            color: t.fg2,
            fontFamily: t.font.mono, fontSize: 9, fontWeight: 700,
            cursor: 'help',
          }}>i</span>
        )}
      </div>
      <div style={{
        fontFamily: t.font.ui, fontSize: 22, fontWeight: 600,
        color: t.fg0, letterSpacing: -0.5, marginTop: 2,
        fontVariantNumeric:'tabular-nums',
      }}>{value}</div>
      {delta && (
        <div style={{
          fontFamily: t.font.mono, fontSize: 10, color: t.semantic.green,
          marginTop: 2,
        }}>{delta}</div>
      )}
    </div>
  );
}

function AuditRow({ t, audit, isDrift, onOpen }) {
  const [hover, setHover] = Sd(false);
  const v = audit.verdict;
  const vTone = v === 'UNSAFE' ? 'red' : v === 'SAFE' ? 'green' : 'amber';
  const hasFinding = v === 'UNSAFE' || v === 'NEEDS_REVIEW';
  return (
    <tr onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      onClick={onOpen}
      style={{
        borderBottom:`1px solid ${t.line}`,
        cursor:'pointer',
        background: hover ? t.bg1 : 'transparent',
      }}>
      <td style={{ padding:'12px 16px' }}>
        <Chip t={t} tone={vTone} size="sm">{v === 'NEEDS_REVIEW' ? 'REVIEW' : v}</Chip>
      </td>
      <td style={{ padding:'12px 16px', color: t.fg0, fontWeight: 500 }}>{audit.title}</td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5, color: t.fg2 }}>{audit.id}</td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5, color: t.fg1 }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap: 4 }}>
          <Icon name={audit.mode==='fast'?'zap':'brain'} size={11} color={t.fg2}/>
          {audit.mode}
        </span>
      </td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5, color: t.fg1 }}>{audit.lang}</td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5, color: t.fg1, fontVariantNumeric:'tabular-nums' }}>{audit.dur}</td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5, color: t.fg1, fontVariantNumeric:'tabular-nums' }}>{audit.nodes}</td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5,
        color: audit.hops>0 ? t.semantic.red : t.fg2, fontVariantNumeric:'tabular-nums' }}>
        {audit.hops>0 ? `${audit.hops} hops` : '—'}
      </td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11.5,
        color: t.fg1, fontVariantNumeric:'tabular-nums' }}
        title="LLM-influence: how much of the verdict relied on language-model reasoning vs deterministic graph analysis. Neutral data — neither high nor low is 'better'.">
        {audit.llm != null ? `${audit.llm}%` : '—'}
      </td>
      <td style={{ padding:'12px 16px', fontFamily: t.font.mono, fontSize: 11, color: t.fg2 }}>{audit.ts}</td>
      <td style={{ padding:'12px 16px' }}>
        {isDrift ? (
          <span title="Sentinel detected a validate-then-use regression 3 commits after deployment. Alert fired in 4s."
            style={{
              color: t.semantic.amber, fontFamily: t.font.mono,
              fontSize: 11, fontWeight: 700, cursor: 'help',
            }}>⚠ drift</span>
        ) : hasFinding ? (
          <span style={{ color: t.semantic.green, fontFamily: t.font.mono, fontSize: 11 }}>● armed</span>
        ) : (
          <span style={{ color: t.fg3, fontFamily: t.font.mono, fontSize: 11 }}>○ n/a</span>
        )}
      </td>
      <td style={{ padding:'12px 16px', color: t.fg3 }}>
        <Icon name="chevR" size={14} color={hover ? t.accent.base : t.fg3}/>
      </td>
    </tr>
  );
}

Object.assign(window, { DashboardHome });
