/* ============================================================
   Vela — S4 · Case detail (DRAFT · COLLECTING · COMPLETED)
   UNDER_REVIEW lives in screen_review.jsx (window.Review)
   ============================================================ */
(function () {
  const { useState } = React;
  const { fmtEur, CaseStatus, DocStatus, Avatar, Progress, caseProgress, templateOf, DOC_COLOR } = window.UI;

  // ---------- shared header ----------
  function CaseHeader({ c, go, action }) {
    const tpl = templateOf(c.template);
    return (
      <div style={{ padding: "22px 0 18px" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 18 }}>
          <Avatar initials={c.initials} size={54} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
              <h1 className="serif" style={{ fontSize: 25 }}>{c.borrower}</h1>
              <CaseStatus status={c.status} dot />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 13, color: "var(--ink-3)", flexWrap: "wrap" }}>
              <span className="mono">{c.id}</span><span style={{ color: "var(--line-strong)" }}>·</span>
              <span>{tpl.label} <span style={{ color: "var(--ink-4)" }}>({tpl.en})</span></span><span style={{ color: "var(--line-strong)" }}>·</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="location" size={13} /> {c.property.address}</span><span style={{ color: "var(--line-strong)" }}>·</span>
              <span className="mono" style={{ color: "var(--ink-2)", fontWeight: 600 }}>{fmtEur(c.property.price)}</span>
            </div>
          </div>
          <div style={{ display: "flex", gap: 9, flexShrink: 0 }}>{action}</div>
        </div>
      </div>
    );
  }

  // ---------- document row ----------
  function DocRow({ doc, onClick, last }) {
    const s = DOC_COLOR[doc.status];
    const isError = doc.status === "error";
    return (
      <div onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px var(--pad)", cursor: "pointer",
        borderBottom: last ? "none" : "1px solid var(--line)", background: isError ? "rgba(188,74,53,.04)" : "transparent", transition: "background .12s" }}
        onMouseEnter={(e) => e.currentTarget.style.background = isError ? "rgba(188,74,53,.07)" : "var(--surface-2)"}
        onMouseLeave={(e) => e.currentTarget.style.background = isError ? "rgba(188,74,53,.04)" : "transparent"}>
        <div style={{ width: 34, height: 34, borderRadius: 8, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--surface-2)", border: "1px solid var(--line)", color: "var(--ink-3)" }}>
          <Icon name="docs" size={16} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{doc.name}</div>
          {doc.note && <div style={{ fontSize: 11.5, color: s.c, marginTop: 2, display: "flex", alignItems: "center", gap: 5 }}>{(doc.status === "error" || doc.status === "conflict") && <Icon name={s.icon} size={11} stroke={2.4} />}{doc.note}</div>}
        </div>
        <DocStatus status={doc.status} />
        <Icon name="chevR" size={15} style={{ color: "var(--ink-4)" }} />
      </div>
    );
  }

  // ---------- add-a-document modal (creation / collection) ----------
  function AddDocModal({ participantName, context, onClose, onAdd }) {
    const [name, setName] = useState("");
    const add = (v) => { const t = (v != null ? v : name).trim(); if (t) onAdd(t); };
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 108, display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "rgba(21,35,63,.45)", backdropFilter: "blur(4px)", animation: "fadeIn .2s ease" }} onClick={onClose}>
        <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 460, overflow: "hidden", boxShadow: "var(--sh-lg)", animation: "pop .3s cubic-bezier(.2,.8,.3,1)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "18px 22px", borderBottom: "1px solid var(--line)" }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: "var(--gold-soft)", color: "var(--gold)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="docs" size={17} /></div>
            <div style={{ flex: 1 }}>
              <h3 style={{ fontSize: 15.5 }}>Request another document</h3>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>From {participantName}</div>
            </div>
            <button onClick={onClose} className="btn-quiet" style={{ width: 32, height: 32, borderRadius: 8, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}><Icon name="x" size={16} /></button>
          </div>
          <div style={{ padding: 22 }}>
            <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
              <input autoFocus list="vela-doclist" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} placeholder="Document type…"
                style={{ flex: 1, height: 42, padding: "0 13px", border: "1px solid var(--line-strong)", borderRadius: 9, fontSize: 14, outline: "none" }} />
              <datalist id="vela-doclist">{window.VELA.COMMON_DOCS.map((d) => <option key={d} value={d} />)}</datalist>
              <button className="btn btn-gold" onClick={() => add()}><Icon name="plus" size={14} /> Add</button>
            </div>
            <div className="label-cap" style={{ marginBottom: 8 }}>Common documents</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {window.VELA.COMMON_DOCS.slice(0, 10).map((d) => (
                <button key={d} onClick={() => add(d)} style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink-2)", background: "var(--surface)", border: "1px dashed var(--line-strong)", borderRadius: 7, padding: "5px 10px", cursor: "pointer", display: "flex", alignItems: "center", gap: 5 }}>
                  <Icon name="plus" size={11} stroke={2.4} /> {d}
                </button>
              ))}
            </div>
            <div style={{ marginTop: 16, padding: "11px 13px", borderRadius: 9, background: context === "collect" ? "var(--cyan-soft)" : "var(--surface-2)", border: "1px solid " + (context === "collect" ? "rgba(6,182,212,.28)" : "var(--line)"), fontSize: 11.5, color: "var(--ink-2)", display: "flex", gap: 8, alignItems: "center" }}>
              <Icon name={context === "collect" ? "sparkles" : "docs"} size={14} style={{ color: context === "collect" ? "var(--cyan)" : "var(--ink-3)", flexShrink: 0 }} />
              {context === "collect" ? "The agent will message the borrower to request this right away." : "This is added to the checklist and requested when you start collecting."}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ---------- DRAFT ----------
  function Draft({ c, onStart, notify }) {
    const [, force] = useState(0);
    const [addTo, setAddTo] = useState(null);
    const addDoc = (name) => { addTo.docs.push({ name, status: "waiting", note: "Added by you" }); force((n) => n + 1); setAddTo(null); notify && notify(`“${name}” added to the checklist`); };
    return (
      <div className="anim-fadein" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }}>
        <div className="card" style={{ overflow: "hidden" }}>
          <div style={{ padding: "16px var(--pad)" }}>
            <h3 style={{ fontSize: 15 }}>Required documents</h3>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 3 }}>Generated from the <strong>{templateOf(c.template).label}</strong> template. Nothing is requested until you start collecting.</div>
          </div>
          {c.participants.map((p, pi) => (
            <div key={pi}>
              <div style={{ padding: "10px var(--pad)", background: "var(--surface-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar initials={p.initials} size={24} tone="soft" />
                <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)" }}>{p.name}</span>
                <span style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{p.role}</span>
              </div>
              {p.docs.map((doc, di) => (
                <div key={di} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px var(--pad)", borderBottom: "1px solid var(--line)" }}>
                  <Icon name="docs" size={15} style={{ color: "var(--ink-4)" }} />
                  <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{doc.name}</span>
                  {doc.note === "Added by you" && <span className="chip" style={{ background: "var(--gold-soft)", color: "var(--gold)", marginLeft: "auto" }}>Added</span>}
                </div>
              ))}
              <button onClick={() => setAddTo(p)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "11px var(--pad)", border: 0, background: "transparent", color: "var(--gold)", fontSize: 12.5, fontWeight: 600, cursor: "pointer", textAlign: "left" }}>
                <Icon name="plus" size={14} stroke={2.4} /> Add a required document
              </button>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: "var(--pad)", textAlign: "center" }}>
            <div style={{ width: 48, height: 48, borderRadius: "50%", background: "var(--green-soft)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px" }}><Icon name="whatsapp" size={24} /></div>
            <h3 style={{ fontSize: 15, marginBottom: 6 }}>Ready to collect</h3>
            <p style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5, margin: "0 0 16px" }}>Starting collection sends the opening WhatsApp message to {c.participants.length > 1 ? "all participants" : c.borrower.split(" ")[0]} and the agent takes it from there.</p>
            <button className="btn btn-gold" style={{ width: "100%", justifyContent: "center" }} onClick={onStart}><Icon name="send" size={15} /> Start collecting</button>
          </div>
          <CaseMeta c={c} />
        </div>
        {addTo && <AddDocModal participantName={addTo.name} context="draft" onClose={() => setAddTo(null)} onAdd={addDoc} />}
      </div>
    );
  }

  // ---------- COLLECTING ----------
  function Collecting({ c, onWhatsApp, notify }) {
    const [open, setOpen] = useState(null);
    const [validate, setValidate] = useState(null);
    const [, force] = useState(0);
    const openDoc = (doc, p) => { (doc.status === "validated" || doc.status === "conflict") ? setValidate({ doc, p }) : setOpen({ doc, p }); };
    const approveDoc = (doc, outcome) => {
      doc.status = outcome === "validated" ? "validated" : "conflict";
      doc.note = outcome === "validated" ? "Confirmed by you" : "Flagged for manual review";
      setValidate(null); force((n) => n + 1);
      notify && notify(outcome === "validated" ? `${doc.name} approved` : `${doc.name} flagged for manual review`);
    };
    const reRequest = (doc) => {
      doc.status = "waiting";
      doc.note = "Re-requested — the agent has asked the borrower again";
      if (c.queue && c.queue.kind === "error" && !c.participants.some((p) => p.docs.some((d) => d.status === "error"))) c.queue = null;
      setOpen(null); force((n) => n + 1);
      notify && notify(`Re-request sent on WhatsApp — the agent asked again for “${doc.name}”`);
    };
    const [addTo, setAddTo] = useState(null);
    const addDocCollect = (name) => { addTo.docs.push({ name, status: "waiting", note: "Requested just now" }); force((n) => n + 1); setAddTo(null); notify && notify(`Requesting “${name}” from ${addTo.name.split(" ")[0]} on WhatsApp`); };
    const pr = caseProgress(c);
    const val = c.participants.reduce((a, p) => a + p.docs.filter((d) => d.status === "validated").length, 0);
    const errors = c.participants.reduce((a, p) => a.concat(p.docs.filter((d) => d.status === "error" || d.status === "conflict")), []);
    return (
      <div className="anim-fadein" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
        <div className="card" style={{ overflow: "hidden" }}>
          <div style={{ padding: "16px var(--pad) 14px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
              <h3 style={{ fontSize: 15 }}>Collection progress</h3>
              <span className="mono" style={{ fontSize: 13, color: "var(--ink-2)", fontWeight: 600 }}>{pr.done} / {pr.total} received</span>
            </div>
            <Progress value={pr.pct} color="var(--blue)" height={7} />
            <div style={{ fontSize: 11.5, color: "var(--ink-4)", marginTop: 7 }}>{val} validated · {pr.done - val} processing · {pr.total - pr.done} still waiting</div>
          </div>
          {c.participants.map((p, pi) => (
            <div key={pi}>
              <div style={{ padding: "10px var(--pad)", background: "var(--surface-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar initials={p.initials} size={24} tone="soft" />
                <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)" }}>{p.name}</span>
                <span style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{p.role}</span>
              </div>
              {p.docs.map((doc, di) => <DocRow key={di} doc={doc} last={false} onClick={() => openDoc(doc, p)} />)}
              <button onClick={() => setAddTo(p)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "11px var(--pad)", border: 0, background: "transparent", color: "var(--gold)", fontSize: 12.5, fontWeight: 600, cursor: "pointer", textAlign: "left" }}>
                <Icon name="plus" size={14} stroke={2.4} /> Request another document
              </button>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: "var(--pad)", background: "linear-gradient(150deg, #1466FF, #06B6D4)", color: "#fff", border: "none", boxShadow: "0 10px 30px -10px rgba(20,102,255,.5)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 9 }}>
              <Icon name="sparkles" size={18} style={{ color: "#CFF6FC" }} />
              <span style={{ fontSize: 13.5, fontWeight: 700 }}>Agent is collecting</span>
              <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#A6F0FB", marginLeft: "auto" }} />
            </div>
            <p style={{ fontSize: 12.5, lineHeight: 1.5, color: "rgba(255,255,255,.88)", margin: "0 0 14px" }}>You don't need to do anything here — the agent gathers documents and only calls you in when something needs a decision.</p>
            <button className="btn btn-sm" style={{ width: "100%", justifyContent: "center", background: "rgba(255,255,255,.18)", color: "#fff" }} onClick={onWhatsApp}><Icon name="whatsapp" size={14} /> View conversation</button>
          </div>

          {errors.length > 0 && (
            <div className="card" style={{ padding: "var(--pad)", border: "1px solid var(--gold-line)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}><Icon name="alert" size={16} style={{ color: "var(--amber)" }} /><h3 style={{ fontSize: 14 }}>Needs your attention</h3></div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {errors.map((d, i) => (
                  <div key={i} style={{ padding: 12, borderRadius: 9, background: d.status === "error" ? "var(--red-soft)" : "var(--amber-soft)", border: "1px solid " + (d.status === "error" ? "#EAC7BD" : "#EBD9B5") }}>
                    <div onClick={() => openDoc(d, null)} style={{ cursor: "pointer" }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: d.status === "error" ? "var(--red)" : "var(--amber)" }}>{d.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 2 }}>{d.note}</div>
                    </div>
                    {d.status === "error" && (
                      <button className="btn btn-sm" style={{ width: "100%", justifyContent: "center", marginTop: 10, background: "var(--cyan)", color: "#04222b" }} onClick={() => reRequest(d)}>
                        <Icon name="sparkles" size={13} /> Re-request via agent
                      </button>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
          <CaseMeta c={c} />
        </div>

        {open && <DocDrawer open={open} onClose={() => setOpen(null)} onReRequest={reRequest} />}
        {validate && <window.ValidateDoc doc={validate.doc} participant={validate.p} onClose={() => setValidate(null)} onApprove={approveDoc} />}
        {addTo && <AddDocModal participantName={addTo.name} context="collect" onClose={() => setAddTo(null)} onAdd={addDocCollect} />}
      </div>
    );
  }

  // ---------- doc drawer (collecting) ----------
  function DocDrawer({ open, onClose, onReRequest }) {
    const { doc } = open;
    const s = DOC_COLOR[doc.status];
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 90, display: "flex", justifyContent: "flex-end", background: "rgba(21,35,63,.35)", animation: "fadeIn .2s ease" }} onClick={onClose}>
        <div onClick={(e) => e.stopPropagation()} style={{ width: 420, maxWidth: "92vw", height: "100%", background: "var(--surface)", boxShadow: "var(--sh-lg)", display: "flex", flexDirection: "column", animation: "slideIn .3s cubic-bezier(.2,.8,.3,1)" }}>
          <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
            <div>
              <h3 style={{ fontSize: 16, marginBottom: 7 }}>{doc.name}</h3>
              <DocStatus status={doc.status} />
            </div>
            <button onClick={onClose} className="btn-quiet" style={{ width: 32, height: 32, borderRadius: 8, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}><Icon name="x" size={16} /></button>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: 24 }}>
            <div style={{ height: 230, borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--line)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: "var(--ink-4)", marginBottom: 18 }}>
              {doc.status === "waiting" ? (<><Icon name="clock" size={26} /><div style={{ fontSize: 12.5, marginTop: 8 }}>Not received yet</div></>)
                : (<><Icon name="docs" size={30} /><div style={{ fontSize: 12, marginTop: 10, fontFamily: "var(--mono)" }}>{doc.name.toLowerCase().replace(/[^a-z0-9]+/g, "_")}.pdf</div></>)}
            </div>
            {doc.status === "received" && <div style={{ padding: 14, borderRadius: 10, background: "var(--blue-soft)", color: "var(--blue)", fontSize: 12.5, display: "flex", gap: 9, alignItems: "center" }}><Icon name="sync" size={15} /> The agent is extracting and validating this document…</div>}
            {doc.status === "error" && <div style={{ padding: 14, borderRadius: 10, background: "var(--red-soft)", color: "var(--ink-2)", fontSize: 12.5 }}><strong style={{ color: "var(--red)" }}>Couldn't process this file.</strong><div style={{ marginTop: 4 }}>{doc.note}</div></div>}
            {doc.status === "conflict" && <div style={{ padding: 14, borderRadius: 10, background: "var(--amber-soft)", color: "var(--ink-2)", fontSize: 12.5 }}><strong style={{ color: "var(--amber)" }}>Conflict detected.</strong><div style={{ marginTop: 4 }}>{doc.note} — resolve in the review step.</div></div>}
            {doc.status === "validated" && <div style={{ padding: 14, borderRadius: 10, background: "var(--green-soft)", color: "var(--green)", fontSize: 12.5, display: "flex", gap: 9, alignItems: "center" }}><Icon name="check" size={15} stroke={2.5} /> Extracted and validated automatically.</div>}
          </div>
          <div style={{ padding: 20, borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
            {doc.status === "error" && (
              <div style={{ marginBottom: 16, paddingBottom: 16, borderBottom: "1px solid var(--line)" }}>
                <div className="label-cap" style={{ marginBottom: 8 }}>Agent action</div>
                <button className="btn" style={{ width: "100%", justifyContent: "center", background: "var(--cyan)", color: "#04222b" }} onClick={() => onReRequest(doc)}>
                  <Icon name="sparkles" size={15} /> Re-request via agent
                </button>
                <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 7, lineHeight: 1.45 }}>The agent will message the borrower asking them to resend this document.</div>
              </div>
            )}
            <div className="label-cap" style={{ marginBottom: 10 }}>Received outside WhatsApp?</div>
            <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", borderStyle: "dashed" }}><Icon name="upload" size={15} /> Upload a file manually</button>
          </div>
        </div>
      </div>
    );
  }

  // ---------- COMPLETED ----------
  function Completed({ c }) {
    const rd = window.VELA.reviewDocs[c.id];
    let nif = "—", dob = "—", net = null;
    if (rd) {
      const af = rd.docs.flatMap((d) => d.fields);
      nif = (af.find((f) => f.ref === "nif" && f.status !== "error") || {}).value || nif;
      dob = (af.find((f) => f.ref === "nacimiento") || {}).value || dob;
      net = (af.find((f) => f.ref === "neto") || {}).value;
    }
    const INCOME = {
      ajena:       { label: "Net monthly salary", value: net || "2.341,17 €", k2: "Annual gross (IRPF)", v2: "35.760,00 €", src: "Adquira España S.A." },
      funcionario: { label: "Net monthly salary", value: net || "2.180,00 €", k2: "Annual gross (IRPF)", v2: "32.400,00 €", src: "Administración General del Estado" },
      pensionista: { label: "Monthly pension",    value: "1.612,40 €",        k2: "Annual gross (IRPF)", v2: "22.573,60 €", src: "Seguridad Social" },
      propia:      { label: "Net annual income",  value: "38.940,00 €",       k2: "Quarterly (Modelo 130)", v2: "9.735,00 €", src: "Actividad por cuenta propia" },
      societario:  { label: "Director's income",  value: "4.500,00 €",        k2: "Annual gross (IRPF)", v2: "54.000,00 €", src: "Sociedad propia" },
    };
    const inc = INCOME[c.template] || INCOME.ajena;
    const identityNif = nif !== "—" ? nif : (c.template === "pensionista" ? "29.481.005-J" : "51.847.392-K");
    const identityDob = dob !== "—" ? dob : (c.template === "pensionista" ? "08·11·1957" : "14·03·1989");
    const sections = [
      { title: "Identity", icon: "idcard", rows: [["Full name", c.borrower], ["NIF / DNI", identityNif], ["Date of birth", identityDob]] },
      { title: "Income", icon: "euro", rows: [[inc.label, inc.value], [inc.k2, inc.v2], ["Income source", inc.src]] },
      { title: "Property & operation", icon: "home", rows: [["Address", c.property.address], ["Purchase price", fmtEur(c.property.price)], ["Agency", c.agency]] },
    ];
    const files = c.participants.flatMap((p) => p.docs.map((d) => ({ name: d.name, who: p.name })));
    return (
      <div className="anim-fadein" style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 16, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: "16px var(--pad)", display: "flex", alignItems: "center", gap: 12, background: "var(--green-soft)", border: "1px solid #CDE6D9" }}>
            <div style={{ width: 36, height: 36, borderRadius: "50%", background: "var(--green)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="check" size={18} stroke={2.6} /></div>
            <div><div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>Case completed</div><div style={{ fontSize: 12.5, color: "var(--ink-2)" }}>Approved {c.completed} · all documents validated and reviewed.</div></div>
          </div>
          {sections.map((sec) => (
            <div key={sec.title} className="card" style={{ padding: "var(--pad)" }}>
              <h3 style={{ fontSize: 14, marginBottom: 14, display: "flex", alignItems: "center", gap: 8 }}><Icon name={sec.icon} size={16} style={{ color: "var(--ink-3)" }} /> {sec.title}</h3>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 20px" }}>
                {sec.rows.map(([k, v]) => (
                  <div key={k}><div className="label-cap" style={{ fontSize: 10, marginBottom: 4 }}>{k}</div><div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{v}</div></div>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div className="card" style={{ overflow: "hidden", position: "sticky", top: 84 }}>
          <div style={{ padding: "16px var(--pad)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <h3 style={{ fontSize: 14 }}>Documents</h3>
            <button className="btn btn-ghost btn-sm"><Icon name="download" size={14} /> Download all</button>
          </div>
          {files.map((f, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px var(--pad)", borderTop: "1px solid var(--line)" }}>
              <Icon name="docs" size={16} style={{ color: "var(--ink-4)" }} />
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name}</div></div>
              <button className="btn-quiet" style={{ width: 30, height: 30, borderRadius: 7, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}><Icon name="eye" size={15} /></button>
              <button className="btn-quiet" style={{ width: 30, height: 30, borderRadius: 7, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}><Icon name="download" size={15} /></button>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ---------- meta card ----------
  function CaseMeta({ c }) {
    const rows = [["Created", c.created], ["Last activity", c.activity], ["Agency", c.agency], ["Appraiser", c.appraiser]];
    return (
      <div className="card" style={{ padding: "var(--pad)" }}>
        <h3 style={{ fontSize: 14, marginBottom: 14 }}>Case details</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
          {rows.map(([k, v]) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
              <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{k}</span>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)", textAlign: "right" }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function CaseDetail({ caseId, go, onStart, onWhatsApp, onApprove, notify }) {
    const c = window.VELA.cases.find((x) => x.id === caseId);
    if (!c) return null;

    let action = null;
    if (c.status === "DRAFT") action = <><button className="btn btn-ghost"><Icon name="x" size={15} /> Cancel case</button><button className="btn btn-gold" onClick={() => onStart(c.id)}><Icon name="send" size={15} /> Start collecting</button></>;
    else if (c.status === "COLLECTING") action = <><button className="btn btn-ghost" onClick={onWhatsApp}><Icon name="whatsapp" size={15} /> Conversation</button><button className="btn btn-ghost"><Icon name="x" size={15} /> Cancel case</button></>;
    else if (c.status === "COMPLETED") action = <button className="btn btn-primary"><Icon name="download" size={15} /> Export case</button>;

    const isReview = c.status === "UNDER_REVIEW";
    return (
      <div className="anim-fadein" style={{ padding: isReview ? "0" : "0 28px 60px", maxWidth: isReview ? "none" : 1180, margin: "0 auto" }}>
        {!isReview && <CaseHeader c={c} go={go} action={action} />}
        {c.status === "DRAFT" && <Draft c={c} onStart={() => onStart(c.id)} notify={notify} />}
        {c.status === "COLLECTING" && <Collecting c={c} onWhatsApp={onWhatsApp} notify={notify} />}
        {c.status === "COMPLETED" && <Completed c={c} />}
        {isReview && <window.Review c={c} go={go} onApprove={onApprove} onWhatsApp={onWhatsApp} />}
      </div>
    );
  }

  window.CaseDetail = CaseDetail;
})();
