/* ============================================================
   Vela — S4 · UNDER_REVIEW review workspace (window.Review)
   Document viewer with annotations linked to an extracted-field
   panel, plus cross-document conflict resolution.
   ============================================================ */
(function () {
  const { useState } = React;
  const { fmtEur, Avatar, CaseStatus } = window.UI;

  // highlight styles for a field span inside a rendered document
  function fieldStyle(active, error) {
    if (active) return { background: error ? "rgba(224,75,67,.16)" : "rgba(20,102,255,.18)", outline: "2px solid " + (error ? "var(--red)" : "var(--gold)"), outlineOffset: 1, borderRadius: 4, animation: "pulseRing 1.4s ease 1" };
    if (error) return { background: "rgba(224,75,67,.10)", outline: "1.5px dashed var(--red)", outlineOffset: 1, borderRadius: 4 };
    return { background: "transparent", outline: "1.5px solid transparent", borderRadius: 4 };
  }
  function F({ id, sel, setSel, error, children }) {
    const active = sel === id;
    return (
      <span data-field={id} onClick={(e) => { e.stopPropagation(); setSel(id); }}
        style={{ cursor: "pointer", padding: "1px 4px", transition: "background .15s, outline-color .15s", ...fieldStyle(active, error) }}>
        {children}
      </span>
    );
  }

  // ---------- DNI document render (real specimen + overlaid annotations) ----------
  const DNI_BOXES = [
    { ref: "nif",        l: 43.5, t: 17,   w: 30,   h: 7.5, label: "1" },
    { ref: "nombre",     l: 40.5, t: 26.5, w: 13.5, h: 22,  label: "2" },
    { ref: "sexo",       l: 40.5, t: 50.5, w: 19,   h: 7,   label: "3" },
    { ref: "nacimiento", l: 77,   t: 50.5, w: 18.5, h: 7,   label: "4" },
    { ref: "validez",    l: 56.5, t: 60,   w: 16.5, h: 6.8, label: "5" },
  ];
  function DocDNI({ sel, setSel }) {
    return (
      <div style={{ width: 460, maxWidth: "100%", margin: "0 auto" }}>
        <div style={{ position: "relative", borderRadius: 14, overflow: "hidden", boxShadow: "var(--sh-md)", border: "1px solid #D3DBE2", lineHeight: 0 }}>
          <img src="assets/dni-specimen.png" alt="DNI · documento nacional de identidad" draggable={false} style={{ width: "100%", display: "block", userSelect: "none" }} />
          {DNI_BOXES.map((b) => {
            const active = sel === b.ref;
            return (
              <button key={b.ref} data-field={b.ref} title="Located by the agent" onClick={(e) => { e.stopPropagation(); setSel(b.ref); }}
                style={{ position: "absolute", left: b.l + "%", top: b.t + "%", width: b.w + "%", height: b.h + "%", padding: 0, border: 0, cursor: "pointer", borderRadius: 5,
                  background: active ? "rgba(20,102,255,.26)" : "rgba(20,102,255,.05)",
                  outline: active ? "2.5px solid var(--gold)" : "1.5px solid rgba(20,102,255,.35)",
                  outlineOffset: 0, transition: "all .15s", animation: active ? "pulseRing 1.4s ease 1" : "none" }}>
                <span style={{ position: "absolute", top: -9, left: -9, width: 17, height: 17, borderRadius: "50%", background: active ? "var(--gold)" : "rgba(20,102,255,.55)",
                  color: "#fff", fontSize: 10, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", lineHeight: 1, boxShadow: "0 1px 2px rgba(0,0,0,.25)" }}>{b.label}</span>
              </button>
            );
          })}
        </div>
        <div style={{ textAlign: "center", fontSize: 11, color: "var(--ink-4)", marginTop: 10, fontFamily: "var(--mono)" }}>dni_carmen_especimen.jpg · specimen</div>
      </div>
    );
  }

  // ---------- Nómina document render ----------
  function DocNomina({ sel, setSel }) {
    return (
      <div style={{ width: 560, maxWidth: "100%", margin: "0 auto", background: "#fff", borderRadius: 12, padding: "26px 30px", boxShadow: "var(--sh-md)", border: "1px solid var(--line)", fontSize: 12.5, color: "#2B3A48" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "2px solid var(--ink)", paddingBottom: 12, marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 9.5, letterSpacing: ".12em", color: "#8995A2", fontWeight: 700 }}>RECIBO DE SALARIOS · NÓMINA</div>
            <div style={{ marginTop: 4 }}><F id="empresa" sel={sel} setSel={setSel}><strong style={{ fontSize: 15, color: "var(--ink)" }}>Adquira España S.A.</strong></F></div>
            <div style={{ fontSize: 11, color: "#7B8896", marginTop: 2 }}>CIF A·82605965 · Madrid</div>
          </div>
          <div style={{ textAlign: "right", fontSize: 11, color: "#7B8896" }}>Período<br/><strong style={{ color: "#2B3A48", fontSize: 13 }}>Febrero 2026</strong></div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 18px", marginBottom: 16 }}>
          <Row label="Trabajador">Carmen Española Española</Row>
          <Row label="NIF"><F id="nif" sel={sel} setSel={setSel} error><span className="mono" style={{ fontWeight: 700 }}>99999998R</span></F></Row>
          <Row label="Antigüedad"><F id="antiguedad" sel={sel} setSel={setSel}>12·09·2019</F></Row>
          <Row label="Grupo de cotización">1 · Ingenieros</Row>
        </div>

        <table style={{ width: "100%", borderCollapse: "collapse", marginBottom: 14 }}>
          <thead><tr style={{ background: "var(--surface-2)" }}>
            <th style={{ textAlign: "left", padding: "7px 10px", fontSize: 10, letterSpacing: ".06em", color: "#7B8896", textTransform: "uppercase" }}>Devengos</th>
            <th style={{ textAlign: "right", padding: "7px 10px", fontSize: 10, letterSpacing: ".06em", color: "#7B8896", textTransform: "uppercase" }}>Importe</th>
          </tr></thead>
          <tbody>
            {[["Salario base", "2.180,00 €"], ["Complemento puesto", "640,00 €"], ["Plus transporte", "160,00 €"]].map(([k, v]) => (
              <tr key={k} style={{ borderBottom: "1px solid var(--line)" }}><td style={{ padding: "7px 10px" }}>{k}</td><td className="mono" style={{ padding: "7px 10px", textAlign: "right" }}>{v}</td></tr>
            ))}
            <tr style={{ borderBottom: "1px solid var(--line)" }}><td style={{ padding: "7px 10px", fontWeight: 700 }}>Total devengado (bruto)</td><td style={{ padding: "7px 10px", textAlign: "right" }}><F id="bruto" sel={sel} setSel={setSel}><span className="mono" style={{ fontWeight: 700 }}>2.980,00 €</span></F></td></tr>
            <tr><td style={{ padding: "7px 10px", color: "#7B8896" }}>Deducciones (IRPF + S.S.)</td><td className="mono" style={{ padding: "7px 10px", textAlign: "right", color: "#7B8896" }}>− 638,83 €</td></tr>
          </tbody>
        </table>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
          <Row label="Base de cotización"><F id="cotizacion" sel={sel} setSel={setSel}><span className="mono">3.214,00 €</span></F></Row>
        </div>
        <div style={{ marginTop: 12, padding: "12px 16px", background: "var(--ink)", borderRadius: 9, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ fontSize: 12, color: "rgba(234,241,251,.75)", fontWeight: 600 }}>LÍQUIDO A PERCIBIR</span>
          <F id="neto" sel={sel} setSel={setSel}><span className="mono" style={{ fontSize: 17, fontWeight: 700, color: "#fff" }}>2.341,17 €</span></F>
        </div>
      </div>
    );
  }
  function Row({ label, children }) {
    return <div style={{ display: "flex", flexDirection: "column" }}><span style={{ fontSize: 9.5, letterSpacing: ".05em", color: "#8995A2", textTransform: "uppercase" }}>{label}</span><span style={{ marginTop: 1 }}>{children}</span></div>;
  }

  // ---------- main review ----------
  function Review({ c, go, onApprove, onWhatsApp }) {
    const rd = window.VELA.reviewDocs[c.id];
    const [selDoc, setSelDoc] = useState(rd.docs[0].id);
    const [selField, setSelField] = useState(null);
    const [confirmed, setConfirmed] = useState({});
    const [edits, setEdits] = useState({});
    const [editing, setEditing] = useState(null);
    const [conflictChoice, setConflictChoice] = useState({});

    const doc = rd.docs.find((d) => d.id === selDoc);
    const key = (ref) => selDoc + ":" + ref;

    const confirmField = (ref) => setConfirmed((s) => ({ ...s, [key(ref)]: true }));
    const confirmAll = () => setConfirmed((s) => { const n = { ...s }; doc.fields.forEach((f) => { if (f.status !== "error") n[selDoc + ":" + f.ref] = true; }); return n; });

    // conflict resolution updates the disputed field value + confirms it
    const resolveConflict = (cf, opt) => {
      setConflictChoice((s) => ({ ...s, [cf.id]: opt.ref }));
      // apply to nómina nif field
      setEdits((e) => ({ ...e, ["nomina-mf:nif"]: opt.value }));
      setConfirmed((s) => ({ ...s, ["nomina-mf:nif"]: true }));
    };

    const fieldValue = (docId, f) => edits[docId + ":" + f.ref] != null ? edits[docId + ":" + f.ref] : f.value;
    const fieldConfirmed = (docId, ref) => !!confirmed[docId + ":" + ref];

    // progress
    const allFields = rd.docs.flatMap((d) => d.fields.map((f) => d.id + ":" + f.ref));
    const confirmedCount = allFields.filter((k) => confirmed[k]).length;
    const conflictsResolved = rd.conflicts.every((cf) => conflictChoice[cf.id]);
    const allConfirmed = confirmedCount === allFields.length;
    const canApprove = allConfirmed && conflictsResolved;

    const docReviewed = (d) => d.fields.every((f) => confirmed[d.id + ":" + f.ref]);

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "calc(100vh - 64px)" }}>
        {/* summary bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 18, padding: "14px 28px", borderBottom: "1px solid var(--line)", background: "var(--surface)" }}>
          <Avatar initials={c.initials} size={40} />
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span className="serif" style={{ fontSize: 18, color: "var(--ink)" }}>{c.borrower}</span>
              <CaseStatus status={c.status} dot />
            </div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}><span className="mono">{c.id}</span> · agent reviewed {rd.docs.length} document types</div>
          </div>
          <div style={{ display: "flex", gap: 20, marginLeft: 14 }}>
            {[["Reviewed", confirmedCount + "/" + allFields.length, "var(--ink)"], ["Conflicts", (rd.conflicts.length - Object.keys(conflictChoice).length) + " open", conflictsResolved ? "var(--green)" : "var(--amber)"]].map(([k, v, col]) => (
              <div key={k}><div className="label-cap" style={{ fontSize: 9.5, marginBottom: 2 }}>{k}</div><div className="mono" style={{ fontSize: 15, fontWeight: 600, color: col }}>{v}</div></div>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onWhatsApp}><Icon name="whatsapp" size={14} /> Conversation</button>
          <button className="btn btn-gold" disabled={!canApprove} style={{ opacity: canApprove ? 1 : 0.4, cursor: canApprove ? "pointer" : "not-allowed" }}
            onClick={() => canApprove && onApprove(c.id)}>
            <Icon name="check" size={15} stroke={2.5} /> Approve & complete
          </button>
        </div>

        <div style={{ flex: 1, display: "grid", gridTemplateColumns: "232px 1fr 340px", minHeight: 0 }}>
          {/* doc navigator */}
          <div style={{ borderRight: "1px solid var(--line)", overflowY: "auto", background: "var(--surface-2)", padding: "16px 12px" }}>
            {c.participants.map((p) => {
              const pdocs = rd.docs.filter((d) => d.participant === p.name);
              if (!pdocs.length) return null;
              return (
                <div key={p.name} style={{ marginBottom: 16 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 8px 8px" }}>
                    <Avatar initials={p.initials} size={22} tone="soft" />
                    <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-2)" }}>{p.name.split(" ").slice(0, 2).join(" ")}</span>
                  </div>
                  {pdocs.map((d) => {
                    const active = selDoc === d.id;
                    const reviewed = docReviewed(d);
                    return (
                      <button key={d.id} onClick={() => { setSelDoc(d.id); setSelField(null); }} style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", textAlign: "left", border: 0,
                        borderRadius: 8, padding: "9px 10px", marginBottom: 2, cursor: "pointer", background: active ? "var(--surface)" : "transparent", boxShadow: active ? "var(--sh-sm)" : "none",
                        color: active ? "var(--ink)" : "var(--ink-2)", fontSize: 12.5, fontWeight: active ? 600 : 500 }}>
                        <Icon name="docs" size={15} style={{ color: active ? "var(--gold)" : "var(--ink-4)", flexShrink: 0 }} />
                        <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.title}</span>
                        {reviewed ? <span style={{ width: 16, height: 16, borderRadius: "50%", background: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="check" size={10} stroke={3} /></span>
                          : <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--ink-4)", flexShrink: 0 }} />}
                      </button>
                    );
                  })}
                </div>
              );
            })}
          </div>

          {/* document viewer */}
          <div onClick={() => setSelField(null)} style={{ overflowY: "auto", padding: "28px 24px", background: "repeating-linear-gradient(45deg,#EAEFF7,#EAEFF7 12px,#F1F5FB 12px,#F1F5FB 24px)" }}>
            <div style={{ maxWidth: 600, margin: "0 auto" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16, color: "var(--ink-3)", fontSize: 12.5 }}>
                <Icon name="sparkles" size={14} style={{ color: "var(--gold)" }} />
                <span>Each highlighted field is where the agent read its value. Select a field to locate it.</span>
              </div>
              {doc.kind === "dni" ? <DocDNI sel={selField} setSel={setSelField} /> : <DocNomina sel={selField} setSel={setSelField} />}
            </div>
          </div>

          {/* field panel */}
          <div style={{ borderLeft: "1px solid var(--line)", overflowY: "auto", background: "var(--surface)", display: "flex", flexDirection: "column" }}>
            <div style={{ padding: "16px 20px 12px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <h3 style={{ fontSize: 14.5 }}>Extracted fields</h3>
              <button className="btn-quiet btn-sm" onClick={confirmAll} style={{ border: 0, color: "var(--gold)", fontWeight: 600 }}>Confirm all</button>
            </div>

            <div style={{ padding: "8px 14px", flex: 1 }}>
              {doc.fields.map((f) => {
                const active = selField === f.ref;
                const conf = fieldConfirmed(doc.id, f.ref);
                const isErr = f.status === "error" && !conf;
                const val = fieldValue(doc.id, f);
                const isEditing = editing === doc.id + ":" + f.ref;
                return (
                  <div key={f.ref} onClick={() => setSelField(f.ref)} style={{ padding: "11px 12px", borderRadius: 10, marginBottom: 4, cursor: "pointer",
                    background: active ? "var(--gold-soft)" : "transparent", border: "1px solid " + (active ? "var(--gold-line)" : "transparent"), transition: "all .12s" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
                      <span style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)" }}>{f.label}</span>
                      {conf ? <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--green)", display: "flex", alignItems: "center", gap: 3 }}><Icon name="check" size={11} stroke={3} /> Confirmed</span>
                        : isErr ? <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--red)", display: "flex", alignItems: "center", gap: 3 }}><Icon name="alert" size={11} /> {f.hint}</span>
                        : <span style={{ fontSize: 10.5, color: "var(--ink-4)" }}>unconfirmed</span>}
                    </div>
                    {isEditing ? (
                      <div style={{ display: "flex", gap: 6 }} onClick={(e) => e.stopPropagation()}>
                        <input autoFocus defaultValue={val} id={"edit-" + f.ref} className="mono" style={{ flex: 1, height: 32, padding: "0 9px", border: "1px solid var(--gold-2)", borderRadius: 7, fontSize: 13, outline: "none" }} />
                        <button className="btn btn-gold btn-sm" onClick={() => { const v = document.getElementById("edit-" + f.ref).value; setEdits((e) => ({ ...e, [doc.id + ":" + f.ref]: v })); confirmField(f.ref); setEditing(null); }}>Save</button>
                      </div>
                    ) : (
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                        <span className="mono" style={{ fontSize: 13.5, fontWeight: 600, color: isErr ? "var(--red)" : "var(--ink)" }}>{val}</span>
                        <div style={{ display: "flex", gap: 4 }} onClick={(e) => e.stopPropagation()}>
                          <button onClick={() => setEditing(doc.id + ":" + f.ref)} title="Edit" style={{ width: 26, height: 26, borderRadius: 6, border: "1px solid var(--line)", background: "var(--surface)", color: "var(--ink-3)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="pencil" size={12} /></button>
                          {!isErr && !conf && <button onClick={() => confirmField(f.ref)} title="Confirm" style={{ width: 26, height: 26, borderRadius: 6, border: "1px solid var(--green)", background: "var(--green-soft)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="check" size={13} stroke={2.6} /></button>}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}

              {/* conflicts */}
              {rd.conflicts.length > 0 && (
                <div style={{ marginTop: 14, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, padding: "0 4px 10px" }}>
                    <Icon name="warn" size={15} style={{ color: "var(--amber)" }} />
                    <h3 style={{ fontSize: 13.5 }}>Conflicts</h3>
                  </div>
                  {rd.conflicts.map((cf) => {
                    const chosen = conflictChoice[cf.id];
                    return (
                      <div key={cf.id} style={{ padding: 13, borderRadius: 10, background: chosen ? "var(--green-soft)" : "var(--amber-soft)", border: "1px solid " + (chosen ? "#CDE6D9" : "#EBD9B5"), marginBottom: 8 }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: chosen ? "var(--green)" : "var(--amber)", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}>
                          {chosen ? <><Icon name="check" size={13} stroke={2.6} /> Resolved</> : <>{cf.summary}</>}
                        </div>
                        {!chosen ? (
                          <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                            {cf.options.map((opt) => (
                              <button key={opt.ref} onClick={() => resolveConflict(cf, opt)} style={{ textAlign: "left", border: "1px solid var(--line)", background: "var(--surface)", borderRadius: 8, padding: "9px 11px", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                                <div style={{ minWidth: 0 }}><div style={{ fontSize: 11, color: "var(--ink-3)" }}>{opt.label}</div><div className="mono" style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>{opt.value}</div></div>
                                <span style={{ fontSize: 11, color: "var(--gold)", fontWeight: 600, whiteSpace: "nowrap" }}>Use this</span>
                              </button>
                            ))}
                          </div>
                        ) : (
                          <div className="mono" style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>{cf.options.find((o) => o.ref === chosen).value}</div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.Review = Review;
  window.VelaDocs = { F, fieldStyle, DocDNI, DocNomina, DNI_BOXES };
})();
