/* ============================================================
   Vela — S3 · New Case creation (overlay wizard)
   ============================================================ */
(function () {
  const { useState } = React;
  const { Avatar, templateOf } = window.UI;

  const initialsOf = (name) => {
    const parts = (name || "").trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) return "—";
    return (parts[0][0] + (parts[1] ? parts[1][0] : "")).toUpperCase();
  };

  const inputStyle = { height: 42, padding: "0 13px", border: "1px solid var(--line-strong)", borderRadius: 9, fontSize: 14, background: "var(--surface)", color: "var(--ink)", outline: "none", width: "100%" };
  function TextInput(props) {
    return <input {...props} style={{ ...inputStyle, ...(props.style || {}) }}
      onFocus={(e) => e.target.style.borderColor = "var(--gold-2)"} onBlur={(e) => e.target.style.borderColor = "var(--line-strong)"} />;
  }
  function Field({ label, children, hint, optional }) {
    return (
      <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)" }}>{label} {optional && <span style={{ color: "var(--ink-4)", fontWeight: 500 }}>· optional</span>}</span>
        {children}
        {hint && <span style={{ fontSize: 11, color: "var(--ink-4)" }}>{hint}</span>}
      </label>
    );
  }

  // Salesforce-blue badge shown next to CRM-sourced contacts.
  const sfBadge = { display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10.5, fontWeight: 700, color: "#00A1E0", background: "rgba(0,161,224,.1)", border: "1px solid rgba(0,161,224,.28)", borderRadius: 5, padding: "2px 6px" };

  // CRM contact selector — search Salesforce, or fall back to manual entry.
  function ContactPicker({ exclude = [], onSelect, placeholder = "Search Salesforce contacts…" }) {
    const [query, setQuery] = useState("");
    const [open, setOpen] = useState(false);
    const [manual, setManual] = useState(false);
    const [mName, setMName] = useState("");
    const [mPhone, setMPhone] = useState("");

    if (manual) {
      const canAdd = mName.trim().length > 0;
      const confirm = () => { if (canAdd) { onSelect({ name: mName.trim(), phone: mPhone.trim(), manual: true }); setMName(""); setMPhone(""); setManual(false); setQuery(""); } };
      return (
        <div style={{ border: "1px solid var(--line-strong)", borderRadius: 11, padding: 14, background: "var(--surface-2)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)" }}>Enter contact manually</div>
            <button onClick={() => setManual(false)} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: "var(--gold)", border: 0, background: "none", cursor: "pointer" }}><Icon name="search" size={13} /> Back to Salesforce</button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 10, alignItems: "center" }}>
            <TextInput placeholder="Full name" value={mName} onChange={(e) => setMName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), confirm())} />
            <TextInput placeholder="+34 6XX XX XX XX" value={mPhone} onChange={(e) => setMPhone(e.target.value)} onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), confirm())} style={{ fontFamily: "var(--mono)" }} />
            <button className="btn btn-gold btn-sm" disabled={!canAdd} style={{ opacity: canAdd ? 1 : 0.45 }} onClick={confirm}>Add</button>
          </div>
        </div>
      );
    }

    const all = window.VELA.CRM_CONTACTS || [];
    const q = query.trim().toLowerCase();
    const qDigits = q.replace(/\D/g, "");
    const results = all
      .filter((c) => !exclude.includes(c.id))
      .filter((c) => !q
        || c.name.toLowerCase().includes(q)
        || (c.email || "").toLowerCase().includes(q)
        || (qDigits && (c.phone || "").replace(/\D/g, "").includes(qDigits)));

    return (
      <div style={{ position: "relative" }}>
        <div style={{ position: "relative" }}>
          <Icon name="search" size={16} style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--ink-4)", pointerEvents: "none" }} />
          <input value={query} onChange={(e) => setQuery(e.target.value)} onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 140)} placeholder={placeholder}
            style={{ ...inputStyle, height: 44, padding: "0 104px 0 38px" }} />
          <span style={{ ...sfBadge, position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }}>
            <Icon name="salesforce" size={12} stroke={2} /> Salesforce
          </span>
        </div>
        {open && (
          <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, zIndex: 20, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 11, boxShadow: "var(--sh-lg)", overflow: "hidden", maxHeight: 290, display: "flex", flexDirection: "column" }}>
            <div style={{ overflowY: "auto" }}>
              {results.length === 0
                ? <div style={{ padding: "16px 14px", fontSize: 12.5, color: "var(--ink-4)" }}>No Salesforce contacts match “{query}”.</div>
                : results.map((c) => (
                    <button key={c.id} onMouseDown={(e) => { e.preventDefault(); onSelect(c); setQuery(""); setOpen(false); }}
                      style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", textAlign: "left", padding: "9px 12px", border: 0, borderBottom: "1px solid var(--line)", background: "none", cursor: "pointer" }}
                      onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")} onMouseLeave={(e) => (e.currentTarget.style.background = "none")}>
                      <Avatar initials={initialsOf(c.name)} size={34} tone="soft" />
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{c.name}</div>
                        <div style={{ fontSize: 11.5, color: "var(--ink-4)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.email} · {c.phone}</div>
                      </div>
                    </button>
                  ))}
            </div>
            <button onMouseDown={(e) => { e.preventDefault(); setManual(true); setOpen(false); }}
              style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", textAlign: "left", padding: "10px 12px", border: 0, borderTop: "1px solid var(--line)", background: "var(--surface-2)", cursor: "pointer", fontSize: 12.5, fontWeight: 600, color: "var(--gold)" }}>
              <Icon name="plus" size={14} /> Enter manually instead
            </button>
          </div>
        )}
      </div>
    );
  }

  // Selected-contact header row (avatar + name + CRM / manual badge + remove action).
  function ContactRow({ contact, onRemove, removeLabel }) {
    const isManual = !!contact.manual;
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <Avatar initials={initialsOf(contact.name)} size={38} tone={isManual ? "soft" : "gold"} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{contact.name}</span>
            {isManual
              ? <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--ink-3)", background: "rgba(107,119,144,.12)", border: "1px solid var(--line)", borderRadius: 5, padding: "2px 6px" }}>Manual</span>
              : <span style={sfBadge}><Icon name="salesforce" size={11} stroke={2} /> Salesforce</span>}
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-4)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{contact.phone || "—"}{contact.email ? " · " + contact.email : ""}</div>
        </div>
        <button onClick={onRemove} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: "var(--ink-3)", border: "1px solid var(--line)", borderRadius: 8, padding: "7px 11px", background: "none", cursor: "pointer", flexShrink: 0 }}>
          {removeLabel === "Change" ? <><Icon name="refresh" size={13} /> Change</> : <Icon name="x" size={15} />}
        </button>
      </div>
    );
  }

  // Per-entity employment-profile picker (each applicant can have a different bundle).
  function ProfileSelect({ value, onChange }) {
    return (
      <select value={value || ""} onChange={(e) => onChange(e.target.value)}
        style={{ flex: 1, height: 40, padding: "0 12px", border: "1px solid var(--line-strong)", borderRadius: 9, fontSize: 13.5, background: "var(--surface)", color: value ? "var(--ink)" : "var(--ink-4)", cursor: "pointer", maxWidth: 280 }}>
        {!value && <option value="">Select profile…</option>}
        {window.VELA.TEMPLATES.map((t) => <option key={t.key} value={t.key} style={{ color: "var(--ink)" }}>{t.label} · {t.en}</option>)}
      </select>
    );
  }

  // Document chips for one applicant: template bundle (neutral) + extras (gold, removable).
  function DocBundle({ baseDocs, extraDocs, onRemoveExtra }) {
    if (baseDocs.length === 0 && extraDocs.length === 0)
      return <div style={{ fontSize: 12.5, color: "var(--ink-4)", marginBottom: 12 }}>Pick a profile to load the document bundle.</div>;
    return (
      <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 12 }}>
        {baseDocs.map((d) => (
          <span key={d} style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 8, padding: "6px 11px" }}>{d}</span>
        ))}
        {extraDocs.map((d, i) => (
          <span key={d} style={{ fontSize: 12, fontWeight: 600, color: "var(--gold)", background: "var(--gold-soft)", border: "1px solid var(--gold-line)", borderRadius: 8, padding: "6px 9px", display: "flex", alignItems: "center", gap: 6 }}>
            {d}<button onClick={() => onRemoveExtra(i)} style={{ border: 0, background: "none", padding: 0, cursor: "pointer", color: "var(--gold)", display: "flex" }}><Icon name="x" size={12} stroke={2.5} /></button>
          </span>
        ))}
      </div>
    );
  }

  // Native <select> + Add button for appending an extra document to one applicant.
  function DocAdder({ exclude, value, setValue, onAdd }) {
    const opts = window.VELA.COMMON_DOCS.filter((d) => !exclude.includes(d));
    return (
      <div style={{ display: "flex", gap: 8 }}>
        <select value={value} onChange={(e) => setValue(e.target.value)}
          style={{ flex: 1, height: 40, padding: "0 12px", border: "1px solid var(--line-strong)", borderRadius: 9, fontSize: 13.5, background: "var(--surface)", color: value ? "var(--ink)" : "var(--ink-4)", cursor: "pointer" }}>
          <option value="">Add an extra document…</option>
          {opts.map((d) => <option key={d} value={d} style={{ color: "var(--ink)" }}>{d}</option>)}
        </select>
        <button className="btn btn-ghost btn-sm" disabled={!value} style={{ opacity: value ? 1 : 0.45 }} onClick={onAdd}><Icon name="plus" size={14} /> Add</button>
      </div>
    );
  }

  // One applicant: contact + their own employment profile + the resulting document bundle.
  function ParticipantBlock({ contact, onRemoveContact, removeLabel, templateKey, onTemplateChange, extraDocs, onRemoveDoc, docDraft, setDocDraft, onAddDoc }) {
    const tplObj = templateOf(templateKey);
    const baseDocs = tplObj ? tplObj.docs : [];
    const extras = extraDocs || [];
    return (
      <div style={{ border: "1px solid var(--line-strong)", borderRadius: 14, overflow: "hidden" }}>
        <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)", background: "var(--surface)" }}>
          <ContactRow contact={contact} onRemove={onRemoveContact} removeLabel={removeLabel} />
        </div>
        <div style={{ padding: "18px 18px 20px", background: "var(--surface-2)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)", flexShrink: 0 }}>Employment profile</span>
            <ProfileSelect value={templateKey} onChange={onTemplateChange} />
          </div>
          <div className="label-cap" style={{ marginBottom: 10 }}>Documents to request · {baseDocs.length + extras.length}</div>
          <DocBundle baseDocs={baseDocs} extraDocs={extras} onRemoveExtra={onRemoveDoc} />
          <DocAdder exclude={baseDocs.concat(extras)} value={docDraft || ""} setValue={setDocDraft} onAdd={onAddDoc} />
        </div>
      </div>
    );
  }

  function NewCase({ onClose, onCreate }) {
    const [tpl, setTpl] = useState(null); // primary borrower's employment profile
    const [data, setData] = useState({ borrower: null, coapps: [] });
    const [addingCo, setAddingCo] = useState(false);
    const [borrowerExtra, setBorrowerExtra] = useState([]); // extra docs for the primary borrower
    const [borrowerDocDraft, setBorrowerDocDraft] = useState("");

    const setBorrower = (c) => setData((d) => ({ ...d, borrower: c }));
    const clearBorrower = () => setData((d) => ({ ...d, borrower: null }));
    // Each co-applicant carries its own profile + document bundle; defaults to the borrower's profile.
    const addCo = (c) => setData((d) => ({ ...d, coapps: [...d.coapps, { ...c, template: tpl || "", extraDocs: [], docDraft: "" }] }));
    const removeCo = (i) => setData((d) => ({ ...d, coapps: d.coapps.filter((_, j) => j !== i) }));
    const updateCo = (i, patch) => setData((d) => ({ ...d, coapps: d.coapps.map((c, j) => j === i ? { ...c, ...patch } : c) }));

    const addBorrowerDoc = () => { const t = borrowerDocDraft.trim(); if (t && !borrowerExtra.includes(t)) setBorrowerExtra((a) => [...a, t]); setBorrowerDocDraft(""); };
    const removeBorrowerDoc = (i) => setBorrowerExtra((a) => a.filter((_, j) => j !== i));
    const addCoDoc = (i) => { const co = data.coapps[i]; const t = (co.docDraft || "").trim(); updateCo(i, { docDraft: "", extraDocs: (t && !co.extraDocs.includes(t)) ? [...co.extraDocs, t] : co.extraDocs }); };
    const removeCoDoc = (i, j) => updateCo(i, { extraDocs: data.coapps[i].extraDocs.filter((_, k) => k !== j) });

    // Need a borrower with a chosen profile; every co-applicant must have a profile too.
    const coappsReady = data.coapps.every((co) => !!co.template);
    const canCreate = !!data.borrower && !!tpl && coappsReady;
    const createMsg = !data.borrower ? "Select a primary borrower first"
      : !tpl ? "Choose the borrower's employment profile"
      : !coappsReady ? "Choose a profile for each co-applicant" : "";

    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "rgba(21,35,63,.42)", backdropFilter: "blur(4px)", animation: "fadeIn .2s ease" }}>
        <div className="card" style={{ width: "100%", maxWidth: 720, maxHeight: "92vh", 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: "flex-start", justifyContent: "space-between", padding: "32px 40px 24px", borderBottom: "1px solid var(--line)" }}>
            <div>
              <div className="label-cap" style={{ marginBottom: 9 }}>New case</div>
              <h2 className="serif" style={{ fontSize: 26, marginBottom: 7 }}>Add the people & their documents</h2>
              <div style={{ fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.5 }}>Search your CRM for everyone on the mortgage. Each applicant gets their own employment profile and document bundle.</div>
            </div>
            <button onClick={onClose} className="btn-quiet" style={{ width: 36, height: 36, borderRadius: 9, border: 0, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", flexShrink: 0, marginLeft: 16 }}><Icon name="x" size={18} /></button>
          </div>

          {/* body */}
          <div style={{ flex: 1, overflowY: "auto", padding: "34px 40px 38px" }}>
            <div className="anim-fadein" style={{ display: "flex", flexDirection: "column", gap: 36 }}>
              <div>
                <div className="label-cap" style={{ marginBottom: 14 }}>Primary borrower</div>
                {data.borrower
                  ? <ParticipantBlock
                      contact={data.borrower} onRemoveContact={clearBorrower} removeLabel="Change"
                      templateKey={tpl} onTemplateChange={setTpl}
                      extraDocs={borrowerExtra} onRemoveDoc={removeBorrowerDoc}
                      docDraft={borrowerDocDraft} setDocDraft={setBorrowerDocDraft} onAddDoc={addBorrowerDoc} />
                  : <ContactPicker onSelect={setBorrower} placeholder="Search Salesforce contacts…" />}
                <div style={{ fontSize: 11.5, color: "var(--ink-4)", marginTop: 10, display: "flex", alignItems: "center", gap: 6 }}><Icon name="whatsapp" size={13} style={{ color: "var(--ink-4)" }} /> The agent contacts each participant on the WhatsApp number from their CRM record.</div>
              </div>

              <div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                  <div className="label-cap">Co-applicants</div>
                  {!addingCo && <button className="btn btn-ghost btn-sm" onClick={() => setAddingCo(true)}><Icon name="plus" size={13} /> Add co-applicant</button>}
                </div>
                {data.coapps.length === 0 && !addingCo
                  ? <div style={{ fontSize: 13, color: "var(--ink-4)", padding: "12px 0" }}>No co-applicants yet. Each co-applicant gets their own profile and document bundle.</div>
                  : <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                      {data.coapps.map((co, i) => (
                        <ParticipantBlock key={co.id || ("manual-" + i)}
                          contact={co} onRemoveContact={() => removeCo(i)}
                          templateKey={co.template} onTemplateChange={(k) => updateCo(i, { template: k })}
                          extraDocs={co.extraDocs} onRemoveDoc={(j) => removeCoDoc(i, j)}
                          docDraft={co.docDraft} setDocDraft={(v) => updateCo(i, { docDraft: v })} onAddDoc={() => addCoDoc(i)} />
                      ))}
                      {addingCo && (
                        <ContactPicker
                          exclude={[data.borrower, ...data.coapps].filter(Boolean).map((c) => c.id).filter(Boolean)}
                          onSelect={(c) => { addCo(c); setAddingCo(false); }}
                          placeholder="Search a co-applicant in Salesforce…" />
                      )}
                    </div>}
                {addingCo && (
                  <button onClick={() => setAddingCo(false)} style={{ marginTop: 12, fontSize: 12, fontWeight: 600, color: "var(--ink-3)", border: 0, background: "none", cursor: "pointer" }}>Cancel</button>
                )}
              </div>
            </div>
          </div>

          {/* footer */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 40px", borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-gold" disabled={!canCreate} title={createMsg} style={{ opacity: canCreate ? 1 : 0.45 }} onClick={() => canCreate && onCreate({ borrower: { ...data.borrower, template: tpl, extraDocs: borrowerExtra }, coapps: data.coapps })}><Icon name="folder" size={15} /> Create case</button>
          </div>
        </div>
      </div>
    );
  }

  window.NewCase = NewCase;
})();
