import React, { useEffect, useMemo, useState } from "react";

import {
  Alert,
  Box,
  Button,
  Chip,
  Paper,
  Stack,
  Tab,
  Tabs,
  TextField,
  Typography,
  Checkbox,
  FormControlLabel,
} from "@mui/material";

import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";

type AiServiceMetrics = {
  healthy: boolean;
  model?: string | null;
  device?: string | null;
  gpuAvailable?: boolean;
  gpuName?: string | null;
  ocrAvailable?: boolean | null;
  ocrLanguages?: string | null;
  ollamaConfigured?: boolean | null;
  ollamaReachable?: boolean | null;
  ollamaModel?: string | null;
  ollamaModelAvailable?: boolean | null;
  ollamaVersion?: string | null;
  ollamaInstalledModels?: string[] | null;
  ollamaLoadedModels?: string[] | null;
  ollamaLoadedCount?: number | null;
  healthLatencyMs?: number | null;
  probeLatencyMs?: number | null;
  lastProbeAt?: string | null;
  lastProbeSuccessAt?: string | null;
  lastProbeFailureAt?: string | null;
  probeFailures: number;
  requests: number;
  cacheHits: number;
  cacheMisses: number;
  failures: number;
  averageLatencyMs?: number | null;
  ocrRequests: number;
  ocrFailures: number;
  averageOcrLatencyMs?: number | null;
  lastOcrSuccessAt?: string | null;
  lastOcrFailureAt?: string | null;
  lastSuccessAt?: string | null;
  lastFailureAt?: string | null;
  lastError?: string | null;
};

type EditableEmailSettings = {
  enabled: boolean;
  host: string;
  port: number;
  user: string;
  from: string;
  fromName: string;
  enableSsl: boolean;
  timeoutMs: number;
  usesOverrides: boolean;
  hasPassword: boolean;
};

type CvBenchmarkEntry = {
  FileName: string;
  Slug: string;
  Extension: string;
  Characters: number;
  OutputPath: string;
  ApprovedFixturePath?: string | null;
  CandidateFixturePath?: string | null;
  ContactLocation?: string | null;
  FirstJob?: string | null;
  FirstJobLocation?: string | null;
  FirstEducation?: string | null;
  FirstEducationLocation?: string | null;
  QualificationLevels: string[];
  SuspiciousLocations: string[];
  CoverageScore: number;
  ConfidenceScore: number;
  ConsistencyScore: number;
  DiffSummary?: string | null;
};

type CvBenchmarkIndex = {
  CorpusRoot: string;
  OutputRoot: string;
  GeneratedAtUtc: string;
  TotalFiles: number;
  AverageCoverage: number;
  AverageConfidence: number;
  AverageConsistency: number;
  FilesWithSuspiciousLocations: number;
  MissingApprovedFixtures: number;
  Entries: CvBenchmarkEntry[];
};

type CvBenchmarkStatus = {
  indexJson?: string | null;
  reportMarkdown?: string | null;
  rootPath: string;
  lastUpdatedAtUtc?: string | null;
};

type SystemStatus = {
  environment: string;
  contentRoot: string;
  version: string;
  commitSha?: string | null;
  buildStamp?: string | null;
  storage: {
    dataRoot: string;
    dbPath: string;
    dbExists: boolean;
    dbSizeBytes?: number | null;
    companyCount: number;
    jobCount: number;
    deletedCount: number;
  };
  email: {
    enabled: boolean;
    host?: string | null;
    port: number;
    enableSsl: boolean;
    from?: string | null;
    fromName?: string | null;
  };
  database: {
    provider: string;
    looksConfigured: boolean;
    canConnect: boolean;
    target?: string | null;
    usesFileStorage: boolean;
    warning?: string | null;
  };
  runtime: {
    framework: string;
    osDescription: string;
    processArchitecture: string;
    machineName?: string | null;
  };
  auth: {
    required: boolean;
    hasJwtKey: boolean;
    googleConfigured: boolean;
    gmailConfigured: boolean;
  };
  ai: AiServiceMetrics;
};

