import { Badge } from '@astryxdesign/core/Badge'
import { Button } from '@astryxdesign/core/Button'
import { Card } from '@astryxdesign/core/Card'
import { EmptyState } from '@astryxdesign/core/EmptyState'
import { MultiSelector } from '@astryxdesign/core/MultiSelector'
import { SegmentedControl, SegmentedControlItem } from '@astryxdesign/core/SegmentedControl'
import { Table, proportional, type TableColumn } from '@astryxdesign/core/Table'
import { TextInput } from '@astryxdesign/core/TextInput'
import {
  DetailDrawer,
  SectionCard,
  TimeSeriesChart,
  formatRelativeTime,
  safeHttpUrl,
} from '@overdeck/deck-ui'
import type {
  ActivityReportSection,
  CapacityAccountRecord,
  CapacityReportSection,
  CapacityUsageBreakdown,
  ExecutionReportSection,
  ExecutionRequestRecord,
  ExecutionRunRecord,
  HistoryReportSection,
  HistoricalMetric,
  LineageReportSection,
  LineageStage,
  ObservabilityReport,
  ReportAttentionRecord,
  ReportCoverageStatus,
  ReportSourceCoverage,
  ReliabilityFailureGroup,
  ReliabilityIncidentRecord,
  ReliabilityReportSection,
} from '@overdeck/report-contract'
import { useCallback, useEffect, useId, useMemo, useState, type JSX } from 'react'
import { useActivitySourceEntries, useObservabilityReport } from '../../lib/collector-queries'
import { ObservabilityReportTimeoutError } from '../../lib/collector-client'
import {
  DEFAULT_REPORT_URL_STATE,
  REPORT_RANGE_MS,
  parseReportUrlState,
  serializeReportUrlState,
  type ReportRange,
  type ReportUrlState,
} from '../../lib/report-url-state'
import {
  MAX_SAVED_REPORT_VIEWS,
  SAVED_REPORT_VIEWS_KEY,
  buildReportCsv,
  buildReportJson,
  createSavedReportView,
  parseSavedReportViews,
  reportExportTables,
  savedViewFilters,
  type SavedReportView,
} from '../../lib/report-tools'

type AttentionRow = ReportAttentionRecord & Record<string, unknown>
type SourceRow = ReportSourceCoverage & Record<string, unknown>
type ExecutionRequestRow = ExecutionRequestRecord & Record<string, unknown>
type ExecutionRunRow = ExecutionRunRecord & Record<string, unknown>
type ReliabilityIncidentRow = ReliabilityIncidentRecord & Record<string, unknown>
type ReliabilityFailureRow = ReliabilityFailureGroup & Record<string, unknown>
type CapacityUsageRow = CapacityUsageBreakdown & Record<string, unknown>
type CapacityAccountRow = CapacityAccountRecord & Record<string, unknown>

const COVERAGE_VARIANT: Record<ReportCoverageStatus, 'success' | 'warning' | 'error' | 'neutral'> = {
  complete: 'success',
  partial: 'warning',
  stale: 'warning',
  unavailable: 'error',
}

function coverageLabel(status: ReportCoverageStatus): string {
  if (status === 'complete') return 'Complete coverage'
  if (status === 'partial') return 'Partial coverage'
  if (status === 'stale') return 'Stale data'
  return 'Unavailable'
}

function sourceStatusVariant(status: ReportSourceCoverage['status']): 'success' | 'warning' | 'error' | 'neutral' {
  if (status === 'ok') return 'success'
  if (status === 'error') return 'error'
  if (status === 'stale') return 'warning'
  return 'neutral'
}

function sourceStatusLabel(status: ReportSourceCoverage['status']): string {
  if (status === 'ok') return 'Readable'
  if (status === 'error') return 'Read failed'
  if (status === 'stale') return 'Out of date'
  return 'Not present'
}

function authorityLabel(authority: ReportSourceCoverage['authority']): string {
  return authority === 'authoritative' ? 'Direct record' : 'Calculated record'
}

function severityVariant(severity: ReportAttentionRecord['severity']): 'warning' | 'error' | 'neutral' {
  if (severity === 'error') return 'error'
  if (severity === 'warn') return 'warning'
  return 'neutral'
}

function formatTimestamp(value?: string): string {
  if (!value) return 'Not recorded'
  const parsed = Date.parse(value)
  return Number.isFinite(parsed) ? formatRelativeTime(parsed) : 'Not recorded'
}

function contextLabel(row: Extract<ReportAttentionRecord, { kind: 'event' }>): string {
  return row.project ?? row.host ?? row.runtime ?? row.session ?? row.account ?? 'Not recorded'
}

function updateBrowserUrl(state: ReportUrlState): void {
  const search = serializeReportUrlState(state)
  window.history.replaceState(null, '', `${window.location.pathname}${search}${window.location.hash}`)
}

function downloadReportFile(filename: string, contents: string, type: string): void {
  const url = URL.createObjectURL(new Blob([contents], { type }))
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = filename
  anchor.click()
  window.setTimeout(() => URL.revokeObjectURL(url), 0)
}

function createSavedViewId(): string {
  if (typeof window.crypto.randomUUID === 'function') return window.crypto.randomUUID().replaceAll('-', '')
  const bytes = window.crypto.getRandomValues(new Uint8Array(16))
  return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')
}

function lineageStageVariant(status: LineageStage['status']): 'success' | 'warning' | 'error' {
  if (status === 'recorded') return 'success'
  if (status === 'failed') return 'error'
  return 'warning'
}

function MetricCard({ metric }: { metric: ActivityReportSection['metrics'][number] }): JSX.Element {
  const value = metric.value === null ? 'Unavailable' : metric.value.toLocaleString()
  const detail = metric.denominator !== undefined
    ? `${metric.numerator ?? 0} of ${metric.denominator}`
    : coverageLabel(metric.coverage)
  return (
    <Card padding={4} minHeight="100%">
      <div className="flex h-full flex-col justify-between gap-3">
        <div>
          <p className="text-sm font-medium text-fg-muted">{metric.label}</p>
          <p className="mt-1 text-2xl font-semibold text-fg tabular-nums">{value}</p>
        </div>
        <p className="text-xs text-fg-subtle">{detail}</p>
      </div>
    </Card>
  )
}

function CoverageSummary({ report }: { report: ObservabilityReport }): JSX.Element {
  const from = new Date(report.coverage.from).toLocaleString()
  const to = new Date(report.coverage.to).toLocaleString()
  return (
    <Card padding={4} variant={report.coverage.status === 'complete' ? 'muted' : 'yellow'}>
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-base font-semibold text-fg">Data coverage</h2>
            <Badge variant={COVERAGE_VARIANT[report.coverage.status]} label={coverageLabel(report.coverage.status)} />
          </div>
          <p className="mt-1 text-sm text-fg-muted">{from} to {to}</p>
          <p className="mt-1 text-xs text-fg-subtle">Updated {formatTimestamp(report.generatedAt)}</p>
        </div>
        <p className="text-sm text-fg-muted">
          {report.coverage.gaps.length === 0
            ? 'Every selected authoritative source covers the full report window.'
            : `${report.coverage.gaps.length.toLocaleString()} coverage ${report.coverage.gaps.length === 1 ? 'gap' : 'gaps'} named below.`}
        </p>
      </div>
      {report.coverage.gaps.length > 0 ? (
        <ul className="mt-4 grid gap-2 text-sm text-fg-muted">
          {report.coverage.gaps.map((gap, index) => (
            <li key={`${gap.sourceId ?? 'report'}:${gap.metric ?? 'all'}:${index}`} className="rounded-md border border-border bg-surface px-3 py-2">
              {gap.reason}
            </li>
          ))}
        </ul>
      ) : null}
    </Card>
  )
}

