"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { CURRENCIES } from "@/src/lib/constants/currencies";

import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import TiptapLink from "@tiptap/extension-link";
import Placeholder from "@tiptap/extension-placeholder";

import {
  fetchCase,
  updateCase,
  deleteCase,
  listCaseNotes,
  createCaseNote,
  patchCaseNote,
  deleteCaseNote,
  uploadCaseDocument,
  listCaseDocuments,
  type Case,
  type CaseNote,
  type CaseDocument,
  type CaseStatus,
  type CasePriority,
} from "@/src/lib/api/cases";
import { NoteThread } from "@/src/components/notes/NoteThread";
import { api } from "@/src/lib/api/client";

import { listTenantUsers, type TenantUser } from "@/src/lib/api/tenant-users";

import {
  listCollectionCases,
  createCollectionCase,
  getCollectionCaseTimeline,
  createCollectionAction,
  createPaymentPromise,
  createPayment,
  type CollectionCaseTimeline,
  type CollectionActionType,
  type CollectionActionOutcome,
  type PaymentPromise,
  type Payment,
} from "@/src/lib/api/collections";

import {
  attachCollectionEmailEml,
  sendCollectionEmail,
  listCollectionEmails,
  type CollectionEmail,
} from "@/src/lib/api/collection-emails";

import { listTreasuryAccounts, type TreasuryAccount } from "@/src/lib/api/treasury";
import { listPortfolios, type Portfolio } from "@/src/lib/api/portfolios";

import {
  Copy,
  RefreshCcw,
  CheckCircle2,
  AlertTriangle,
  UserPlus2,
  Lock,
  Unlock,
  UploadCloud,
  Paperclip,
  Download,
  Phone,
  MessageSquareText,
  Mail,
  CalendarClock,
  CreditCard as CreditCardIcon,
  Gavel,
  X,
} from "lucide-react";

function cx(...c: Array<string | false | null | undefined>) {
  return c.filter(Boolean).join(" ");
}

function Modal({
  open,
  title,
  subtitle,
  children,
  onClose,
}: {
  open: boolean;
  title: string;
  subtitle?: string;
  children: React.ReactNode;
  onClose: () => void;
}) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
      {/* ✅ Important: max height + internal scroll so actions/buttons remain reachable */}
      <div className="w-full max-w-3xl max-h-[85vh] rounded-2xl bg-white shadow-xl overflow-hidden flex flex-col">
        <div
          className="px-5 py-4 border-b flex items-start justify-between gap-3 shrink-0"
          style={{ borderColor: CC.border }}
        >
          <div className="min-w-0">
            <div className="text-lg font-semibold truncate">{title}</div>
            {subtitle ? <div className="text-sm text-neutral-500">{subtitle}</div> : null}
          </div>
          <button className="rounded-xl p-2 hover:bg-slate-50" onClick={onClose} aria-label="Close">
            <X className="h-5 w-5 text-neutral-500" />
          </button>
        </div>

        {/* scroll container */}
        <div className="p-5 overflow-y-auto overflow-x-hidden min-h-0">{children}</div>
      </div>
    </div>
  );
}


function htmlToText(html: string) {
  // Safe-ish HTML -> text for email fallback
  try {
    const div = document.createElement("div");
    div.innerHTML = html;
    return (div.textContent || div.innerText || "").trim();
  } catch {
    return (html || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
  }
}

function EmailHtmlEditor({
  value,
  onChange,
  placeholder,
}: {
  value: string;
  onChange: (html: string) => void;
  placeholder?: string;
}) {
  const editor = useEditor({
    extensions: [
      StarterKit,
      Underline,
      TiptapLink.configure({ openOnClick: false }),
      Placeholder.configure({ placeholder: placeholder || "Écrivez votre message…" }),
    ],
    content: value || "",
    immediatelyRender: false,
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML());
    },
    editorProps: {
      attributes: {
        class: "min-h-[220px] px-3 py-2 text-sm focus:outline-none focus:ring-0 bg-white",
      },
    },
  });

  // Keep editor content in sync when value is reset from outside
  useEffect(() => {
    if (!editor) return;
    const current = editor.getHTML();
    if ((value || "") !== current) {
      editor.commands.setContent(value || "", { emitUpdate: false });
    }
  }, [value, editor]);

  if (!editor) {
    return (
      <div className="min-h-[220px] rounded-xl border px-3 py-2 text-sm text-neutral-500 flex items-center" style={{ borderColor: CC.border }}>
        {placeholder || "Chargement de l'éditeur…"}
      </div>
    );
  }

  const Btn = ({
    active,
    onClick,
    children,
    title,
  }: {
    active?: boolean;
    onClick: () => void;
    children: React.ReactNode;
    title?: string;
  }) => (
    <button
      type="button"
      title={title}
      onClick={onClick}
      className="px-2 py-1 rounded-lg text-xs border transition"
      style={active
        ? { background: CC.navy, color: "#fff", borderColor: "transparent" }
        : { background: "#fff", borderColor: CC.border, color: CC.muted }}
    >
      {children}
    </button>
  );

  function setLink() {
    if (!editor) return;
    const previousUrl = editor.getAttributes("link").href as string | undefined;
    const url = window.prompt("URL", previousUrl || "https://");
    if (url === null) return;
    if (url.trim() === "") {
      editor.chain().focus().extendMarkRange("link").unsetLink().run();
      return;
    }
    editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
  }

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap items-center gap-2">
        <Btn
          title="Bold"
          active={editor.isActive("bold")}
          onClick={() => editor.chain().focus().toggleBold().run()}
        >
          <b>B</b>
        </Btn>
        <Btn
          title="Italic"
          active={editor.isActive("italic")}
          onClick={() => editor.chain().focus().toggleItalic().run()}
        >
          <i>I</i>
        </Btn>
        <Btn
          title="Underline"
          active={editor.isActive("underline")}
          onClick={() => editor.chain().focus().toggleUnderline().run()}
        >
          <u>U</u>
        </Btn>
        <Btn
          title="Bullet list"
          active={editor.isActive("bulletList")}
          onClick={() => editor.chain().focus().toggleBulletList().run()}
        >
          • List
        </Btn>
        <Btn
          title="Ordered list"
          active={editor.isActive("orderedList")}
          onClick={() => editor.chain().focus().toggleOrderedList().run()}
        >
          1. List
        </Btn>
        <Btn title="Link" active={editor.isActive("link")} onClick={setLink}>
          🔗 Link
        </Btn>
        <span className="mx-1 h-5 w-px bg-neutral-200" />
        <Btn title="Undo" onClick={() => editor.chain().focus().undo().run()}>
          ↶ Undo
        </Btn>
        <Btn title="Redo" onClick={() => editor.chain().focus().redo().run()}>
          ↷ Redo
        </Btn>
      </div>

      {/* Editor */}
      <div className="rounded-xl border overflow-hidden" style={{ borderColor: CC.border }}>
        <EditorContent editor={editor} />
      </div>
      <div className="text-[11px] text-neutral-500">
        {`HTML sera envoyé automatiquement. (Le texte brut sera dérivé du HTML.)`}
      </div>
    </div>
  );
}

type Tab = "overview" | "notes" | "documents" | "collections";

const STATUS: Array<{ v: CaseStatus; fr: string; en: string }> = [
  { v: "open", fr: "Ouvert", en: "Open" },
  { v: "in_progress", fr: "En cours", en: "In progress" },
  { v: "on_hold", fr: "En attente", en: "On hold" },
  { v: "closed", fr: "Clôturé", en: "Closed" },
];

const PRIORITY: Array<{ v: CasePriority; fr: string; en: string }> = [
  { v: "low", fr: "Faible", en: "Low" },
  { v: "medium", fr: "Moyenne", en: "Medium" },
  { v: "high", fr: "Élevée", en: "High" },
  { v: "urgent", fr: "Urgente", en: "Urgent" },
];

function labelStatus(locale: string, v: CaseStatus) {
  const s = STATUS.find((x) => x.v === v);
  return s ? (locale === "fr" ? s.fr : s.en) : v;
}

function labelPriority(locale: string, v: CasePriority) {
  const p = PRIORITY.find((x) => x.v === v);
  return p ? (locale === "fr" ? p.fr : p.en) : v;
}

function money(v: string | number, currency?: string | null) {
  const n = typeof v === "string" ? Number(v) : v;
  if (Number.isNaN(n)) return String(v);
  try {
    return new Intl.NumberFormat(undefined, { style: "currency", currency: currency || "XAF" }).format(n);
  } catch {
    return `${n} ${currency || ""}`.trim();
  }
}

function fmtDate(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return d;
  return dt.toLocaleDateString() + " " + dt.toLocaleTimeString().slice(0, 5);
}

function statusPillClass(s: CaseStatus) {
  switch (s) {
    case "open":
      return "bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200";
    case "in_progress":
      return "bg-blue-50 text-blue-700 ring-1 ring-blue-200";
    case "on_hold":
      return "bg-amber-50 text-amber-700 ring-1 ring-amber-200";
    case "closed":
      return "bg-neutral-100 text-neutral-700 ring-1 ring-neutral-200";
    default:
      return "bg-neutral-100 text-neutral-700 ring-1 ring-neutral-200";
  }
}

function priorityPillClass(p: CasePriority) {
  switch (p) {
    case "low":
      return "bg-neutral-100 text-neutral-700 ring-1 ring-neutral-200";
    case "medium":
      return "bg-sky-50 text-sky-700 ring-1 ring-sky-200";
    case "high":
      return "bg-orange-50 text-orange-700 ring-1 ring-orange-200";
    case "urgent":
      return "bg-red-50 text-red-700 ring-1 ring-red-200";
    default:
      return "bg-neutral-100 text-neutral-700 ring-1 ring-neutral-200";
  }
}

function mapPriority(p: CasePriority) {
  if (p === "urgent" || p === "high") return "high";
  if (p === "low") return "low";
  return "medium";
}

const COL_ACTION_TYPES: Array<{ v: CollectionActionType; fr: string; en: string }> = [
  { v: "call", fr: "Appel", en: "Call" },
  { v: "sms", fr: "SMS", en: "SMS" },
  { v: "email", fr: "Email", en: "Email" },
  { v: "visit", fr: "Visite", en: "Visit" },
  { v: "letter", fr: "Courrier", en: "Letter" },
  { v: "negotiation", fr: "Négociation", en: "Negotiation" },
  { v: "notice", fr: "Mise en demeure", en: "Formal notice" },
  { v: "lawyer", fr: "Avocat", en: "Lawyer" },
  { v: "other", fr: "Autre", en: "Other" },
];

const COL_OUTCOMES: Array<{ v: CollectionActionOutcome; fr: string; en: string }> = [
  { v: "reached", fr: "Joint", en: "Reached" },
  { v: "not_reached", fr: "Non joint", en: "Not reached" },
  { v: "promise", fr: "Promesse", en: "Payment promise" },
  { v: "refused", fr: "Refus", en: "Refused" },
  { v: "wrong_number", fr: "Mauvais numéro", en: "Wrong number" },
  { v: "rescheduled", fr: "Replanifié", en: "Rescheduled" },
  { v: "partial_payment", fr: "Paiement partiel", en: "Partial payment" },
  { v: "full_payment", fr: "Paiement total", en: "Full payment" },
  { v: "dispute", fr: "Contesté", en: "Dispute" },
  { v: "other", fr: "Autre", en: "Other" },
];

function safeJsonStringify(v: any) {
  try {
    return JSON.stringify(v, null, 2);
  } catch {
    return String(v);
  }
}

function parseMetaFromText(s?: string | null): Record<string, any> | null {
  if (!s) return null;
  const t = String(s).trim();
  if (!t) return null;

  // 1) Try parse full string
  try {
    const v = JSON.parse(t);
    if (v && typeof v === "object" && !Array.isArray(v)) return v as Record<string, any>;
  } catch {
    // ignore
  }

  // 2) Try parse after "META:"
  const idx = t.indexOf("META:");
  if (idx >= 0) {
    const part = t.slice(idx + 5).trim();
    // Remove leading markers/lines
    const braceStart = part.indexOf("{");
    const braceEnd = part.lastIndexOf("}");
    if (braceStart >= 0 && braceEnd > braceStart) {
      const jsonPart = part.slice(braceStart, braceEnd + 1);
      try {
        const v = JSON.parse(jsonPart);
        if (v && typeof v === "object" && !Array.isArray(v)) return v as Record<string, any>;
      } catch {
        // ignore
      }
    }
  }

  // 3) Heuristic: find first {...} block
  const first = t.indexOf("{");
  const last = t.lastIndexOf("}");
  if (first >= 0 && last > first) {
    const jsonPart = t.slice(first, last + 1);
    try {
      const v = JSON.parse(jsonPart);
      if (v && typeof v === "object" && !Array.isArray(v)) return v as Record<string, any>;
    } catch {
      // ignore
    }
  }

  return null;
}