function formatBytes(bytes?: number | null) {
  if (bytes == null) return "-";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function displayMetadata(value?: string | null) {
  return value && value.trim().length > 0 ? value : "-";
}

function formatDate(value?: string | null) {
  return value ? new Date(value).toLocaleString() : "-";
}

function formatPercent(value?: number | null) {
  return typeof value === "number" ? `${Math.round(value * 100)}%` : "-";
}

function parseBenchmarkIndex(indexJson?: string | null): CvBenchmarkIndex | null {
  if (!indexJson?.trim()) return null;
  try {
    return JSON.parse(indexJson) as CvBenchmarkIndex;
  } catch {
    return null;
  }
}

function benchmarkTone(value?: number | null) {
  if (typeof value !== "number") return "default" as const;
  if (value >= 0.8) return "success" as const;
  if (value >= 0.6) return "warning" as const;
  return "error" as const;
}

function SummaryCard({ title, value, subtitle, tone = "default" }: { title: string; value: string; subtitle?: string; tone?: "default" | "success" | "warning" | "error" }) {
  const color = tone === "success" ? "success.main" : tone === "warning" ? "warning.main" : tone === "error" ? "error.main" : "text.primary";
  return (
    <Paper sx={{ p: 2, borderRadius: 3 }}>
      <Typography variant="overline" sx={{ color: "text.secondary" }}>{title}</Typography>
      <Typography variant="h5" sx={{ fontWeight: 950, color }}>{value}</Typography>
      <Typography variant="body2" sx={{ color: "text.secondary", mt: 1 }}>{subtitle || "-"}</Typography>
    </Paper>
  );
}

function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
  return <Typography variant="body2"><strong>{label}:</strong> {value}</Typography>;
}

