"use client"

import Link from "next/link"
import { useEffect, useMemo, useState } from "react"
import { useParams } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"

import {
  getCustomerCase,
  listCustomerCaseNotes,
  addCustomerCaseNote,
  patchCustomerCaseNote,
  deleteCustomerCaseNote,
  getCustomerPortalMe,
  patchCustomerCaseCustomerPortal,
  listCustomerCaseDocuments,
  uploadCustomerCaseDocument,
  patchCustomerCaseDocument,
  deleteCustomerCaseDocument,
  type CaseNote,
  type CustomerPortalCaseDocument,
  type CaseDocumentType,
} from "@/src/lib/api/customer-portal"
import { NoteThread } from "@/src/components/notes/NoteThread"

import { customerPortalApi } from "@/src/lib/api/customer-portal-client"

import {
  AlertTriangle,
  ArrowLeft,
  Loader2,
  Save,
  Send,
  Paperclip,
  Upload,
  UserCog,
  FileText,
  MessageSquareText,
  FolderKanban,
  RefreshCw,
  Lock,
  BadgeInfo,
  User,
  Building2,
  Phone,
  Mail,
  MapPin,
  CalendarDays,
  CreditCard,
  Hash,
  Pencil,
  Trash2,
  X,
  Tag,
  Wallet,
  Clock,
  Briefcase,
} from "lucide-react"

type AssigneeCP = {
  id: number
  username: string
  first_name?: string | null
  last_name?: string | null
  email?: string | null
}

function displayUser(u: AssigneeCP) {
  const full = `${u.first_name ?? ""} ${u.last_name ?? ""}`.trim()
  return full ? `@${u.username} — ${full}` : `@${u.username}`
}

async function listCustomerPortalAssignees(): Promise<AssigneeCP[]> {
  return customerPortalApi.request("/customer-portal/assignees/", { method: "GET" })
}

const DOC_TYPES: { value: CaseDocumentType; key: string }[] = [
  { value: "contract", key: "documents.types.contract" },
  { value: "invoice", key: "documents.types.invoice" },
  { value: "letter", key: "documents.types.letter" },
  { value: "id", key: "documents.types.id" },
  { value: "other", key: "documents.types.other" },
]

type TabKey = "case" | "documents" | "notes"

function TabButton({
  active,
  icon,
  label,
  onClick,
}: {
  active: boolean
  icon: React.ReactNode
  label: string
  onClick: () => void
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={[
        "inline-flex items-center gap-2 rounded-xl px-3 py-2 text-sm border transition",
        active
          ? "bg-emerald-600 text-white border-emerald-600"
          : "bg-white hover:bg-black/5 border-emerald-200",
      ].join(" ")}
    >
      {icon}
      {label}
    </button>
  )
}

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

function Badge({
  children,
  tone = "neutral",
}: {
  children: React.ReactNode
  tone?: "neutral" | "emerald" | "amber" | "slate"
}) {
  const cls =
    tone === "emerald"
      ? "bg-emerald-50 text-emerald-700 border-emerald-200"
      : tone === "amber"
      ? "bg-amber-50 text-amber-700 border-amber-200"
      : tone === "slate"
      ? "bg-slate-50 text-slate-700 border-slate-200"
      : "bg-neutral-50 text-neutral-700 border-neutral-200"

  return <span className={`inline-flex items-center rounded-full border px-2.5 py-1 text-xs ${cls}`}>{children}</span>
}

function Field({
  icon,
  label,
  value,
  muted,
}: {
  icon?: React.ReactNode
  label: string
  value: React.ReactNode
  muted?: boolean
}) {
  return (
    <div className="rounded-xl border p-3 bg-white">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          {icon ? <span className="text-emerald-600">{icon}</span> : null}
          <span>{label}</span>
        </div>
      </div>
      <div className={`mt-2 text-sm ${muted ? "text-muted-foreground" : "text-neutral-900"} break-words`}>
        {value}
      </div>
    </div>
  )
}

function Section({
  title,
  icon,
  children,
}: {
  title: string
  icon?: React.ReactNode
  children: React.ReactNode
}) {
  return (
    <div className="rounded-2xl border bg-white p-4 space-y-3">
      <div className="flex items-center gap-2 font-medium">
        <span className="text-emerald-600">{icon}</span>
        <span>{title}</span>
      </div>
      {children}
    </div>
  )
}

