/* ============================================================
   Vela — Single-document validation (window.ValidateDoc)
   Opens when the broker clicks an extracted document during
   COLLECTING: shows the AI-extracted document + field panel so
   they can confirm/correct the extracted data, then approve.
   ============================================================ */
(function () {
  const { useState } = React;
  const { Avatar } = window.UI;

  // F highlight component reused from the review workspace
  const F = (props) => window.VelaDocs.F(props);
  const byRef = (fields) => Object.fromEntries(fields.map((x) => [x.ref, x]));

  // ---- document renderers (parameterised by extracted fields) ----
  function DocLabel({ children }) { return <span style={{ fontSize: 9, letterSpacing: ".06em", color: "#8995A2", textTransform: "uppercase", display: "block" }}>{children}</span>; }

  function IdCard({ fields, sel, setSel, attn }) {
    const f = byRef(fields);
    const fp = (ref) => ({ id: ref, sel, setSel, error: attn.has(ref) });
    return (
      <div style={{ width: 420, maxWidth: "100%", margin: "0 auto", background: "linear-gradient(150deg,#EFF3F6,#E3E9EE)", borderRadius: 14, padding: 20, boxShadow: "var(--sh-md)", border: "1px solid #D3DBE2" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".06em", color: "#5A6B7B" }}>DOCUMENTO NACIONAL DE IDENTIDAD</div>
          <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: ".14em", color: "#8895A8" }}>ESPAÑA</div>
        </div>
        <div style={{ display: "flex", gap: 16 }}>
          <div style={{ width: 86, height: 108, borderRadius: 8, background: "linear-gradient(160deg,#C4CDD6,#9FAAB6)", display: "flex", alignItems: "flex-end", justifyContent: "center", flexShrink: 0, overflow: "hidden" }}>
            <Icon name="user" size={60} style={{ color: "rgba(255,255,255,.55)", marginBottom: -6 }} />
          </div>
          <div style={{ flex: 1, fontSize: 13, color: "#2B3A48", lineHeight: 1.9 }}>
            <div><DocLabel>Apellidos y nombre</DocLabel><F {...fp("nombre")}><strong>{f.nombre && f.nombre.value}</strong></F></div>
            <div style={{ display: "flex", gap: 18 }}>
              <div><DocLabel>Sexo · Nac.</DocLabel><F {...fp("sexo")}>{f.sexo && f.sexo.value}</F></div>
              <div><DocLabel>Nacimiento</DocLabel><F {...fp("nacimiento")}>{f.nacimiento && f.nacimiento.value}</F></div>
            </div>
            <div><DocLabel>Válido hasta</DocLabel><F {...fp("validez")}>{f.validez && f.validez.value}</F></div>
          </div>
        </div>
        <div style={{ marginTop: 12, paddingTop: 10, borderTop: "1px solid #CDD6DE", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <DocLabel>DNI</DocLabel>
          <F id="nif" sel={sel} setSel={setSel} error={attn.has("nif")}><span className="mono" style={{ fontSize: 15, fontWeight: 700, color: "#2B3A48" }}>{f.nif && f.nif.value}</span></F>
        </div>
      </div>
    );
  }

  function Payslip({ fields, sel, setSel, attn, period }) {
    const f = byRef(fields);
    const fp = (ref) => ({ id: ref, sel, setSel, error: attn.has(ref) });
    return (
      <div style={{ width: 480, maxWidth: "100%", margin: "0 auto", background: "#fff", borderRadius: 12, padding: "24px 28px", boxShadow: "var(--sh-md)", border: "1px solid var(--line)", fontSize: 13, 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: ".1em", color: "#8995A2", fontWeight: 700 }}>RECIBO DE SALARIOS · NÓMINA</div>
            <div style={{ marginTop: 4 }}><F {...fp("empresa")}><strong style={{ fontSize: 15, color: "var(--ink)" }}>{f.empresa && f.empresa.value}</strong></F></div>
          </div>
          <div style={{ textAlign: "right", fontSize: 11, color: "#7B8896" }}>Período<br /><strong style={{ color: "#2B3A48", fontSize: 13 }}>{period}</strong></div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 18px", marginBottom: 16 }}>
          <div><DocLabel>NIF trabajador</DocLabel><F {...fp("nif")}><span className="mono" style={{ fontWeight: 700 }}>{f.nif && f.nif.value}</span></F></div>
          <div><DocLabel>Antigüedad</DocLabel><F {...fp("antiguedad")}>{f.antiguedad && f.antiguedad.value}</F></div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0", borderTop: "1px solid var(--line)" }}>
          <span style={{ color: "#7B8896" }}>Total devengado (bruto)</span><F {...fp("bruto")}><span className="mono" style={{ fontWeight: 700 }}>{f.bruto && f.bruto.value}</span></F>
        </div>
        <div style={{ marginTop: 10, 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 {...fp("neto")}><span className="mono" style={{ fontSize: 17, fontWeight: 700, color: "#fff" }}>{f.neto && f.neto.value}</span></F>
        </div>
      </div>
    );
  }

  function GenericDoc({ fields, sel, setSel, attn, title }) {
    return (
      <div style={{ width: 470, maxWidth: "100%", margin: "0 auto", background: "#fff", borderRadius: 12, padding: "26px 30px", boxShadow: "var(--sh-md)", border: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
        <div style={{ borderBottom: "2px solid var(--ink)", paddingBottom: 12, marginBottom: 16 }}>
          <div style={{ fontSize: 9.5, letterSpacing: ".12em", color: "#8995A2", fontWeight: 700 }}>DOCUMENTO ACREDITATIVO</div>
          <div className="serif" style={{ fontSize: 18, color: "var(--ink)", marginTop: 3 }}>{title}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {fields.map((fld) => (
            <div key={fld.ref} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16, paddingBottom: 12, borderBottom: "1px dotted var(--line-strong)" }}>
              <span style={{ fontSize: 12.5, color: "#7B8896" }}>{fld.label}</span>
              <F id={fld.ref} sel={sel} setSel={setSel} error={attn.has(fld.ref)}><span className="mono" style={{ fontSize: 13.5, fontWeight: 600, color: "#2B3A48" }}>{fld.value}</span></F>
            </div>
          ))}
        </div>
        <div style={{ position: "absolute", right: -10, bottom: -10, transform: "rotate(-12deg)", fontSize: 40, fontWeight: 800, color: "rgba(21,35,63,.04)", letterSpacing: ".1em" }}>VÁLIDO</div>
      </div>
    );
  }

  // ---- the validation modal ----
  function ValidateDoc({ doc, participant, onClose, onApprove }) {
    const ext = window.VELA.buildExtraction(doc.name, participant ? participant.name : "");
    const [sel, setSel] = useState(null);
    const [confirmed, setConfirmed] = useState({});
    const [edits, setEdits] = useState({});
    const [editing, setEditing] = useState(null);

    const valueOf = (fld) => (edits[fld.ref] != null ? edits[fld.ref] : fld.value);
    const resolved = (fld) => fld.status === "ok" || confirmed[fld.ref];
    const attn = new Set(ext.fields.filter((fld) => fld.status === "check" && !confirmed[fld.ref]).map((fld) => fld.ref));
    const canApprove = attn.size === 0;
    const checkCount = ext.fields.filter((fld) => fld.status === "check").length;

    const liveFields = ext.fields.map((fld) => ({ ...fld, value: valueOf(fld) }));
    const confirmField = (ref) => setConfirmed((s) => ({ ...s, [ref]: true }));

    return (
      <div style={{ position: "fixed", top: 64, left: 0, right: 0, bottom: 0, zIndex: 105, 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: 940, height: "86vh", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "var(--sh-lg)", animation: "pop .3s cubic-bezier(.2,.8,.3,1)" }}>
          {/* header */}
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 22px", borderBottom: "1px solid var(--line)" }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: "var(--gold-soft)", color: "var(--gold)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="sparkles" size={18} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 style={{ fontSize: 16 }}>{doc.name}</h2>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 1 }}>AI-extracted{participant ? " · " + participant.name : ""} · confirm the values match the document</div>
            </div>
            <button onClick={onClose} className="btn-quiet" style={{ width: 34, height: 34, borderRadius: 8, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}><Icon name="x" size={18} /></button>
          </div>

          <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 360px", minHeight: 0 }}>
            {/* document */}
            <div onClick={() => setSel(null)} style={{ overflowY: "auto", padding: "26px 22px", background: "repeating-linear-gradient(45deg,#EAEFF7,#EAEFF7 12px,#F1F5FB 12px,#F1F5FB 24px)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16, color: "var(--ink-3)", fontSize: 12.5, justifyContent: "center" }}>
                <Icon name="sparkles" size={14} style={{ color: "var(--gold)" }} /><span>Select a value to locate where the agent read it.</span>
              </div>
              {ext.kind === "dni" ? <IdCard fields={liveFields} sel={sel} setSel={setSel} attn={attn} />
                : ext.kind === "nomina" ? <Payslip fields={liveFields} sel={sel} setSel={setSel} attn={attn} period={ext.period} />
                : <GenericDoc fields={liveFields} sel={sel} setSel={setSel} attn={attn} title={ext.title} />}
              <div style={{ textAlign: "center", fontSize: 11, color: "var(--ink-4)", marginTop: 12, fontFamily: "var(--mono)" }}>{doc.name.toLowerCase().replace(/[^a-z0-9]+/g, "_")}.pdf</div>
            </div>

            {/* field panel */}
            <div style={{ borderLeft: "1px solid var(--line)", display: "flex", flexDirection: "column", background: "var(--surface)" }}>
              <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <h3 style={{ fontSize: 14 }}>Extracted data</h3>
                {checkCount > 0
                  ? <span className="chip" style={{ background: canApprove ? "var(--green-soft)" : "var(--amber-soft)", color: canApprove ? "var(--green)" : "var(--amber)" }}>{canApprove ? "All checked" : attn.size + " to check"}</span>
                  : <span className="chip" style={{ background: "var(--green-soft)", color: "var(--green)" }}><Icon name="check" size={12} stroke={2.6} /> High confidence</span>}
              </div>

              <div style={{ flex: 1, overflowY: "auto", padding: "8px 12px" }}>
                {liveFields.map((fld) => {
                  const active = sel === fld.ref;
                  const conf = confirmed[fld.ref] || edits[fld.ref] != null;
                  const needs = fld.status === "check" && !conf;
                  const isEditing = editing === fld.ref;
                  return (
                    <div key={fld.ref} onClick={() => setSel(fld.ref)} style={{ padding: "11px 12px", borderRadius: 10, marginBottom: 4, cursor: "pointer",
                      background: active ? "var(--gold-soft)" : needs ? "rgba(183,121,31,.06)" : "transparent", border: "1px solid " + (active ? "var(--gold-line)" : needs ? "#EBD9B5" : "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)" }}>{fld.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>
                          : needs ? <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--amber)", display: "flex", alignItems: "center", gap: 3 }}><Icon name="alert" size={11} /> Check</span>
                          : <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--green)", display: "flex", alignItems: "center", gap: 3 }}><Icon name="sparkles" size={11} /> AI validated</span>}
                      </div>
                      {isEditing ? (
                        <div style={{ display: "flex", gap: 6 }} onClick={(e) => e.stopPropagation()}>
                          <input autoFocus defaultValue={valueOf(fld)} id={"ve-" + fld.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("ve-" + fld.ref).value; setEdits((e) => ({ ...e, [fld.ref]: v })); confirmField(fld.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: needs ? "var(--amber)" : "var(--ink)" }}>{valueOf(fld)}</span>
                          <div style={{ display: "flex", gap: 4 }} onClick={(e) => e.stopPropagation()}>
                            <button onClick={() => setEditing(fld.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>
                            {needs && <button onClick={() => confirmField(fld.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>
                  );
                })}
              </div>

              <div style={{ padding: "14px 16px", borderTop: "1px solid var(--line)", background: "var(--surface-2)", display: "flex", flexDirection: "column", gap: 9 }}>
                {!canApprove && <div style={{ fontSize: 11.5, color: "var(--amber)", display: "flex", alignItems: "center", gap: 6 }}><Icon name="alert" size={13} /> Confirm the flagged value before approving.</div>}
                <button className="btn btn-gold" disabled={!canApprove} style={{ width: "100%", justifyContent: "center", opacity: canApprove ? 1 : 0.45, cursor: canApprove ? "pointer" : "not-allowed" }}
                  onClick={() => canApprove && onApprove(doc, "validated")}>
                  <Icon name="check" size={15} stroke={2.5} /> Approve document
                </button>
                <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center" }} onClick={() => onApprove(doc, "flagged")}>
                  <Icon name="flag" size={14} /> Flag for manual review
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.ValidateDoc = ValidateDoc;
})();
