import { useEffect, useMemo, useState } from "react";
import { AlertTriangle, CheckCircle2, ClipboardCheck, Clock3, FilePenLine, RefreshCw, ShieldCheck, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { trpc } from "@/lib/trpc";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

type SupplierFormState = {
  id: string;
  supplierName: string;
  service: string;
  location: string;
  criticality: "critique" | "elevee" | "moyenne";
  dpaStatus: "signed" | "pending" | "renew" | "expired" | "missing";
  reviewDate: string;
  owner: string;
  notes: string;
};

type DpaFormState = {
  id: string;
  supplierId: string;
  supplierName: string;
  status: "signed" | "pending" | "renew" | "expired";
  signedAt: string;
  expiresAt: string;
  reviewDueAt: string;
  owner: string;
  notes: string;
};

type BackupFormState = {
  id: string;
  scope: "database" | "documents" | "system" | "global";
  environment: "production" | "preproduction" | "staging" | "local" | "external";
  backupType: "scheduled" | "manual" | "snapshot" | "replication" | "external";
  lastSuccessAt: string;
  lastFailureAt: string;
  monthlySuccessRate: number;
  volumeLabel: string;
  retentionLabel: string;
  proofLabel: string;
  proofUrl: string;
  notes: string;
};

type RestoreTestFormState = {
  id: string;
  testedAt: string;
  environment: "production" | "preproduction" | "staging" | "local" | "external";
  scopeLabel: string;
  result: "success" | "warning" | "failed";
  responsible: string;
  observations: string;
  proofLabel: string;
  nextPlannedAt: string;
};

type RetentionFormState = {
  id: string;
  generatedAt: string;
  periodLabel: string;
  deletedAccounts: number;
  pendingPurge: number;
  anonymizedRecords: number;
  executedPurges: number;
  legalHoldCount: number;
  incidentsCount: number;
  notes: string;
};

type EvidenceFormState = {
  id: string;
  category: "security_policy" | "processing_register" | "dpa" | "audit_report" | "backup_report" | "retention_report" | "restore_test" | "incident_report" | "other";
  title: string;
  reference: string;
  url: string;
  description: string;
  updatedAt: string;
};

type IsoDeliverableSectionFormState = {
  id: string;
  title: string;
  content: string;
  guidance: string;
};

type IsoDeliverableFormState = {
  id: string;
  reference: string;
  title: string;
  domain: "gouvernance" | "acces" | "incidents" | "sauvegardes" | "fournisseurs" | "risques" | "continuite" | "rgpd" | "audit";
  status: "a_rediger" | "en_cours" | "a_relire" | "a_valider" | "valide" | "a_reviser";
  owner: string;
  approverName: string;
  approverEmail: string;
  summary: string;
  notes: string;
  lastReviewedAt: string;
  validatedAt: string;
  revisionDueAt: string;
  sections: IsoDeliverableSectionFormState[];
};

const emptySupplier: SupplierFormState = {
  id: "",
  supplierName: "",
  service: "",
  location: "UE",
  criticality: "moyenne",
  dpaStatus: "pending",
  reviewDate: "",
  owner: "",
  notes: "",
};

const emptyDpa: DpaFormState = {
  id: "",
  supplierId: "",
  supplierName: "",
  status: "pending",
  signedAt: "",
  expiresAt: "",
  reviewDueAt: "",
  owner: "",
  notes: "",
};

const emptyBackup: BackupFormState = {
  id: "",
  scope: "global",
  environment: "production",
  backupType: "scheduled",
  lastSuccessAt: "",
  lastFailureAt: "",
  monthlySuccessRate: 100,
  volumeLabel: "",
  retentionLabel: "",
  proofLabel: "",
  proofUrl: "",
  notes: "",
};

const emptyRestoreTest: RestoreTestFormState = {
  id: "",
  testedAt: "",
  environment: "preproduction",
  scopeLabel: "",
  result: "warning",
  responsible: "",
  observations: "",
  proofLabel: "",
  nextPlannedAt: "",
};

const emptyRetentionReport: RetentionFormState = {
  id: "",
  generatedAt: "",
  periodLabel: "",
  deletedAccounts: 0,
  pendingPurge: 0,
  anonymizedRecords: 0,
  executedPurges: 0,
  legalHoldCount: 0,
  incidentsCount: 0,
  notes: "",
};

const emptyEvidence: EvidenceFormState = {
  id: "",
  category: "other",
  title: "",
  reference: "",
  url: "",
  description: "",
  updatedAt: "",
};

const emptyIsoDeliverable: IsoDeliverableFormState = {
  id: "",
  reference: "",
  title: "",
  domain: "gouvernance",
  status: "a_rediger",
  owner: "",
  approverName: "",
  approverEmail: "",
  summary: "",
  notes: "",
  lastReviewedAt: "",
  validatedAt: "",
  revisionDueAt: "",
  sections: [],
};

const isoStatusLabels: Record<IsoDeliverableFormState["status"], string> = {
  a_rediger: "À rédiger",
  en_cours: "En cours",
  a_relire: "À relire",
  a_valider: "À valider",
  valide: "Validé",
  a_reviser: "À réviser",
};

const isoStatusClasses: Record<IsoDeliverableFormState["status"], string> = {
  a_rediger: "bg-slate-100 text-slate-700",
  en_cours: "bg-blue-100 text-blue-700",
  a_relire: "bg-amber-100 text-amber-800",
  a_valider: "bg-purple-100 text-purple-700",
  valide: "bg-green-100 text-green-700",
  a_reviser: "bg-red-100 text-red-700",
};

const isoDomainLabels: Record<IsoDeliverableFormState["domain"], string> = {
  gouvernance: "Gouvernance",
  acces: "Accès",
  incidents: "Incidents",
  sauvegardes: "Sauvegardes",
  fournisseurs: "Fournisseurs",
  risques: "Risques",
  continuite: "Continuité",
  rgpd: "RGPD",
  audit: "Audit",
};

const complianceEnvironmentLabels: Record<BackupFormState["environment"], string> = {
  production: "Production",
  preproduction: "Préproduction",
  staging: "Recette / staging",
  local: "Local / labo",
  external: "Externe",
};

const backupTypeLabels: Record<BackupFormState["backupType"], string> = {
  scheduled: "Planifiée",
  manual: "Manuelle",
  snapshot: "Snapshot",
  replication: "Réplication",
  external: "Export externe",
};

const evidenceCategoryLabels: Record<EvidenceFormState["category"], string> = {
  security_policy: "Politique sécurité",
  processing_register: "Registre des traitements",
  dpa: "DPA",
  audit_report: "Rapport d'audit",
  backup_report: "Rapport sauvegarde",
  retention_report: "Rapport rétention",
  restore_test: "Test restauration",
  incident_report: "Rapport incident",
  other: "Autre",
};

const buildDateTimeEvidenceLabel = () => new Date().toISOString().slice(0, 16);

const buildCurrentMonthLabel = () => {
  const now = new Date();
  return now.toLocaleDateString("fr-FR", {
    month: "long",
    year: "numeric",
  });
};

const getProofStatusMeta = (proofLabel?: string | null, proofUrl?: string | null) => {
  const hasLabel = Boolean(proofLabel?.trim());
  const hasUrl = Boolean(proofUrl?.trim());
  if (hasLabel && hasUrl) {
    return {
      label: "Preuve exploitable",
      className: "border-emerald-200 bg-emerald-50 text-emerald-700",
    };
  }
  if (hasLabel || hasUrl) {
    return {
      label: "Preuve partielle",
      className: "border-amber-200 bg-amber-50 text-amber-800",
    };
  }
  return {
    label: "Preuve manquante",
    className: "border-slate-200 bg-slate-50 text-slate-700",
  };
};

const getRestoreProofStatusMeta = (proofLabel?: string | null, observations?: string | null) => {
  const hasProof = Boolean(proofLabel?.trim());
  const hasObservations = Boolean(observations?.trim());
  if (hasProof && hasObservations) {
    return {
      label: "Test documenté",
      className: "border-emerald-200 bg-emerald-50 text-emerald-700",
    };
  }
  if (hasProof || hasObservations) {
    return {
      label: "Test partiellement tracé",
      className: "border-amber-200 bg-amber-50 text-amber-800",
    };
  }
  return {
    label: "Trace à compléter",
    className: "border-slate-200 bg-slate-50 text-slate-700",
  };
};

const getEvidenceFreshnessMeta = (updatedAt?: string | null) => {
  if (!updatedAt?.trim()) {
    return {
      label: "Date à compléter",
      className: "border-slate-200 bg-slate-50 text-slate-700",
    };
  }
  const parsed = new Date(updatedAt);
  if (Number.isNaN(parsed.getTime())) {
    return {
      label: "Date à vérifier",
      className: "border-amber-200 bg-amber-50 text-amber-800",
    };
  }
  const ageDays = Math.floor((Date.now() - parsed.getTime()) / (1000 * 60 * 60 * 24));
  if (ageDays <= 90) {
    return {
      label: "Preuve récente",
      className: "border-emerald-200 bg-emerald-50 text-emerald-700",
    };
  }
  if (ageDays <= 365) {
    return {
      label: "À revoir",
      className: "border-amber-200 bg-amber-50 text-amber-800",
    };
  }
  return {
    label: "Preuve ancienne",
    className: "border-red-200 bg-red-50 text-red-700",
  };
};

export default function ComplianceOperationsPanel() {
  const utils = trpc.useUtils();
  const { data, isLoading } = trpc.compliance.getOperations.useQuery();
  type OperationsData = NonNullable<typeof data>;
  const invalidateAll = async () => {
    await Promise.all([
      utils.compliance.getOperations.invalidate(),
      utils.compliance.getSnapshot.invalidate(),
    ]);
  };

  const [supplierForm, setSupplierForm] = useState<SupplierFormState>(emptySupplier);
  const [dpaForm, setDpaForm] = useState<DpaFormState>(emptyDpa);
  const [backupForm, setBackupForm] = useState<BackupFormState>(emptyBackup);
  const [restoreTestForm, setRestoreTestForm] = useState<RestoreTestFormState>(emptyRestoreTest);
  const [retentionForm, setRetentionForm] = useState<RetentionFormState>(emptyRetentionReport);
  const [evidenceForm, setEvidenceForm] = useState<EvidenceFormState>(emptyEvidence);
  const [selectedIsoDeliverableId, setSelectedIsoDeliverableId] = useState<string>("");
  const [isoDeliverableForm, setIsoDeliverableForm] = useState<IsoDeliverableFormState>(emptyIsoDeliverable);

  const upsertSupplier = trpc.compliance.upsertSupplier.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setSupplierForm(emptySupplier);
      toast.success("Fournisseur enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer le fournisseur"),
  });
  const deleteSupplier = trpc.compliance.deleteSupplier.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Fournisseur supprimé");
    },
  });

  const upsertDpa = trpc.compliance.upsertDpa.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setDpaForm(emptyDpa);
      toast.success("Suivi DPA enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer le DPA"),
  });
  const deleteDpa = trpc.compliance.deleteDpa.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Suivi DPA supprimé");
    },
  });

  const upsertBackupRecord = trpc.compliance.upsertBackupRecord.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setBackupForm(emptyBackup);
      toast.success("Supervision sauvegarde enregistrée");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer la sauvegarde"),
  });
  const deleteBackupRecord = trpc.compliance.deleteBackupRecord.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Entrée sauvegarde supprimée");
    },
  });

  const upsertRestoreTest = trpc.compliance.upsertRestoreTest.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setRestoreTestForm(emptyRestoreTest);
      toast.success("Test de restauration enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer le test"),
  });
  const deleteRestoreTest = trpc.compliance.deleteRestoreTest.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Test de restauration supprimé");
    },
  });

  const upsertRetentionReport = trpc.compliance.upsertRetentionReport.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setRetentionForm(emptyRetentionReport);
      toast.success("Rapport de rétention enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer le rapport"),
  });
  const deleteRetentionReport = trpc.compliance.deleteRetentionReport.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Rapport de rétention supprimé");
    },
  });

  const upsertEvidence = trpc.compliance.upsertEvidence.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      setEvidenceForm(emptyEvidence);
      toast.success("Élément de conformité enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer la preuve"),
  });
  const deleteEvidence = trpc.compliance.deleteEvidence.useMutation({
    onSuccess: async () => {
      await invalidateAll();
      toast.success("Élément de conformité supprimé");
    },
  });
  const bootstrapOperations = trpc.compliance.bootstrapOperations.useMutation({
    onSuccess: async (result) => {
      await invalidateAll();
      const details = [
        result.suppliersAdded ? `${result.suppliersAdded} fournisseur(s)` : null,
        result.dpasAdded ? `${result.dpasAdded} DPA` : null,
        result.evidenceAdded ? `${result.evidenceAdded} preuve(s)` : null,
      ].filter(Boolean).join(" • ");
      toast.success(details ? `Initialisation conformité terminée : ${details}` : "Initialisation conformité terminée");
    },
    onError: (error) => toast.error(error.message || "Impossible d'initialiser le pilotage conformité"),
  });
  const scrollToSection = (sectionId: string) => {
    document.getElementById(sectionId)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  const prepareBackupProofStarter = () => {
    setBackupForm({
      ...emptyBackup,
      scope: "global",
      environment: "production",
      backupType: "scheduled",
      notes:
        "Compléter avec la preuve réelle d’exploitation : journal cron ou Docker, export OVH, rapport de supervision, date de succès, volumétrie et conservation observées.",
    });
    scrollToSection("compliance-backups-section");
    toast.success("Formulaire sauvegarde préparé pour raccorder une preuve réelle");
  };
  const prepareRestoreTestStarter = () => {
    setRestoreTestForm({
      ...emptyRestoreTest,
      testedAt: buildDateTimeEvidenceLabel(),
      environment: "preproduction",
      scopeLabel: "Base de données + documents",
      result: "warning",
      responsible: "À confirmer",
      proofLabel: "Compte-rendu de test à joindre",
      observations:
        "Compléter après le test réel : déroulé, durée, contrôles effectués, écarts observés et validation finale.",
    });
    scrollToSection("compliance-restore-section");
    toast.success("Formulaire restauration préparé pour historiser un premier test");
  };
  const prepareRetentionStarter = () => {
    setRetentionForm({
      ...emptyRetentionReport,
      generatedAt: buildDateTimeEvidenceLabel(),
      periodLabel: `Suivi DPO ${buildCurrentMonthLabel()}`,
      notes:
        "Compléter avec le bilan mensuel : purges observées, exceptions legal hold, incidents éventuels et commentaire DPO.",
    });
    scrollToSection("compliance-retention-section");
    toast.success("Rapport DPO prérempli pour historiser le suivi mensuel");
  };
  const prepareEvidenceStarter = (category: EvidenceFormState["category"]) => {
    const starterByCategory: Record<EvidenceFormState["category"], Partial<EvidenceFormState>> = {
      security_policy: {
        title: "Politique ou procédure interne à centraliser",
        reference: "Document interne",
        description: "Préciser ici la politique, la procédure ou la note interne à conserver comme preuve de pilotage.",
      },
      processing_register: {
        title: "Registre des traitements - version de travail",
        reference: "RGPD-002",
        description: "Renseigner la version du registre, son périmètre, le responsable et le support de validation CCDS.",
      },
      dpa: {
        title: "DPA ou justificatif fournisseur",
        reference: "Contrat / avenant",
        description: "Conserver ici le DPA signé, la clause contractuelle ou la preuve de revue fournisseur utile à l’audit.",
      },
      audit_report: {
        title: "Rapport de contrôle ou d’audit",
        reference: "Audit interne",
        description: "Décrire brièvement le contrôle mené, son périmètre, la synthèse et le support associé.",
      },
      backup_report: {
        title: "Preuve de sauvegarde",
        reference: "Journal ou supervision",
        description: "Indiquer la source réelle de la preuve: cron, Docker, OVH, export externe, monitoring ou compte-rendu d’exploitation.",
      },
      retention_report: {
        title: "Rapport mensuel DPO rétention",
        reference: `Suivi DPO ${buildCurrentMonthLabel()}`,
        description: "Historiser ici le rapport mensuel de purge, d’anonymisation, d’exceptions legal hold et d’incidents liés à la rétention.",
      },
      restore_test: {
        title: "Compte-rendu de test de restauration",
        reference: "Test exploitation",
        description: "Préciser le périmètre restauré, le résultat, la durée, les écarts observés et le responsable du contrôle.",
      },
      incident_report: {
        title: "Rapport ou fiche d’incident",
        reference: "SEC-003",
        description: "Conserver ici l’incident, son niveau, le confinement, l’investigation, la décision RGPD et la revue post-incident.",
      },
      other: {
        title: "Élément de conformité complémentaire",
        reference: "Référence libre",
        description: "Ajouter ici tout autre justificatif utile au pilotage conformité ou à l’audit.",
      },
    };

    setEvidenceForm({
      ...emptyEvidence,
      category,
      updatedAt: buildDateTimeEvidenceLabel(),
      ...starterByCategory[category],
    });
    scrollToSection("compliance-evidence-section");
    toast.success(`Fiche preuve préparée pour ${evidenceCategoryLabels[category].toLowerCase()}`);
  };
  const upsertIsoDeliverable = trpc.compliance.upsertIsoDeliverable.useMutation({
    onSuccess: async (result) => {
      await invalidateAll();
      setSelectedIsoDeliverableId(result.id);
      toast.success("Livrable ISO enregistré");
    },
    onError: (error) => toast.error(error.message || "Impossible d'enregistrer le livrable ISO"),
  });
  const setIsoDeliverableStatus = trpc.compliance.setIsoDeliverableStatus.useMutation({
    onSuccess: async (result) => {
      await invalidateAll();
      setSelectedIsoDeliverableId(result.id);
      toast.success(`Livrable passé en ${isoStatusLabels[result.status as IsoDeliverableFormState["status"]].toLowerCase()}`);
    },
    onError: (error) => toast.error(error.message || "Impossible de mettre à jour le statut du livrable"),
  });

  const suppliersById = useMemo(
    () => Object.fromEntries((data?.suppliers || []).map((entry) => [entry.id, entry.supplierName])),
    [data?.suppliers]
  );

  const exploitation = data?.exploitation;
  const exploitationConfidenceMeta = useMemo(() => {
    if (!exploitation) {
      return {
        label: "Chargement…",
        badgeClassName: "border-slate-200 bg-slate-50 text-slate-700",
      };
    }
    if (exploitation.confidenceStatus === "ok") {
      return {
        label: "Pilotage maîtrisé",
        badgeClassName: "border-emerald-200 bg-emerald-50 text-emerald-700",
      };
    }
    if (exploitation.confidenceStatus === "warning") {
      return {
        label: "Pilotage à surveiller",
        badgeClassName: "border-amber-200 bg-amber-50 text-amber-800",
      };
    }
    return {
      label: "Traçabilité à compléter",
      badgeClassName: "border-violet-200 bg-violet-50 text-violet-700",
    };
  }, [exploitation]);

  const builtInEvidence = useMemo(() => ([
    {
      id: "builtin-privacy",
      category: "security_policy",
      title: "Politique de confidentialité publique",
      reference: "Page portail",
      url: "/confidentialite?returnTo=%2Fadmin%3Ftab%3Dconformite",
      description: "Version publique exposée dans le portail.",
      updatedAt: "",
    },
    {
      id: "builtin-cgu",
      category: "security_policy",
      title: "CGU publiques",
      reference: "Page portail",
      url: "/cgu?returnTo=%2Fadmin%3Ftab%3Dconformite",
      description: "Version publique exposée dans le portail.",
      updatedAt: "",
    },
  ]), []);

  const isoDeliverables = data?.isoDeliverables || [];
  const selectedIsoDeliverable = useMemo(
    () => isoDeliverables.find((entry) => entry.id === selectedIsoDeliverableId) || isoDeliverables[0] || null,
    [isoDeliverables, selectedIsoDeliverableId]
  );

  useEffect(() => {
    if (!selectedIsoDeliverableId && isoDeliverables[0]?.id) {
      setSelectedIsoDeliverableId(isoDeliverables[0].id);
    }
  }, [isoDeliverables, selectedIsoDeliverableId]);

  useEffect(() => {
    if (!selectedIsoDeliverable) {
      setIsoDeliverableForm(emptyIsoDeliverable);
      return;
    }
    setIsoDeliverableForm({
      id: selectedIsoDeliverable.id,
      reference: selectedIsoDeliverable.reference,
      title: selectedIsoDeliverable.title,
      domain: selectedIsoDeliverable.domain,
      status: selectedIsoDeliverable.status,
      owner: selectedIsoDeliverable.owner || "",
      approverName: selectedIsoDeliverable.approverName || "",
      approverEmail: selectedIsoDeliverable.approverEmail || "",
      summary: selectedIsoDeliverable.summary || "",
      notes: selectedIsoDeliverable.notes || "",
      lastReviewedAt: selectedIsoDeliverable.lastReviewedAt || "",
      validatedAt: selectedIsoDeliverable.validatedAt || "",
      revisionDueAt: selectedIsoDeliverable.revisionDueAt || "",
      sections: (selectedIsoDeliverable.sections || []).map((section) => ({
        id: section.id,
        title: section.title,
        content: section.content || "",
        guidance: section.guidance || "",
      })),
    });
  }, [selectedIsoDeliverable]);

  const hydrateSupplierForm = (entry: OperationsData["suppliers"][number]) => setSupplierForm({
    id: entry.id,
    supplierName: entry.supplierName,
    service: entry.service,
    location: entry.location,
    criticality: entry.criticality,
    dpaStatus: entry.dpaStatus,
    reviewDate: entry.reviewDate || "",
    owner: entry.owner,
    notes: entry.notes || "",
  });

  const hydrateDpaForm = (entry: OperationsData["dpas"][number]) => setDpaForm({
    id: entry.id,
    supplierId: entry.supplierId || "",
    supplierName: entry.supplierName,
    status: entry.status,
    signedAt: entry.signedAt || "",
    expiresAt: entry.expiresAt || "",
    reviewDueAt: entry.reviewDueAt || "",
    owner: entry.owner,
    notes: entry.notes || "",
  });

  const hydrateBackupForm = (entry: OperationsData["backupRecords"][number]) => setBackupForm({
    id: entry.id,
    scope: entry.scope,
    environment: entry.environment || "production",
    backupType: entry.backupType || "scheduled",
    lastSuccessAt: entry.lastSuccessAt || "",
    lastFailureAt: entry.lastFailureAt || "",
    monthlySuccessRate: entry.monthlySuccessRate,
    volumeLabel: entry.volumeLabel || "",
    retentionLabel: entry.retentionLabel || "",
    proofLabel: entry.proofLabel || "",
    proofUrl: entry.proofUrl || "",
    notes: entry.notes || "",
  });

  const hydrateRestoreTestForm = (entry: OperationsData["restoreTests"][number]) => setRestoreTestForm({
    id: entry.id,
    testedAt: entry.testedAt || "",
    environment: entry.environment || "preproduction",
    scopeLabel: entry.scopeLabel || "",
    result: entry.result,
    responsible: entry.responsible || "",
    observations: entry.observations || "",
    proofLabel: entry.proofLabel || "",
    nextPlannedAt: entry.nextPlannedAt || "",
  });

  const hydrateRetentionForm = (entry: OperationsData["retentionReports"][number]) => setRetentionForm({
    id: entry.id,
    generatedAt: entry.generatedAt || "",
    periodLabel: entry.periodLabel || "",
    deletedAccounts: entry.deletedAccounts,
    pendingPurge: entry.pendingPurge,
    anonymizedRecords: entry.anonymizedRecords,
    executedPurges: entry.executedPurges,
    legalHoldCount: entry.legalHoldCount,
    incidentsCount: entry.incidentsCount,
    notes: entry.notes || "",
  });

  const hydrateEvidenceForm = (entry: OperationsData["evidenceCenter"][number]) => setEvidenceForm({
    id: entry.id,
    category: entry.category,
    title: entry.title,
    reference: entry.reference || "",
    url: entry.url || "",
    description: entry.description || "",
    updatedAt: entry.updatedAt,
  });

  const submitBackupRecord = () => {
    upsertBackupRecord.mutate({
      ...backupForm,
      proofLabel: backupForm.proofLabel.trim(),
      proofUrl: backupForm.proofUrl.trim(),
      volumeLabel: backupForm.volumeLabel.trim(),
      retentionLabel: backupForm.retentionLabel.trim(),
      notes: backupForm.notes.trim(),
    });
  };

  const submitRestoreTest = () => {
    upsertRestoreTest.mutate({
      ...restoreTestForm,
      testedAt: restoreTestForm.testedAt.trim() || buildDateTimeEvidenceLabel(),
      scopeLabel: restoreTestForm.scopeLabel.trim(),
      responsible: restoreTestForm.responsible.trim(),
      proofLabel: restoreTestForm.proofLabel.trim(),
      observations: restoreTestForm.observations.trim(),
      nextPlannedAt: restoreTestForm.nextPlannedAt.trim(),
    });
  };

  const submitRetentionReport = () => {
    upsertRetentionReport.mutate({
      ...retentionForm,
      generatedAt: retentionForm.generatedAt.trim() || buildDateTimeEvidenceLabel(),
      periodLabel: retentionForm.periodLabel.trim() || `Suivi DPO ${buildCurrentMonthLabel()}`,
      notes: retentionForm.notes.trim(),
    });
  };

  const submitEvidence = () => {
    upsertEvidence.mutate({
      ...evidenceForm,
      title: evidenceForm.title.trim(),
      reference: evidenceForm.reference.trim(),
      url: evidenceForm.url.trim(),
      description: evidenceForm.description.trim(),
      updatedAt: evidenceForm.updatedAt.trim() || buildDateTimeEvidenceLabel(),
    });
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5 text-primary" />
            Pilotage opérationnel conformité
          </CardTitle>
          <CardDescription>
            Registre fournisseurs, DPA, sauvegardes, restaurations, rétention et centre de preuves pour alimenter un audit réel.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap items-start justify-between gap-3 rounded-lg border border-primary/15 bg-primary/[0.03] p-4">
            <div className="space-y-1">
              <p className="text-sm text-muted-foreground">État global d’exploitation</p>
              <p className="text-lg font-semibold">Sauvegardes et restaurations auditées</p>
              <p className="text-sm text-muted-foreground">
                Cette vue sert à démontrer ce qui est réellement suivi, testé et historisé, même si une partie des preuves reste encore saisie manuellement.
              </p>
            </div>
            <Badge variant="outline" className={exploitationConfidenceMeta.badgeClassName}>
              {exploitationConfidenceMeta.label}
            </Badge>
          </div>

          <div className="flex flex-wrap gap-2">
            <Button
              type="button"
              onClick={() => bootstrapOperations.mutate()}
              disabled={bootstrapOperations.isPending}
            >
              <RefreshCw className={`mr-2 h-4 w-4 ${bootstrapOperations.isPending ? "animate-spin" : ""}`} />
              Amorcer avec les données connues
            </Button>
            <Button type="button" variant="outline" onClick={prepareBackupProofStarter}>
              Préparer une preuve de sauvegarde
            </Button>
            <Button type="button" variant="outline" onClick={prepareRestoreTestStarter}>
              Préparer un test de restauration
            </Button>
            <Button type="button" variant="outline" onClick={prepareRetentionStarter}>
              Préparer un rapport DPO mensuel
            </Button>
            <p className="self-center text-sm text-muted-foreground">
              Cette action ajoute seulement les éléments détectés ou documentés sans inventer de fausses preuves d’exploitation.
            </p>
          </div>
          {(data?.backupRecords.length === 0 || data?.restoreTests.length === 0) ? (
            <div className="rounded-lg border border-blue-200 bg-blue-50 p-4 text-sm text-blue-950">
              <p className="font-medium">Amorçage exploitation recommandé</p>
              <ul className="mt-2 list-disc space-y-1 pl-5">
                {data?.backupRecords.length === 0 ? (
                  <li>Créer une première fiche de sauvegarde avec environnement, type, source de preuve et notes d’exploitation.</li>
                ) : null}
                {data?.restoreTests.length === 0 ? (
                  <li>Historiser un premier test de restauration en précisant au minimum le périmètre, le résultat, le responsable et les observations.</li>
                ) : null}
              </ul>
            </div>
          ) : null}
          {exploitation?.alerts?.length ? (
            <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
              <div className="flex items-start gap-2">
                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                <div className="space-y-2">
                  <p className="font-medium">Alertes exploitation à surveiller</p>
                  <ul className="list-disc space-y-1 pl-5">
                    {exploitation.alerts.map((alert) => (
                      <li key={alert}>{alert}</li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          ) : null}
          {bootstrapOperations.data?.notes?.length ? (
            <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
              <p className="font-medium">Points encore à compléter côté exploitation</p>
              <ul className="mt-2 list-disc space-y-1 pl-5">
                {bootstrapOperations.data.notes.map((note) => (
                  <li key={note}>{note}</li>
                ))}
              </ul>
            </div>
          ) : null}
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Dernière sauvegarde réussie</p>
              <p className="mt-2 text-base font-semibold">
                {exploitation?.latestBackupSuccess?.lastSuccessAt || "Aucune trace"}
              </p>
              <p className="mt-2 text-xs text-muted-foreground">
                {exploitation?.latestBackupSuccess
                  ? `${complianceEnvironmentLabels[exploitation.latestBackupSuccess.environment || "production"]} • ${backupTypeLabels[exploitation.latestBackupSuccess.backupType || "scheduled"]}`
                  : "À saisir ou raccorder depuis l’exploitation"}
              </p>
              {exploitation?.latestBackupFailure?.lastFailureAt ? (
                <p className="mt-2 text-xs text-amber-700">
                  Dernier échec visible : {exploitation.latestBackupFailure.lastFailureAt}
                </p>
              ) : null}
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Dernier test de restauration</p>
              <p className="mt-2 text-base font-semibold">
                {exploitation?.latestRestoreTest?.testedAt || "Aucun test"}
              </p>
              <p className="mt-2 text-xs text-muted-foreground">
                {exploitation?.latestRestoreTest
                  ? `${complianceEnvironmentLabels[exploitation.latestRestoreTest.environment || "preproduction"]} • ${exploitation.latestRestoreTest.scopeLabel || "Périmètre non précisé"}`
                  : "Historique de test à construire"}
              </p>
              {exploitation?.latestSuccessfulRestore?.testedAt ? (
                <p className="mt-2 text-xs text-emerald-700">
                  Dernier succès confirmé : {exploitation.latestSuccessfulRestore.testedAt}
                </p>
              ) : null}
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Preuves de sauvegarde</p>
              <p className="mt-2 text-2xl font-semibold">
                {exploitation?.proofCoverageCount ?? 0}/{data?.backupRecords.length ?? 0}
              </p>
              <p className="mt-2 text-xs text-muted-foreground">
                Entrées avec source ou lien de preuve associé
              </p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Preuves de restauration</p>
              <p className="mt-2 text-2xl font-semibold">
                {exploitation?.restoreProofCoverageCount ?? 0}/{data?.restoreTests.length ?? 0}
              </p>
              <p className="mt-2 text-xs text-muted-foreground">
                Comptes-rendus de test réellement documentés
              </p>
            </div>
          </div>
          <div className="grid gap-4 md:grid-cols-4">
          <div className="rounded-lg border p-4">
            <p className="text-sm text-muted-foreground">Fournisseurs suivis</p>
            <p className="mt-2 text-2xl font-semibold">{data?.suppliers.length ?? 0}</p>
          </div>
          <div className="rounded-lg border p-4">
            <p className="text-sm text-muted-foreground">DPA en alerte</p>
            <p className="mt-2 text-2xl font-semibold">
              {data?.dpas.filter((entry) => entry.status === "pending" || entry.status === "renew" || entry.status === "expired").length ?? 0}
            </p>
          </div>
          <div className="rounded-lg border p-4">
            <p className="text-sm text-muted-foreground">Purges en attente</p>
            <p className="mt-2 text-2xl font-semibold">{data?.metrics.pendingPurgeCount ?? 0}</p>
          </div>
          <div className="rounded-lg border p-4">
            <p className="text-sm text-muted-foreground">Exceptions legal hold</p>
            <p className="mt-2 text-2xl font-semibold">{data?.metrics.legalHoldCount ?? 0}</p>
          </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>1. Registre fournisseurs</CardTitle>
          <CardDescription>Prestataires réels, criticité, localisation, DPA et responsable interne.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-3 md:grid-cols-4">
            <Input placeholder="Fournisseur" value={supplierForm.supplierName} onChange={(e) => setSupplierForm((prev) => ({ ...prev, supplierName: e.target.value }))} />
            <Input placeholder="Service" value={supplierForm.service} onChange={(e) => setSupplierForm((prev) => ({ ...prev, service: e.target.value }))} />
            <Input placeholder="Localisation" value={supplierForm.location} onChange={(e) => setSupplierForm((prev) => ({ ...prev, location: e.target.value }))} />
            <Input placeholder="Responsable" value={supplierForm.owner} onChange={(e) => setSupplierForm((prev) => ({ ...prev, owner: e.target.value }))} />
            <Select value={supplierForm.criticality} onValueChange={(value) => setSupplierForm((prev) => ({ ...prev, criticality: value as SupplierFormState["criticality"] }))}>
              <SelectTrigger><SelectValue placeholder="Criticité" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="critique">Critique</SelectItem>
                <SelectItem value="elevee">Élevée</SelectItem>
                <SelectItem value="moyenne">Moyenne</SelectItem>
              </SelectContent>
            </Select>
            <Select value={supplierForm.dpaStatus} onValueChange={(value) => setSupplierForm((prev) => ({ ...prev, dpaStatus: value as SupplierFormState["dpaStatus"] }))}>
              <SelectTrigger><SelectValue placeholder="DPA" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="signed">Signé</SelectItem>
                <SelectItem value="pending">En attente</SelectItem>
                <SelectItem value="renew">À renouveler</SelectItem>
                <SelectItem value="expired">Expiré</SelectItem>
                <SelectItem value="missing">Manquant</SelectItem>
              </SelectContent>
            </Select>
            <Input placeholder="Date de révision" value={supplierForm.reviewDate} onChange={(e) => setSupplierForm((prev) => ({ ...prev, reviewDate: e.target.value }))} />
            <div className="md:col-span-2">
              <Input placeholder="Notes" value={supplierForm.notes} onChange={(e) => setSupplierForm((prev) => ({ ...prev, notes: e.target.value }))} />
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button onClick={() => upsertSupplier.mutate(supplierForm)}>Enregistrer le fournisseur</Button>
            <Button variant="outline" onClick={() => setSupplierForm(emptySupplier)}>Réinitialiser</Button>
          </div>
          <div className="space-y-2">
            {(data?.suppliers || []).map((entry) => (
              <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium">{entry.supplierName}</p>
                    <Badge variant="outline">{entry.service}</Badge>
                    <Badge className={entry.criticality === "critique" ? "bg-red-100 text-red-700" : entry.criticality === "elevee" ? "bg-amber-100 text-amber-800" : "bg-blue-100 text-blue-700"}>{entry.criticality}</Badge>
                    <Badge variant="outline">DPA {entry.dpaStatus}</Badge>
                  </div>
                  <p className="text-sm text-muted-foreground">{entry.location} • {entry.owner}{entry.reviewDate ? ` • révision ${entry.reviewDate}` : ""}</p>
                  {entry.notes ? <p className="mt-1 text-xs text-muted-foreground">{entry.notes}</p> : null}
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateSupplierForm(entry)}>Modifier</Button>
                  <Button variant="outline" size="sm" onClick={() => deleteSupplier.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>2. Suivi des DPA</CardTitle>
          <CardDescription>Échéances, renouvellements et contrats manquants.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-3 md:grid-cols-4">
            <Select value={dpaForm.supplierId || "__none__"} onValueChange={(value) => {
              const supplierId = value === "__none__" ? "" : value;
              setDpaForm((prev) => ({
                ...prev,
                supplierId,
                supplierName: supplierId ? suppliersById[supplierId] || prev.supplierName : prev.supplierName,
              }));
            }}>
              <SelectTrigger><SelectValue placeholder="Fournisseur lié" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="__none__">Aucun lien direct</SelectItem>
                {(data?.suppliers || []).map((entry) => (
                  <SelectItem key={entry.id} value={entry.id}>{entry.supplierName}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Input placeholder="Nom fournisseur" value={dpaForm.supplierName} onChange={(e) => setDpaForm((prev) => ({ ...prev, supplierName: e.target.value }))} />
            <Input placeholder="Responsable" value={dpaForm.owner} onChange={(e) => setDpaForm((prev) => ({ ...prev, owner: e.target.value }))} />
            <Select value={dpaForm.status} onValueChange={(value) => setDpaForm((prev) => ({ ...prev, status: value as DpaFormState["status"] }))}>
              <SelectTrigger><SelectValue placeholder="Statut DPA" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="signed">Signé</SelectItem>
                <SelectItem value="pending">En attente</SelectItem>
                <SelectItem value="renew">À renouveler</SelectItem>
                <SelectItem value="expired">Expiré</SelectItem>
              </SelectContent>
            </Select>
            <Input placeholder="Signé le" value={dpaForm.signedAt} onChange={(e) => setDpaForm((prev) => ({ ...prev, signedAt: e.target.value }))} />
            <Input placeholder="Expire le" value={dpaForm.expiresAt} onChange={(e) => setDpaForm((prev) => ({ ...prev, expiresAt: e.target.value }))} />
            <Input placeholder="Révision due le" value={dpaForm.reviewDueAt} onChange={(e) => setDpaForm((prev) => ({ ...prev, reviewDueAt: e.target.value }))} />
            <div className="md:col-span-4">
              <Input placeholder="Notes" value={dpaForm.notes} onChange={(e) => setDpaForm((prev) => ({ ...prev, notes: e.target.value }))} />
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button onClick={() => upsertDpa.mutate(dpaForm)}>Enregistrer le DPA</Button>
            <Button variant="outline" onClick={() => setDpaForm(emptyDpa)}>Réinitialiser</Button>
          </div>
          <div className="space-y-2">
            {(data?.dpas || []).map((entry) => (
              <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium">{entry.supplierName}</p>
                    <Badge className={entry.status === "signed" ? "bg-green-100 text-green-700" : entry.status === "expired" ? "bg-red-100 text-red-700" : "bg-amber-100 text-amber-800"}>{entry.status}</Badge>
                    {entry.reviewDueAt ? <Badge variant="outline">Révision {entry.reviewDueAt}</Badge> : null}
                  </div>
                  <p className="text-sm text-muted-foreground">{entry.owner}{entry.signedAt ? ` • signé ${entry.signedAt}` : ""}{entry.expiresAt ? ` • échéance ${entry.expiresAt}` : ""}</p>
                  {entry.notes ? <p className="mt-1 text-xs text-muted-foreground">{entry.notes}</p> : null}
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateDpaForm(entry)}>Modifier</Button>
                  <Button variant="outline" size="sm" onClick={() => deleteDpa.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-4 xl:grid-cols-2">
        <Card id="compliance-backups-section">
          <CardHeader>
            <CardTitle>3. Sauvegardes</CardTitle>
            <CardDescription>Preuves d’exécution, environnement, type, volumétrie, conservation et source de contrôle. Les champs date, volume et conservation peuvent être complétés plus tard si l’exploitation n’a pas encore remonté l’information.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-lg border border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-700">
              <p className="font-medium text-slate-950">Repère d’exploitation</p>
              <p className="mt-1">
                Conserve ici au moins une ligne par périmètre utile: base, documents, système ou global. Si la preuve n’est pas encore automatisée, indique la source réelle observée: cron, Docker, OVH, export externe ou supervision.
              </p>
            </div>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              <Select value={backupForm.scope} onValueChange={(value) => setBackupForm((prev) => ({ ...prev, scope: value as BackupFormState["scope"] }))}>
                <SelectTrigger><SelectValue placeholder="Périmètre" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="global">Global</SelectItem>
                  <SelectItem value="database">Base de données</SelectItem>
                  <SelectItem value="documents">Documents</SelectItem>
                  <SelectItem value="system">Configuration système</SelectItem>
                </SelectContent>
              </Select>
              <Select value={backupForm.environment} onValueChange={(value) => setBackupForm((prev) => ({ ...prev, environment: value as BackupFormState["environment"] }))}>
                <SelectTrigger><SelectValue placeholder="Environnement" /></SelectTrigger>
                <SelectContent>
                  {Object.entries(complianceEnvironmentLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>{label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={backupForm.backupType} onValueChange={(value) => setBackupForm((prev) => ({ ...prev, backupType: value as BackupFormState["backupType"] }))}>
                <SelectTrigger><SelectValue placeholder="Type de sauvegarde" /></SelectTrigger>
                <SelectContent>
                  {Object.entries(backupTypeLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>{label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Input placeholder="Dernière sauvegarde réussie (optionnel)" value={backupForm.lastSuccessAt} onChange={(e) => setBackupForm((prev) => ({ ...prev, lastSuccessAt: e.target.value }))} />
              <Input placeholder="Dernier échec" value={backupForm.lastFailureAt} onChange={(e) => setBackupForm((prev) => ({ ...prev, lastFailureAt: e.target.value }))} />
              <Input type="number" placeholder="Taux de réussite %" value={backupForm.monthlySuccessRate} onChange={(e) => setBackupForm((prev) => ({ ...prev, monthlySuccessRate: Number(e.target.value || 0) }))} />
              <Input placeholder="Volume sauvegardé (optionnel)" value={backupForm.volumeLabel} onChange={(e) => setBackupForm((prev) => ({ ...prev, volumeLabel: e.target.value }))} />
              <Input placeholder="Durée de conservation (optionnel)" value={backupForm.retentionLabel} onChange={(e) => setBackupForm((prev) => ({ ...prev, retentionLabel: e.target.value }))} />
              <Input placeholder="Source / preuve (journal, job, rapport)" value={backupForm.proofLabel} onChange={(e) => setBackupForm((prev) => ({ ...prev, proofLabel: e.target.value }))} />
              <Input placeholder="Lien de preuve si disponible" value={backupForm.proofUrl} onChange={(e) => setBackupForm((prev) => ({ ...prev, proofUrl: e.target.value }))} />
            </div>
            <Textarea placeholder="Observations" value={backupForm.notes} onChange={(e) => setBackupForm((prev) => ({ ...prev, notes: e.target.value }))} />
            <div className="flex flex-wrap gap-2">
              <Button onClick={submitBackupRecord}>Enregistrer</Button>
              <Button variant="outline" onClick={() => setBackupForm(emptyBackup)}>Réinitialiser</Button>
            </div>
	            <div className="space-y-2">
	              {(data?.backupRecords || []).map((entry) => (
	                <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
	                  <div>
                      {(() => {
                        const proofStatus = getProofStatusMeta(entry.proofLabel, entry.proofUrl);
                        return (
                          <div className="mb-2">
                            <Badge variant="outline" className={proofStatus.className}>{proofStatus.label}</Badge>
                          </div>
                        );
                      })()}
	                    <div className="flex flex-wrap items-center gap-2">
                      <p className="font-medium">{entry.scope}</p>
                      <Badge variant="outline">{complianceEnvironmentLabels[entry.environment || "production"]}</Badge>
                      <Badge variant="outline">{backupTypeLabels[entry.backupType || "scheduled"]}</Badge>
                      <Badge className={entry.monthlySuccessRate >= 95 ? "bg-green-100 text-green-700" : entry.monthlySuccessRate >= 80 ? "bg-amber-100 text-amber-800" : "bg-red-100 text-red-700"}>{entry.monthlySuccessRate}%</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Succès : {entry.lastSuccessAt || "non renseigné"} • Échec : {entry.lastFailureAt || "aucun"} • Volume : {entry.volumeLabel || "non renseigné"} • Conservation : {entry.retentionLabel || "non renseignée"}
                    </p>
                    {entry.proofLabel || entry.proofUrl ? (
                      <p className="mt-1 text-xs text-muted-foreground">
                        Preuve : {entry.proofLabel || "Lien direct"}
                        {entry.proofUrl ? (
                          <>
                            {" "}
                            • <a href={entry.proofUrl} target="_blank" rel="noreferrer" className="text-primary underline underline-offset-4">ouvrir</a>
                          </>
                        ) : null}
                      </p>
                    ) : null}
                    {entry.notes ? <p className="mt-1 text-xs text-muted-foreground">{entry.notes}</p> : null}
                  </div>
                  <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateBackupForm(entry)}>Modifier</Button>
                    <Button variant="outline" size="sm" onClick={() => deleteBackupRecord.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card id="compliance-restore-section">
          <CardHeader>
            <CardTitle>Tests de restauration</CardTitle>
            <CardDescription>Historise les tests réellement menés: environnement, périmètre restauré, résultat, responsable et prochaine échéance. La date peut être complétée plus tard si l’exploitation prépare encore la preuve.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-lg border border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-700">
              <p className="font-medium text-slate-950">Repère d’exploitation</p>
              <p className="mt-1">
                L’objectif n’est pas de déclarer une restauration théorique, mais de garder une trace simple du test réellement mené: périmètre restauré, résultat, durée, écarts et prochaine vérification prévue.
              </p>
            </div>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              <Input placeholder="Date du test (optionnel)" value={restoreTestForm.testedAt} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, testedAt: e.target.value }))} />
              <Select value={restoreTestForm.environment} onValueChange={(value) => setRestoreTestForm((prev) => ({ ...prev, environment: value as RestoreTestFormState["environment"] }))}>
                <SelectTrigger><SelectValue placeholder="Environnement" /></SelectTrigger>
                <SelectContent>
                  {Object.entries(complianceEnvironmentLabels).map(([value, label]) => (
                    <SelectItem key={value} value={value}>{label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={restoreTestForm.result} onValueChange={(value) => setRestoreTestForm((prev) => ({ ...prev, result: value as RestoreTestFormState["result"] }))}>
                <SelectTrigger><SelectValue placeholder="Résultat" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="success">Succès</SelectItem>
                  <SelectItem value="warning">Avec réserves</SelectItem>
                  <SelectItem value="failed">Échec</SelectItem>
                </SelectContent>
              </Select>
              <Input placeholder="Périmètre restauré (DB, docs, portail complet...)" value={restoreTestForm.scopeLabel} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, scopeLabel: e.target.value }))} />
              <Input placeholder="Responsable du contrôle" value={restoreTestForm.responsible} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, responsible: e.target.value }))} />
              <Input placeholder="Preuve / compte-rendu" value={restoreTestForm.proofLabel} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, proofLabel: e.target.value }))} />
              <Input placeholder="Prochain contrôle prévu" value={restoreTestForm.nextPlannedAt} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, nextPlannedAt: e.target.value }))} />
            </div>
            <Textarea placeholder="Observations" value={restoreTestForm.observations} onChange={(e) => setRestoreTestForm((prev) => ({ ...prev, observations: e.target.value }))} />
            <div className="flex flex-wrap gap-2">
              <Button onClick={submitRestoreTest}>Enregistrer</Button>
              <Button variant="outline" onClick={() => setRestoreTestForm(emptyRestoreTest)}>Réinitialiser</Button>
            </div>
	            <div className="space-y-2">
	              {(data?.restoreTests || []).map((entry) => (
	                <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
	                  <div>
                      {(() => {
                        const proofStatus = getRestoreProofStatusMeta(entry.proofLabel, entry.observations);
                        return (
                          <div className="mb-2">
                            <Badge variant="outline" className={proofStatus.className}>{proofStatus.label}</Badge>
                          </div>
                        );
                      })()}
	                    <div className="flex flex-wrap items-center gap-2">
                      <p className="font-medium">{entry.testedAt || "Date non renseignée"}</p>
                      <Badge variant="outline">{complianceEnvironmentLabels[entry.environment || "preproduction"]}</Badge>
                      <Badge className={entry.result === "success" ? "bg-green-100 text-green-700" : entry.result === "warning" ? "bg-amber-100 text-amber-800" : "bg-red-100 text-red-700"}>{entry.result}</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {entry.scopeLabel || "Périmètre non précisé"}
                      {entry.responsible ? ` • contrôlé par ${entry.responsible}` : ""}
                      {entry.nextPlannedAt ? ` • prochain test ${entry.nextPlannedAt}` : " • prochain test à planifier"}
                    </p>
                    {entry.proofLabel ? <p className="mt-1 text-xs text-muted-foreground">Preuve : {entry.proofLabel}</p> : null}
                    {entry.observations ? <p className="mt-1 text-xs text-muted-foreground">{entry.observations}</p> : null}
                  </div>
                  <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateRestoreTestForm(entry)}>Modifier</Button>
                    <Button variant="outline" size="sm" onClick={() => deleteRestoreTest.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card id="compliance-retention-section">
        <CardHeader>
          <CardTitle>4. Tableau DPO rétention et purge</CardTitle>
          <CardDescription>Historique, rapports mensuels et suivi des purges, anonymisations et exceptions. La date et la période peuvent être complétées après coup si le rapport est encore en consolidation.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="rounded-lg border border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-700">
            <p className="font-medium text-slate-950">Repère DPO</p>
            <p className="mt-1">
              Ce tableau sert à historiser le suivi mensuel: comptes supprimés, purges réellement exécutées, exceptions legal hold, données anonymisées et incidents éventuels.
            </p>
          </div>
          <div className="grid gap-4 md:grid-cols-4">
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Comptes purgés</p>
              <p className="mt-2 text-2xl font-semibold">{data?.metrics.purgedCount ?? 0}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">En attente</p>
              <p className="mt-2 text-2xl font-semibold">{data?.metrics.pendingPurgeCount ?? 0}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Legal hold</p>
              <p className="mt-2 text-2xl font-semibold">{data?.metrics.legalHoldCount ?? 0}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Rapports historisés</p>
              <p className="mt-2 text-2xl font-semibold">{data?.retentionReports.length ?? 0}</p>
            </div>
          </div>

          <div className="grid gap-3 md:grid-cols-4">
            <Input placeholder="Date du rapport (optionnel)" value={retentionForm.generatedAt} onChange={(e) => setRetentionForm((prev) => ({ ...prev, generatedAt: e.target.value }))} />
            <Input placeholder="Période (optionnel)" value={retentionForm.periodLabel} onChange={(e) => setRetentionForm((prev) => ({ ...prev, periodLabel: e.target.value }))} />
            <Input type="number" placeholder="Comptes supprimés" value={retentionForm.deletedAccounts} onChange={(e) => setRetentionForm((prev) => ({ ...prev, deletedAccounts: Number(e.target.value || 0) }))} />
            <Input type="number" placeholder="En attente de purge" value={retentionForm.pendingPurge} onChange={(e) => setRetentionForm((prev) => ({ ...prev, pendingPurge: Number(e.target.value || 0) }))} />
            <Input type="number" placeholder="Données anonymisées" value={retentionForm.anonymizedRecords} onChange={(e) => setRetentionForm((prev) => ({ ...prev, anonymizedRecords: Number(e.target.value || 0) }))} />
            <Input type="number" placeholder="Purges exécutées" value={retentionForm.executedPurges} onChange={(e) => setRetentionForm((prev) => ({ ...prev, executedPurges: Number(e.target.value || 0) }))} />
            <Input type="number" placeholder="Exceptions legal hold" value={retentionForm.legalHoldCount} onChange={(e) => setRetentionForm((prev) => ({ ...prev, legalHoldCount: Number(e.target.value || 0) }))} />
            <Input type="number" placeholder="Incidents" value={retentionForm.incidentsCount} onChange={(e) => setRetentionForm((prev) => ({ ...prev, incidentsCount: Number(e.target.value || 0) }))} />
          </div>
          <Textarea placeholder="Observations" value={retentionForm.notes} onChange={(e) => setRetentionForm((prev) => ({ ...prev, notes: e.target.value }))} />
          <div className="flex flex-wrap gap-2">
            <Button onClick={submitRetentionReport}>Enregistrer le rapport</Button>
            <Button variant="outline" onClick={() => setRetentionForm(emptyRetentionReport)}>Réinitialiser</Button>
          </div>
          <div className="space-y-2">
            {(data?.retentionReports || []).map((entry) => (
              <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium">{entry.periodLabel || "Période non renseignée"}</p>
                    <Badge variant="outline">{entry.generatedAt || "Date non renseignée"}</Badge>
                    {entry.legalHoldCount > 0 ? <Badge className="bg-amber-100 text-amber-800">{entry.legalHoldCount} legal hold</Badge> : null}
                    {entry.incidentsCount > 0 ? <Badge className="bg-red-100 text-red-700">{entry.incidentsCount} incident(s)</Badge> : null}
                  </div>
                  <p className="text-sm text-muted-foreground">
                    Supprimés : {entry.deletedAccounts} • En attente : {entry.pendingPurge} • Anonymisés : {entry.anonymizedRecords} • Purges : {entry.executedPurges}
                  </p>
                  {entry.notes ? <p className="mt-1 text-xs text-muted-foreground">{entry.notes}</p> : null}
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateRetentionForm(entry)}>Modifier</Button>
                  <Button variant="outline" size="sm" onClick={() => deleteRetentionReport.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FilePenLine className="h-5 w-5 text-primary" />
            6. Livrables ISO 27001 interactifs
          </CardTitle>
          <CardDescription>
            Rédaction structurée, validation interne et suivi des livrables nécessaires à une trajectoire ISO 27001 crédible.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-4">
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Livrables suivis</p>
              <p className="mt-2 text-2xl font-semibold">{isoDeliverables.length}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">À valider</p>
              <p className="mt-2 text-2xl font-semibold">{isoDeliverables.filter((entry) => entry.status === "a_valider").length}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">Validés</p>
              <p className="mt-2 text-2xl font-semibold">{isoDeliverables.filter((entry) => entry.status === "valide").length}</p>
            </div>
            <div className="rounded-lg border p-4">
              <p className="text-sm text-muted-foreground">À compléter</p>
              <p className="mt-2 text-2xl font-semibold">{isoDeliverables.filter((entry) => entry.status === "a_rediger" || entry.status === "en_cours" || entry.status === "a_reviser").length}</p>
            </div>
          </div>

          <div className="grid gap-4 xl:grid-cols-[0.95fr_1.05fr]">
            <div className="space-y-3">
              {isoDeliverables.map((entry) => (
                <button
                  key={entry.id}
                  type="button"
                  className={`w-full rounded-lg border p-4 text-left transition-colors ${selectedIsoDeliverable?.id === entry.id ? "border-primary bg-primary/5" : "hover:bg-muted/40"}`}
                  onClick={() => setSelectedIsoDeliverableId(entry.id)}
                >
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium">{entry.reference}</p>
                    <Badge variant="outline">{isoDomainLabels[entry.domain as IsoDeliverableFormState["domain"]]}</Badge>
                    <Badge className={isoStatusClasses[entry.status as IsoDeliverableFormState["status"]]}>
                      {isoStatusLabels[entry.status as IsoDeliverableFormState["status"]]}
                    </Badge>
                  </div>
                  <p className="mt-2 text-sm font-medium">{entry.title}</p>
                  <p className="mt-1 text-xs text-muted-foreground">{entry.summary || "Résumé à compléter"}</p>
                  <p className="mt-2 text-xs text-muted-foreground">
                    Responsable : {entry.owner || "à désigner"}{entry.revisionDueAt ? ` • révision ${entry.revisionDueAt}` : ""}
                  </p>
                </button>
              ))}
            </div>

            <div className="space-y-4 rounded-lg border p-4">
              {selectedIsoDeliverable ? (
                <>
                  <div className="grid gap-3 md:grid-cols-2">
                    <div>
                      <Label>Référence</Label>
                      <Input value={isoDeliverableForm.reference} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, reference: e.target.value }))} />
                    </div>
                    <div>
                      <Label>Domaine</Label>
                      <Select
                        value={isoDeliverableForm.domain}
                        onValueChange={(value) => setIsoDeliverableForm((prev) => ({ ...prev, domain: value as IsoDeliverableFormState["domain"] }))}
                      >
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {Object.entries(isoDomainLabels).map(([value, label]) => (
                            <SelectItem key={value} value={value}>{label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div>
                    <Label>Titre du livrable</Label>
                    <Input value={isoDeliverableForm.title} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, title: e.target.value }))} />
                  </div>

                  <div className="grid gap-3 md:grid-cols-3">
                    <div>
                      <Label>Statut</Label>
                      <Select
                        value={isoDeliverableForm.status}
                        onValueChange={(value) => setIsoDeliverableForm((prev) => ({ ...prev, status: value as IsoDeliverableFormState["status"] }))}
                      >
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {Object.entries(isoStatusLabels).map(([value, label]) => (
                            <SelectItem key={value} value={value}>{label}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Responsable</Label>
                      <Input value={isoDeliverableForm.owner} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, owner: e.target.value }))} />
                    </div>
                    <div>
                      <Label>Révision prévue</Label>
                      <Input value={isoDeliverableForm.revisionDueAt} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, revisionDueAt: e.target.value }))} placeholder="2026-12-31" />
                    </div>
                  </div>

                  <div>
                    <Label>Résumé opérationnel</Label>
                    <Textarea value={isoDeliverableForm.summary} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, summary: e.target.value }))} />
                  </div>

                  <div className="space-y-3">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <p className="font-medium">Sections du livrable</p>
                        <p className="text-sm text-muted-foreground">Chaque bloc peut être complété et validé progressivement.</p>
                      </div>
                    </div>
                    {isoDeliverableForm.sections.map((section, index) => (
                      <div key={section.id} className="rounded-lg border p-4">
                        <div className="flex items-center justify-between gap-3">
                          <p className="font-medium">{section.title}</p>
                          <Badge variant="outline">Section {index + 1}</Badge>
                        </div>
                        {section.guidance ? <p className="mt-2 text-xs text-muted-foreground">{section.guidance}</p> : null}
                        <Textarea
                          className="mt-3 min-h-[120px]"
                          value={section.content}
                          onChange={(e) => {
                            const nextSections = [...isoDeliverableForm.sections];
                            nextSections[index] = { ...section, content: e.target.value };
                            setIsoDeliverableForm((prev) => ({ ...prev, sections: nextSections }));
                          }}
                          placeholder="Compléter cette section..."
                        />
                      </div>
                    ))}
                  </div>

                  <div className="grid gap-3 md:grid-cols-2">
                    <div>
                      <Label>Validateur</Label>
                      <Input value={isoDeliverableForm.approverName} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, approverName: e.target.value }))} />
                    </div>
                    <div>
                      <Label>Email validateur</Label>
                      <Input value={isoDeliverableForm.approverEmail} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, approverEmail: e.target.value }))} />
                    </div>
                  </div>

                  <div>
                    <Label>Observations et historique de travail</Label>
                    <Textarea className="min-h-[140px]" value={isoDeliverableForm.notes} onChange={(e) => setIsoDeliverableForm((prev) => ({ ...prev, notes: e.target.value }))} />
                  </div>

                  <div className="flex flex-wrap gap-2">
                    <Button onClick={() => upsertIsoDeliverable.mutate(isoDeliverableForm)}>
                      <FilePenLine className="mr-2 h-4 w-4" />
                      Enregistrer le livrable
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setIsoDeliverableStatus.mutate({
                        id: isoDeliverableForm.id,
                        status: "a_relire",
                        approverName: isoDeliverableForm.approverName,
                        approverEmail: isoDeliverableForm.approverEmail,
                        note: "Livrable prêt pour relecture interne.",
                      })}
                    >
                      <ClipboardCheck className="mr-2 h-4 w-4" />
                      Marquer à relire
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setIsoDeliverableStatus.mutate({
                        id: isoDeliverableForm.id,
                        status: "valide",
                        approverName: isoDeliverableForm.approverName,
                        approverEmail: isoDeliverableForm.approverEmail,
                        note: "Validation interne confirmée.",
                      })}
                    >
                      <CheckCircle2 className="mr-2 h-4 w-4" />
                      Valider
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setIsoDeliverableStatus.mutate({
                        id: isoDeliverableForm.id,
                        status: "a_reviser",
                        approverName: isoDeliverableForm.approverName,
                        approverEmail: isoDeliverableForm.approverEmail,
                        note: "Révision demandée avant validation.",
                      })}
                    >
                      Demander une révision
                    </Button>
                  </div>

                  <div className="rounded-lg border bg-muted/20 p-4 text-sm text-muted-foreground">
                    <p>Dernière relecture : {isoDeliverableForm.lastReviewedAt || "aucune"}</p>
                    <p>Dernière validation : {isoDeliverableForm.validatedAt || "non validé"}</p>
                  </div>
                </>
              ) : (
                <p className="text-sm text-muted-foreground">Aucun livrable ISO disponible.</p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      <Card id="compliance-evidence-section">
        <CardHeader>
          <CardTitle>7. Centre de conformité</CardTitle>
          <CardDescription>Politiques, rapports, DPA, preuves et éléments d’audit centralisés.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="rounded-lg border border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-700">
            <p className="font-medium text-slate-950">Repère d’audit</p>
            <p className="mt-1">
              Ce centre rassemble les preuves utiles au pilotage: documents internes, registre, contrats DPA, rapports de sauvegarde, tests de restauration, rétention et incidents.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button type="button" variant="outline" onClick={() => prepareEvidenceStarter("processing_register")}>
              Amorcer le registre
            </Button>
            <Button type="button" variant="outline" onClick={() => prepareEvidenceStarter("backup_report")}>
              Amorcer une preuve sauvegarde
            </Button>
            <Button type="button" variant="outline" onClick={() => prepareEvidenceStarter("restore_test")}>
              Amorcer une preuve restauration
            </Button>
            <Button type="button" variant="outline" onClick={() => prepareEvidenceStarter("incident_report")}>
              Amorcer une fiche incident
            </Button>
          </div>
          <div className="grid gap-3 md:grid-cols-3">
            <Select value={evidenceForm.category} onValueChange={(value) => setEvidenceForm((prev) => ({ ...prev, category: value as EvidenceFormState["category"] }))}>
              <SelectTrigger><SelectValue placeholder="Catégorie" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="security_policy">Politique sécurité</SelectItem>
                <SelectItem value="processing_register">Registre des traitements</SelectItem>
                <SelectItem value="dpa">DPA</SelectItem>
                <SelectItem value="audit_report">Rapport d'audit</SelectItem>
                <SelectItem value="backup_report">Rapport sauvegarde</SelectItem>
                <SelectItem value="retention_report">Rapport rétention</SelectItem>
                <SelectItem value="restore_test">Test restauration</SelectItem>
                <SelectItem value="incident_report">Rapport incident</SelectItem>
                <SelectItem value="other">Autre</SelectItem>
              </SelectContent>
            </Select>
            <Input placeholder="Titre" value={evidenceForm.title} onChange={(e) => setEvidenceForm((prev) => ({ ...prev, title: e.target.value }))} />
            <Input placeholder="Référence" value={evidenceForm.reference} onChange={(e) => setEvidenceForm((prev) => ({ ...prev, reference: e.target.value }))} />
            <Input placeholder="URL / lien" value={evidenceForm.url} onChange={(e) => setEvidenceForm((prev) => ({ ...prev, url: e.target.value }))} />
            <Input placeholder="Mis à jour le" value={evidenceForm.updatedAt} onChange={(e) => setEvidenceForm((prev) => ({ ...prev, updatedAt: e.target.value }))} />
            <div className="md:col-span-3">
              <Textarea placeholder="Description" value={evidenceForm.description} onChange={(e) => setEvidenceForm((prev) => ({ ...prev, description: e.target.value }))} />
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button onClick={submitEvidence}>Enregistrer</Button>
            <Button variant="outline" onClick={() => setEvidenceForm(emptyEvidence)}>Réinitialiser</Button>
          </div>
          <div className="space-y-2">
            {builtInEvidence.map((entry) => (
              <div key={entry.id} className="rounded-lg border border-primary/20 bg-primary/5 p-3">
                <div className="flex flex-wrap items-center gap-2">
                  <p className="font-medium">{entry.title}</p>
                  <Badge variant="outline">{entry.reference}</Badge>
                  <Badge variant="outline" className={getEvidenceFreshnessMeta(entry.updatedAt).className}>
                    {getEvidenceFreshnessMeta(entry.updatedAt).label}
                  </Badge>
                  <a href={entry.url} className="text-sm text-primary underline underline-offset-4">Ouvrir</a>
                </div>
                <p className="mt-1 text-xs text-muted-foreground">{entry.description}</p>
              </div>
            ))}
            {(data?.evidenceCenter || []).map((entry) => (
              <div key={entry.id} className="flex flex-wrap items-start justify-between gap-3 rounded-lg border p-3">
                <div>
                  {(() => {
                    const freshness = getEvidenceFreshnessMeta(entry.updatedAt);
                    return (
                      <div className="mb-2">
                        <Badge variant="outline" className={freshness.className}>{freshness.label}</Badge>
                      </div>
                    );
                  })()}
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium">{entry.title}</p>
                    <Badge variant="outline">{evidenceCategoryLabels[entry.category as EvidenceFormState["category"]] || entry.category}</Badge>
                    {entry.reference ? <Badge variant="outline">{entry.reference}</Badge> : null}
                    {entry.url ? <a href={entry.url} target="_blank" rel="noreferrer" className="text-sm text-primary underline underline-offset-4">Ouvrir</a> : null}
                  </div>
                  <p className="text-sm text-muted-foreground">{entry.updatedAt}</p>
                  {entry.description ? <p className="mt-1 text-xs text-muted-foreground">{entry.description}</p> : null}
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => hydrateEvidenceForm(entry)}>Modifier</Button>
                  <Button variant="outline" size="sm" onClick={() => deleteEvidence.mutate({ id: entry.id })}><Trash2 className="h-4 w-4" /></Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {isLoading ? (
        <Card>
          <CardContent className="py-8 text-sm text-muted-foreground">
            <div className="flex items-center gap-2">
              <RefreshCw className="h-4 w-4 animate-spin" />
              Chargement du pilotage conformité…
            </div>
          </CardContent>
        </Card>
      ) : null}
    </div>
  );
}