export default function ClientCaseDetailPage() {
  const t = useTranslations("clientPortal")
  const locale = useLocale()
  const params = useParams<{ id: string }>()
  const caseId = Number(params.id)

  const [tab, setTab] = useState<TabKey>("case")

  const [item, setItem] = useState<any>(null)
  const [assignees, setAssignees] = useState<AssigneeCP[]>([])

  const [meUsername, setMeUsername] = useState<string>("")

  // Edition (client)
  const [edit, setEdit] = useState({
    title: "",
    priority: "medium" as any,
    due_date: "" as string,
    customer_assigned_to_id: "" as "" | string,
  })
  const [saving, setSaving] = useState(false)

  // Notes
  const [notes, setNotes] = useState<CaseNote[]>([])
  const [postingNote, setPostingNote] = useState(false)

  // Docs
  const [docs, setDocs] = useState<CustomerPortalCaseDocument[]>([])
  const [docTitle, setDocTitle] = useState("")
  const [docType, setDocType] = useState<CaseDocumentType>("other")
  const [docFile, setDocFile] = useState<File | null>(null)
  const [uploading, setUploading] = useState(false)

  // Doc edit modal
  const [docEditOpen, setDocEditOpen] = useState(false)
  const [docEditing, setDocEditing] = useState<CustomerPortalCaseDocument | null>(null)
  const [docEditTitle, setDocEditTitle] = useState("")
  const [docEditType, setDocEditType] = useState<CaseDocumentType>("other")
  const [docEditFile, setDocEditFile] = useState<File | null>(null)
  const [docEditBusy, setDocEditBusy] = useState(false)

  const [err, setErr] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const headerRef = useMemo(() => {
    if (!item) return `#${caseId}`
    return item.reference ? item.reference : `#${caseId}`
  }, [item, caseId])

  const debtor = item?.debtor || null
  const debtorType = debtor?.type || null
  const debtorName = debtor?.full_name || "—"

  const tenantAssigned = item?.assigned_to || null
  const customerAssigned = item?.customer_assigned_to || null

  function statusTone(v: string): "emerald" | "amber" | "slate" {
    if (v === "closed") return "slate"
    if (v === "on_hold") return "amber"
    return "emerald"
  }

  function priorityTone(v: string): "emerald" | "amber" | "slate" {
    if (v === "urgent" || v === "high") return "amber"
    return "emerald"
  }

  async function loadAll() {
    setLoading(true)
    setErr(null)
    try {
      const [me, d, n, asg, documents] = await Promise.all([
        getCustomerPortalMe(),
        getCustomerCase(caseId),
        listCustomerCaseNotes(caseId),
        listCustomerPortalAssignees(),
        listCustomerCaseDocuments(caseId),
      ])

      setMeUsername(me?.user?.username || "")
      setItem(d)
      setNotes(n)
      setAssignees(asg)
      setDocs(documents)

      setEdit({
        title: d.title ?? "",
        priority: d.priority ?? "medium",
        due_date: d.due_date ?? "",
        customer_assigned_to_id: d.customer_assigned_to?.id ? String(d.customer_assigned_to.id) : "",
      })
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!Number.isFinite(caseId)) return
    loadAll()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [caseId])

  async function saveChanges() {
    if (saving) return
    setSaving(true)
    setErr(null)
    try {
      const payload: any = {
        title: edit.title.trim(),
        priority: edit.priority || undefined,
        due_date: edit.due_date || null,
        customer_assigned_to_id: edit.customer_assigned_to_id ? Number(edit.customer_assigned_to_id) : null,
      }

      const updated = await patchCustomerCaseCustomerPortal(caseId, payload)
      setItem(updated)

      setEdit((p) => ({
        ...p,
        title: updated.title ?? p.title,
        priority: updated.priority ?? p.priority,
        due_date: updated.due_date ?? p.due_date,
        customer_assigned_to_id: updated.customer_assigned_to?.id ? String(updated.customer_assigned_to.id) : p.customer_assigned_to_id,
      }))
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setSaving(false)
    }
  }

  async function submitNote(body: string) {
    setPostingNote(true)
    try {
      const created = await addCustomerCaseNote(caseId, body)
      setNotes((prev) => [...prev, created])
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setPostingNote(false)
    }
  }

  async function editNote(noteId: number, body: string) {
    const updated = await patchCustomerCaseNote(caseId, noteId, body)
    setNotes((prev) => prev.map((x) => (x.id === updated.id ? updated : x)))
  }

  async function removeNote(noteId: number) {
    await deleteCustomerCaseNote(caseId, noteId)
    setNotes((prev) => prev.filter((x) => x.id !== noteId))
  }

  async function uploadDoc() {
    if (!docFile || !docTitle.trim() || uploading) return
    setUploading(true)
    setErr(null)
    try {
      const created = await uploadCustomerCaseDocument(caseId, {
        title: docTitle.trim(),
        doc_type: docType,
        file: docFile,
      })
      setDocs((prev) => [created, ...prev])
      setDocTitle("")
      setDocType("other")
      setDocFile(null)
      setTab("documents")
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setUploading(false)
    }
  }

  function openEditDoc(d: CustomerPortalCaseDocument) {
    setDocEditing(d)
    setDocEditTitle(d.title || "")
    setDocEditType((d.doc_type as any) || "other")
    setDocEditFile(null)
    setDocEditOpen(true)
  }

  async function saveDocEdit() {
    if (!docEditing || docEditBusy) return
    setDocEditBusy(true)
    setErr(null)
    try {
      const updated = await patchCustomerCaseDocument(caseId, docEditing.id, {
        title: docEditTitle.trim(),
        doc_type: docEditType,
        file: docEditFile || undefined,
      })

      setDocs((prev) => prev.map((x) => (x.id === updated.id ? updated : x)))
      setDocEditOpen(false)
      setDocEditing(null)
      setDocEditFile(null)
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setDocEditBusy(false)
    }
  }

  async function removeDoc(d: CustomerPortalCaseDocument) {
    const ok = window.confirm(t("documents.confirmDelete"))
    if (!ok) return
    setErr(null)
    try {
      await deleteCustomerCaseDocument(caseId, d.id)
      setDocs((prev) => prev.filter((x) => x.id !== d.id))
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    }
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-start justify-between gap-3">
        <div className="space-y-1">
          <div className="text-sm text-muted-foreground">{t("caseDetail.title")}</div>

          {(() => {
            const rawStatus = (item?.status || "") as string
            const rawPriority = (item?.priority || "") as string

            const statusKey = rawStatus ? `cases.status.${rawStatus}` : null
            const priorityKey = rawPriority ? `cases.priority.${rawPriority}` : null

            return (
              <div className="flex flex-wrap items-center gap-2">
                <h1 className="text-xl font-semibold">{headerRef}</h1>

                <Badge tone={statusTone(rawStatus)}>
                  {statusKey && (t as any).has?.(statusKey) ? t(statusKey) : (rawStatus || "—")}

                </Badge>

                <Badge tone={priorityTone(rawPriority)}>
                  {priorityKey ? t(priorityKey) : "—"}
                </Badge>
              </div>
            )
          })()}

          {item?.title ? <div className="text-sm text-muted-foreground">{item.title}</div> : null}
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={loadAll}
            className="inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-sm hover:bg-black/5"
            type="button"
          >
            <RefreshCw className="h-4 w-4" />
            {t("common.refresh")}
          </button>

          <Link
            href={`/${locale}/client/cases`}
            className="inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-sm hover:bg-black/5"
          >
            <ArrowLeft className="h-4 w-4" />
            {t("common.back")}
          </Link>
        </div>
      </div>

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

      {loading || !item ? (
        <div className="rounded-xl border p-3 text-sm flex items-center gap-2">
          <Loader2 className="h-4 w-4 animate-spin" />
          {t("common.loading")}
        </div>
      ) : (
        <>
          {/* Tabs */}
          <div className="flex flex-wrap gap-2">
            <TabButton
              active={tab === "case"}
              icon={<FolderKanban className="h-4 w-4" />}
              label={locale === "fr" ? "Dossier" : "Case"}
              onClick={() => setTab("case")}
            />
            <TabButton
              active={tab === "documents"}
              icon={<FileText className="h-4 w-4" />}
              label={locale === "fr" ? "Documents" : "Documents"}
              onClick={() => setTab("documents")}
            />
            <TabButton
              active={tab === "notes"}
              icon={<MessageSquareText className="h-4 w-4" />}
              label={locale === "fr" ? "Commentaires" : "Comments"}
              onClick={() => setTab("notes")}
            />
          </div>

          {/* CASE (inchangé: tu as déjà validé) */}
          {tab === "case" ? (
            <div className="space-y-4">
              <Section title={locale === "fr" ? "Résumé" : "Summary"} icon={<BadgeInfo className="h-4 w-4" />}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <Field icon={<Hash className="h-4 w-4" />} label={locale === "fr" ? "Référence" : "Reference"} value={<span className="font-medium">{item.reference || "—"}</span>} />
                  <Field icon={<Tag className="h-4 w-4" />} label={locale === "fr" ? "Titre" : "Title"} value={<span className="font-medium">{item.title || "—"}</span>} />
                  <Field icon={<CalendarDays className="h-4 w-4" />} label={locale === "fr" ? "Échéance" : "Due date"} value={item.due_date || "—"} muted={!item.due_date} />
                  <Field icon={<Briefcase className="h-4 w-4" />} label={locale === "fr" ? "Portefeuille" : "Portfolio"} value={item.portfolio?.name || item.portfolio?.code || item.portfolio || "—"} muted={!item.portfolio} />
                </div>
              </Section>

              <Section title={locale === "fr" ? "Montants" : "Amounts"} icon={<Wallet className="h-4 w-4" />}>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <Field icon={<CreditCard className="h-4 w-4" />} label={locale === "fr" ? "Devise" : "Currency"} value={item.currency || "—"} muted={!item.currency} />
                  <Field icon={<Lock className="h-4 w-4" />} label={locale === "fr" ? "Montant initial" : "Original amount"} value={<span className="tabular-nums">{item.original_amount ?? "—"}</span>} />
                  <Field icon={<Lock className="h-4 w-4" />} label={locale === "fr" ? "Solde" : "Balance"} value={<span className="tabular-nums">{item.balance_amount ?? "—"}</span>} />
                </div>
                <div className="text-[11px] text-muted-foreground flex items-start gap-2">
                  <Lock className="h-4 w-4 mt-0.5 text-emerald-600" />
                  <span>{locale === "fr" ? "Les montants sont mis à jour par le tenant pendant le recouvrement." : "Amounts are updated by the tenant during collections."}</span>
                </div>
              </Section>

              <Section title={locale === "fr" ? "Débiteur" : "Debtor"} icon={debtorType === "company" ? <Building2 className="h-4 w-4" /> : <User className="h-4 w-4" />}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <Field icon={debtorType === "company" ? <Building2 className="h-4 w-4" /> : <User className="h-4 w-4" />} label={locale === "fr" ? "Nom" : "Name"} value={<span className="font-medium">{debtorName}</span>} />
                  <Field icon={<Phone className="h-4 w-4" />} label={locale === "fr" ? "Téléphone" : "Phone"} value={debtor?.phone || "—"} muted={!debtor?.phone} />
                  <Field icon={<Mail className="h-4 w-4" />} label="Email" value={debtor?.email || "—"} muted={!debtor?.email} />
                  <Field icon={<MapPin className="h-4 w-4" />} label={locale === "fr" ? "Adresse" : "Address"} value={[debtor?.address, debtor?.city, debtor?.country].filter(Boolean).join(", ") || "—"} muted={!(debtor?.address || debtor?.city || debtor?.country)} />
                </div>
              </Section>

              <Section title={locale === "fr" ? "Assignations" : "Assignments"} icon={<UserCog className="h-4 w-4" />}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <Field icon={<UserCog className="h-4 w-4" />} label={t("caseDetail.customerAssignedTo")} value={customerAssigned?.username ? `@${customerAssigned.username}` : "—"} muted={!customerAssigned?.username} />
                  <Field icon={<UserCog className="h-4 w-4" />} label={t("caseDetail.tenantAssignedTo")} value={tenantAssigned?.username ? `@${tenantAssigned.username}` : "—"} muted={!tenantAssigned?.username} />
                </div>
              </Section>

              <Section title={locale === "fr" ? "Dates" : "Dates"} icon={<Clock className="h-4 w-4" />}>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <Field icon={<Clock className="h-4 w-4" />} label={locale === "fr" ? "Ouvert le" : "Opened at"} value={fmtDate(item.opened_at)} />
                  <Field icon={<Clock className="h-4 w-4" />} label={locale === "fr" ? "Clôturé le" : "Closed at"} value={fmtDate(item.closed_at)} muted={!item.closed_at} />
                </div>
              </Section>

              {/* Edit block (inchangé) */}
              <div className="rounded-2xl border bg-white p-4 space-y-3">
                <div className="flex items-center justify-between gap-2">
                  <div className="font-medium">{t("caseDetail.editTitle")}</div>
                  <button
                    onClick={saveChanges}
                    disabled={saving}
                    className="inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                    type="button"
                  >
                    {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                    {t("caseDetail.save")}
                  </button>
                </div>

                <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">{t("caseDetail.titleLabel")}</div>
                    <input
                      value={edit.title}
                      onChange={(e) => setEdit((p) => ({ ...p, title: e.target.value }))}
                      className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                    />
                  </div>

                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">{t("caseDetail.priority")}</div>
                    <select
                      value={edit.priority}
                      onChange={(e) => setEdit((p) => ({ ...p, priority: e.target.value as any }))}
                      className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                    >
                      <option value="low">{t("cases.priority.low")}</option>
                      <option value="medium">{t("cases.priority.medium")}</option>
                      <option value="high">{t("cases.priority.high")}</option>
                      <option value="urgent">{t("cases.priority.urgent")}</option>
                    </select>
                  </div>

                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">{t("caseDetail.dueDate")}</div>
                    <input
                      type="date"
                      value={edit.due_date || ""}
                      onChange={(e) => setEdit((p) => ({ ...p, due_date: e.target.value }))}
                      className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                    />
                  </div>

                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground flex items-center gap-2">
                      <UserCog className="h-4 w-4 text-emerald-600" />
                      {t("caseDetail.customerAssignedTo")}
                    </div>

                    <select
                      value={edit.customer_assigned_to_id}
                      onChange={(e) => setEdit((p) => ({ ...p, customer_assigned_to_id: e.target.value }))}
                      className="w-full rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                    >
                      <option value="">{t("caseDetail.unassigned")}</option>
                      {assignees.map((u) => (
                        <option key={u.id} value={String(u.id)}>
                          {displayUser(u)}
                        </option>
                      ))}
                    </select>

                    <div className="text-[11px] text-muted-foreground mt-1">
                      {t("caseDetail.tenantAssignedTo")}:{" "}
                      <span className="font-medium">{tenantAssigned?.username ? `@${tenantAssigned.username}` : "—"}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) : null}

          {/* DOCUMENTS (inchangé : edit/delete déjà OK) */}
          {tab === "documents" ? (
            <div className="rounded-2xl border bg-white p-4 space-y-3">
              <div className="font-medium flex items-center gap-2">
                <Paperclip className="h-4 w-4 text-emerald-600" />
                {t("documents.title")}
              </div>

              <div className="grid grid-cols-1 gap-2 md:grid-cols-4">
                <input
                  value={docTitle}
                  onChange={(e) => setDocTitle(e.target.value)}
                  placeholder={t("documents.fields.title")}
                  className="md:col-span-2 rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                />

                <select
                  value={docType}
                  onChange={(e) => setDocType(e.target.value as CaseDocumentType)}
                  className="rounded-xl border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
                >
                  {DOC_TYPES.map((d) => (
                    <option key={d.value} value={d.value}>
                      {t(d.key)}
                    </option>
                  ))}
                </select>

                <label className="rounded-xl border px-3 py-2 text-sm flex items-center gap-2 cursor-pointer hover:bg-black/5">
                  <Upload className="h-4 w-4" />
                  {docFile ? docFile.name : t("documents.fields.file")}
                  <input type="file" className="hidden" onChange={(e) => setDocFile(e.target.files?.[0] || null)} />
                </label>
              </div>

              <div className="flex justify-end">
                <button
                  onClick={uploadDoc}
                  disabled={uploading || !docFile || !docTitle.trim()}
                  className="inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                  type="button"
                >
                  {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
                  {t("documents.actions.upload")}
                </button>
              </div>

              <div className="rounded-xl border overflow-hidden">
                {docs.length === 0 ? (
                  <div className="p-3 text-sm text-muted-foreground">{t("documents.empty")}</div>
                ) : (
                  docs.map((d) => (
                    <div key={d.id} className="p-3 border-b text-sm">
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <div className="font-medium truncate">{d.title}</div>
                          <div className="text-xs text-muted-foreground">
                            {t("documents.fields.type")}: {t(`documents.types.${d.doc_type}`)} •{" "}
                            {new Date(d.created_at).toLocaleString()}
                          </div>
                          {d.file ? (
                            <a className="text-emerald-700 underline text-xs" href={d.file} target="_blank" rel="noreferrer">
                              {t("documents.actions.open")}
                            </a>
                          ) : null}
                        </div>

                        <div className="flex items-center gap-2 shrink-0">
                          <button
                            type="button"
                            onClick={() => openEditDoc(d)}
                            className="inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs hover:bg-black/5"
                          >
                            <Pencil className="h-4 w-4" />
                            {t("documents.actions.replace")}
                          </button>

                          <button
                            type="button"
                            onClick={() => removeDoc(d)}
                            className="inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs hover:bg-red-50 border-red-200 text-red-700"
                          >
                            <Trash2 className="h-4 w-4" />
                            {t("documents.actions.delete")}
                          </button>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>

              {/* Edit Doc Modal */}
              {docEditOpen && docEditing ? (
                <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
                  <div className="w-full max-w-xl rounded-2xl bg-white shadow-xl overflow-hidden">
                    <div className="px-5 py-4 border-b flex items-start justify-between gap-3">
                      <div>
                        <div className="text-lg font-semibold">{t("documents.edit.title")}</div>
                        <div className="text-sm text-muted-foreground">{t("documents.edit.subtitle")}</div>
                      </div>

                      <button
                        className="rounded-xl p-2 hover:bg-neutral-50"
                        onClick={() => {
                          setDocEditOpen(false)
                          setDocEditing(null)
                          setDocEditFile(null)
                        }}
                        disabled={docEditBusy}
                        type="button"
                      >
                        <X className="h-5 w-5 text-neutral-500" />
                      </button>
                    </div>

                    <div className="p-5 space-y-3">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div className="space-y-1 md:col-span-2">
                          <label className="text-xs text-muted-foreground">{t("documents.fields.title")}</label>
                          <input
                            className="w-full rounded-xl border px-3 py-2 text-sm"
                            value={docEditTitle}
                            onChange={(e) => setDocEditTitle(e.target.value)}
                            disabled={docEditBusy}
                          />
                        </div>

                        <div className="space-y-1">
                          <label className="text-xs text-muted-foreground">{t("documents.fields.type")}</label>
                          <select
                            className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
                            value={docEditType}
                            onChange={(e) => setDocEditType(e.target.value as CaseDocumentType)}
                            disabled={docEditBusy}
                          >
                            {DOC_TYPES.map((x) => (
                              <option key={x.value} value={x.value}>
                                {t(x.key)}
                              </option>
                            ))}
                          </select>
                        </div>

                        <div className="space-y-1">
                          <label className="text-xs text-muted-foreground">{t("documents.edit.newFile")}</label>
                          <label className="w-full rounded-xl border px-3 py-2 text-sm flex items-center gap-2 cursor-pointer hover:bg-black/5">
                            <Upload className="h-4 w-4" />
                            {docEditFile ? docEditFile.name : t("documents.edit.chooseFile")}
                            <input
                              type="file"
                              className="hidden"
                              onChange={(e) => setDocEditFile(e.target.files?.[0] || null)}
                            />
                          </label>
                          <div className="text-[11px] text-muted-foreground">{t("documents.edit.hint")}</div>
                        </div>
                      </div>

                      <div className="flex justify-end gap-2 pt-2">
                        <button
                          onClick={() => {
                            setDocEditOpen(false)
                            setDocEditing(null)
                            setDocEditFile(null)
                          }}
                          className="rounded-xl px-4 py-2 text-sm border bg-white hover:bg-neutral-50"
                          disabled={docEditBusy}
                          type="button"
                        >
                          {t("documents.edit.cancel")}
                        </button>

                        <button
                          onClick={saveDocEdit}
                          className="rounded-xl px-4 py-2 text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 inline-flex items-center gap-2 disabled:opacity-60"
                          disabled={docEditBusy || !docEditTitle.trim()}
                          type="button"
                        >
                          {docEditBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                          {t("documents.edit.save")}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ) : null}
            </div>
          ) : null}

          {/* NOTES — NoteThread partagé */}
          {tab === "notes" ? (
            <div className="h-[calc(100vh-16rem)] min-h-[400px]">
              <NoteThread
                notes={notes}
                myUsername={meUsername || null}
                loading={loading}
                submitting={postingNote}
                error={err}
                onAdd={submitNote}
                onEdit={editNote}
                onDelete={removeNote}
                accentColor="#059669"
                placeholder={t("notes.placeholder")}
                emptyLabel={t("caseDetail.noNotes")}
              />
            </div>
          ) : null}
        </>
      )}
    </div>
  )
}