export default function AdminSystemPage() {
  const { t } = useI18n();
  const [tab, setTab] = useState(0);
  const [status, setStatus] = useState<SystemStatus | null>(null);
  const [emailSettings, setEmailSettings] = useState<EditableEmailSettings | null>(null);
  const [benchmarkStatus, setBenchmarkStatus] = useState<CvBenchmarkStatus | null>(null);
  const [smtpPassword, setSmtpPassword] = useState("");
  const [clearPassword, setClearPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [runningProbe, setRunningProbe] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [testEmailTo, setTestEmailTo] = useState("");
  const [testEmailSubject, setTestEmailSubject] = useState("Jobbjakt SMTP test");
  const [testEmailMessage, setTestEmailMessage] = useState("This is a test email from the Jobbjakt system panel.");
  const [sendingTestEmail, setSendingTestEmail] = useState(false);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const [statusRes, emailRes, benchmarkRes] = await Promise.all([
        api.get<SystemStatus>("/admin/system"),
        api.get<EditableEmailSettings>("/admin/system/email-settings"),
        api.get<CvBenchmarkStatus>("/admin/system/cv-benchmark").catch(() => ({ data: null } as any)),
      ]);
      setStatus(statusRes.data);
      setEmailSettings(emailRes.data);
      setBenchmarkStatus(benchmarkRes.data ?? null);
      setSmtpPassword("");
      setClearPassword(false);
    } catch (e: any) {
      setError(getApiErrorMessage(e, "Failed to load system status."));
      setStatus(null);
      setEmailSettings(null);
      setBenchmarkStatus(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const dbTone = useMemo(() => {
    if (!status) return "default" as const;
    if (!status.database.looksConfigured || !status.database.canConnect) return "error" as const;
    if (status.database.warning) return "warning" as const;
    return "success" as const;
  }, [status]);

  const aiTone = useMemo(() => {
    if (!status) return "default" as const;
    if (!status.ai.healthy) return "error" as const;
    if (status.ai.probeFailures > 0 || status.ai.failures > 0 || (status.ai.ocrFailures ?? 0) > 0) return "warning" as const;
    return "success" as const;
  }, [status]);

  const benchmarkIndex = useMemo(() => parseBenchmarkIndex(benchmarkStatus?.indexJson), [benchmarkStatus?.indexJson]);
  const weakestEntries = useMemo(() => {
    if (!benchmarkIndex) return [] as CvBenchmarkEntry[];
    return [...benchmarkIndex.Entries]
      .sort((a, b) => (a.CoverageScore + a.ConfidenceScore + a.ConsistencyScore) - (b.CoverageScore + b.ConfidenceScore + b.ConsistencyScore))
      .slice(0, 6);
  }, [benchmarkIndex]);

  const benchmarkFindings = useMemo(() => {
    if (!benchmarkIndex) return [] as Array<{ file: string; issue: string }>;
    return benchmarkIndex.Entries.flatMap((entry) => {
      const findings: Array<{ file: string; issue: string }> = [];
      if (entry.ContactLocation && /(culture|education|arial|hobbies|cooperate|ag, ni|bold)/i.test(entry.ContactLocation)) {
        findings.push({ file: entry.FileName, issue: `Suspicious contact location: ${entry.ContactLocation}` });
      }
      if (entry.FirstEducation && entry.FirstEducation.length > 120) {
        findings.push({ file: entry.FileName, issue: "Education qualification looks over-captured." });
      }
      if ((entry.FirstJob ?? "").length > 120) {
        findings.push({ file: entry.FileName, issue: "Work title looks over-captured." });
      }
      if ((entry.QualificationLevels ?? []).includes("Other")) {
        findings.push({ file: entry.FileName, issue: "Qualification level fell back to Other." });
      }
      return findings;
    }).slice(0, 10);
  }, [benchmarkIndex]);

  const sendTestEmail = async () => {
    setSendingTestEmail(true);
    try {
      await api.post("/users/send-test-email", {
        toEmail: testEmailTo.trim() || null,
        subject: testEmailSubject.trim() || null,
        message: testEmailMessage.trim() || null,
      });
      setError(null);
    } catch (e: any) {
      setError(getApiErrorMessage(e, "Failed to send test email."));
    } finally {
      setSendingTestEmail(false);
    }
  };

  const saveEmailSettings = async () => {
    if (!emailSettings) return;
    setSavingSettings(true);
    try {
      const res = await api.put<EditableEmailSettings>("/admin/system/email-settings", {
        enabled: emailSettings.enabled,
        host: emailSettings.host,
        port: Number(emailSettings.port) || 587,
        user: emailSettings.user,
        password: smtpPassword.trim() || null,
        clearPassword,
        from: emailSettings.from,
        fromName: emailSettings.fromName,
        enableSsl: emailSettings.enableSsl,
        timeoutMs: Number(emailSettings.timeoutMs) || 15000,
      });
      setEmailSettings(res.data);
      setSmtpPassword("");
      setClearPassword(false);
      await load();
    } catch (e: any) {
      setError(getApiErrorMessage(e, "Failed to save email settings."));
    } finally {
      setSavingSettings(false);
    }
  };

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
        <Box>
          <Typography variant="h5" sx={{ fontWeight: 950 }}>{t("adminSystemTitle")}</Typography>
          <Typography sx={{ color: "text.secondary" }}>{t("adminSystemSubtitle")}</Typography>
        </Box>
        <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
          <Button
            variant="outlined"
            onClick={async () => {
              setRunningProbe(true);
              setError(null);
              try {
                await api.post("/admin/system/ai/probe");
                await load();
              } catch (e: any) {
                setError(getApiErrorMessage(e, "Failed to run AI service probe."));
              } finally {
                setRunningProbe(false);
              }
            }}
            disabled={loading || runningProbe}
          >
            {runningProbe ? t("adminSystemRunningProbe") : t("adminSystemRunProbe")}
          </Button>
          <Button variant="contained" onClick={() => void load()} disabled={loading}>
            {loading ? t("adminSystemRefreshing") : t("adminSystemRefresh")}
          </Button>
        </Box>
      </Box>

      <Tabs value={tab} onChange={(_, value) => setTab(value)}>
        <Tab label={t("adminSystemStatusTab")} />
        <Tab label={t("adminSystemSettingsTab")} />
      </Tabs>

      {error ? <Alert severity="error">{error}</Alert> : null}
      {status?.database.warning && tab === 0 ? <Alert severity={status.database.canConnect ? "warning" : "error"}>{status.database.warning}</Alert> : null}
      {status?.ai.lastError && tab === 0 ? <Alert severity={status.ai.healthy ? "warning" : "error"}>{status.ai.lastError}</Alert> : null}

      {tab === 0 ? (
        <>
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(4, 1fr)" }, gap: 2 }}>
            <SummaryCard
              title={t("adminSystemEnvironment")}
              value={status?.environment ?? "-"}
              subtitle={`Version ${displayMetadata(status?.version)} · Commit ${displayMetadata(status?.commitSha)}`}
            />
            <SummaryCard
              title={t("adminSystemDatabase")}
              value={status ? (status.database.canConnect ? t("adminSystemConnected") : t("adminSystemOffline")) : "-"}
              subtitle={status ? `${status.database.provider} · ${status.database.target || "No target"}` : "-"}
              tone={dbTone}
            />
            <SummaryCard
              title={t("adminSystemSmtp")}
              value={status?.email.enabled ? t("adminSystemEnabled") : t("adminSystemDisabled")}
              subtitle={status?.email.host || t("adminSystemNoSmtpHost")}
              tone={status?.email.enabled ? "success" : "default"}
            />
            <SummaryCard
              title={t("adminSystemSummarizer")}
              value={status?.ai.healthy ? t("adminSystemHealthy") : t("adminSystemOffline")}
              subtitle={status?.ai.probeLatencyMs != null
                ? `${status.ai.probeLatencyMs} ms probe · ${status.ai.device || "unknown device"}`
                : status?.ai.healthLatencyMs != null
                  ? `${status.ai.healthLatencyMs} ms health · ${status.ai.device || "unknown device"}`
                  : t("adminSystemNoLatencyData")}
              tone={aiTone}
            />
          </Box>

          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1.2fr 1fr" }, gap: 2 }}>
            <Paper sx={{ p: 2, borderRadius: 3 }}>
              <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemDatabaseStorage")}</Typography>
              <Stack spacing={0.75}>
                <DetailRow label={t("adminSystemProvider")} value={status?.database.provider || "-"} />
                <DetailRow label={t("adminSystemTarget")} value={status?.database.target || "-"} />
                <DetailRow label={t("adminSystemConfigured")} value={status?.database.looksConfigured ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemCanConnect")} value={status?.database.canConnect ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemUsesFileStorage")} value={status?.database.usesFileStorage ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemDataRoot")} value={status?.storage.dataRoot || "-"} />
                <DetailRow label={t("adminSystemDbPath")} value={status?.storage.dbPath || "-"} />
                <DetailRow label={t("adminSystemDbFileExists")} value={status?.storage.dbExists ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemDbSize")} value={formatBytes(status?.storage.dbSizeBytes)} />
                <DetailRow label={t("companies")} value={status?.storage.companyCount ?? 0} />
                <DetailRow label={t("adminSystemJobs")} value={status?.storage.jobCount ?? 0} />
                <DetailRow label={t("adminSystemDeletedJobs")} value={status?.storage.deletedCount ?? 0} />
              </Stack>
            </Paper>

            <Paper sx={{ p: 2, borderRadius: 3 }}>
              <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemRuntimeAuth")}</Typography>
              <Stack spacing={0.75}>
                <DetailRow label={t("adminSystemFramework")} value={status?.runtime.framework || "-"} />
                <DetailRow label={t("adminSystemOs")} value={status?.runtime.osDescription || "-"} />
                <DetailRow label={t("adminSystemArchitecture")} value={status?.runtime.processArchitecture || "-"} />
                <DetailRow label={t("adminSystemMachine")} value={status?.runtime.machineName || "-"} />
                <DetailRow label={t("adminSystemContentRoot")} value={status?.contentRoot || "-"} />
                <DetailRow label={t("adminSystemBuildStamp")} value={displayMetadata(status?.buildStamp)} />
                <DetailRow label={t("adminSystemAuthRequired")} value={status?.auth.required ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemJwtConfigured")} value={status?.auth.hasJwtKey ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemGoogleConfigured")} value={status?.auth.googleConfigured ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemGmailConfigured")} value={status?.auth.gmailConfigured ? t("yes") : t("noWord")} />
              </Stack>
            </Paper>
          </Box>

          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" }, gap: 2 }}>
            <Paper sx={{ p: 2, borderRadius: 3 }}>
              <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailConfig")}</Typography>
              <Stack spacing={0.75}>
                <DetailRow label={t("adminSystemEnabled")} value={status?.email.enabled ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemFrom")} value={status?.email.from || "-"} />
                <DetailRow label={t("adminSystemFromName")} value={status?.email.fromName || "-"} />
                <DetailRow label={t("adminSystemHost")} value={status?.email.host || "-"} />
                <DetailRow label={t("adminSystemPort")} value={status?.email.port ?? "-"} />
                <DetailRow label={t("adminSystemSsl")} value={status?.email.enableSsl ? t("yes") : t("noWord")} />
              </Stack>
            </Paper>

            <Paper sx={{ p: 2, borderRadius: 3 }}>
              <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerRuntime")}</Typography>
              <Stack spacing={0.75}>
                <DetailRow label={t("adminSystemModel")} value={status?.ai.model || "-"} />
                <DetailRow label={t("adminSystemDevice")} value={status?.ai.device || "-"} />
                <DetailRow label={t("adminSystemGpuAvailable")} value={status?.ai.gpuAvailable ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemGpuName")} value={status?.ai.gpuName || "-"} />
                <DetailRow label={t("adminSystemOllamaConfigured")} value={status?.ai.ollamaConfigured ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemOllamaReachable")} value={status?.ai.ollamaReachable ? t("yes") : t("noWord")} />
                <DetailRow label={t("adminSystemOllamaModel")} value={status?.ai.ollamaModel || "-"} />
                <DetailRow label={t("adminSystemOllamaModelAvailable")} value={status?.ai.ollamaModelAvailable ? t("yes") : t("noWord")} />
                <DetailRow label="Ollama version" value={status?.ai.ollamaVersion || "-"} />
                <DetailRow label="Loaded models" value={status?.ai.ollamaLoadedCount ?? 0} />
                <DetailRow label={t("adminSystemHealthLatency")} value={status?.ai.healthLatencyMs != null ? `${status.ai.healthLatencyMs} ms` : "-"} />
                <DetailRow label={t("adminSystemProbeLatency")} value={status?.ai.probeLatencyMs != null ? `${status.ai.probeLatencyMs} ms` : "-"} />
                <DetailRow label={t("adminSystemLastProbe")} value={formatDate(status?.ai.lastProbeAt)} />
                <DetailRow label={t("adminSystemLastSuccessfulProbe")} value={formatDate(status?.ai.lastProbeSuccessAt)} />
                <DetailRow label={t("adminSystemLastSummarizationSuccess")} value={formatDate(status?.ai.lastSuccessAt)} />
              </Stack>
            </Paper>
          </Box>

          <Paper sx={{ p: 2, borderRadius: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSummarizerTelemetry")}</Typography>
            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(8, 1fr)" }, gap: 2 }}>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemRequests")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.requests ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemCacheHits")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.cacheHits ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemCacheMisses")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.cacheMisses ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemFailures")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.failures ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemProbeFailures")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.probeFailures ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemAvgLatency")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.averageLatencyMs != null ? `${status.ai.averageLatencyMs} ms` : "-"}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemOcrRequests")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.ocrRequests ?? 0}</Typography></Box>
              <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>{t("adminSystemOcrAvgLatency")}</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.ai.averageOcrLatencyMs != null ? `${status.ai.averageOcrLatencyMs} ms` : "-"}</Typography></Box>
            </Box>
            <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mt: 2 }}>
              <Chip label={status?.database.canConnect ? t("adminSystemDatabaseConnected") : t("adminSystemDatabaseIssue")} color={status?.database.canConnect ? "success" : "error"} size="small" />
              <Chip label={status?.auth.required ? t("adminSystemAuthEnforced") : t("adminSystemAuthOptional")} color={status?.auth.required ? "success" : "warning"} size="small" />
              <Chip label={status?.auth.googleConfigured ? t("adminSystemGoogleReady") : t("adminSystemGoogleOff")} variant="outlined" size="small" />
              <Chip label={status?.auth.gmailConfigured ? t("adminSystemGmailReady") : t("adminSystemGmailIncomplete")} variant="outlined" size="small" />
              <Chip label={status?.ai.gpuAvailable ? t("adminSystemGpuVisible") : t("adminSystemCpuMode")} color={status?.ai.gpuAvailable ? "success" : "default"} size="small" />
              <Chip label={status?.ai.ocrAvailable ? `OCR ${status.ai.ocrLanguages || "enabled"}` : t("adminSystemOcrUnavailable")} variant="outlined" size="small" />
              {(status?.ai.ollamaInstalledModels ?? []).slice(0, 4).map((model) => (
                <Chip key={model} label={`Model · ${model}`} variant="outlined" size="small" />
              ))}
              {(status?.ai.ollamaLoadedModels ?? []).slice(0, 3).map((model) => (
                <Chip key={`loaded-${model}`} label={`Loaded · ${model}`} color="primary" variant="outlined" size="small" />
              ))}
            </Box>
          </Paper>

          <Paper sx={{ p: 2, borderRadius: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>CV benchmark review</Typography>
            <Stack spacing={0.75}>
              <DetailRow label="Benchmark root" value={benchmarkStatus?.rootPath || "-"} />
              <DetailRow label="Last benchmark update" value={formatDate(benchmarkStatus?.lastUpdatedAtUtc)} />
              <DetailRow label="Corpus root" value={benchmarkIndex?.CorpusRoot || "-"} />
            </Stack>

            {benchmarkIndex ? (
              <>
                <Box sx={{ mt: 2, display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(5, 1fr)" }, gap: 1.25 }}>
                  <SummaryCard title="Files" value={String(benchmarkIndex.TotalFiles)} subtitle="Corpus inputs" />
                  <SummaryCard title="Coverage" value={formatPercent(benchmarkIndex.AverageCoverage)} subtitle="Structured field coverage" tone={benchmarkTone(benchmarkIndex.AverageCoverage)} />
                  <SummaryCard title="Confidence" value={formatPercent(benchmarkIndex.AverageConfidence)} subtitle="Field metadata confidence" tone={benchmarkTone(benchmarkIndex.AverageConfidence)} />
                  <SummaryCard title="Consistency" value={formatPercent(benchmarkIndex.AverageConsistency)} subtitle="Normalization consistency" tone={benchmarkTone(benchmarkIndex.AverageConsistency)} />
                  <SummaryCard title="Missing approved" value={String(benchmarkIndex.MissingApprovedFixtures)} subtitle="Needs fixture review" tone={benchmarkIndex.MissingApprovedFixtures > 0 ? "warning" : "success"} />
                </Box>

                <Box sx={{ mt: 2.5, display: "grid", gridTemplateColumns: { xs: "1fr", xl: "1.1fr 0.9fr" }, gap: 2 }}>
                  <Paper variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 900, mb: 1 }}>Top parser findings</Typography>
                    <Stack spacing={1}>
                      {benchmarkFindings.length > 0 ? benchmarkFindings.map((finding) => (
                        <Box key={`${finding.file}:${finding.issue}`} sx={{ p: 1.25, borderRadius: 2, backgroundColor: "background.default", border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
                          <Typography variant="caption" sx={{ color: "text.secondary" }}>{finding.file}</Typography>
                          <Typography variant="body2">{finding.issue}</Typography>
                        </Box>
                      )) : <Typography variant="body2" sx={{ color: "text.secondary" }}>No standout benchmark anomalies in the current run.</Typography>}
                    </Stack>
                  </Paper>

                  <Paper variant="outlined" sx={{ p: 1.5, borderRadius: 3 }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 900, mb: 1 }}>Weakest files in current run</Typography>
                    <Stack spacing={1}>
                      {weakestEntries.map((entry) => (
                        <Box key={entry.Slug} sx={{ p: 1.25, borderRadius: 2, backgroundColor: "background.default", border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
                          <Typography variant="body2" sx={{ fontWeight: 800 }}>{entry.FileName}</Typography>
                          <Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", mt: 0.75 }}>
                            <Chip size="small" label={`Coverage ${formatPercent(entry.CoverageScore)}`} color={benchmarkTone(entry.CoverageScore)} />
                            <Chip size="small" label={`Confidence ${formatPercent(entry.ConfidenceScore)}`} color={benchmarkTone(entry.ConfidenceScore)} />
                            <Chip size="small" label={`Consistency ${formatPercent(entry.ConsistencyScore)}`} color={benchmarkTone(entry.ConsistencyScore)} />
                          </Box>
                          <Typography variant="caption" sx={{ display: "block", color: "text.secondary", mt: 0.75 }}>{entry.DiffSummary || "-"}</Typography>
                        </Box>
                      ))}
                    </Stack>
                  </Paper>
                </Box>

                <Box sx={{ mt: 2, p: 1.5, borderRadius: 2, backgroundColor: "background.default", border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)", maxHeight: 280, overflow: "auto" }}>
                  <Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>Latest markdown summary</Typography>
                  <Typography variant="body2" sx={{ whiteSpace: "pre-wrap", fontFamily: "ui-monospace, SFMono-Regular, monospace" }}>
                    {benchmarkStatus?.reportMarkdown || "-"}
                  </Typography>
                </Box>
              </>
            ) : (
              <Box sx={{ mt: 1.5, p: 1.5, borderRadius: 2, backgroundColor: "background.default", border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
                <Typography variant="body2" sx={{ whiteSpace: "pre-wrap", fontFamily: "ui-monospace, SFMono-Regular, monospace" }}>
                  {benchmarkStatus?.reportMarkdown || "Run scripts/run-cv-benchmark.sh to generate the latest corpus report and fixture candidates."}
                </Typography>
              </Box>
            )}
          </Paper>
        </>
      ) : (
        <Box sx={{ display: "grid", gap: 2 }}>
          <Paper sx={{ p: 2, borderRadius: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemEmailSettingsTitle")}</Typography>
            <Typography variant="body2" sx={{ color: "text.secondary", mb: 1.5 }}>{t("adminSystemEmailSettingsBody")}</Typography>
            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
              <FormControlLabel
                control={<Checkbox checked={Boolean(emailSettings?.enabled)} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, enabled: e.target.checked } : prev)} />}
                label={t("adminSystemEnabled")}
                sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }}
              />
              <TextField label={t("adminSystemHost")} value={emailSettings?.host ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, host: e.target.value } : prev)} fullWidth />
              <TextField label={t("adminSystemPort")} type="number" value={emailSettings?.port ?? 587} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, port: Number(e.target.value) } : prev)} fullWidth />
              <TextField label={t("adminSystemUsername")} value={emailSettings?.user ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, user: e.target.value } : prev)} fullWidth />
              <TextField label={t("adminSystemPassword")} type="password" value={smtpPassword} onChange={(e) => { setSmtpPassword(e.target.value); if (e.target.value.trim()) setClearPassword(false); }} helperText={emailSettings?.hasPassword ? t("adminSystemPasswordStored") : t("adminSystemPasswordMissing")} fullWidth />
              <TextField label={t("adminSystemFrom")} value={emailSettings?.from ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, from: e.target.value } : prev)} fullWidth />
              <TextField label={t("adminSystemFromName")} value={emailSettings?.fromName ?? ""} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, fromName: e.target.value } : prev)} fullWidth />
              <TextField label={t("adminSystemTimeoutMs")} type="number" value={emailSettings?.timeoutMs ?? 15000} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, timeoutMs: Number(e.target.value) } : prev)} fullWidth />
              <FormControlLabel control={<Checkbox checked={Boolean(emailSettings?.enableSsl)} onChange={(e) => setEmailSettings((prev) => prev ? { ...prev, enableSsl: e.target.checked } : prev)} />} label={t("adminSystemSsl")} />
              <FormControlLabel control={<Checkbox checked={clearPassword} onChange={(e) => { setClearPassword(e.target.checked); if (e.target.checked) setSmtpPassword(""); }} />} label={t("adminSystemClearStoredPassword")} sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }} />
            </Box>
            <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1.5 }}>
              <Button variant="contained" disabled={savingSettings || !emailSettings} onClick={() => void saveEmailSettings()}>
                {savingSettings ? t("adminSystemSaving") : t("adminSystemSaveSettings")}
              </Button>
            </Box>
          </Paper>

          <Paper sx={{ p: 2, borderRadius: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>{t("adminSystemSmtpTest")}</Typography>
            <Typography variant="body2" sx={{ color: "text.secondary", mb: 1.5 }}>
              {t("adminSystemSmtpTestBody")}
            </Typography>
            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
              <TextField label={t("adminSystemRecipientEmail")} value={testEmailTo} onChange={(e) => setTestEmailTo(e.target.value)} placeholder={t("adminSystemRecipientPlaceholder")} />
              <TextField label={t("adminSystemSubject")} value={testEmailSubject} onChange={(e) => setTestEmailSubject(e.target.value)} />
              <TextField label={t("adminSystemMessage")} multiline minRows={3} value={testEmailMessage} onChange={(e) => setTestEmailMessage(e.target.value)} sx={{ gridColumn: { xs: "1 / -1", md: "1 / -1" } }} />
            </Box>
            <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1.5 }}>
              <Button variant="contained" disabled={sendingTestEmail} onClick={() => void sendTestEmail()}>
                {sendingTestEmail ? t("adminSystemSending") : t("adminSystemSendTestEmail")}
              </Button>
            </Box>
          </Paper>
        </Box>
      )}
    </Box>
  );
}