function metaToEntries(locale: string, meta: Record<string, any>): Array<{ label: string; value: string }> {
  const fr: Record<string, string> = {
    phone: "Téléphone",
    reached: "Joint",
    duration_seconds: "Durée (s)",
    contact_name: "Contact",
    to: "À",
    cc: "Cc",
    subject: "Objet",
    body: "Contenu",
    message: "Message",
    provider: "Fournisseur",
    external_id: "ID externe",
    status: "Statut",
    channel: "Canal",
    received_by: "Reçu par",
    made_by: "Promesse faite par",
    type: "Type",
    lawyer_name: "Avocat",
    lawyer_phone: "Téléphone avocat",
    lawyer_email: "Email avocat",
    reference: "Référence",
  };

  const en: Record<string, string> = {
    phone: "Phone",
    reached: "Reached",
    duration_seconds: "Duration (s)",
    contact_name: "Contact",
    to: "To",
    cc: "Cc",
    subject: "Subject",
    body: "Body",
    message: "Message",
    provider: "Provider",
    external_id: "External ID",
    status: "Status",
    channel: "Channel",
    received_by: "Received by",
    made_by: "Made by",
    type: "Type",
    lawyer_name: "Lawyer",
    lawyer_phone: "Lawyer phone",
    lawyer_email: "Lawyer email",
    reference: "Reference",
  };

  const map = locale === "fr" ? fr : en;

  const entries: Array<{ label: string; value: string }> = [];
  for (const [k, v] of Object.entries(meta)) {
    if (v === undefined || v === null || v === "") continue;

    let val: string;
    if (typeof v === "string") val = v;
    else if (typeof v === "number") val = String(v);
    else if (typeof v === "boolean") val = v ? (locale === "fr" ? "Oui" : "Yes") : (locale === "fr" ? "Non" : "No");
    else val = safeJsonStringify(v);

    const label = map[k] || k.replaceAll("_", " ");
    entries.push({ label, value: val });
  }

  // deterministic order (phone/to/subject first, etc.) — keep basic sort by label
  entries.sort((a, b) => a.label.localeCompare(b.label));
  return entries;
}

function MetaGrid({ locale, meta }: { locale: string; meta: Record<string, any> }) {
  const entries = metaToEntries(locale, meta);
  if (entries.length === 0) return null;

  return (
    <div className="mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2">
      {entries.map((e) => (
        <div key={e.label} className="rounded-xl border bg-neutral-50 p-3" style={{ borderColor: CC.border }}>
          <div className="text-[11px] text-neutral-500">{e.label}</div>
          <div className="text-[13px] text-neutral-800 whitespace-pre-wrap">{e.value}</div>
        </div>
      ))}
    </div>
  );
}

function stripMetaBlock(text?: string | null): string {
  if (!text) return "";
  const t = String(text);
  const idx = t.indexOf("META:");
  if (idx >= 0) return t.slice(0, idx).trim();
  // If it's pure JSON, don't show as text
  const meta = parseMetaFromText(t);
  if (meta && t.trim().startsWith("{")) return "";
  return t.trim();
}

function labelPaymentMethod(locale: string, m: string) {
  const fr: Record<string, string> = {
    cash: "Espèces",
    bank_transfer: "Virement",
    mobile_money: "Mobile Money",
    cheque: "Chèque",
    card: "Carte",
    other: "Autre",
  };
  const en: Record<string, string> = {
    cash: "Cash",
    bank_transfer: "Bank transfer",
    mobile_money: "Mobile money",
    cheque: "Cheque",
    card: "Card",
    other: "Other",
  };
  const map = locale === "fr" ? fr : en;
  return map[m] || m;
}


function labelReceivedBy(locale: string, v: string) {
  const fr: Record<string, string> = {
    acx: "ACX (encaissé)",
    customer_direct: "Client (direct)",
    client: "Client (direct)",
  };
  const en: Record<string, string> = {
    acx: "ACX (collected)",
    customer_direct: "Client (direct)",
    client: "Client (direct)",
  };
  const map = locale === "fr" ? fr : en;
  return map[v] || v;
}

function receivedByPillClass(v: string) {
  if (v === "acx") return "bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200";
  if (v === "customer_direct" || v === "client") return "bg-blue-50 text-blue-700 ring-1 ring-blue-200";
  return "bg-neutral-100 text-neutral-700 ring-1 ring-neutral-200";
}

function labelPromiseStatus(locale: string, s: string) {
  const fr: Record<string, string> = {
    pending: "En attente",
    kept: "Respectée",
    broken: "Non respectée",
    cancelled: "Annulée",
  };
  const en: Record<string, string> = {
    pending: "Pending",
    kept: "Kept",
    broken: "Broken",
    cancelled: "Cancelled",
  };
  const map = locale === "fr" ? fr : en;
  return map[s] || s;
}

function fmtDateOnly(d?: string | null) {
  if (!d) return "—";
  const dt = new Date(d);
  if (Number.isNaN(dt.getTime())) return d;
  return dt.toLocaleDateString();
}

function iconForActionType(t: string) {
  switch (t) {
    case "call":
      return Phone;
    case "sms":
      return MessageSquareText;
    case "email":
      return Mail;
    case "notice":
    case "lawyer":
      return Gavel;
    default:
      return AlertTriangle;
  }
}


// ── Palette navy/teal ───────────────────────────────────────────────────────
const CC = {
  navy:   "#1a3578",
  navy2:  "#2655b0",
  teal:   "#4dba96",
  amber:  "#f59e0b",
  red:    "#ef4444",
  blue:   "#0ea5e9",
  muted:  "#64748b",
  border: "rgba(15,23,42,.07)",
};

const STATUS_STYLE_MAP: Record<string, { bg: string; color: string }> = {
  open:        { bg: "rgba(14,165,233,.12)",  color: CC.blue },
  in_progress: { bg: "rgba(77,186,150,.12)",  color: CC.teal },
  on_hold:     { bg: "rgba(245,158,11,.12)",  color: CC.amber },
  closed:      { bg: "rgba(15,23,42,.07)",    color: "#475569" },
};

const PRIORITY_STYLE_MAP: Record<string, { bg: string; color: string }> = {
  low:    { bg: "rgba(148,163,184,.12)", color: "#64748b" },
  medium: { bg: "rgba(14,165,233,.12)",  color: CC.blue },
  high:   { bg: "rgba(245,158,11,.12)",  color: CC.amber },
  urgent: { bg: "rgba(239,68,68,.12)",   color: CC.red },
};

const inputCls = `w-full rounded-xl border bg-white px-3 py-2.5 text-sm text-slate-800 outline-none
  placeholder:text-slate-400 transition
  focus:border-[#4dba96] focus:shadow-[0_0_0_3px_rgba(77,186,150,0.12)]`;