function EvidenceDrawer({ selected, sourceLabel, onClose }: { selected: ReportAttentionRecord | null; sourceLabel: string; onClose(): void }): JSX.Element | null {
  const titleId = useId()
  const evidence = selected?.evidenceQuery
  const query = useActivitySourceEntries({
    sourceId: evidence?.sourceId ?? '',
    from: evidence?.from,
    to: evidence?.to,
    severity: evidence?.severity,
    q: evidence?.q,
    recordId: evidence?.recordId,
    offset: 0,
    limit: 50,
  }, selected !== null, false)

  if (!selected) return null
  const sourceParams = new URLSearchParams()
  if (evidence?.from) sourceParams.set('from', evidence.from)
  if (evidence?.to) sourceParams.set('to', evidence.to)
  if (evidence?.recordId) sourceParams.set('event', evidence.recordId)
  const sourceHref = `/logs/${encodeURIComponent(selected.sourceId)}?${sourceParams.toString()}`

  return (
    <DetailDrawer eyebrow="Recorded evidence" title={selected.title} titleId={titleId} onClose={onClose} size="wide">
      <div className="grid gap-4 pt-4">
        <Card padding={3} variant="muted">
          <dl className="grid gap-2 text-sm sm:grid-cols-2">
            <div><dt className="text-fg-subtle">Source</dt><dd className="font-medium text-fg">{sourceLabel}</dd></div>
            <div><dt className="text-fg-subtle">Severity</dt><dd className="font-medium text-fg">{selected.severity}</dd></div>
            {selected.kind === 'event' ? <div><dt className="text-fg-subtle">Recorded</dt><dd className="font-medium text-fg">{new Date(selected.ts).toLocaleString()}</dd></div> : null}
            {selected.kind === 'event' ? <div><dt className="text-fg-subtle">Context</dt><dd className="font-medium text-fg">{contextLabel(selected)}</dd></div> : null}
            {selected.kind !== 'event' ? <div className="sm:col-span-2"><dt className="text-fg-subtle">What happened</dt><dd className="font-medium text-fg">{selected.reason}</dd></div> : null}
          </dl>
        </Card>
        <div className="flex flex-wrap gap-2">
          <Button label="Open source records" href={sourceHref} variant="secondary" />
          <Button label="Refresh evidence" onClick={() => { void query.refetch() }} variant="secondary" isLoading={query.isFetching} />
        </div>
        {query.isLoading ? <p className="text-sm text-fg-muted">Loading recorded evidence…</p> : null}
        {query.isError ? (
          <EmptyState title="Evidence could not be loaded" description="The report remains visible. Retry this evidence query or open the source records." isCompact />
        ) : null}
        {query.data ? (
          <div className="grid gap-3">
            {query.data.events.length === 0 && query.data.skipped.length === 0 ? (
              <EmptyState title="No matching records" description="The source answered, but no retained record matches this evidence query." isCompact />
            ) : null}
            {query.data.events.map((event) => (
              <Card key={event.id} padding={3}>
                <div className="flex flex-wrap items-center gap-2">
                  <Badge variant={event.severity === 'error' ? 'error' : event.severity === 'warn' ? 'warning' : 'neutral'} label={event.severity} />
                  <time className="text-xs text-fg-subtle" dateTime={event.ts}>{new Date(event.ts).toLocaleString()}</time>
                </div>
                <p className="mt-2 text-sm font-medium text-fg">{event.title}</p>
                <p className="mt-1 text-xs text-fg-muted">{event.project ?? event.host ?? event.runtime ?? event.session ?? 'No additional context recorded'}</p>
              </Card>
            ))}
            {query.data.skipped.map((skipped) => (
              <Card key={skipped.id} padding={3} variant="yellow">
                <p className="text-sm font-medium text-fg">Skipped retained record</p>
                <p className="mt-1 text-sm text-fg-muted">{skipped.explanation}</p>
              </Card>
            ))}
          </div>
        ) : null}
      </div>
    </DetailDrawer>
  )
}

function formatDuration(value: number | null): string {
  if (value === null) return 'Not recorded'
  if (value < 60_000) return `${Math.round(value / 1000).toLocaleString()} sec`
  if (value < 3_600_000) return `${Math.round(value / 60_000).toLocaleString()} min`
  return `${(value / 3_600_000).toFixed(1)} hr`
}

function executionOutcomeLabel(outcome: ExecutionRunRecord['outcome']): string {
  if (outcome === 'succeeded') return 'Succeeded'
  if (outcome === 'failed') return 'Failed'
  if (outcome === 'running') return 'Running'
  if (outcome === 'cancelled') return 'Cancelled'
  return 'Not recorded'
}

function executionOutcomeVariant(outcome: ExecutionRunRecord['outcome']): 'success' | 'warning' | 'error' | 'neutral' {
  if (outcome === 'succeeded') return 'success'
  if (outcome === 'failed') return 'error'
  if (outcome === 'running') return 'warning'
  return 'neutral'
}

function requestStateLabel(state: ExecutionRequestRecord['state']): string {
  if (state === 'in_flight') return 'In progress'
  if (state === 'blocked_needs_owner') return 'Needs owner'
  if (state === 'shipped') return 'Shipped'
  return 'Asked'
}

function RequestExecutionDrawer({ selected, run, onClose }: {
  selected: ExecutionRequestRecord | null
  run: ExecutionRunRecord | undefined
  onClose(): void
}): JSX.Element | null {
  const titleId = useId()
  if (!selected) return null
  return (
    <DetailDrawer eyebrow="Delivery story" title={selected.title} titleId={titleId} onClose={onClose} size="wide">
      <div className="grid gap-4 pt-4">
        <Card padding={3} variant="muted">
          <dl className="grid gap-3 text-sm sm:grid-cols-2">
            <div><dt className="text-fg-subtle">Asked</dt><dd className="font-medium text-fg">{new Date(selected.askedAt).toLocaleString()}</dd></div>
            <div><dt className="text-fg-subtle">Current state</dt><dd className="font-medium text-fg">{requestStateLabel(selected.state)}</dd></div>
            <div><dt className="text-fg-subtle">Factory run</dt><dd className="font-medium text-fg">{run ? executionOutcomeLabel(run.outcome) : selected.correlationReason ?? 'Not linked'}</dd></div>
            <div><dt className="text-fg-subtle">Run duration</dt><dd className="font-medium text-fg">{run ? formatDuration(run.durationMs) : 'Not recorded'}</dd></div>
            <div><dt className="text-fg-subtle">Landed</dt><dd className="font-medium text-fg">{selected.delivery.landedAt ? new Date(selected.delivery.landedAt).toLocaleString() : 'Not recorded'}</dd></div>
            <div><dt className="text-fg-subtle">Deployed</dt><dd className="font-medium text-fg">{selected.delivery.deployedAt ? new Date(selected.delivery.deployedAt).toLocaleString() : 'Not recorded'}</dd></div>
            <div><dt className="text-fg-subtle">Owner proof</dt><dd className="font-medium text-fg">{selected.delivery.proofRecorded ? 'Recorded' : 'Not recorded'}</dd></div>
            {run ? <div><dt className="text-fg-subtle">Recorded work</dt><dd className="font-medium text-fg">{run.changedFiles.toLocaleString()} files · {run.insertions === null ? 'additions not recorded' : `${run.insertions.toLocaleString()} additions`} · {run.deletions === null ? 'deletions not recorded' : `${run.deletions.toLocaleString()} deletions`}</dd></div> : null}
            {run ? <div><dt className="text-fg-subtle">Attempts</dt><dd className="font-medium text-fg">{run.attempts.toLocaleString()} attempts · {run.retries.toLocaleString()} retries · {run.toolCalls.toLocaleString()} tool calls</dd></div> : null}
            {run ? <div><dt className="text-fg-subtle">Models</dt><dd className="font-medium text-fg">{run.models.join(', ') || 'Not recorded'}</dd></div> : null}
            {run ? <div><dt className="text-fg-subtle">Accounts</dt><dd className="font-medium text-fg">{run.accounts.join(', ') || 'Not recorded'}</dd></div> : null}
            {run ? <div><dt className="text-fg-subtle">Sessions</dt><dd className="font-medium text-fg">{run.sessions.join(', ') || 'Not recorded'}</dd></div> : null}
            {run ? <div><dt className="text-fg-subtle">Hosts</dt><dd className="font-medium text-fg">{run.hosts.join(', ') || 'Not recorded'}</dd></div> : null}
          </dl>
        </Card>
        {run ? (
          <SectionCard title="Recorded phases" titleBadge={run.phases.length.toLocaleString()}>
            {run.phases.length === 0 ? <EmptyState title="No phase detail retained" description="The run exists, but no phase records are available." isCompact /> : (
              <ul className="grid gap-2">
                {run.phases.map((phase, index) => (
                  <li key={`${phase.label}:${index}`} className="rounded-md border border-border px-3 py-2 text-sm">
                    <div className="flex flex-wrap items-center justify-between gap-2"><strong className="text-fg">{phase.label}</strong><span className="text-fg-muted">{formatDuration(phase.durationMs)}</span></div>
                    <p className="mt-1 text-xs text-fg-subtle">{phase.retries ?? 0} retries · {phase.gateFailed} failed checks · {phase.toolCalls} tool calls</p>
                  </li>
                ))}
              </ul>
            )}
          </SectionCard>
        ) : null}
        <div className="flex flex-wrap gap-2">
          <Button label="Open request" href={safeHttpUrl(selected.requestHref)} variant="secondary" />
          {run ? <Button label="Open factory run" href={safeHttpUrl(run.href)} variant="secondary" /> : null}
          {selected.proofHref ? <Button label="Open owner proof" href={safeHttpUrl(selected.proofHref)} variant="secondary" /> : null}
        </div>
      </div>
    </DetailDrawer>
  )
}