export default function CaseDetailPage() {
  const locale = useLocale();
  const t = useTranslations("cases.detail");
  const params = useParams<{ id: string }>();
  const caseId = Number(params.id);
  const [currencySearch, setCurrencySearch] = useState("");

  const [tab, setTab] = useState<Tab>("overview");
  const [item, setItem] = useState<Case | null>(null);
  const [notes, setNotes] = useState<CaseNote[]>([]);
  const [docs, setDocs] = useState<CaseDocument[]>([]);
  const [users, setUsers] = useState<TenantUser[]>([]);
  const [portfolios, setPortfolios] = useState<Portfolio[]>([]);

  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [meUsername, setMeUsername] = useState<string | null>(null);
  const [noteSubmitting, setNoteSubmitting] = useState(false);

  const [dirty, setDirty] = useState(false);
  const lastSavedRef = useRef<string>("");

  // Recouvrement
  const [col, setCol] = useState<CollectionCaseTimeline | null>(null);
  const [colLoading, setColLoading] = useState(false);
  const [colErr, setColErr] = useState<string | null>(null);

  const [colFlash, setColFlash] = useState<{ kind: "success" | "error"; message: string } | null>(null);
  const colFlashTimer = useRef<number | null>(null);

  function showColFlash(kind: "success" | "error", message: string) {
    setColFlash({ kind, message });
    if (colFlashTimer.current) window.clearTimeout(colFlashTimer.current);
    colFlashTimer.current = window.setTimeout(() => setColFlash(null), 4500);
  }


  // Modals recouvrement
  const [mCall, setMCall] = useState(false);
  const [mSms, setMSms] = useState(false);
  const [mEmail, setMEmail] = useState(false);
  const [mPromise, setMPromise] = useState(false);
  const [mPayment, setMPayment] = useState(false);
  const [mContentious, setMContentious] = useState(false);

  // Email (hybride): soit log manuel, soit preuve Outlook (.eml)
  const [emailTab, setEmailTab] = useState<"log" | "send" | "outlook">("log");
  const [emailAttach, setEmailAttach] = useState({
    action_id: "" as "" | string,
    file: null as File | null,
    notes: "",
    direction: "outbound" as "outbound" | "inbound",
    source: "outlook",
  });

  // Viewer preuves email
  const [emailSend, setEmailSend] = useState({
    to: "",
    cc: "",
    bcc: "",
    from_address: "",
    subject: "",
    body_text: "",
    body_html: "",
    notes: "",
  });
  const [emailSendFiles, setEmailSendFiles] = useState<File[]>([]);

  // Viewer preuves email
  const [mEmailProofs, setMEmailProofs] = useState(false);
  const [emailProofsLoading, setEmailProofsLoading] = useState(false);
  const [emailProofsErr, setEmailProofsErr] = useState<string | null>(null);
  const [emailProofs, setEmailProofs] = useState<CollectionEmail[]>([]);
  const [emailProofsActionId, setEmailProofsActionId] = useState<number | null>(null);


  // Forms recouvrement (tous paramètres)
  const [callForm, setCallForm] = useState({
    phone: "",
    reached: true,
    duration_seconds: "",
    contact_name: "",
    outcome: "" as "" | CollectionActionOutcome,
    summary: "",
    notes: "",
    next_action_type: "" as "" | CollectionActionType,
    next_action_date: "",
  });

  const [smsForm, setSmsForm] = useState({
    to: "",
    message: "",
    provider: "",
    external_id: "",
    status: "sent",
    summary: "",
    next_action_type: "" as "" | CollectionActionType,
    next_action_date: "",
  });

  const [emailForm, setEmailForm] = useState({
    to: "",
    cc: "",
    subject: "",
    body: "",
    provider: "",
    external_id: "",
    status: "sent",
    summary: "",
    next_action_type: "" as "" | CollectionActionType,
    next_action_date: "",
  });

  const [promiseForm, setPromiseForm] = useState({
    amount: "",
    promised_date: "",
    notes: "",
    channel: "call",
    made_by: "",
  });

    const [paymentForm, setPaymentForm] = useState({
    amount: "",
    method: "cash" as Payment["method"],
    reference: "",
    notes: "",
    paid_at: "",
    channel: "",
    received_by: "acx" as "acx" | "customer_direct",
    treasury_account_id: "" as "" | string,
  });

  // Trésorerie (encaissements ACX)
  const [treasuryAccounts, setTreasuryAccounts] = useState<TreasuryAccount[]>([]);
  const [treasuryLoading, setTreasuryLoading] = useState(false);
  const [treasuryErr, setTreasuryErr] = useState<string | null>(null);

  async function loadTreasuryAccounts(force = false) {
    if (!force && treasuryAccounts.length) return;
    setTreasuryErr(null);
    setTreasuryLoading(true);
    try {
      const rows = await listTreasuryAccounts();
      setTreasuryAccounts(rows || []);

      // Auto-sélection d'un compte par défaut (si on est en mode "ACX encaissé")
      setPaymentForm((p) => {
        if ((p.received_by || "acx") !== "acx") return p;
        if (p.treasury_account_id) return p;
        const def = (rows || []).find((a: any) => (a as any).is_default) || (rows || [])[0];
        return def ? { ...p, treasury_account_id: String(def.id) } : p;
      });
    } catch (e: any) {
      setTreasuryErr(
        e?.message ||
          (locale === "fr"
            ? "Impossible de charger les comptes de trésorerie."
            : "Failed to load treasury accounts.")
      );
      setTreasuryAccounts([]);
    } finally {
      setTreasuryLoading(false);
    }
  }


  const [contentiousForm, setContentiousForm] = useState({
    type: "notice" as "notice" | "lawyer" | "dispute",
    summary: "",
    details: "",
    lawyer_name: "",
    lawyer_phone: "",
    lawyer_email: "",
    reference: "",
    next_action_type: "" as "" | CollectionActionType,
    next_action_date: "",
  });

  const [edit, setEdit] = useState({
    title: "",
    status: "open" as CaseStatus,
    priority: "medium" as CasePriority,
    currency: "XAF",
    original_amount: "0",
    balance_amount: "0",
    due_date: "",
    assigned_to_id: "" as "" | string,
    portfolio_id: "" as "" | string,
  });


  const [upload, setUpload] = useState({
    title: "",
    doc_type: "other" as CaseDocument["doc_type"],
    file: null as File | null,
  });

  const [uploadProgress, setUploadProgress] = useState<number | null>(null);

  const userOptions = useMemo(() => {
    return users.filter((u) => u.is_active).slice().sort((a, b) => a.username.localeCompare(b.username));
  }, [users]);

  function setEditSafe(next: typeof edit) {
    setEdit(next);
    setDirty(true);
  }

  async function ensureCollections(c: Case) {
    if (!c?.reference) return;
    setColLoading(true);
    setColErr(null);
    try {
      const found = await listCollectionCases({ q: c.reference });
      let colCase = found?.[0] || null;

      if (!colCase) {
        colCase = await createCollectionCase({
          reference: c.reference,
          debtor: c.debtor?.id ?? null,
          portfolio: c.portfolio?.id ?? null,
          priority: mapPriority(c.priority),
          assigned_to: c.assigned_to_id ?? null,
          principal_amount: c.original_amount || "0",
          interest_amount: "0",
          penalty_amount: "0",
          fees_amount: "0",
          due_date: c.due_date || null,
          notes: c.title ? `From case: ${c.title}` : "",
        } as any);
      }

      const tl = await getCollectionCaseTimeline(colCase.id, 100);
      setCol(tl);
    } catch (e: any) {
      setCol(null);
      setColErr(e?.message || (locale === "fr" ? "Recouvrement indisponible." : "Collections unavailable."));
    } finally {
      setColLoading(false);
    }
  }

  async function loadAll() {
    setLoading(true);
    setErr(null);
    try {
      const [c, ns, ds, us, me, pfs] = await Promise.all([
        fetchCase(caseId),
        listCaseNotes(caseId),
        listCaseDocuments(caseId),
        listTenantUsers(),
        api.request<{ id: number; username: string }>("/auth/me/").catch(() => null),
        listPortfolios({ is_active: true }).catch(() => [] as Portfolio[]),
      ]);

      setItem(c);
      setNotes(ns);
      setDocs(ds);
      setUsers(us);
      setPortfolios(pfs);
      if (me) setMeUsername(me.username);

      // assigned_to_id : priorité à la valeur API, sinon lookup par username
      const assignedId = (() => {
        if (c.assigned_to_id) return String(c.assigned_to_id);
        if (c.assigned_to_username) {
          const found = us.find((u) => u.username === c.assigned_to_username);
          if (found) return String(found.id);
        }
        return "";
      })();

      const nextEdit = {
        title: c.title || "",
        status: c.status,
        priority: c.priority,
        currency: c.currency || "XAF",
        original_amount: c.original_amount || "0",
        balance_amount: c.balance_amount || "0",
        due_date: c.due_date || "",
        assigned_to_id: assignedId,
        portfolio_id: c.portfolio?.id ? String(c.portfolio.id) : "",
      };
      setEdit(nextEdit);
      setDirty(false);
      lastSavedRef.current = JSON.stringify(nextEdit);

      ensureCollections(c);
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Erreur chargement dossier." : "Failed to load case."));
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadAll();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [caseId]);

  useEffect(() => {
    const snap = JSON.stringify(edit);
    if (!lastSavedRef.current) return;
    setDirty(snap !== lastSavedRef.current);
  }, [edit]);

  async function onSave() {
    if (!item) return;
    setErr(null);
    setBusy("save");
    try {
      const updated = await updateCase(item.id, {
        title: edit.title.trim(),
        status: edit.status,
        priority: edit.priority,
        currency: edit.currency || null,
        original_amount: edit.original_amount || "0",
        balance_amount: edit.balance_amount || "0",
        due_date: edit.due_date || null,
        assigned_to_id: edit.assigned_to_id ? Number(edit.assigned_to_id) : null,
        portfolio_id: edit.portfolio_id ? Number(edit.portfolio_id) : null,
      });

      setItem(updated);

      const nextEdit = {
        title: updated.title || "",
        status: updated.status,
        priority: updated.priority,
        currency: updated.currency || "XAF",
        original_amount: updated.original_amount || "0",
        balance_amount: updated.balance_amount || "0",
        due_date: updated.due_date || "",
        assigned_to_id: updated.assigned_to_id ? String(updated.assigned_to_id) : "",
        portfolio_id: updated.portfolio?.id ? String(updated.portfolio.id) : "",
      };

      setEdit(nextEdit);
      lastSavedRef.current = JSON.stringify(nextEdit);
      setDirty(false);

      ensureCollections(updated);
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Erreur sauvegarde." : "Save failed."));
    } finally {
      setBusy(null);
    }
  }

  async function onQuickStatus(next: CaseStatus) {
    if (!item) return;
    setErr(null);
    setBusy("quick-status");
    try {
      const updated = await updateCase(item.id, { status: next });
      setItem(updated);
      setEdit((p) => ({ ...p, status: updated.status }));
      lastSavedRef.current = JSON.stringify({ ...edit, status: updated.status });
      setDirty(false);
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Action impossible." : "Action failed."));
    } finally {
      setBusy(null);
    }
  }

  async function onAssignTo(userId: string) {
    if (!item) return;
    setErr(null);
    setBusy("assign");
    try {
      const updated = await updateCase(item.id, { assigned_to_id: userId ? Number(userId) : null });
      setItem(updated);
      setEdit((p) => ({ ...p, assigned_to_id: userId }));
      lastSavedRef.current = JSON.stringify({ ...edit, assigned_to_id: userId });
      setDirty(false);
      ensureCollections(updated);
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Assignation impossible." : "Assignment failed."));
    } finally {
      setBusy(null);
    }
  }

  async function onDelete() {
    if (!item) return;
    const ok = window.confirm(locale === "fr" ? `Supprimer le dossier ${item.reference} ?` : `Delete case ${item.reference}?`);
    if (!ok) return;

    setBusy("delete");
    try {
      await deleteCase(item.id);
      window.location.href = `/${locale}/cases`;
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Suppression impossible." : "Delete failed."));
    } finally {
      setBusy(null);
    }
  }

  async function onAddNote(body: string) {
    setNoteSubmitting(true);
    try {
      const created = await createCaseNote(caseId, body);
      setNotes((prev) => [...prev, created]);
    } catch (e: any) {
      setErr(e?.message || "Erreur ajout note.");
    } finally {
      setNoteSubmitting(false);
    }
  }

  async function onEditNote(noteId: number, body: string) {
    try {
      const updated = await patchCaseNote(caseId, noteId, body);
      setNotes((prev) => prev.map((n) => (n.id === updated.id ? updated : n)));
    } catch (e: any) {
      setErr(e?.message || "Erreur modification note.");
    }
  }

  async function onDeleteNote(noteId: number) {
    try {
      await deleteCaseNote(caseId, noteId);
      setNotes((prev) => prev.filter((n) => n.id !== noteId));
    } catch (e: any) {
      setErr(e?.message || "Erreur suppression note.");
    }
  }

  function copyRef() {
    if (!item?.reference) return;
    navigator.clipboard?.writeText(item.reference).catch(() => {});
  }

  async function onUploadDoc() {
    setErr(null);
    if (!upload.title.trim() || !upload.file) {
      setErr(locale === "fr" ? "Titre et fichier sont obligatoires." : "Title and file are required.");
      return;
    }

    setBusy("upload");
    try {
      await uploadCaseDocument(caseId, {
        title: upload.title.trim(),
        doc_type: upload.doc_type,
        file: upload.file,
      });

      setUpload({ title: "", doc_type: "other", file: null });
      const ds = await listCaseDocuments(caseId);
      setDocs(ds);
      setTab("documents");
    } catch (e: any) {
      setErr(e?.message || (locale === "fr" ? "Erreur upload document." : "Document upload failed."));
    } finally {
      setBusy(null);
    }
  }

  async function refreshTimeline() {
    if (!col?.case?.id) return;
    const tl = await getCollectionCaseTimeline(col.case.id, 100);
    setCol(tl);
  }

  function resetCollectionsDefaults() {
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");

    setCallForm((p) => ({
      ...p,
      phone: item?.debtor?.phone || p.phone,
      summary: p.summary || (locale === "fr" ? "Appel sortant" : "Outbound call"),
    }));

    setSmsForm((p) => ({
      ...p,
      to: item?.debtor?.phone || p.to,
      summary: p.summary || "SMS",
    }));

    setEmailForm((p) => ({
      ...p,
      to: item?.debtor?.email || p.to,
      subject: p.subject || (item?.reference ? `Recouvrement ${item.reference}` : "Recouvrement"),
    }));

    setEmailSend((p) => ({
      ...p,
      to: p.to || item?.debtor?.email || "",
      subject: p.subject || (item?.reference ? `Recouvrement ${item.reference}` : "Recouvrement"),
    }));

    setPromiseForm((p) => ({
      ...p,
      promised_date: p.promised_date || `${yyyy}-${mm}-${dd}`,
      amount: p.amount || (col?.case?.amount_due ? String(col.case.amount_due) : ""),
    }));
  }

  async function submitCall() {
    if (!col?.case?.id) return;
    setColErr(null);
    setBusy("submit-call");
    try {
      const outcome =
        (callForm.outcome as any) ||
        (callForm.reached ? ("reached" as any) : ("not_reached" as any));

      await createCollectionAction({
        case: col.case.id,
        action_type: "call",
        outcome: outcome || undefined,
        summary: callForm.summary?.trim() || "",
        details: callForm.notes?.trim() || "",
        details_json: {
          phone: callForm.phone || null,
          reached: !!callForm.reached,
          duration_seconds: callForm.duration_seconds ? Number(callForm.duration_seconds) : null,
          contact_name: callForm.contact_name || null,
        },
        next_action_type: (callForm.next_action_type || null) as any,
        next_action_date: callForm.next_action_date || undefined,
      });

      await refreshTimeline();
      setMCall(false);
    } catch (e: any) {
      setColErr(e?.message || (locale === "fr" ? "Enregistrement appel impossible." : "Failed to log call."));
    } finally {
      setBusy(null);
    }
  }

  async function submitSms() {
    if (!col?.case?.id) return;
    setColErr(null);
    setBusy("submit-sms");
    try {
      await createCollectionAction({
        case: col.case.id,
        action_type: "sms",
        outcome: undefined,
        summary: smsForm.summary?.trim() || "",
        details: "",
        details_json: {
          to: smsForm.to || null,
          message: smsForm.message || "",
          provider: smsForm.provider || null,
          external_id: smsForm.external_id || null,
          status: smsForm.status || null,
        },
        next_action_type: (smsForm.next_action_type || null) as any,
        next_action_date: smsForm.next_action_date || undefined,
      });

      await refreshTimeline();
      setMSms(false);
    } catch (e: any) {
      setColErr(e?.message || (locale === "fr" ? "Enregistrement SMS impossible." : "Failed to log SMS."));
    } finally {
      setBusy(null);
    }
  }

  async function submitEmail() {
    if (!col?.case?.id) return;
    setColErr(null);
    setBusy("submit-email");
    try {
      await createCollectionAction({
        case: col.case.id,
        action_type: "email",
        outcome: undefined,
        summary: emailForm.summary?.trim() || emailForm.subject?.trim() || "",
        details: "",
        details_json: {
          to: emailForm.to || null,
          cc: emailForm.cc || null,
          subject: emailForm.subject || "",
          body: emailForm.body || "",
          provider: emailForm.provider || null,
          external_id: emailForm.external_id || null,
          status: (emailForm.status || "sent"),
        },
        next_action_type: (emailForm.next_action_type || null) as any,
        next_action_date: emailForm.next_action_date || undefined,
      });

      await refreshTimeline();
      showColFlash("success", locale === "fr" ? "Email enregistré." : "Email logged.");
      setMEmail(false);
    } catch (e: any) {
      const msg = e?.message || (locale === "fr" ? "Enregistrement email impossible." : "Failed to log email.");
      setColErr(msg);
      showColFlash("error", msg);
    } finally {
      setBusy(null);
    }
  }

  
  async function submitEmailAttach() {
    if (!col?.case?.id) return;

    if (!emailAttach.file) {
      setColErr(locale === "fr" ? "Veuillez sélectionner un fichier .eml (preuve Outlook)." : "Please select a .eml file (Outlook proof).");
      return;
    }

    setColErr(null);
    setBusy("submit-email-attach");
    try {
      const actionId = emailAttach.action_id ? Number(emailAttach.action_id) : null;

      const res = await attachCollectionEmailEml({
        caseId: col.case.id,
        emlFile: emailAttach.file,
        actionId,
        notes: emailAttach.notes || undefined,
        direction: emailAttach.direction,
        source: emailAttach.source || "outlook",
      });

      // Timeline: l'action email est créée / mise à jour (date + details)
      await refreshTimeline();
      showColFlash("success", locale === "fr" ? "Preuve email attachée." : "Email proof attached.");

      // Optionnel: ouvrir automatiquement le viewer de preuves sur l'action créée/attachée
      // await openEmailProofs(res.timeline_action_id);

      // Reset attach form
      setEmailAttach((p) => ({ ...p, file: null, notes: "" }));
      setMEmail(false);
    } catch (e: any) {
      const msg = e?.message || (locale === "fr" ? "Attachement de la preuve email impossible." : "Failed to attach email proof.");
      setColErr(msg);
      showColFlash("error", msg);
    } finally {
      setBusy(null);
    }
  }

  async function submitEmailSend() {
    if (!col?.case?.id) return;

    const to = (emailSend.to || "").trim();
    if (!to) {
      setColErr(locale === "fr" ? "Destinataire (to) obligatoire." : "Recipient (to) is required.");
      return;
    }

    const bodyHtml = (emailSend.body_html || "").trim();
    if (!bodyHtml || bodyHtml === "<p></p>") {
      setColErr(locale === "fr" ? "Le message est obligatoire." : "Message is required.");
      return;
    }

    const bodyText = htmlToText(bodyHtml);

    setColErr(null);
    setBusy("submit-email-send");
    try {
      await sendCollectionEmail({
        caseId: col.case.id,
        to,
        cc: emailSend.cc || undefined,
        bcc: emailSend.bcc || undefined,
        subject: emailSend.subject || undefined,
        body_text: bodyText || undefined,
        body_html: bodyHtml || undefined,
        from_address: emailSend.from_address || undefined,
        notes: emailSend.notes || undefined,
        attachments: emailSendFiles,
      });

      await refreshTimeline();
      showColFlash("success", locale === "fr" ? "Email envoyé." : "Email sent.");

      // Reset send form
      setEmailSend((p) => ({
        ...p,
        body_text: "",
        body_html: "",
        notes: "",
      }));
      setEmailSendFiles([]);
      setMEmail(false);
    } catch (e: any) {
      setColErr(e?.message || (locale === "fr" ? "Envoi email impossible." : "Failed to send email."));
    } finally {
      setBusy(null);
    }
  }

  async function openEmailProofs(actionId: number) {
    if (!col?.case?.id) return;

    setEmailProofsActionId(actionId);
    setEmailProofsErr(null);
    setEmailProofsLoading(true);
    setMEmailProofs(true);

    try {
      const rows = await listCollectionEmails({ actionId });
      setEmailProofs(rows);
    } catch (e: any) {
      setEmailProofs([]);
      setEmailProofsErr(e?.message || (locale === "fr" ? "Impossible de charger les preuves email." : "Failed to load email proofs."));
    } finally {
      setEmailProofsLoading(false);
    }
  }

async function submitPromise() {
    if (!col?.case?.id) return;

    const amount = Number(promiseForm.amount || "0");
    if (!promiseForm.promised_date || Number.isNaN(amount) || amount <= 0) {
      setColErr(locale === "fr" ? "Montant et date de promesse sont obligatoires." : "Amount and promised date are required.");
      return;
    }

    setColErr(null);
    setBusy("submit-promise");
    try {
      await createPaymentPromise({
        case: col.case.id,
        amount,
        promised_date: promiseForm.promised_date,
        notes: promiseForm.notes?.trim() || "",
        meta: {
          channel: promiseForm.channel || null,
          made_by: promiseForm.made_by || null,
        },
      } as any);

      await refreshTimeline();
      setMPromise(false);
    } catch (e: any) {
      setColErr(e?.message || (locale === "fr" ? "Création promesse impossible." : "Failed to create promise."));
    } finally {
      setBusy(null);
    }
  }

  async function submitPayment() {
    if (!col?.case?.id) return;

    const amount = Number(paymentForm.amount || "0");
    if (Number.isNaN(amount) || amount <= 0) {
      setColErr(locale === "fr" ? "Montant paiement obligatoire." : "Amount is required.");
      return;
    }

    const receivedBy = (paymentForm.received_by || "acx") as "acx" | "customer_direct";
    const treasuryAccountId =
      receivedBy === "acx"
        ? paymentForm.treasury_account_id
          ? Number(paymentForm.treasury_account_id)
          : null
        : null;

    if (receivedBy === "acx" && !treasuryAccountId) {
      setColErr(locale === "fr" ? "Veuillez sélectionner un compte de trésorerie." : "Please select a treasury account.");
      return;
    }

    setColErr(null);
    setBusy("submit-payment");
    try {
      // paid_at: datetime-local -> ISO
      const paidAtIso = paymentForm.paid_at ? new Date(paymentForm.paid_at).toISOString() : undefined;

      await createPayment(
        {
          case: col.case.id,
          amount,
          method: paymentForm.method,
          reference: paymentForm.reference?.trim() || "",
          notes: paymentForm.notes?.trim() || "",
          ...(paidAtIso ? { paid_at: paidAtIso } : {}),
          received_by: receivedBy,
          treasury_account: treasuryAccountId,
          details_json: {
            channel: paymentForm.channel || null,
            received_by: receivedBy,
            treasury_account: treasuryAccountId,
          },
        } as any
      );

      await refreshTimeline();

      // Refresh the core Case amounts (balance/original) in UI
      try {
        const updated = await fetchCase(caseId);
        setItem(updated);
        setEdit((p) => ({
          ...p,
          original_amount: updated.original_amount || p.original_amount,
          balance_amount: updated.balance_amount || p.balance_amount,
        }));
        // also refresh collections aggregate if needed
        await ensureCollections(updated);
      } catch {
        // ignore refresh errors (timeline already updated)
      }

      showColFlash("success", locale === "fr" ? "Paiement enregistré." : "Payment recorded.");
      setMPayment(false);
      setPaymentForm({
        amount: "",
        method: "cash",
        reference: "",
        notes: "",
        paid_at: "",
        channel: "",
        received_by: "acx",
        treasury_account_id: "",
      });
    } catch (e: any) {
      const msg = e?.message || (locale === "fr" ? "Enregistrement paiement impossible." : "Failed to log payment.");
      setColErr(msg);
      showColFlash("error", msg);
    } finally {
      setBusy(null);
    }
  }

  async function submitContentious() {
    if (!col?.case?.id) return;

    if (!contentiousForm.summary.trim()) {
      setColErr(locale === "fr" ? "Résumé obligatoire." : "Summary is required.");
      return;
    }

    const actionType =
      contentiousForm.type === "lawyer"
        ? ("lawyer" as any)
        : contentiousForm.type === "notice"
          ? ("notice" as any)
          : ("other" as any);

    setColErr(null);
    setBusy("submit-contentious");
    try {
      await createCollectionAction({
        case: col.case.id,
        action_type: actionType,
        outcome: contentiousForm.type === "dispute" ? ("dispute" as any) : undefined,
        summary: contentiousForm.summary.trim(),
        details: contentiousForm.details?.trim() || "",
        details_json: {
          type: contentiousForm.type,
          lawyer_name: contentiousForm.lawyer_name || null,
          lawyer_phone: contentiousForm.lawyer_phone || null,
          lawyer_email: contentiousForm.lawyer_email || null,
          reference: contentiousForm.reference || null,
        },
        next_action_type: (contentiousForm.next_action_type || null) as any,
        next_action_date: contentiousForm.next_action_date || undefined,
      });

      await refreshTimeline();
      setMContentious(false);
    } catch (e: any) {
      setColErr(e?.message || (locale === "fr" ? "Enregistrement contentieux impossible." : "Failed to log legal step."));
    } finally {
      setBusy(null);
    }
  }

  const counts = useMemo(() => ({ notes: notes.length, docs: docs.length }), [notes.length, docs.length]);
  type RecTimelineItem =
    | { kind: "action"; at: string; id: number; action: any }
    | { kind: "payment"; at: string; id: number; payment: Payment }
    | { kind: "promise"; at: string; id: number; promise: PaymentPromise };

  const recTimeline = useMemo<RecTimelineItem[]>(() => {
    if (!col) return [];
    const items: RecTimelineItem[] = [];

    for (const a of col.actions || []) {
      items.push({ kind: "action", at: a.action_date ?? "", id: a.id, action: a });
    }
    for (const p of col.payments || []) {
      items.push({ kind: "payment", at: p.paid_at ?? "", id: p.id, payment: p });
    }
    for (const pr of col.promises || []) {
      items.push({ kind: "promise", at: pr.created_at ?? "", id: pr.id, promise: pr });
    }

    items.sort((x, y) => new Date(y.at).getTime() - new Date(x.at).getTime());
    return items;
  }, [col]);



  // ── "Assigner à moi" : cherche l'utilisateur courant dans la liste ──────
  function onAssignToMe() {
    const raw = typeof window !== "undefined" ? localStorage.getItem("acx_me") : null;
    const me = raw ? (() => { try { return JSON.parse(raw); } catch { return null; } })() : null;
    if (!me?.id) { setErr("Impossible de récupérer votre identifiant utilisateur."); return; }
    const uid = String(me.id);
    setEditSafe({ ...edit, assigned_to_id: uid });
    onAssignTo(uid);
  }

  const statusStyle   = item ? (STATUS_STYLE_MAP[item.status]   ?? { bg: "rgba(15,23,42,.07)", color: "#475569" }) : null;
  const priorityStyle = item ? (PRIORITY_STYLE_MAP[item.priority] ?? { bg: "rgba(15,23,42,.07)", color: "#475569" }) : null;

  return (
    <div className="space-y-4">

      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div
        className="rounded-2xl p-5 text-white relative overflow-hidden"
        style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }}
      >
        {/* déco */}
        <div className="pointer-events-none absolute -top-10 -right-10 h-40 w-40 rounded-full opacity-[0.08]"
          style={{ background: `radial-gradient(circle, ${CC.teal}, transparent 70%)` }} />

        <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="min-w-0">
            {/* Badges */}
            <div className="flex items-center gap-2 flex-wrap mb-2">
              <span className="font-mono text-xs text-white/60">{item?.reference ?? "…"}</span>
              {statusStyle && item && (
                <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold"
                  style={{ background: statusStyle.bg, color: statusStyle.color }}>
                  {labelStatus(locale, item.status)}
                </span>
              )}
              {priorityStyle && item && (
                <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold"
                  style={{ background: priorityStyle.bg, color: priorityStyle.color }}>
                  {labelPriority(locale, item.priority)}
                </span>
              )}
              {dirty ? (
                <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold bg-amber-100 text-amber-800 flex items-center gap-1">
                  <AlertTriangle className="h-3 w-3" /> {t("modified")}
                </span>
              ) : (
                <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold bg-emerald-100 text-emerald-800 flex items-center gap-1">
                  <CheckCircle2 className="h-3 w-3" /> {t("saved")}
                </span>
              )}
            </div>

            <h1 className="text-xl font-bold leading-tight truncate">
              {item?.title || t("case_fallback")}
            </h1>
            {item?.debtor?.full_name && (
              <p className="mt-1 text-sm text-white/60">{t("debtor_label")} : {item.debtor.full_name}</p>
            )}
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2 flex-wrap">
            <Link href={`/${locale}/cases`}
              className="inline-flex items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-medium text-white/80 transition hover:bg-white/10"
              style={{ border: "1px solid rgba(255,255,255,0.15)" }}>
              ← {t("back")}
            </Link>
            <button onClick={copyRef} disabled={!item?.reference}
              className="inline-flex items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-medium text-white/80 transition hover:bg-white/10"
              style={{ border: "1px solid rgba(255,255,255,0.15)" }}
              title="Copier la référence">
              <Copy className="h-3.5 w-3.5" />
            </button>
            <button onClick={loadAll} disabled={busy !== null}
              className="inline-flex items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-medium text-white/80 transition hover:bg-white/10"
              style={{ border: "1px solid rgba(255,255,255,0.15)" }}>
              <RefreshCcw className={cx("h-3.5 w-3.5", loading && "animate-spin")} />
            </button>
            <button onClick={onSave} disabled={busy !== null || !dirty}
              className="inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-semibold text-white transition disabled:opacity-50"
              style={{ background: `rgba(77,186,150,0.25)`, border: "1px solid rgba(77,186,150,0.40)" }}>
              {busy === "save" ? t("saving") : t("save")}
            </button>
            <button onClick={onDelete} disabled={busy !== null}
              className="inline-flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition hover:bg-red-500/20"
              style={{ color: "#fca5a5", border: "1px solid rgba(239,68,68,0.25)" }}>
              {t("delete")}
            </button>
          </div>
        </div>
      </div>

      {err && (
        <div className="flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />{err}
        </div>
      )}

      {/* ── Barre actions rapides ────────────────────────────────────────── */}
      {item && (
        <div className="rounded-2xl border bg-white p-3 flex flex-wrap items-center gap-2 shadow-sm"
          style={{ borderColor: CC.border }}>

          {/* Clôturer / Réouvrir */}
          <button
            onClick={() => onQuickStatus(item.status === "closed" ? "open" : "closed")}
            disabled={busy !== null}
            className="inline-flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-semibold transition"
            style={
              item.status === "closed"
                ? { background: `rgba(77,186,150,.12)`, color: CC.teal, border: `1px solid rgba(77,186,150,.22)` }
                : { background: `rgba(15,23,42,.05)`,  color: "#475569",  border: `1px solid ${CC.border}` }
            }
          >
            {item.status === "closed" ? <Unlock className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
            {item.status === "closed" ? t("reopen") : t("close_case")}
          </button>

          <div className="h-5 w-px bg-slate-200" />

          {/* Sélecteur assignation */}
          <select
            className="rounded-xl border bg-white px-3 py-2 text-sm text-slate-700 outline-none transition"
            style={{ borderColor: CC.border }}
            value={edit.assigned_to_id ?? ""}
            onChange={(e) => { const v = e.target.value; setEditSafe({ ...edit, assigned_to_id: v }); onAssignTo(v); }}
            disabled={busy !== null}
            onFocus={(e) => { e.currentTarget.style.borderColor = CC.teal; e.currentTarget.style.boxShadow = `0 0 0 3px rgba(77,186,150,0.12)`; }}
            onBlur={(e)  => { e.currentTarget.style.borderColor = CC.border; e.currentTarget.style.boxShadow = ""; }}
          >
            <option value="">— {t("unassigned")} —</option>
            {userOptions.map((u) => (
              <option key={u.id} value={String(u.id)}>
                @{u.username}{u.first_name || u.last_name ? ` — ${(u.first_name + " " + u.last_name).trim()}` : ""}
              </option>
            ))}
          </select>

          <button
            onClick={onAssignToMe}
            disabled={busy !== null}
            className="inline-flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-semibold transition"
            style={{ background: `rgba(26,53,120,.08)`, color: CC.navy, border: `1px solid rgba(26,53,120,.15)` }}
          >
            <UserPlus2 className="h-4 w-4" />
            {t("assign_to_me")}
          </button>

          {busy === "assign" && (
            <span className="text-xs text-slate-400">{t("assigning")}</span>
          )}
        </div>
      )}

      {/* ── Tabs ─────────────────────────────────────────────────────────── */}
      <div className="rounded-2xl border bg-white p-1.5 flex gap-1 flex-wrap shadow-sm" style={{ borderColor: CC.border }}>
        {(["overview", "notes", "documents", "collections"] as const).map((tabKey) => {
          const tabLabels: Record<string, string> = {
            overview:    t("tab_overview"),
            notes:       `${t("tab_notes")} (${counts.notes})`,
            documents:   `${t("tab_documents")} (${counts.docs})`,
            collections: t("tab_collections"),
          };
          const active = tab === tabKey;
          return (
            <button
              key={tabKey}
              onClick={() => setTab(tabKey)}
              className="rounded-xl px-4 py-2 text-sm font-semibold transition"
              style={
                active
                  ? { background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)`, color: "#fff" }
                  : { color: CC.muted, background: "transparent" }
              }
            >
              {tabLabels[tabKey]}
            </button>
          );
        })}
      </div>

      {loading ? (
        <div className="flex flex-col gap-3 p-2">
          {[1,2,3].map(i => <div key={i} className="h-16 rounded-2xl animate-pulse bg-slate-100" />)}
        </div>
      ) : !item ? (
        <div className="rounded-2xl border bg-white p-8 text-center text-sm text-slate-400" style={{ borderColor: CC.border }}>
          {t("not_found")}
        </div>
      ) : tab === "overview" ? (
        <div className="space-y-4">

          {/* KPI cards */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {[
              { label: t("kpi_balance"),    value: money(item.balance_amount, item.currency),  color: CC.red,   bg: "rgba(239,68,68,.08)" },
              { label: t("kpi_original"),   value: money(item.original_amount, item.currency), color: CC.navy,  bg: "rgba(26,53,120,.07)" },
              { label: t("kpi_due_date"),   value: item.due_date ? fmtDateOnly(item.due_date) : "—",           color: CC.amber, bg: "rgba(245,158,11,.08)" },
              { label: t("kpi_assigned"),   value: item.assigned_to_username ? `@${item.assigned_to_username}` : t("not_assigned"), color: CC.teal, bg: "rgba(77,186,150,.08)" },
            ].map(({ label, value, color, bg }) => (
              <div key={label} className="rounded-2xl border bg-white p-4 shadow-sm" style={{ borderColor: CC.border }}>
                <div className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-2">{label}</div>
                <div className="text-base font-bold truncate" style={{ color }}>{value}</div>
              </div>
            ))}
          </div>

          {/* Formulaire édition */}
          <div className="rounded-2xl border bg-white p-5 shadow-sm space-y-4" style={{ borderColor: CC.border }}>
            <div className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-1">{t("edit_section")}</div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_title")}</label>
                <input className={inputCls} value={edit.title} onChange={(e) => setEditSafe({ ...edit, title: e.target.value })} />
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_status")}</label>
                <select className={inputCls} value={edit.status} onChange={(e) => setEditSafe({ ...edit, status: e.target.value as any })}>
                  {STATUS.map((s) => <option key={s.v} value={s.v}>{locale === "fr" ? s.fr : s.en}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_priority")}</label>
                <select className={inputCls} value={edit.priority} onChange={(e) => setEditSafe({ ...edit, priority: e.target.value as any })}>
                  {PRIORITY.map((p) => (
                    <option key={p.v} value={p.v}>{locale === "fr" ? p.fr : p.en}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_currency")}</label>
                <div className="space-y-1">
                  <input
                    className={inputCls}
                    placeholder={t("currency_search")}
                    value={currencySearch}
                    onChange={(e) => setCurrencySearch(e.target.value)}
                  />
                  <select
                    className={inputCls}
                    value={edit.currency}
                    onChange={(e) => { setEditSafe({ ...edit, currency: e.target.value }); setCurrencySearch(""); }}
                  >
                    {CURRENCIES
                      .filter((c) => {
                        if (!currencySearch) return true;
                        const q = currencySearch.toLowerCase();
                        return c.code.toLowerCase().includes(q) || c.fr.toLowerCase().includes(q) || c.en.toLowerCase().includes(q);
                      })
                      .map((c) => (
                        <option key={c.code} value={c.code}>
                          {c.code} — {locale === "fr" ? c.fr : c.en}
                        </option>
                      ))
                    }
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_due_date")}</label>
                <input type="date" className={inputCls} value={edit.due_date} onChange={(e) => setEditSafe({ ...edit, due_date: e.target.value })} />
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_original_amount")}</label>
                <input className={inputCls} value={edit.original_amount} onChange={(e) => setEditSafe({ ...edit, original_amount: e.target.value })} />
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_balance")}</label>
                <input className={inputCls} value={edit.balance_amount} onChange={(e) => setEditSafe({ ...edit, balance_amount: e.target.value })} />
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_assigned_to")}</label>
                <select className={inputCls} value={edit.assigned_to_id ?? ""} onChange={(e) => setEditSafe({ ...edit, assigned_to_id: e.target.value })}>
                  <option value="">— {t("unassigned")} —</option>
                  {userOptions.map((u) => (
                    <option key={u.id} value={String(u.id)}>
                      @{u.username}{u.first_name || u.last_name ? ` — ${(u.first_name + " " + u.last_name).trim()}` : ""}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{t("field_portfolio")}</label>
                <select className={inputCls} value={edit.portfolio_id ?? ""} onChange={(e) => setEditSafe({ ...edit, portfolio_id: e.target.value })}>
                  <option value="">— {locale === "fr" ? "Aucun" : "None"} —</option>
                  {portfolios.map((p) => (
                    <option key={p.id} value={String(p.id)}>
                      {p.name}{p.code ? ` (${p.code})` : ""}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Débiteur */}
          {item.debtor && (
            <div className="rounded-2xl border bg-white p-5 shadow-sm" style={{ borderColor: CC.border }}>
              <div className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-3">{t("debtor_section")}</div>
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
                {[
                  { label: t("debtor_name"), value: item.debtor.full_name },
                  { label: "Email", value: item.debtor.email },
                  { label: t("debtor_phone"), value: item.debtor.phone },
                ].map(({ label, value }) => value ? (
                  <div key={label} className="rounded-xl border bg-slate-50 p-3" style={{ borderColor: CC.border }}>
                    <div className="text-[11px] font-medium text-slate-400 mb-0.5">{label}</div>
                    <div className="text-sm font-medium text-slate-700 truncate">{value}</div>
                  </div>
                ) : null)}
              </div>
            </div>
          )}
        </div>
      ) : tab === "notes" ? (
        <div className="h-[calc(100vh-16rem)] min-h-[400px]">
          <NoteThread
            notes={notes}
            myUsername={meUsername}
            loading={loading}
            submitting={noteSubmitting}
            error={err}
            onAdd={onAddNote}
            onEdit={onEditNote}
            onDelete={onDeleteNote}
            accentColor={CC.navy}
            placeholder="Ajouter une note… (Ctrl+Entrée pour envoyer)"
            emptyLabel="Aucune note pour le moment. Commencez par ajouter un commentaire."
          />
        </div>
      ) : tab === "collections" ? (
        <div className="rounded-2xl border bg-white p-5 space-y-4">
          {colFlash ? (
            <div
              className={cx(
                "rounded-2xl border p-4 text-sm",
                colFlash.kind === "success" ? "bg-emerald-50 text-emerald-800" : "bg-red-50 text-red-800"
              )}
              style={{ borderColor: CC.border }}
            >
              {colFlash.message}
            </div>
          ) : null}

          {colErr ? <div className="rounded-2xl border bg-white p-4 text-sm text-red-700">{colErr}</div> : null}

          <div className="rounded-2xl border bg-white p-3 flex flex-wrap items-center gap-2 shadow-sm" style={{ borderColor: CC.border }}>
            {[
              { label: t("action_call"),    icon: Phone,              onClick: () => { resetCollectionsDefaults(); setMCall(true); } },
              { label: "SMS",               icon: MessageSquareText,  onClick: () => { resetCollectionsDefaults(); setMSms(true); } },
              { label: "Email",             icon: Mail,               onClick: () => { resetCollectionsDefaults(); setEmailTab("log"); setEmailAttach((p) => ({ ...p, file: null, notes: "", action_id: "" })); setMEmail(true); } },
              { label: t("action_outlook"), icon: UploadCloud,        onClick: () => { resetCollectionsDefaults(); setEmailTab("outlook"); setEmailAttach((p) => ({ ...p, file: null, notes: "", action_id: "" })); setMEmail(true); } },
              { label: t("action_promise"), icon: CalendarClock,      onClick: () => { resetCollectionsDefaults(); setMPromise(true); } },
              { label: t("action_payment"), icon: CreditCardIcon,     onClick: () => { resetCollectionsDefaults(); loadTreasuryAccounts(false); setMPayment(true); }, teal: true },
            ].map(({ label, icon: Icon, onClick, teal }) => (
              <button key={label} onClick={onClick}
                disabled={busy !== null || colLoading || !col}
                className="inline-flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium transition disabled:opacity-50"
                style={teal
                  ? { background: `rgba(77,186,150,.1)`, color: CC.teal, border: `1px solid rgba(77,186,150,.2)` }
                  : { background: "rgba(15,23,42,.03)", color: CC.muted, border: `1px solid ${CC.border}` }
                }
              >
                <Icon className="h-4 w-4" />{label}
              </button>
            ))}

            <button
              onClick={() => { resetCollectionsDefaults(); setMContentious(true); }}
              disabled={busy !== null || colLoading || !col}
              className="inline-flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium transition disabled:opacity-50"
              style={{ background: "rgba(239,68,68,.06)", color: CC.red, border: `1px solid rgba(239,68,68,.15)` }}
            >
              <Gavel className="h-4 w-4" /> {t("action_contentious")}
            </button>

            <button
              onClick={() => item && ensureCollections(item)}
              disabled={busy !== null || colLoading || !item}
              className="inline-flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-medium transition disabled:opacity-50 ml-auto"
              style={{ background: "rgba(15,23,42,.03)", color: CC.muted, border: `1px solid ${CC.border}` }}
            >
              <RefreshCcw className={cx("h-4 w-4", colLoading && "animate-spin")} /> {t("action_refresh")}
            </button>
          </div>

          {colLoading ? (
            <div className="flex items-center gap-2 text-sm text-slate-400 py-4">
              <RefreshCcw className="h-4 w-4 animate-spin" /> {t("col_loading")}
            </div>
          ) : !col ? (
            <div className="text-sm text-slate-400 text-center py-8">{t("col_empty")}</div>
          ) : (
            <>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {(() => {
                  const cur = item?.currency ?? undefined
                  // Source de vérité : le dossier principal (item).
                  // col.case.amount_due/amount_collected viennent du module
                  // collections qui n'est pas toujours synchronisé.
                  // Dans Case : original_amount = dette initiale, amount_due = solde restant
                  const originalAmount = Number(item?.original_amount ?? 0)
                  const balanceAmount = Number(item?.balance_amount ?? 0)
                  // Si le module collections a ses propres données on les préfère,
                  // sinon on déduit depuis le dossier principal :
                  //   original_amount = dette initiale (Total dû)
                  //   balance_amount  = solde restant
                  //   payé            = initial - restant
                  const colAmountDue = Number(col.case.amount_due ?? 0)
                  const colAmountCollected = Number(col.case.amount_collected ?? 0)
                  const totalDue = colAmountDue > 0 ? colAmountDue : originalAmount
                  const totalPaid = colAmountCollected > 0 ? colAmountCollected : Math.max(0, originalAmount - balanceAmount)
                  const remaining = totalDue - totalPaid
                  const colStats = [
                    { key: "col_total_due",  value: money(totalDue, cur),       color: CC.red,   isNext: false },
                    { key: "col_paid",       value: money(totalPaid, cur),       color: CC.teal,  isNext: false },
                    { key: "col_remaining",  value: money(remaining, cur),       color: CC.navy,  isNext: false },
                    { key: "col_next_action", value: (col.case as any).next_action_date ? fmtDate((col.case as any).next_action_date) : "—", color: CC.amber, isNext: true },
                  ]
                  return colStats.map(({ key, value, color, isNext }) => (
                    <div key={key} className="rounded-2xl border bg-white p-4 shadow-sm" style={{ borderColor: CC.border }}>
                      <div className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-2">{t(key as any)}</div>
                      <div className="text-base font-bold truncate" style={{ color }}>{value}</div>
                      {isNext && (col.case as any).next_action_type && (
                        <div className="text-[11px] text-slate-400 mt-0.5">{(col.case as any).next_action_type}</div>
                      )}
                    </div>
                  ))
                })()}
              </div>

              <div className="rounded-2xl border bg-white overflow-hidden shadow-sm" style={{ borderColor: CC.border }}>
                <div className="px-5 py-4 border-b flex items-center justify-between" style={{ borderColor: CC.border }}>
                  <div className="text-sm font-semibold text-slate-700">{t("col_timeline_title")}</div>
                  <div className="text-[11px] text-slate-400">{recTimeline.length !== 1 ? t("col_events_plural", { count: recTimeline.length }) : t("col_events", { count: recTimeline.length })}</div>
                </div>

                {recTimeline.length === 0 ? (
                  <div className="p-5 text-sm text-neutral-500">
                    {t("col_no_activity")}
                  </div>
                ) : (
                  <div className="divide-y">
                    {recTimeline.map((it) => {
                      if (it.kind === "action") {
                        const a = it.action as any;
                        const Ico = iconForActionType(a.action_type);
                        const meta = a.details_json || parseMetaFromText(a.details);
                        const text = stripMetaBlock(a.details);

                        return (
                          <div key={`a-${a.id}`} className="p-4">
                            <div className="text-xs text-neutral-500 inline-flex items-center gap-2 flex-wrap">
                              <span className="inline-flex items-center gap-1">
                                <Ico className="h-4 w-4" />
                                <span className="font-medium">
                                  {locale === "fr" ? "Action" : "Action"} : {a.action_type}
                                </span>
                              </span>
                              <span>•</span>
                              <span>{fmtDate(a.action_date)}</span>
                              {a.outcome ? (
                                <>
                                  <span>•</span>
                                  <span className="text-neutral-600">{a.outcome}</span>
                                </>
                              ) : null}
                            </div>

                            <div className="text-sm mt-1">{a.summary || "—"}</div>

                            {a.action_type === "email" ? (
                              <div className="mt-2">
                                <button
                                  onClick={() => openEmailProofs(a.id)}
                                  className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold transition"
                                  style={{ background: `rgba(26,53,120,.07)`, color: CC.navy, border: `1px solid rgba(26,53,120,.12)` }}
                                  disabled={emailProofsLoading}
                                >
                                  <Paperclip className="h-4 w-4" /> {locale === "fr" ? "Preuves email" : "Email proofs"}
                                </button>
                              </div>
                            ) : null}

                            {(text || meta) ? (
                              <details className="mt-2">
                                <summary className="cursor-pointer text-xs text-neutral-600 hover:text-neutral-800">
                                  {locale === "fr" ? "Détails" : "Details"}
                                </summary>
                                {text ? (
                                  <div className="mt-2 text-xs text-neutral-700 whitespace-pre-wrap">{text}</div>
                                ) : null}
                                {meta ? <MetaGrid locale={locale} meta={meta} /> : null}
                              </details>
                            ) : null}

                            {a.next_action_date ? (
                              <div className="text-xs text-neutral-600 mt-2">
                                {locale === "fr" ? "Prochaine action" : "Next action"} : {fmtDateOnly(a.next_action_date)} •{" "}
                                {a.next_action_type || "—"}
                              </div>
                            ) : null}
                          </div>
                        );
                      }

                      if (it.kind === "payment") {
                        const p = it.payment;
                        const meta = (p as any).notes_json || parseMetaFromText(p.notes);
                        const text = stripMetaBlock(p.notes);

                        const receivedBy = String((p as any).received_by || (meta as any)?.received_by || "");
                        const treasuryAccountId =
                          (p as any).treasury_account ||
                          (meta as any)?.treasury_account ||
                          (meta as any)?.treasury_account_id ||
                          null;
                        const treasuryAccountName =
                          (p as any).treasury_account_name ||
                          (treasuryAccountId
                            ? (treasuryAccounts.find((a) => a.id === Number(treasuryAccountId))?.name ||
                                `#${treasuryAccountId}`)
                            : "");

                        return (
                          <div key={`p-${p.id}`} className="p-4">
                            <div className="text-xs text-neutral-500 inline-flex items-center gap-2 flex-wrap">
                              <span className="inline-flex items-center gap-1">
                                <CreditCardIcon className="h-4 w-4" />
                                <span className="font-medium">{locale === "fr" ? "Paiement" : "Payment"}</span>
                              </span>
                              <span>•</span>
                              <span>{fmtDate(p.paid_at)}</span>
                              <span>•</span>
                              <span className="text-neutral-700">
                                {money(p.amount, item?.currency || edit.currency || "XAF")}
                              </span>
                              <span className="text-neutral-600">{labelPaymentMethod(locale, p.method)}</span>
                              {receivedBy ? (
                                <span
                                  className={cx(
                                    "text-[11px] px-2 py-0.5 rounded-full",
                                    receivedByPillClass(receivedBy)
                                  )}
                                >
                                  {labelReceivedBy(locale, receivedBy)}
                                </span>
                              ) : null}
                              {receivedBy === "acx" && treasuryAccountName ? (
                                <span className="text-neutral-600">
                                  {locale === "fr" ? "Compte" : "Account"}: {treasuryAccountName}
                                </span>
                              ) : null}

                            </div>

                            {p.reference ? <div className="text-xs text-neutral-700 mt-1">{locale === "fr" ? "Réf." : "Ref."} : {p.reference}</div> : null}

                            {(text || meta) ? (
                            <details className="mt-2">
                              <summary className="cursor-pointer text-xs text-neutral-600 hover:text-neutral-800">
                                {locale === "fr" ? "Détails" : "Details"}
                              </summary>
                              {text ? <div className="mt-2 text-xs text-neutral-700 whitespace-pre-wrap">{text}</div> : null}
                              {meta ? <MetaGrid locale={locale} meta={meta} /> : null}
                            </details>
                          ) : null}
                          </div>
                        );
                      }

                      // Promise
                      const pr = it.promise;
                      const meta = (pr as any).notes_json || parseMetaFromText(pr.notes);
                      const text = stripMetaBlock(pr.notes);

                      return (
                        <div key={`pr-${pr.id}`} className="p-4">
                          <div className="text-xs text-neutral-500 inline-flex items-center gap-2 flex-wrap">
                            <span className="inline-flex items-center gap-1">
                              <CalendarClock className="h-4 w-4" />
                              <span className="font-medium">{locale === "fr" ? "Promesse" : "Promise"}</span>
                            </span>
                            <span>•</span>
                            <span>{fmtDate(pr.created_at)}</span>
                            <span>•</span>
                            <span className="text-neutral-700">{money(pr.amount, item?.currency || edit.currency || "XAF")}</span>
                            <span className="text-neutral-600">{labelPromiseStatus(locale, pr.status)}</span>
                          </div>

                          <div className="text-xs text-neutral-700 mt-1">
                            {locale === "fr" ? "Date promise" : "Promised date"} : {fmtDateOnly(pr.promised_date)}
                          </div>

                          {(text || meta) ? (
                            <details className="mt-2">
                              <summary className="cursor-pointer text-xs text-neutral-600 hover:text-neutral-800">
                                {locale === "fr" ? "Détails" : "Details"}
                              </summary>
                              {text ? <div className="mt-2 text-xs text-neutral-700 whitespace-pre-wrap">{text}</div> : null}
                              {meta ? <MetaGrid locale={locale} meta={meta} /> : null}
                            </details>
                          ) : null}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </>
          )}

          {/* Modales */}
          <Modal
            open={mCall}
            title={locale === "fr" ? "Enregistrer un appel" : "Log a call"}
            subtitle={locale === "fr" ? "Renseigne tous les paramètres de l’appel." : "Capture all call details."}
            onClose={() => setMCall(false)}
          >
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Téléphone" : "Phone"}</label>
                  <input className={inputCls} value={callForm.phone} onChange={(e) => setCallForm((p) => ({ ...p, phone: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Contact" : "Contact"}</label>
                  <input className={inputCls} value={callForm.contact_name} onChange={(e) => setCallForm((p) => ({ ...p, contact_name: e.target.value }))} />
                </div>
                <div className="flex items-center gap-2">
                  <input type="checkbox" checked={callForm.reached} onChange={(e) => setCallForm((p) => ({ ...p, reached: e.target.checked }))} />
                  <span className="text-sm">{locale === "fr" ? "Contact joint" : "Reached"}</span>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Durée (sec)" : "Duration (sec)"}</label>
                  <input className={inputCls} value={callForm.duration_seconds} onChange={(e) => setCallForm((p) => ({ ...p, duration_seconds: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Issue" : "Outcome"}</label>
                  <select className={inputCls} value={callForm.outcome} onChange={(e) => setCallForm((p) => ({ ...p, outcome: e.target.value as any }))}>
                    <option value="">{locale === "fr" ? "Auto" : "Auto"}</option>
                    {COL_OUTCOMES.map((o) => (
                      <option key={o.v} value={o.v}>{locale === "fr" ? o.fr : o.en}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Résumé" : "Summary"}</label>
                  <input className={inputCls} value={callForm.summary} onChange={(e) => setCallForm((p) => ({ ...p, summary: e.target.value }))} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Notes" : "Notes"}</label>
                  <textarea className={cx(inputCls, "min-h-[90px]")} value={callForm.notes} onChange={(e) => setCallForm((p) => ({ ...p, notes: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Prochaine action" : "Next action"}</label>
                  <select className={inputCls} value={callForm.next_action_type} onChange={(e) => setCallForm((p) => ({ ...p, next_action_type: e.target.value as any }))}>
                    <option value="">{locale === "fr" ? "—" : "—"}</option>
                    {COL_ACTION_TYPES.map((t) => (
                      <option key={t.v} value={t.v}>{locale === "fr" ? t.fr : t.en}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date" : "Date"}</label>
                  <input type="date" className={inputCls} value={callForm.next_action_date} onChange={(e) => setCallForm((p) => ({ ...p, next_action_date: e.target.value }))} />
                </div>
              </div>

              <div className="flex justify-end gap-2">
                <button onClick={() => setMCall(false)} className="rounded-xl px-4 py-2 text-sm font-medium border bg-white hover:bg-slate-50 transition text-slate-600" style={{ borderColor: CC.border }}>
                  {locale === "fr" ? "Annuler" : "Cancel"}
                </button>
                <button onClick={submitCall} className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-call" && "opacity-60")} style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }} disabled={busy !== null}>
                  {busy === "submit-call" ? (locale === "fr" ? "Enregistrement…" : "Saving…") : (locale === "fr" ? "Enregistrer" : "Save")}
                </button>
              </div>
            </div>
          </Modal>

          <Modal open={mSms} title={locale === "fr" ? "Enregistrer un SMS" : "Log an SMS"} onClose={() => setMSms(false)}>
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">To</label>
                  <input className={inputCls} value={smsForm.to ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, to: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Status</label>
                  <input className={inputCls} value={smsForm.status ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, status: e.target.value }))} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Message" : "Message"}</label>
                  <textarea className={cx(inputCls, "min-h-[110px]")} value={smsForm.message ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, message: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Provider</label>
                  <input className={inputCls} value={smsForm.provider ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, provider: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">External ID</label>
                  <input className={inputCls} value={smsForm.external_id ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, external_id: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Prochaine action" : "Next action"}</label>
                  <select className={inputCls} value={smsForm.next_action_type ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, next_action_type: e.target.value as any }))}>
                    <option value="">{locale === "fr" ? "—" : "—"}</option>
                    {COL_ACTION_TYPES.map((t) => (
                      <option key={t.v} value={t.v}>{locale === "fr" ? t.fr : t.en}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date" : "Date"}</label>
                  <input type="date" className={inputCls} value={smsForm.next_action_date ?? ""} onChange={(e) => setSmsForm((p) => ({ ...p, next_action_date: e.target.value }))} />
                </div>
              </div>

              <div className="flex justify-end gap-2">
                <button onClick={() => setMSms(false)} className="rounded-xl px-4 py-2 text-sm font-medium border bg-white hover:bg-slate-50 transition text-slate-600" style={{ borderColor: CC.border }}>
                  {locale === "fr" ? "Annuler" : "Cancel"}
                </button>
                <button onClick={submitSms} className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-sms" && "opacity-60")} style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }} disabled={busy !== null}>
                  {busy === "submit-sms" ? (locale === "fr" ? "Enregistrement…" : "Saving…") : (locale === "fr" ? "Enregistrer" : "Save")}
                </button>
              </div>
            </div>
          </Modal>

          <Modal
            open={mEmail}
            title={locale === "fr" ? "Email" : "Email"}
            subtitle={
              emailTab === "send"
                ? (locale === "fr" ? "Envoyer un email depuis ACX" : "Send an email from ACX")
                : emailTab === "outlook"
                  ? (locale === "fr" ? "Attacher une preuve Outlook (.eml)" : "Attach an Outlook proof (.eml)")
                  : (locale === "fr" ? "Enregistrer un email (log)" : "Log an email")
            }
            onClose={() => setMEmail(false)}
          >
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => setEmailTab("log")}
                  className="rounded-xl px-3 py-2 text-sm font-medium border transition"
                  style={emailTab === "log"
                    ? { background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)`, color: "#fff", borderColor: "transparent" }
                    : { borderColor: CC.border, color: CC.muted, background: "#fff" }}
                  disabled={busy !== null}
                >
                  {locale === "fr" ? "Enregistrer" : "Log"}
                </button>

                <button
                  type="button"
                  onClick={() => setEmailTab("send")}
                  className="rounded-xl px-3 py-2 text-sm font-medium border inline-flex items-center gap-2 transition"
                  style={emailTab === "send"
                    ? { background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)`, color: "#fff", borderColor: "transparent" }
                    : { borderColor: CC.border, color: CC.muted, background: "#fff" }}
                  disabled={busy !== null}
                >
                  <Mail className="h-4 w-4" />
                  {locale === "fr" ? "Envoyer ACX" : "Send (ACX)"}
                </button>

                <button
                  type="button"
                  onClick={() => setEmailTab("outlook")}
                  className="rounded-xl px-3 py-2 text-sm font-medium border inline-flex items-center gap-2 transition"
                  style={emailTab === "outlook"
                    ? { background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)`, color: "#fff", borderColor: "transparent" }
                    : { borderColor: CC.border, color: CC.muted, background: "#fff" }}
                  disabled={busy !== null}
                >
                  <UploadCloud className="h-4 w-4" />
                  {locale === "fr" ? "Preuve Outlook" : "Outlook proof"}
                </button>
              </div>

              {/* emailTab error */}
              {colErr ? (
                <div className="rounded-2xl border bg-red-50 p-3 text-sm text-red-700" style={{ borderColor: "rgba(220, 38, 38, 0.25)" }}>
                  {colErr}
                </div>
              ) : null}

              {emailTab === "log" ? (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">To</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.to ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, to: e.target.value }))}
                      />
                    </div>
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">CC (comma)</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.cc ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, cc: e.target.value }))}
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Sujet" : "Subject"}</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.subject ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, subject: e.target.value }))}
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Contenu" : "Body"}</label>
                      <textarea
                        className="w-full rounded-xl border px-3 py-2 text-sm min-h-[140px]"
                        style={{ borderColor: CC.border }}
                        value={emailForm.body ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, body: e.target.value }))}
                      />
                    </div>
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Provider</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.provider ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, provider: e.target.value }))}
                      />
                    </div>
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">External ID</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.external_id ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, external_id: e.target.value }))}
                      />
                    </div>
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Prochaine action" : "Next action"}</label>
                      <select
                        className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                        style={{ borderColor: CC.border }}
                        value={emailForm.next_action_type ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, next_action_type: e.target.value as any }))}
                      >
                        <option value="">{locale === "fr" ? "—" : "—"}</option>
                        {COL_ACTION_TYPES.map((t) => (
                          <option key={t.v} value={t.v}>
                            {locale === "fr" ? t.fr : t.en}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date" : "Date"}</label>
                      <input
                        type="date"
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailForm.next_action_date ?? ""}
                        onChange={(e) => setEmailForm((p) => ({ ...p, next_action_date: e.target.value }))}
                      />
                    </div>
                  </div>

                  <div className="flex justify-end gap-2">
                    <button
                      onClick={() => setMEmail(false)}
                      className="rounded-xl px-4 py-2 text-sm border bg-white hover:bg-slate-50"
                      style={{ borderColor: CC.border }}
                    >
                      {locale === "fr" ? "Annuler" : "Cancel"}
                    </button>
                    <button
                      onClick={submitEmail}
                      className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-email" && "opacity-60")}
                      style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }}
                      disabled={busy !== null}
                    >
                      {busy === "submit-email"
                        ? locale === "fr"
                          ? "Enregistrement…"
                          : "Saving…"
                        : locale === "fr"
                          ? "Enregistrer"
                          : "Save"}
                    </button>
                  </div>
                </>
              ) : emailTab === "send" ? (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">To (comma)</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailSend.to ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, to: e.target.value }))}
                        placeholder="client@example.com"
                      />
                    </div>

                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">CC (comma)</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailSend.cc ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, cc: e.target.value }))}
                        placeholder="cc@example.com"
                      />
                    </div>

                    <div>
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">BCC (comma)</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailSend.bcc ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, bcc: e.target.value }))}
                        placeholder="bcc@example.com"
                      />
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Sujet" : "Subject"}</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailSend.subject ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, subject: e.target.value }))}
                      />
                    </div>

                    
                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">
                        {locale === "fr" ? "Message (HTML)" : "Message (HTML)"}
                      </label>

                      <EmailHtmlEditor
                        value={emailSend.body_html ?? ""}
                        onChange={(html) => setEmailSend((p) => ({ ...p, body_html: html }))}
                        placeholder={locale === "fr" ? "Écrivez votre message…" : "Write your message…"}
                      />
                    </div>

<div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "From (optionnel)" : "From (optional)"}</label>
                      <input
                        className="w-full rounded-xl border px-3 py-2 text-sm"
                        style={{ borderColor: CC.border }}
                        value={emailSend.from_address ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, from_address: e.target.value }))}
                        placeholder="ACX <no-reply@domaine.com>"
                      />
                      <div className="text-[11px] text-neutral-500 mt-1">
                        {locale === "fr"
                          ? "Si vide, DEFAULT_FROM_EMAIL (backend) sera utilisé."
                          : "If empty, DEFAULT_FROM_EMAIL (backend) will be used."}
                      </div>
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Pièces jointes" : "Attachments"}</label>
                      <input
                        type="file"
                        multiple
                        className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                        style={{ borderColor: CC.border }}
                        onChange={(e) => setEmailSendFiles(Array.from(e.target.files || []))}
                        disabled={busy !== null}
                      />
                      {emailSendFiles.length ? (
                        <div className="mt-2 rounded-xl border bg-white p-2 text-xs" style={{ borderColor: CC.border }}>
                          <div className="font-medium text-neutral-700 mb-1">{locale === "fr" ? "Fichiers" : "Files"}</div>
                          <ul className="list-disc pl-5 space-y-0.5 text-neutral-600">
                            {emailSendFiles.map((f) => (
                              <li key={f.name}>{f.name}</li>
                            ))}
                          </ul>
                        </div>
                      ) : null}
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Notes (optionnel)" : "Notes (optional)"}</label>
                      <textarea
                        className="w-full rounded-xl border px-3 py-2 text-sm min-h-[70px]"
                        style={{ borderColor: CC.border }}
                        value={emailSend.notes ?? ""}
                        onChange={(e) => setEmailSend((p) => ({ ...p, notes: e.target.value }))}
                      />
                    </div>
                  </div>

                  <div className="flex items-center justify-end gap-2 pt-4 sticky bottom-0 bg-white border-t" style={{ borderColor: CC.border }}>
                    <button
                      onClick={() => setMEmail(false)}
                      className="rounded-xl border px-4 py-2 text-sm hover:bg-slate-50"
                      style={{ borderColor: CC.border }}
                      disabled={busy !== null}
                    >
                      {locale === "fr" ? "Annuler" : "Cancel"}
                    </button>
                    <button
                      onClick={submitEmailSend}
                      className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-email-send" && "opacity-60")}
                      style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }}
                      disabled={busy !== null}
                    >
                      {busy === "submit-email-send"
                        ? locale === "fr"
                          ? "Envoi…"
                          : "Sending…"
                        : locale === "fr"
                          ? "Envoyer"
                          : "Send"}
                    </button>
                  </div>
                </>

              ) : (
                <>
                  <div className="rounded-2xl border bg-neutral-50 p-3 text-xs text-neutral-700" style={{ borderColor: CC.border }}>
                    <div className="font-medium mb-1">{locale === "fr" ? "Preuve Outlook" : "Outlook proof"}</div>
                    <div>
                      {locale === "fr"
                        ? "Depuis Outlook : ouvrez l'email envoyé → Enregistrer sous → .eml, puis attachez le fichier ici. ACX créera/mettra à jour l'action Email dans la timeline."
                        : "From Outlook: open the sent email → Save as → .eml, then attach it here. ACX will create/update the Email action in the timeline."}
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">
                        {locale === "fr" ? "Associer à une action Email existante (optionnel)" : "Link to an existing Email action (optional)"}
                      </label>
                      <select
                        className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                        style={{ borderColor: CC.border }}
                        value={emailAttach.action_id ?? ""}
                        onChange={(e) => setEmailAttach((p) => ({ ...p, action_id: e.target.value }))}
                      >
                        <option value="">{locale === "fr" ? "Créer une nouvelle action Email automatiquement" : "Create a new Email action automatically"}</option>
                        {(col?.actions || [])
                          .filter((a: any) => a.action_type === "email")
                          .slice(0, 25)
                          .map((a: any) => (
                            <option key={a.id} value={String(a.id)}>
                              #{a.id} • {fmtDate(a.action_date)} • {(a.summary || "").slice(0, 60)}
                            </option>
                          ))}
                      </select>
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Fichier .eml" : ".eml file"}</label>
                      <input
                        type="file"
                        accept=".eml,message/rfc822"
                        className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                        style={{ borderColor: CC.border }}
                        onChange={(e) => {
                          const f = e.target.files?.[0] || null;
                          setEmailAttach((p) => ({ ...p, file: f }));
                        }}
                      />
                      {emailAttach.file ? (
                        <div className="mt-1 text-xs text-neutral-600">{emailAttach.file.name}</div>
                      ) : null}
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Notes (optionnel)" : "Notes (optional)"}</label>
                      <textarea
                        className="w-full rounded-xl border px-3 py-2 text-sm min-h-[90px]"
                        style={{ borderColor: CC.border }}
                        value={emailAttach.notes ?? ""}
                        onChange={(e) => setEmailAttach((p) => ({ ...p, notes: e.target.value }))}
                      />
                    </div>
                  </div>

                  <div className="flex justify-end gap-2">
                    <button
                      onClick={() => setMEmail(false)}
                      className="rounded-xl px-4 py-2 text-sm border bg-white hover:bg-slate-50"
                      style={{ borderColor: CC.border }}
                    >
                      {locale === "fr" ? "Annuler" : "Cancel"}
                    </button>
                    <button
                      onClick={submitEmailAttach}
                      className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-email-attach" && "opacity-60")}
                      style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }}
                      disabled={busy !== null || !emailAttach.file}
                    >
                      {busy === "submit-email-attach"
                        ? locale === "fr"
                          ? "Attachement…"
                          : "Attaching…"
                        : locale === "fr"
                          ? "Attacher la preuve"
                          : "Attach proof"}
                    </button>
                  </div>
                </>
              )}
            </div>
          </Modal>

          
          <Modal
            open={mEmailProofs}
            title={locale === "fr" ? "Preuves email" : "Email proofs"}
            subtitle={
              emailProofsActionId
                ? (locale === "fr"
                    ? `Action email #${emailProofsActionId}`
                    : `Email action #${emailProofsActionId}`)
                : undefined
            }
            onClose={() => setMEmailProofs(false)}
          >
            <div className="space-y-3">
              {emailProofsLoading ? (
                <div className="text-sm text-neutral-500">{locale === "fr" ? "Chargement…" : "Loading…"}</div>
              ) : emailProofsErr ? (
                <div className="rounded-2xl border bg-white p-4 text-sm text-red-700" style={{ borderColor: "rgba(239,68,68,0.30)" }}>
                  {emailProofsErr}
                </div>
              ) : emailProofs.length === 0 ? (
                <div className="text-sm text-neutral-500">{locale === "fr" ? "Aucune preuve attachée." : "No proof attached."}</div>
              ) : (
                <div className="space-y-3">
                  {emailProofs.map((em) => (
                    <div key={em.id} className="rounded-2xl border bg-white p-4" style={{ borderColor: CC.border }}>
                      <div className="text-xs text-neutral-500">
                        {em.sent_at ? fmtDate(em.sent_at) : "—"} • {em.source || "outlook"} • {em.direction || "outbound"}
                      </div>
                      <div className="text-sm font-medium mt-1">{em.subject || (locale === "fr" ? "Email" : "Email")}</div>

                      <div className="text-xs text-neutral-700 mt-2 space-y-1">
                        {em.status ? <div><span className="text-neutral-500">Status:</span> {em.status}</div> : null}
                        {em.error_message ? (
                          <div className="text-red-700"><span className="text-neutral-500">Error:</span> {em.error_message}</div>
                        ) : null}
                        {em.from_address ? <div><span className="text-neutral-500">From:</span> {em.from_address}</div> : null}
                        {em.to?.length ? <div><span className="text-neutral-500">To:</span> {em.to.join(", ")}</div> : null}
                        {em.cc?.length ? <div><span className="text-neutral-500">CC:</span> {em.cc.join(", ")}</div> : null}
                      </div>

                      <div className="flex flex-wrap gap-2 mt-3">
                        {em.raw_eml_url ? (
                          <a
                            href={em.raw_eml_url}
                            target="_blank"
                            rel="noreferrer"
                            className="rounded-xl px-3 py-2 text-xs font-medium border bg-white hover:bg-slate-50 inline-flex items-center gap-2"
                            style={{ borderColor: CC.border }}
                          >
                            <Download className="h-4 w-4" />
                            {locale === "fr" ? "Télécharger .eml" : "Download .eml"}
                          </a>
                        ) : null}
                      </div>

                      {em.attachments?.length ? (
                        <details className="mt-3">
                          <summary className="cursor-pointer text-xs text-neutral-600 hover:text-neutral-800">
                            {locale === "fr" ? "Pièces jointes" : "Attachments"} ({em.attachments.length})
                          </summary>
                          <div className="mt-2 space-y-2">
                            {em.attachments.map((a) => (
                              <div key={a.id} className="flex items-center justify-between gap-3 text-xs">
                                <div className="min-w-0 truncate">{a.filename}</div>
                                {a.file_url ? (
                                  <a
                                    href={a.file_url}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="rounded-xl px-3 py-1.5 border bg-white hover:bg-slate-50"
                                    style={{ borderColor: CC.border }}
                                  >
                                    {locale === "fr" ? "Ouvrir" : "Open"}
                                  </a>
                                ) : (
                                  <span className="text-neutral-400">—</span>
                                )}
                              </div>
                            ))}
                          </div>
                        </details>
                      ) : null}

                      {(em.body_text || em.body_html) ? (
                        <details className="mt-3">
                          <summary className="cursor-pointer text-xs text-neutral-600 hover:text-neutral-800">
                            {locale === "fr" ? "Contenu" : "Body"}
                          </summary>
                          {em.body_text ? (
                            <div className="mt-2 text-xs text-neutral-700 whitespace-pre-wrap">{em.body_text}</div>
                          ) : em.body_html ? (
                            <div className="mt-2 text-xs text-neutral-700 whitespace-pre-wrap">{em.body_html}</div>
                          ) : null}
                        </details>
                      ) : null}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </Modal>

<Modal open={mPromise} title={locale === "fr" ? "Promesse de paiement" : "Payment promise"} onClose={() => setMPromise(false)}>
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Montant" : "Amount"}</label>
                  <input className={inputCls} value={promiseForm.amount} onChange={(e) => setPromiseForm((p) => ({ ...p, amount: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date promesse" : "Promised date"}</label>
                  <input type="date" className={inputCls} value={promiseForm.promised_date} onChange={(e) => setPromiseForm((p) => ({ ...p, promised_date: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Canal" : "Channel"}</label>
                  <input className={inputCls} value={promiseForm.channel} onChange={(e) => setPromiseForm((p) => ({ ...p, channel: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Fait par" : "Made by"}</label>
                  <input className={inputCls} value={promiseForm.made_by} onChange={(e) => setPromiseForm((p) => ({ ...p, made_by: e.target.value }))} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Notes" : "Notes"}</label>
                  <textarea className={cx(inputCls, "min-h-[90px]")} value={promiseForm.notes} onChange={(e) => setPromiseForm((p) => ({ ...p, notes: e.target.value }))} />
                </div>
              </div>

              <div className="flex justify-end gap-2">
                <button onClick={() => setMPromise(false)} className="rounded-xl px-4 py-2 text-sm font-medium border bg-white hover:bg-slate-50 transition text-slate-600" style={{ borderColor: CC.border }}>
                  {locale === "fr" ? "Annuler" : "Cancel"}
                </button>
                <button onClick={submitPromise} className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-promise" && "opacity-60")} style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }} disabled={busy !== null}>
                  {busy === "submit-promise" ? (locale === "fr" ? "Création…" : "Creating…") : (locale === "fr" ? "Créer" : "Create")}
                </button>
              </div>
            </div>
          </Modal>

          <Modal open={mPayment} title={locale === "fr" ? "Paiement" : "Payment"} onClose={() => setMPayment(false)}>
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Montant" : "Amount"}</label>
                  <input className={inputCls} value={paymentForm.amount} onChange={(e) => setPaymentForm((p) => ({ ...p, amount: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Méthode" : "Method"}</label>
                  <select className={inputCls} value={paymentForm.method} onChange={(e) => setPaymentForm((p) => ({ ...p, method: e.target.value as any }))}>
                    <option value="cash">Cash</option>
                    <option value="bank_transfer">{locale === "fr" ? "Virement" : "Bank transfer"}</option>
                    <option value="mobile_money">Mobile money</option>
                    <option value="cheque">{locale === "fr" ? "Chèque" : "Cheque"}</option>
                    <option value="card">{locale === "fr" ? "Carte" : "Card"}</option>
                    <option value="other">{locale === "fr" ? "Autre" : "Other"}</option>
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Référence" : "Reference"}</label>
                  <input className={inputCls} value={paymentForm.reference} onChange={(e) => setPaymentForm((p) => ({ ...p, reference: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date/heure" : "Paid at"}</label>
                  <input type="datetime-local" className={inputCls} value={paymentForm.paid_at} onChange={(e) => setPaymentForm((p) => ({ ...p, paid_at: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Canal" : "Channel"}</label>
                  <input className={inputCls} value={paymentForm.channel} onChange={(e) => setPaymentForm((p) => ({ ...p, channel: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">
                    {locale === "fr" ? "Reçu par" : "Received by"}
                  </label>
                  <select
                    className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                    style={{ borderColor: CC.border }}
                    value={paymentForm.received_by ?? "acx"}
                    onChange={(e) =>
                      setPaymentForm((p) => ({
                        ...p,
                        received_by: e.target.value as any,
                        // si on passe sur Client, on vide le compte trésorerie
                        treasury_account_id: e.target.value === "acx" ? p.treasury_account_id : "",
                      }))
                    }
                    disabled={busy !== null}
                  >
                    <option value="acx">{locale === "fr" ? "ACX (encaissé)" : "ACX (collected)"}</option>
                    <option value="customer_direct">{locale === "fr" ? "Client (direct)" : "Client (direct)"}</option>
                  </select>
                  <div className="text-[11px] text-neutral-500 mt-1">
                    {locale === "fr"
                      ? "ACX = on encaisse sur un compte de trésorerie. Client = paiement directement chez le créancier."
                      : "ACX = money received on a treasury account. Client = paid directly to the creditor."}
                  </div>
                </div>

                {paymentForm.received_by === "acx" ? (
                  <div className="md:col-span-2">
                    <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">
                      {locale === "fr" ? "Compte de trésorerie *" : "Treasury account *"}
                    </label>

                    <div className="flex items-center gap-2 flex-wrap">
                      <select
                        className="flex-1 min-w-[220px] rounded-xl border px-3 py-2 text-sm bg-white"
                        style={{ borderColor: CC.border }}
                        value={paymentForm.treasury_account_id ?? ""}
                        onChange={(e) => setPaymentForm((p) => ({ ...p, treasury_account_id: e.target.value }))}
                        disabled={busy !== null || treasuryLoading}
                      >
                        <option value="">
                          {treasuryLoading
                            ? locale === "fr"
                              ? "Chargement des comptes…"
                              : "Loading accounts…"
                            : locale === "fr"
                              ? "— Sélectionner un compte —"
                              : "— Select an account —"}
                        </option>
                        {treasuryAccounts.map((a) => (
                          <option key={a.id} value={String(a.id)}>
                            {a.name}{a.currency ? ` (${a.currency})` : ""}
                            {(a as any).is_default ? (locale === "fr" ? " • défaut" : " • default") : ""}
                          </option>
                        ))}
                      </select>

                      <button
                        type="button"
                        onClick={() => loadTreasuryAccounts(true)}
                        className="rounded-xl px-3 py-2 text-sm font-medium border bg-white hover:bg-slate-50 inline-flex items-center gap-2"
                        style={{ borderColor: CC.border }}
                        disabled={busy !== null || treasuryLoading}
                        title={locale === "fr" ? "Rafraîchir les comptes" : "Refresh accounts"}
                      >
                        <RefreshCcw className={cx("h-4 w-4", treasuryLoading && "animate-spin")} />
                        {locale === "fr" ? "Rafraîchir" : "Refresh"}
                      </button>

                      <Link
                        href={`/${locale}/treasury`}
                        className="rounded-xl px-3 py-2 text-sm font-medium border bg-white hover:bg-slate-50"
                        style={{ borderColor: CC.border }}
                      >
                        {locale === "fr" ? "Trésorerie" : "Treasury"}
                      </Link>
                    </div>

                    {treasuryErr ? (
                      <div className="mt-1 text-[11px] text-red-700">{treasuryErr}</div>
                    ) : null}

                    <div className="mt-1 text-[11px] text-neutral-500">
                      {locale === "fr"
                        ? "Obligatoire si ACX encaisse. Cela alimente automatiquement le journal de trésorerie."
                        : "Required when ACX collects. This automatically feeds the treasury journal."}
                    </div>
                  </div>
                ) : null}

                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Notes" : "Notes"}</label>
                  <textarea className={cx(inputCls, "min-h-[90px]")} value={paymentForm.notes} onChange={(e) => setPaymentForm((p) => ({ ...p, notes: e.target.value }))} />
                </div>
              </div>

              <div className="flex justify-end gap-2">
                <button onClick={() => setMPayment(false)} className="rounded-xl px-4 py-2 text-sm font-medium border bg-white hover:bg-slate-50 transition text-slate-600" style={{ borderColor: CC.border }}>
                  {locale === "fr" ? "Annuler" : "Cancel"}
                </button>
                <button onClick={submitPayment} className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-payment" && "opacity-60")} style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }} disabled={busy !== null}>
                  {busy === "submit-payment" ? (locale === "fr" ? "Enregistrement…" : "Saving…") : (locale === "fr" ? "Enregistrer" : "Save")}
                </button>
              </div>
            </div>
          </Modal>

          <Modal open={mContentious} title={locale === "fr" ? "Contentieux" : "Legal"} onClose={() => setMContentious(false)}>
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Type" : "Type"}</label>
                  <select className={inputCls} value={contentiousForm.type} onChange={(e) => setContentiousForm((p) => ({ ...p, type: e.target.value as any }))}>
                    <option value="notice">{locale === "fr" ? "Mise en demeure" : "Formal notice"}</option>
                    <option value="lawyer">{locale === "fr" ? "Transfert avocat" : "Transfer to lawyer"}</option>
                    <option value="dispute">{locale === "fr" ? "Contestation" : "Dispute"}</option>
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Référence" : "Reference"}</label>
                  <input className={inputCls} value={contentiousForm.reference} onChange={(e) => setContentiousForm((p) => ({ ...p, reference: e.target.value }))} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Résumé *" : "Summary *"}</label>
                  <input className={inputCls} value={contentiousForm.summary} onChange={(e) => setContentiousForm((p) => ({ ...p, summary: e.target.value }))} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Détails" : "Details"}</label>
                  <textarea className={cx(inputCls, "min-h-[110px]")} value={contentiousForm.details} onChange={(e) => setContentiousForm((p) => ({ ...p, details: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Nom avocat" : "Lawyer name"}</label>
                  <input className={inputCls} value={contentiousForm.lawyer_name} onChange={(e) => setContentiousForm((p) => ({ ...p, lawyer_name: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Téléphone avocat" : "Lawyer phone"}</label>
                  <input className={inputCls} value={contentiousForm.lawyer_phone} onChange={(e) => setContentiousForm((p) => ({ ...p, lawyer_phone: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Email avocat" : "Lawyer email"}</label>
                  <input className={inputCls} value={contentiousForm.lawyer_email} onChange={(e) => setContentiousForm((p) => ({ ...p, lawyer_email: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Prochaine action" : "Next action"}</label>
                  <select className={inputCls} value={contentiousForm.next_action_type} onChange={(e) => setContentiousForm((p) => ({ ...p, next_action_type: e.target.value as any }))}>
                    <option value="">{locale === "fr" ? "—" : "—"}</option>
                    {COL_ACTION_TYPES.map((t) => (
                      <option key={t.v} value={t.v}>{locale === "fr" ? t.fr : t.en}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1.5">{locale === "fr" ? "Date" : "Date"}</label>
                  <input type="date" className={inputCls} value={contentiousForm.next_action_date} onChange={(e) => setContentiousForm((p) => ({ ...p, next_action_date: e.target.value }))} />
                </div>
              </div>

              <div className="flex justify-end gap-2">
                <button onClick={() => setMContentious(false)} className="rounded-xl px-4 py-2 text-sm font-medium border bg-white hover:bg-slate-50 transition text-slate-600" style={{ borderColor: CC.border }}>
                  {locale === "fr" ? "Annuler" : "Cancel"}
                </button>
                <button onClick={submitContentious} className={cx("rounded-xl px-4 py-2 text-sm font-medium text-white", busy === "submit-contentious" && "opacity-60")} style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }} disabled={busy !== null}>
                  {busy === "submit-contentious" ? (locale === "fr" ? "Enregistrement…" : "Saving…") : (locale === "fr" ? "Enregistrer" : "Save")}
                </button>
              </div>
            </div>
          </Modal>
        </div>
      ) : (
        <div className="rounded-2xl border bg-white p-5 shadow-sm space-y-4" style={{ borderColor: CC.border }}>
          <div className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-1">Documents</div>

          {/* Upload form */}
          <div className="rounded-2xl border bg-slate-50/60 p-4 space-y-3" style={{ borderColor: CC.border }}>
            <div className="text-sm font-semibold text-slate-700">Ajouter un document</div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <input
                className={cx(inputCls, "md:col-span-2")}
                placeholder="Titre du document"
                value={upload.title}
                onChange={(e) => setUpload({ ...upload, title: e.target.value })}
              />
              <select className={inputCls} value={upload.doc_type} onChange={(e) => setUpload({ ...upload, doc_type: e.target.value as any })}>
                <option value="contract">Contrat</option>
                <option value="invoice">Facture</option>
                <option value="letter">Courrier</option>
                <option value="id">Pièce d'identité</option>
                <option value="other">Autre</option>
              </select>
              <div className="md:col-span-2">
                <input type="file" className={inputCls} onChange={(e) => setUpload({ ...upload, file: e.target.files?.[0] || null })} />
                {upload.file && <div className="mt-1 text-xs text-slate-500 truncate">Fichier : <span className="font-medium text-slate-700">{upload.file.name}</span></div>}
              </div>
              <button
                onClick={onUploadDoc}
                disabled={busy !== null}
                className={cx("rounded-xl px-4 py-2.5 text-sm font-semibold text-white inline-flex items-center justify-center gap-2 transition disabled:opacity-60")}
                style={{ background: `linear-gradient(135deg, ${CC.navy} 0%, ${CC.navy2} 100%)` }}
              >
                <UploadCloud className="h-4 w-4" />
                {busy === "upload" ? "Upload…" : "Uploader"}
              </button>
            </div>
          </div>

          {/* Document list */}
          <div className="space-y-2">
            {docs.length === 0 ? (
              <div className="text-sm text-slate-400 text-center py-8">Aucun document.</div>
            ) : (
              docs.map((d) => (
                <div key={d.id} className="rounded-2xl border bg-slate-50/60 p-4 flex items-start justify-between gap-3" style={{ borderColor: CC.border }}>
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="h-9 w-9 rounded-xl flex items-center justify-center shrink-0"
                      style={{ background: `rgba(26,53,120,.08)`, border: `1px solid rgba(26,53,120,.12)` }}>
                      <Paperclip className="h-4 w-4" style={{ color: CC.navy }} />
                    </div>
                    <div className="min-w-0">
                      <div className="text-sm font-semibold text-slate-800 truncate">{d.title}</div>
                      <div className="text-[11px] text-slate-400 mt-0.5 capitalize">{d.doc_type} • {fmtDate(d.created_at)} {d.uploaded_by_username ? `• @${d.uploaded_by_username}` : ""}</div>
                    </div>
                  </div>
                  {d.file_url ? (
                    <a href={d.file_url} target="_blank" rel="noreferrer"
                      className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold shrink-0 transition"
                      style={{ background: `rgba(26,53,120,.07)`, color: CC.navy, border: `1px solid rgba(26,53,120,.12)` }}>
                      <Download className="h-3.5 w-3.5" /> Ouvrir
                    </a>
                  ) : (
                    <span className="text-xs text-slate-300">—</span>
                  )}
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}