function ExecutionReport({ section }: { section: ExecutionReportSection }): JSX.Element {
  const [selected, setSelected] = useState<ExecutionRequestRecord | null>(null)
  const runById = useMemo(() => new Map(section.runs.map((run) => [run.id, run])), [section.runs])
  useEffect(() => {
    if (!selected) return
    const current = section.requests.find((row) => row.id === selected.id) ?? null
    if (current !== selected) setSelected(current)
  }, [section.requests, selected])

  const requestColumns = useMemo<TableColumn<ExecutionRequestRow>[]>(() => [
    { key: 'title', header: 'Request', width: proportional(3), renderCell: (row) => <div><p className="font-medium text-fg">{row.title}</p><p className="mt-1 text-xs text-fg-subtle">{row.project}</p></div> },
    { key: 'state', header: 'State', width: proportional(1), renderCell: (row) => requestStateLabel(row.state) },
    { key: 'run', header: 'Factory run', width: proportional(1), renderCell: (row) => row.correlation === 'linked' ? 'Linked' : row.correlation === 'missing-run' ? 'Record missing' : 'Not linked' },
    { key: 'proof', header: 'Owner proof', width: proportional(1), renderCell: (row) => row.delivery.proofRecorded ? 'Recorded' : 'Not recorded' },
    { key: 'detail', header: 'Story', width: proportional(1), renderCell: (row) => <Button label="View story" size="sm" variant="secondary" onClick={() => setSelected(row)} /> },
  ], [])
  const runColumns = useMemo<TableColumn<ExecutionRunRow>[]>(() => [
    { key: 'label', header: 'Run', width: proportional(2), renderCell: (row) => <div><p className="font-medium text-fg">{row.label}</p><p className="mt-1 text-xs text-fg-subtle">{row.project ?? 'Project not recorded'}</p></div> },
    { key: 'outcome', header: 'Outcome', width: proportional(1), renderCell: (row) => <Badge variant={executionOutcomeVariant(row.outcome)} label={executionOutcomeLabel(row.outcome)} /> },
    { key: 'duration', header: 'Duration', width: proportional(1), renderCell: (row) => formatDuration(row.durationMs) },
    { key: 'attempts', header: 'Attempts', width: proportional(1), align: 'end', renderCell: (row) => row.attempts.toLocaleString() },
    { key: 'retries', header: 'Retries', width: proportional(1), align: 'end', renderCell: (row) => row.retries.toLocaleString() },
    { key: 'detail', header: 'Details', width: proportional(1), renderCell: (row) => <Button label="Open" size="sm" variant="secondary" href={safeHttpUrl(row.href)} /> },
  ], [])
  const selectedRun = selected?.factoryRunId ? runById.get(selected.factoryRunId) : undefined

  return (
    <section className="grid gap-6" aria-labelledby="execution-report-title">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h2 id="execution-report-title" className="text-lg font-semibold text-fg">Work execution and delivery</h2>
        <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {section.metrics.map((metric) => (
          <Card key={metric.id} padding={4} minHeight="100%"><p className="text-sm font-medium text-fg-muted">{metric.label}</p><p className="mt-1 text-2xl font-semibold text-fg tabular-nums">{metric.value === null ? 'Unavailable' : metric.value.toLocaleString()}</p><p className="mt-3 text-xs text-fg-subtle">{coverageLabel(metric.coverage)}</p></Card>
        ))}
      </div>
      <div className="grid gap-6 xl:grid-cols-3">
        <SectionCard title="Run duration" className="xl:col-span-2">
          <TimeSeriesChart label="Recorded run duration" points={section.durationSeries} status={section.status === 'unavailable' ? 'unavailable' : 'available'} reason={section.status === 'unavailable' ? section.gaps[0]?.reason : undefined} valueLabel="milliseconds" />
        </SectionCard>
        <SectionCard title="Request states">
          {section.requestStates.length === 0 ? <EmptyState title="No requests in this window" description="No recorded requests match the current filters." isCompact /> : <ul className="grid gap-2">{section.requestStates.map((entry) => <li key={entry.key} className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-sm"><span className="text-fg-muted">{entry.label}</span><strong className="tabular-nums text-fg">{entry.count.toLocaleString()}</strong></li>)}</ul>}
        </SectionCard>
      </div>
      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title="Run outcomes">{section.runOutcomes.length === 0 ? <EmptyState title="No runs in this window" description="No recorded factory runs match the current filters." isCompact /> : <ul className="grid gap-2">{section.runOutcomes.map((entry) => <li key={entry.key} className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-sm"><span className="text-fg-muted">{entry.label}</span><strong className="tabular-nums text-fg">{entry.count.toLocaleString()}</strong></li>)}</ul>}</SectionCard>
        <SectionCard title="Failed phases">{section.failureBreakdown.length === 0 ? <EmptyState title="No failed phases recorded" description="No failed factory phase matches this report." isCompact /> : <ul className="grid gap-2">{section.failureBreakdown.map((entry) => <li key={entry.key} className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-sm"><span className="text-fg-muted">{entry.label}</span><strong className="tabular-nums text-fg">{entry.count.toLocaleString()}</strong></li>)}</ul>}</SectionCard>
      </div>
      <SectionCard title="Request delivery" titleBadge={section.requests.length.toLocaleString()}>
        <Table<ExecutionRequestRow> data={section.requests as ExecutionRequestRow[]} columns={requestColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No request records" description="No recorded requests match this report." isCompact />} />
      </SectionCard>
      <SectionCard title="Factory runs" titleBadge={section.runs.length.toLocaleString()}>
        <Table<ExecutionRunRow> data={section.runs as ExecutionRunRow[]} columns={runColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No factory run records" description="No recorded factory runs match this report." isCompact />} />
      </SectionCard>
      <RequestExecutionDrawer selected={selected} run={selectedRun} onClose={() => setSelected(null)} />
    </section>
  )
}

function ReliabilityReport({ section }: { section: ReliabilityReportSection }): JSX.Element {
  const incidentColumns = useMemo<TableColumn<ReliabilityIncidentRow>[]>(() => [
    { key: 'title', header: 'Incident', width: proportional(3), renderCell: (row) => <div><p className="font-medium text-fg">{row.title}</p><p className="mt-1 text-xs text-fg-subtle">{row.incidentType ?? 'Type not recorded'}</p></div> },
    { key: 'state', header: 'State', width: proportional(1), renderCell: (row) => row.state === 'needs-attention' ? 'Needs attention' : row.state === 'resolved' ? 'Resolved' : row.state === 'running' ? 'In progress' : row.state === 'dispatching' ? 'Starting' : 'Filed' },
    { key: 'priority', header: 'Priority', width: proportional(1), renderCell: (row) => row.priority ?? 'Not recorded' },
    { key: 'recovery', header: 'Recovery', width: proportional(1), renderCell: (row) => row.durationMs !== null ? formatDuration(row.durationMs) : row.ageMs !== null ? `${formatDuration(row.ageMs)} unresolved` : 'Not recorded' },
    { key: 'details', header: 'Details', width: proportional(1), renderCell: (row) => <Button label="Open" size="sm" variant="secondary" href={safeHttpUrl(row.href)} /> },
  ], [])
  const failureColumns = useMemo<TableColumn<ReliabilityFailureRow>[]>(() => [
    { key: 'label', header: 'Failure class', width: proportional(3), renderCell: (row) => <div><p className="font-medium text-fg">{row.label}</p><p className="mt-1 text-xs text-fg-subtle">{row.source}</p></div> },
    { key: 'count', header: 'Occurrences', width: proportional(1), align: 'end', renderCell: (row) => row.count.toLocaleString() },
    { key: 'context', header: 'Context', width: proportional(2), renderCell: (row) => row.project ?? row.host ?? row.service ?? 'Not recorded' },
    { key: 'latestAt', header: 'Latest', width: proportional(1), renderCell: (row) => formatTimestamp(row.latestAt) },
    { key: 'details', header: 'Records', width: proportional(1), renderCell: (row) => row.href ? <Button label="Open" size="sm" variant="secondary" href={safeHttpUrl(row.href)} /> : 'Not linked' },
  ], [])
  const breakdowns = [
    { title: 'Failures by project', values: section.projectBreakdown },
    { title: 'Failures by host', values: section.hostBreakdown },
    { title: 'Failures by service', values: section.serviceBreakdown },
  ]

  return (
    <section className="grid gap-6" aria-labelledby="reliability-report-title">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h2 id="reliability-report-title" className="text-lg font-semibold text-fg">Reliability and recovery</h2>
        <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {section.metrics.map((metric) => (
          <Card key={metric.id} padding={4} minHeight="100%"><p className="text-sm font-medium text-fg-muted">{metric.label}</p><p className="mt-1 text-2xl font-semibold text-fg tabular-nums">{metric.value === null ? 'Unavailable' : metric.value.toLocaleString()}</p><p className="mt-3 text-xs text-fg-subtle">{coverageLabel(metric.coverage)}</p></Card>
        ))}
      </div>
      <SectionCard title="Recovery duration">
        <TimeSeriesChart label="Resolved incident duration" points={section.resolvedDurationSeries} status={section.status === 'unavailable' ? 'unavailable' : 'available'} reason={section.status === 'unavailable' ? section.gaps[0]?.reason : undefined} valueLabel="milliseconds" />
      </SectionCard>
      <SectionCard title="Incidents" titleBadge={section.incidents.length.toLocaleString()}>
        <Table<ReliabilityIncidentRow> data={section.incidents as ReliabilityIncidentRow[]} columns={incidentColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No incidents in this window" description="No recorded incident lifecycle overlaps this report." isCompact />} />
      </SectionCard>
      <SectionCard title="Recurring and isolated failures" titleBadge={section.failureGroups.length.toLocaleString()}>
        <Table<ReliabilityFailureRow> data={section.failureGroups as ReliabilityFailureRow[]} columns={failureColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No failures recorded" description="No incident, CI, service, guard, reaper, deploy, or buildbox failure matches this report." isCompact />} />
      </SectionCard>
      <div className="grid gap-6 lg:grid-cols-3">
        {breakdowns.map((breakdown) => (
          <SectionCard key={breakdown.title} title={breakdown.title}>
            {breakdown.values.length === 0 ? <EmptyState title="No attributed failures" description="Matching failures did not record this dimension." isCompact /> : <ul className="grid gap-2">{breakdown.values.map((entry) => <li key={entry.key} className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-sm"><span className="text-fg-muted">{entry.label}</span><strong className="tabular-nums text-fg">{entry.count.toLocaleString()}</strong></li>)}</ul>}
          </SectionCard>
        ))}
      </div>
    </section>
  )
}

function formatCost(value: number | null, currency = 'USD'): string {
  if (value === null) return 'Unavailable'
  try {
    return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(value)
  } catch {
    return `${value.toLocaleString()} ${currency}`
  }
}

function CapacityReport({ section }: { section: CapacityReportSection }): JSX.Element {
  const usageColumns = useMemo<TableColumn<CapacityUsageRow>[]>(() => [
    { key: 'label', header: 'Recorded as', width: proportional(2), renderCell: (row) => <div><p className="font-medium text-fg">{row.label}</p>{row.unattributed ? <p className="mt-1 text-xs text-fg-subtle">Explicit attribution missing</p> : null}</div> },
    { key: 'tokens', header: 'Tokens', width: proportional(1), align: 'end', renderCell: (row) => row.tokens.toLocaleString() },
    { key: 'cost', header: 'Provider cost', width: proportional(1), align: 'end', renderCell: (row) => formatCost(row.cost) },
    { key: 'attempts', header: 'Attempts', width: proportional(1), align: 'end', renderCell: (row) => row.attempts.toLocaleString() },
  ], [])
  const accountColumns = useMemo<TableColumn<CapacityAccountRow>[]>(() => [
    { key: 'label', header: 'Account', width: proportional(2), renderCell: (row) => <div><p className="font-medium text-fg">{row.label}</p><p className="mt-1 text-xs text-fg-subtle">{row.provider}</p></div> },
    { key: 'usedPercent', header: 'Window used', width: proportional(1), align: 'end', renderCell: (row) => row.usedPercent === null ? 'Not recorded' : `${row.usedPercent.toLocaleString()}%` },
    { key: 'status', header: 'Status', width: proportional(1), renderCell: (row) => row.status },
    { key: 'spend', header: 'Recorded spend', width: proportional(1), align: 'end', renderCell: (row) => formatCost(row.spendAmount, row.currency ?? 'USD') },
    { key: 'resetAt', header: 'Reset', width: proportional(1), renderCell: (row) => formatTimestamp(row.resetAt) },
  ], [])
  const breakdowns = [
    { title: 'Usage by model', rows: section.byModel },
    { title: 'Usage by account', rows: section.byAccount },
    { title: 'Usage by host', rows: section.byHost },
    { title: 'Usage by project', rows: section.byProject },
  ]

  return (
    <section className="grid gap-6" aria-labelledby="capacity-report-title">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h2 id="capacity-report-title" className="text-lg font-semibold text-fg">Capacity, accounts, and spend</h2>
        <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {section.metrics.map((metric) => (
          <Card key={metric.id} padding={4} minHeight="100%">
            <p className="text-sm font-medium text-fg-muted">{metric.label}</p>
            <p className="mt-1 text-2xl font-semibold text-fg tabular-nums">{metric.value === null ? 'Unavailable' : metric.unit === 'currency' ? formatCost(metric.value) : metric.value.toLocaleString()}</p>
            <p className="mt-3 text-xs text-fg-subtle">{metric.denominator !== undefined ? `${metric.numerator ?? 0} of ${metric.denominator} attempts recorded` : coverageLabel(metric.coverage)}</p>
          </Card>
        ))}
      </div>
      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title="Current workload">
          <dl className="grid grid-cols-2 gap-3 text-sm">
            <div><dt className="text-fg-subtle">Active sessions</dt><dd className="mt-1 font-semibold text-fg tabular-nums">{section.snapshot.activeSessions?.toLocaleString() ?? 'Unavailable'}</dd></div>
            <div><dt className="text-fg-subtle">Live agents</dt><dd className="mt-1 font-semibold text-fg tabular-nums">{section.snapshot.liveAgents?.toLocaleString() ?? 'Unavailable'}</dd></div>
            <div><dt className="text-fg-subtle">Running builds</dt><dd className="mt-1 font-semibold text-fg tabular-nums">{section.snapshot.runningBuilds?.toLocaleString() ?? 'Unavailable'}</dd></div>
            <div><dt className="text-fg-subtle">Queued builds</dt><dd className="mt-1 font-semibold text-fg tabular-nums">{section.snapshot.queuedBuilds?.toLocaleString() ?? 'Unavailable'}</dd></div>
            <div className="col-span-2"><dt className="text-fg-subtle">95th percentile build wait</dt><dd className="mt-1 font-semibold text-fg tabular-nums">{formatDuration(section.snapshot.buildWaitP95Ms)}</dd></div>
          </dl>
          <div className="mt-4 flex flex-wrap gap-2"><Button label="Open sessions" href="/sessions" variant="secondary" /><Button label="Open agents" href="/agents" variant="secondary" /><Button label="Open cluster" href="/cluster" variant="secondary" /></div>
        </SectionCard>
        <SectionCard title="Recorded efficiency">
          <p className="text-sm text-fg-muted">Provider cost per succeeded factory run</p>
          <p className="mt-2 text-2xl font-semibold text-fg tabular-nums">{formatCost(section.costPerSucceededRun)}</p>
          <p className="mt-2 text-xs text-fg-subtle">Unavailable unless every matching succeeded run has compatible recorded provider cost.</p>
        </SectionCard>
      </div>
      <SectionCard title="Account windows" titleBadge={section.accounts.length.toLocaleString()}>
        <Table<CapacityAccountRow> data={section.accounts as CapacityAccountRow[]} columns={accountColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No account windows recorded" description="The account limit source has no readable records." isCompact />} />
        <div className="mt-3"><Button label="Open account limits" href="/limits" variant="secondary" /></div>
      </SectionCard>
      <div className="grid gap-6 xl:grid-cols-2">
        {breakdowns.map((breakdown) => (
          <SectionCard key={breakdown.title} title={breakdown.title} titleBadge={breakdown.rows.length.toLocaleString()}>
            <Table<CapacityUsageRow> data={breakdown.rows as CapacityUsageRow[]} columns={usageColumns} density="compact" hasHover textOverflow="wrap" emptyState={<EmptyState title="No recorded usage" description="No factory attempt usage matches this report." isCompact />} />
          </SectionCard>
        ))}
      </div>
    </section>
  )
}

function formatHistoricalValue(metric: HistoricalMetric, value: number | null): string {
  if (value === null) return 'Unavailable'
  if (metric.unit === 'currency') return formatCost(value)
  if (metric.unit === 'percent') return `${value.toLocaleString()}%`
  if (metric.unit === 'milliseconds') return formatDuration(value)
  return value.toLocaleString()
}

function historicalComparisonLabel(metric: HistoricalMetric): string {
  if (!metric.comparisonCompatible) return metric.comparisonReason ?? 'The preceding period cannot be compared.'
  const delta = metric.delta ?? 0
  const change = delta === 0 ? 'No change' : `${delta > 0 ? '+' : '−'}${formatHistoricalValue(metric, Math.abs(delta))}`
  return `${change} from ${formatHistoricalValue(metric, metric.previous)} in the preceding period`
}

function HistoryReport({ section }: { section: HistoryReportSection }): JSX.Element {
  return (
    <section className="grid gap-6" aria-labelledby="history-report-title">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h2 id="history-report-title" className="text-lg font-semibold text-fg">History and comparison</h2>
          <p className="mt-1 text-sm text-fg-muted">
            {section.earliestAvailable
              ? `Recorded history is available from ${new Date(section.earliestAvailable).toLocaleString()} and retained for up to ${section.retentionDays.toLocaleString()} days.`
              : `No retained report history is available yet. New history is retained for up to ${section.retentionDays.toLocaleString()} days.`}
          </p>
        </div>
        <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {section.metrics.map((metric) => (
          <Card key={metric.key} padding={4} minHeight="100%">
            <p className="text-sm font-medium text-fg-muted">{metric.label}</p>
            <p className="mt-1 text-2xl font-semibold text-fg tabular-nums">{formatHistoricalValue(metric, metric.current)}</p>
            <p className="mt-3 text-xs text-fg-subtle">{historicalComparisonLabel(metric)}</p>
          </Card>
        ))}
      </div>
      <div className="grid gap-6 xl:grid-cols-2">
        {section.series.map((series) => (
          <SectionCard key={series.key} title={`${series.label} over time`}>
            <TimeSeriesChart
              label={series.label}
              points={series.points}
              status={series.points.length === 0 ? 'unavailable' : 'available'}
              reason={series.points.length === 0 ? 'No retained measurements cover this report window.' : undefined}
              gaps={series.gaps}
              valueLabel={series.unit === 'count' ? 'events' : series.unit}
            />
          </SectionCard>
        ))}
      </div>
      {section.gaps.length > 0 ? (
        <SectionCard title="History coverage" titleBadge={section.gaps.length.toLocaleString()}>
          <ul className="grid gap-2 text-sm text-fg-muted">
            {section.gaps.map((gap, index) => (
              <li key={`${gap.metric ?? 'all'}:${gap.from ?? ''}:${index}`} className="rounded-md border border-border px-3 py-2">{gap.reason}</li>
            ))}
          </ul>
        </SectionCard>
      ) : null}
    </section>
  )
}

function LineageReport({ section }: { section: LineageReportSection }): JSX.Element {
  return (
    <section id="lineage" className="grid gap-6" aria-labelledby="lineage-report-title">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h2 id="lineage-report-title" className="text-lg font-semibold text-fg">Delivery lineage</h2>
          <p className="mt-1 text-sm text-fg-muted">Each path uses only explicitly linked request, run, check, change, landing, deployment, and owner-proof records.</p>
        </div>
        <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
      </div>
      {section.lineages.length === 0 ? (
        <EmptyState title="No delivery paths recorded" description="No request records match this report, or the request registry is unavailable." isCompact />
      ) : (
        <div className="grid gap-4">
          {section.lineages.map((lineage) => (
            <SectionCard
              key={lineage.requestId}
              title={lineage.title}
              titleBadge={
                <Badge
                  variant={lineage.complete ? 'success' : 'warning'}
                  label={lineage.complete ? 'Complete path' : 'Incomplete path'}
                />
              }
            >
              <p className="mb-3 text-sm text-fg-muted">{lineage.project}</p>
              <ol className="grid gap-2 lg:grid-cols-7">
                {lineage.stages.map((stage) => (
                  <li key={stage.kind} className="rounded-md border border-border px-3 py-3">
                    <Badge variant={lineageStageVariant(stage.status)} label={stage.status === 'recorded' ? 'Recorded' : stage.status === 'failed' ? 'Failed' : 'Missing'} />
                    <p className="mt-2 text-sm font-medium text-fg">{stage.label}</p>
                    <p className="mt-1 text-xs text-fg-muted">{stage.detail}</p>
                    {stage.recordedAt ? <time className="mt-2 block text-xs text-fg-subtle" dateTime={stage.recordedAt}>{new Date(stage.recordedAt).toLocaleString()}</time> : null}
                    {stage.evidence ? <div className="mt-2"><Button label={`Open ${stage.kind} record`} size="sm" variant="secondary" href={safeHttpUrl(stage.evidence.href)} /></div> : null}
                  </li>
                ))}
              </ol>
            </SectionCard>
          ))}
        </div>
      )}
      {section.gaps.length > 0 ? (
        <SectionCard title="Lineage gaps" titleBadge={section.gaps.length.toLocaleString()}>
          <ul className="grid gap-2 text-sm text-fg-muted">
            {section.gaps.map((gap, index) => <li key={`${gap.sourceId ?? 'lineage'}:${index}`} className="rounded-md border border-border px-3 py-2">{gap.reason}</li>)}
          </ul>
        </SectionCard>
      ) : null}
    </section>
  )
}

function ReportTools({ report, filters, onApplyView }: {
  report: ObservabilityReport
  filters: ReportUrlState
  onApplyView(filters: ReportUrlState): void
}): JSX.Element {
  const [savedViews, setSavedViews] = useState<SavedReportView[]>([])
  const [viewName, setViewName] = useState('')
  const [storageError, setStorageError] = useState(false)
  const exportTables = useMemo(() => reportExportTables(report), [report])
  const [selectedTables, setSelectedTables] = useState<string[]>([])

  useEffect(() => {
    try {
      setSavedViews(parseSavedReportViews(window.localStorage.getItem(SAVED_REPORT_VIEWS_KEY)))
      setStorageError(false)
    } catch {
      setSavedViews([])
      setStorageError(true)
    }
  }, [])

  useEffect(() => {
    setSelectedTables((current) => {
      if (exportTables.length === 0) return current.length === 0 ? current : []
      if (current[0] && exportTables.some((table) => table.id === current[0])) return current
      return [exportTables[0]!.id]
    })
  }, [exportTables])

  const persistViews = useCallback((next: SavedReportView[]) => {
    setSavedViews(next)
    try {
      window.localStorage.setItem(SAVED_REPORT_VIEWS_KEY, JSON.stringify(next))
      setStorageError(false)
    } catch {
      setStorageError(true)
    }
  }, [])

  const saveCurrentView = useCallback(() => {
    if (savedViews.length >= MAX_SAVED_REPORT_VIEWS) return
    const id = createSavedViewId()
    const view = createSavedReportView(id, viewName, filters)
    if (!view) return
    persistViews([...savedViews, view])
    setViewName('')
  }, [filters, persistViews, savedViews, viewName])

  const selectedTable = selectedTables[0]
  const date = report.generatedAt.slice(0, 10)
  return (
    <SectionCard title="Save and share this report" className="print:hidden">
      <div className="grid gap-6 xl:grid-cols-2">
        <div>
          <h3 className="text-sm font-semibold text-fg">Saved views</h3>
          <p className="mt-1 text-xs text-fg-muted">Saved only in this browser. A view stores validated report filters, never report data.</p>
          {storageError ? <p className="mt-2 text-xs text-fg-muted">Browser storage is unavailable. Saved views remain only until this page closes.</p> : null}
          <div className="mt-3 flex items-end gap-2">
            <div className="min-w-0 flex-1"><TextInput label="View name" value={viewName} onChange={setViewName} placeholder="For example: weekly failures" width="100%" /></div>
            <Button label="Save view" onClick={saveCurrentView} isDisabled={!viewName.trim() || savedViews.length >= MAX_SAVED_REPORT_VIEWS} />
          </div>
          {savedViews.length >= MAX_SAVED_REPORT_VIEWS ? <p className="mt-2 text-xs text-fg-muted">Remove a saved view before adding another.</p> : null}
          {savedViews.length > 0 ? (
            <ul className="mt-3 grid gap-2">
              {savedViews.map((view) => (
                <li key={view.id} className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2">
                  <span className="text-sm font-medium text-fg">{view.name}</span>
                  <span className="flex gap-2">
                    <Button label="Apply" size="sm" variant="secondary" onClick={() => onApplyView(savedViewFilters(view))} />
                    <Button label="Remove" size="sm" variant="secondary" onClick={() => persistViews(savedViews.filter((candidate) => candidate.id !== view.id))} />
                  </span>
                </li>
              ))}
            </ul>
          ) : <p className="mt-3 text-sm text-fg-muted">No saved views yet.</p>}
        </div>
        <div>
          <h3 className="text-sm font-semibold text-fg">Export and print</h3>
          <p className="mt-1 text-xs text-fg-muted">CSV includes the selected visible table plus query and coverage metadata. JSON preserves the exact report envelope.</p>
          <div className="mt-3">
            <MultiSelector
              label="CSV table"
              options={exportTables.map((table) => ({ value: table.id, label: table.label }))}
              value={selectedTables}
              onChange={(values) => setSelectedTables(values.length > 0 ? [values.at(-1)!] : [])}
              placeholder="Choose a visible table"
              width="100%"
            />
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            <Button
              label="Download CSV"
              variant="secondary"
              isDisabled={!selectedTable}
              onClick={() => {
                if (!selectedTable) return
                const csv = buildReportCsv(report, selectedTable)
                if (csv) downloadReportFile(`observability-report-${date}.csv`, csv, 'text/csv;charset=utf-8')
              }}
            />
            <Button label="Download JSON" variant="secondary" onClick={() => downloadReportFile(`observability-report-${date}.json`, buildReportJson(report), 'application/json;charset=utf-8')} />
            <Button label="Print report" variant="secondary" onClick={() => window.print()} />
          </div>
        </div>
      </div>
    </SectionCard>
  )
}

function ReportBody({ report }: { report: ObservabilityReport }): JSX.Element {
  const section = report.sections.find((candidate): candidate is ActivityReportSection => candidate.kind === 'activity')
  const execution = report.sections.find((candidate): candidate is ExecutionReportSection => candidate.kind === 'execution')
  const reliability = report.sections.find((candidate): candidate is ReliabilityReportSection => candidate.kind === 'reliability')
  const capacity = report.sections.find((candidate): candidate is CapacityReportSection => candidate.kind === 'capacity')
  const history = report.sections.find((candidate): candidate is HistoryReportSection => candidate.kind === 'history')
  const lineage = report.sections.find((candidate): candidate is LineageReportSection => candidate.kind === 'lineage')
  const [selected, setSelected] = useState<ReportAttentionRecord | null>(null)
  const sourceLabels = useMemo(() => new Map(section?.sources.map((source) => [source.id, source.label]) ?? []), [section?.sources])

  useEffect(() => {
    if (!selected) return
    const current = section?.attention.find((row) => row.id === selected.id) ?? null
    if (current !== selected) setSelected(current)
  }, [section?.attention, selected])

  const attentionColumns = useMemo<TableColumn<AttentionRow>[]>(() => [
    {
      key: 'title', header: 'Needs attention', width: proportional(3), renderCell: (row) => (
        <div><p className="font-medium text-fg">{row.title}</p><p className="mt-1 text-xs text-fg-subtle">{row.kind === 'event' ? contextLabel(row) : row.reason}</p></div>
      ),
    },
    { key: 'severity', header: 'Severity', width: proportional(1), renderCell: (row) => <Badge variant={severityVariant(row.severity)} label={row.severity} /> },
    { key: 'sourceId', header: 'Source', width: proportional(1), renderCell: (row) => sourceLabels.get(row.sourceId) ?? 'Unknown source' },
    { key: 'recorded', header: 'Recorded', width: proportional(1), renderCell: (row) => row.kind === 'event' ? formatTimestamp(row.ts) : 'Source state' },
    { key: 'evidence', header: 'Evidence', width: proportional(1), renderCell: (row) => <Button label="Inspect" size="sm" variant="secondary" onClick={() => setSelected(row)} /> },
  ], [sourceLabels])

  const sourceColumns = useMemo<TableColumn<SourceRow>[]>(() => [
    { key: 'label', header: 'Source', width: proportional(2), renderCell: (row) => <div><p className="font-medium text-fg">{row.label}</p><p className="mt-1 text-xs text-fg-subtle">{authorityLabel(row.authority)}</p></div> },
    { key: 'status', header: 'Status', width: proportional(1), renderCell: (row) => <Badge variant={sourceStatusVariant(row.status)} label={sourceStatusLabel(row.status)} /> },
    { key: 'matchingRecords', header: 'Matching', width: proportional(1), align: 'end', renderCell: (row) => row.matchingRecords.toLocaleString() },
    { key: 'retainedRecords', header: 'Retained', width: proportional(1), align: 'end', renderCell: (row) => row.retainedRecords.toLocaleString() },
    { key: 'latest', header: 'Latest', width: proportional(1), renderCell: (row) => formatTimestamp(row.latest) },
    { key: 'records', header: 'Records', width: proportional(1), renderCell: (row) => <Button label="Open" size="sm" variant="secondary" href={safeHttpUrl(row.href)} /> },
  ], [])

  if (!section) {
    return <EmptyState title="Activity report unavailable" description="The collector returned no activity section for this report." />
  }

  const activitySeries = section.series.find((series) => series.id === 'activity-volume')
  return (
    <div className="grid gap-6">
      <CoverageSummary report={report} />
      <section aria-labelledby="report-metrics-title">
        <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
          <h2 id="report-metrics-title" className="text-lg font-semibold text-fg">What was recorded</h2>
          <Badge variant={COVERAGE_VARIANT[section.status]} label={coverageLabel(section.status)} />
        </div>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
          {section.metrics.map((metric) => <MetricCard key={metric.id} metric={metric} />)}
        </div>
      </section>
      <div className="grid gap-6 xl:grid-cols-3">
        <SectionCard title="Activity over time" className="xl:col-span-2">
          {activitySeries ? (
            <TimeSeriesChart
              label={activitySeries.label}
              points={activitySeries.points}
              status={activitySeries.coverage === 'unavailable' ? 'unavailable' : 'available'}
              reason={activitySeries.coverage === 'unavailable' ? activitySeries.gaps[0]?.reason : undefined}
              gaps={activitySeries.gaps}
              valueLabel="events"
            />
          ) : <EmptyState title="Trend unavailable" description="No activity series was returned." isCompact />}
        </SectionCard>
        <SectionCard title="Recorded by category">
          {section.categoryBreakdown.length === 0 ? (
            <EmptyState title="No category totals" description="No readable records match the current filters." isCompact />
          ) : (
            <ul className="grid gap-2">
              {section.categoryBreakdown.map((entry) => (
                <li key={entry.category} className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-sm">
                  <span className="text-fg-muted">{entry.category}</span>
                  <strong className="tabular-nums text-fg">{entry.count.toLocaleString()}</strong>
                </li>
              ))}
            </ul>
          )}
        </SectionCard>
      </div>
      <SectionCard title="Needs attention" titleBadge={section.attention.length.toLocaleString()}>
        {section.truncated ? <p className="mb-3 text-sm text-fg-muted">The collector reached its report limit. Totals remain marked by their recorded coverage.</p> : null}
        <Table<AttentionRow>
          data={section.attention as AttentionRow[]}
          columns={attentionColumns}
                   density="compact"
          hasHover
          textOverflow="wrap"
          emptyState={<EmptyState title="Nothing needs attention" description="No warning, failure, skipped record, or source problem matches this report." isCompact />}
        />
      </SectionCard>
      <SectionCard title="Source trust" titleBadge={section.sources.length.toLocaleString()}>
        <Table<SourceRow>
          data={section.sources as SourceRow[]}
          columns={sourceColumns}
                   density="compact"
          hasHover
          textOverflow="wrap"
          emptyState={<EmptyState title="No sources selected" description="Choose at least one registered source to inspect its coverage." isCompact />}
        />
      </SectionCard>
      {execution ? <ExecutionReport section={execution} /> : (
        <SectionCard title="Work execution and delivery">
          <EmptyState title="Execution report unavailable" description="The collector returned no request or factory-run section." isCompact />
        </SectionCard>
      )}
      {reliability ? <ReliabilityReport section={reliability} /> : (
        <SectionCard title="Reliability and recovery">
          <EmptyState title="Reliability report unavailable" description="The collector returned no incident or failure section." isCompact />
        </SectionCard>
      )}
      {capacity ? <CapacityReport section={capacity} /> : (
        <SectionCard title="Capacity, accounts, and spend">
          <EmptyState title="Capacity report unavailable" description="The collector returned no usage, account-window, session, agent, or build capacity section." isCompact />
        </SectionCard>
      )}
      {lineage ? <LineageReport section={lineage} /> : (
        <SectionCard title="Delivery lineage">
          <EmptyState title="Delivery lineage unavailable" description="The collector returned no explicitly linked delivery-path section." isCompact />
        </SectionCard>
      )}
      {history ? <HistoryReport section={history} /> : (
        <SectionCard title="History and comparison">
          <EmptyState title="History unavailable" description="The collector returned the current report, but no retained comparison history." isCompact />
        </SectionCard>
      )}
      <EvidenceDrawer
        selected={selected}
        sourceLabel={selected ? sourceLabels.get(selected.sourceId) ?? 'Unknown source' : ''}
        onClose={() => setSelected(null)}
      />
    </div>
  )
}

function PrintableReport({ report }: { report: ObservabilityReport }): JSX.Element {
  const metricSections = report.sections.filter((section): section is ActivityReportSection | ExecutionReportSection | ReliabilityReportSection | CapacityReportSection =>
    section.kind === 'activity' || section.kind === 'execution' || section.kind === 'reliability' || section.kind === 'capacity')
  const history = report.sections.find((section): section is HistoryReportSection => section.kind === 'history')
  const lineage = report.sections.find((section): section is LineageReportSection => section.kind === 'lineage')
  const shownGaps = report.coverage.gaps.slice(0, 20)
  return (
    <article className="hidden print:block" aria-label="Printable observability report">
      <h1 className="text-2xl font-semibold text-fg">Observability report</h1>
      <p className="mt-1 text-sm text-fg-muted">{new Date(report.query.from).toLocaleString()} to {new Date(report.query.to).toLocaleString()} · {report.query.timezone}</p>
      <p className="mt-1 text-sm text-fg-muted">Generated {new Date(report.generatedAt).toLocaleString()} · {coverageLabel(report.coverage.status)}</p>
      <dl className="mt-6 grid grid-cols-2 gap-3">
        {metricSections.map((section) => section.metrics.map((metric) => (
          <div key={`${section.kind}:${metric.id}`} className="border-b border-border pb-2">
            <dt className="text-xs text-fg-muted">{metric.label}</dt>
            <dd className="text-base font-semibold tabular-nums text-fg">{metric.value === null ? 'Unavailable' : metric.unit === 'currency' ? formatCost(metric.value) : metric.value.toLocaleString()}</dd>
          </div>
        )))}
        {history?.metrics.map((metric) => (
          <div key={metric.key} className="border-b border-border pb-2">
            <dt className="text-xs text-fg-muted">{metric.label} over selected period</dt>
            <dd className="text-base font-semibold tabular-nums text-fg">{formatHistoricalValue(metric, metric.current)}</dd>
          </div>
        ))}
        {lineage ? (
          <div className="border-b border-border pb-2">
            <dt className="text-xs text-fg-muted">Complete delivery paths</dt>
            <dd className="text-base font-semibold tabular-nums text-fg">{lineage.lineages.filter((item) => item.complete).length.toLocaleString()} of {lineage.lineages.length.toLocaleString()}</dd>
          </div>
        ) : null}
      </dl>
      <h2 className="mt-6 text-lg font-semibold text-fg">Coverage notes</h2>
      {shownGaps.length > 0 ? <ul className="mt-2 grid gap-1 text-sm text-fg-muted">{shownGaps.map((gap, index) => <li key={`${gap.domain}:${index}`}>{gap.reason}</li>)}</ul> : <p className="mt-2 text-sm text-fg-muted">No coverage gaps recorded.</p>}
      {report.coverage.gaps.length > shownGaps.length ? <p className="mt-2 text-sm text-fg-muted">{(report.coverage.gaps.length - shownGaps.length).toLocaleString()} additional coverage notes remain in the interactive and JSON reports.</p> : null}
    </article>
  )
}

export function ReportsContent(): JSX.Element {
  const [filters, setFilters] = useState<ReportUrlState>(DEFAULT_REPORT_URL_STATE)
  const [urlReady, setUrlReady] = useState(false)
  const timezone = useMemo(() => Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', [])
  const query = useObservabilityReport({
    timezone,
    ...(filters.projects.length > 0 ? { projects: filters.projects } : {}),
    ...(filters.sources.length > 0 ? { sources: filters.sources } : {}),
    ...(filters.severity ? { severity: filters.severity } : {}),
    ...(filters.q ? { q: filters.q } : {}),
  }, REPORT_RANGE_MS[filters.range], urlReady)

  useEffect(() => {
    const readUrl = () => {
      setFilters(parseReportUrlState(window.location.search))
      setUrlReady(true)
    }
    readUrl()
    window.addEventListener('popstate', readUrl)
    return () => window.removeEventListener('popstate', readUrl)
  }, [])

  const updateFilters = useCallback((next: ReportUrlState) => {
    setFilters(next)
    updateBrowserUrl(next)
  }, [])

  const report = query.data
  const projectOptions = useMemo(() => [...new Set([...(report?.filters.projects ?? []), ...filters.projects])].sort(), [filters.projects, report?.filters.projects])
  const sourceOptions = useMemo(() => {
    const labels = new Map((report?.filters.sources ?? []).map((source) => [source.id, source.label]))
    filters.sources.forEach((source) => { if (!labels.has(source)) labels.set(source, source) })
    return [...labels].map(([value, label]) => ({ value, label }))
  }, [filters.sources, report?.filters.sources])

  return (
    <>
      {report ? <PrintableReport report={report} /> : null}
      <div className="grid gap-6 print:hidden" data-testid="observability-reports">
      <div>
        <h1 className="text-2xl font-semibold text-fg">Observability reports</h1>
        <p className="mt-1 max-w-3xl text-sm text-fg-muted">A trustworthy view of recorded activity, work delivery, reliability, capacity, accounts, spend, retained history, and the sources behind them. Missing coverage stays visible instead of becoming zero.</p>
      </div>
      <Card padding={4}>
        <div className="grid gap-4">
          <div className="flex flex-wrap items-end gap-3">
            <div>
              <p className="mb-1 text-xs font-medium text-fg-muted">Report window</p>
              <SegmentedControl value={filters.range} onChange={(range) => updateFilters({ ...filters, range: range as ReportRange })} label="Report window">
                <SegmentedControlItem value="1h" label="1 hour" />
                <SegmentedControlItem value="24h" label="24 hours" />
                <SegmentedControlItem value="3d" label="3 days" />
                <SegmentedControlItem value="7d" label="7 days" />
                <SegmentedControlItem value="30d" label="30 days" />
                <SegmentedControlItem value="90d" label="90 days" />
              </SegmentedControl>
            </div>
            <div>
              <p className="mb-1 text-xs font-medium text-fg-muted">Minimum severity</p>
              <SegmentedControl value={filters.severity ?? 'all'} onChange={(severity) => updateFilters({ ...filters, severity: severity === 'all' ? undefined : severity as 'warn' | 'error' })} label="Minimum severity">
                <SegmentedControlItem value="all" label="All" />
                <SegmentedControlItem value="warn" label="Warning" />
                <SegmentedControlItem value="error" label="Error" />
              </SegmentedControl>
            </div>
          </div>
          <div className="grid gap-3 lg:grid-cols-3">
            <MultiSelector label="Projects" options={projectOptions} value={filters.projects} onChange={(projects) => updateFilters({ ...filters, projects })} placeholder="All projects" hasClear hasSearch width="100%" />
            <MultiSelector label="Sources" options={sourceOptions} value={filters.sources} onChange={(sources) => updateFilters({ ...filters, sources })} placeholder="All authoritative sources" hasClear hasSearch width="100%" />
            <TextInput label="Search recorded activity" value={filters.q} onChange={(q) => updateFilters({ ...filters, q })} placeholder="Title or recorded context" hasClear width="100%" />
          </div>
        </div>
      </Card>
      {query.isLoading ? <SectionCard title="Building report">Reading registered activity sources. This attempt stops and reports an error after two minutes.</SectionCard> : null}
      {query.isError ? (
        <Card padding={6}>
          <EmptyState
            title="Report could not be built"
            description={query.error instanceof ObservabilityReportTimeoutError
              ? query.error.message
              : 'The collector returned an error instead of this report. Existing pages remain available while you retry.'}
            actions={<Button label="Retry report" onClick={() => { void query.refetch() }} isLoading={query.isFetching} />}
          />
        </Card>
      ) : null}
      {report ? (
        <>
          <ReportTools report={report} filters={filters} onApplyView={updateFilters} />
          <ReportBody report={report} />
        </>
      ) : null}
      </div>
    </>
  )
}
