/* ============================================================
   Vela — Templates view + editor (window.Templates, window.TemplateEditor)
   Brokers manage the default document bundle requested per case type.
   ============================================================ */
(function () {
  const { useState } = React;

  // ---------- Templates list ----------
  function Templates({ onEdit, onNew }) {
    const { TEMPLATES, cases } = window.VELA;
    return (
      <div style={{ padding: "24px 28px 60px", maxWidth: 1040, margin: "0 auto" }} className="anim-fadein">
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 20 }}>
          <div style={{ maxWidth: 560 }}>
            <p style={{ fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.5, margin: 0 }}>
              Each template defines the documents the agent requests for a borrower's employment situation. Edit a bundle or create your own — the choice drives every new case.
            </p>
          </div>
          <button className="btn btn-gold" onClick={onNew} style={{ flexShrink: 0 }}><Icon name="plus" size={15} stroke={2.2} /> New template</button>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          {TEMPLATES.map((t) => {
            const used = cases.filter((c) => c.template === t.key).length;
            return (
              <div key={t.key} className="card" style={{ padding: "var(--pad)", display: "flex", flexDirection: "column" }}>
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 8 }}>
                  <div>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 9 }}>
                      <h3 className="serif" style={{ fontSize: 18 }}>{t.label}</h3>
                      <span style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{t.en}</span>
                    </div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 3 }}>{t.desc}</div>
                  </div>
                  <button className="btn btn-ghost btn-sm" onClick={() => onEdit(t)}><Icon name="pencil" size={13} /> Edit</button>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, margin: "12px 0 14px" }}>
                  {t.docs.map((d) => (
                    <span key={d} style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-2)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 6, padding: "3px 8px", whiteSpace: "nowrap" }}>{d}</span>
                  ))}
                </div>
                <div style={{ marginTop: "auto", paddingTop: 10, borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 14, fontSize: 12, color: "var(--ink-3)" }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 6 }}><Icon name="docs" size={13} /> {t.docs.length} documents</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 6 }}><Icon name="folder" size={13} /> {used} active {used === 1 ? "case" : "cases"}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ---------- Template editor (modal) ----------
  const inputStyle = { height: 40, padding: "0 12px", border: "1px solid var(--line-strong)", borderRadius: 9, fontSize: 14, background: "var(--surface)", color: "var(--ink)", outline: "none", width: "100%" };

  function TemplateEditor({ template, onClose, onSave }) {
    const isNew = !template;
    const [label, setLabel] = useState(template ? template.label : "");
    const [en, setEn] = useState(template ? template.en : "");
    const [desc, setDesc] = useState(template ? template.desc : "");
    const [docs, setDocs] = useState(template ? [...template.docs] : []);
    const [adding, setAdding] = useState("");

    const addDoc = (name) => { const v = (name || "").trim(); if (v && !docs.includes(v)) setDocs((d) => [...d, v]); setAdding(""); };
    const removeDoc = (i) => setDocs((d) => d.filter((_, j) => j !== i));
    const move = (i, dir) => setDocs((d) => { const n = [...d]; const j = i + dir; if (j < 0 || j >= n.length) return n; [n[i], n[j]] = [n[j], n[i]]; return n; });

    const suggestions = window.VELA.COMMON_DOCS.filter((d) => !docs.includes(d));
    const canSave = label.trim() && docs.length > 0;

    return (
      <div style={{ position: "fixed", inset: 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: 720, maxHeight: "90vh", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "var(--sh-lg)", animation: "pop .3s cubic-bezier(.2,.8,.3,1)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "18px 24px", 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="template" size={18} /></div>
            <div style={{ flex: 1 }}>
              <h2 className="serif" style={{ fontSize: 19 }}>{isNew ? "New template" : "Edit template"}</h2>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{isNew ? "Define a document bundle for a borrower situation" : "Changes apply to new cases created from this template"}</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, overflowY: "auto", padding: "22px 24px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14, marginBottom: 18 }}>
              <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)" }}>Template name</span>
                <input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="p. ej. Cuenta ajena" style={inputStyle} />
              </label>
              <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)" }}>Short label (EN)</span>
                <input value={en} onChange={(e) => setEn(e.target.value)} placeholder="Employed" style={inputStyle} />
              </label>
              <label style={{ display: "flex", flexDirection: "column", gap: 6, gridColumn: "1 / -1" }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)" }}>Description</span>
                <input value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="When does a broker pick this template?" style={inputStyle} />
              </label>
            </div>

            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <span className="label-cap">Documents to request · {docs.length}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 14 }}>
              {docs.length === 0 && <div style={{ fontSize: 12.5, color: "var(--ink-4)", padding: "8px 2px" }}>No documents yet — add from the suggestions below.</div>}
              {docs.map((d, i) => (
                <div key={d + i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 6, background: "var(--surface)", border: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "var(--ink-3)", flexShrink: 0 }}>{i + 1}</span>
                  <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>{d}</span>
                  <div style={{ display: "flex", gap: 2 }}>
                    <button onClick={() => move(i, -1)} disabled={i === 0} title="Move up" style={iconBtn(i === 0)}><Icon name="chevD" size={14} style={{ transform: "rotate(180deg)" }} /></button>
                    <button onClick={() => move(i, 1)} disabled={i === docs.length - 1} title="Move down" style={iconBtn(i === docs.length - 1)}><Icon name="chevD" size={14} /></button>
                    <button onClick={() => removeDoc(i)} title="Remove" style={iconBtn(false, true)}><Icon name="trash" size={14} /></button>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <input list="vela-doclist" value={adding} onChange={(e) => setAdding(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addDoc(adding)} placeholder="Add a document type…" style={{ ...inputStyle, flex: 1 }} />
              <datalist id="vela-doclist">{window.VELA.COMMON_DOCS.map((d) => <option key={d} value={d} />)}</datalist>
              <button className="btn btn-primary" onClick={() => addDoc(adding)}><Icon name="plus" size={14} /> Add</button>
            </div>

            {suggestions.length > 0 && (
              <div>
                <div className="label-cap" style={{ marginBottom: 8 }}>Quick add</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {suggestions.slice(0, 12).map((d) => (
                    <button key={d} onClick={() => addDoc(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>
            )}
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 24px", borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-gold" disabled={!canSave} style={{ opacity: canSave ? 1 : 0.45, cursor: canSave ? "pointer" : "not-allowed" }}
              onClick={() => canSave && onSave({ key: template ? template.key : null, label: label.trim(), en: en.trim() || "—", desc: desc.trim() || "Custom template.", docs })}>
              <Icon name="check" size={15} stroke={2.4} /> {isNew ? "Create template" : "Save changes"}
            </button>
          </div>
        </div>
      </div>
    );
  }

  function iconBtn(disabled, danger) {
    return { width: 28, height: 28, borderRadius: 6, border: "1px solid var(--line)", background: "var(--surface)", color: danger ? "var(--red)" : "var(--ink-3)", display: "flex", alignItems: "center", justifyContent: "center", cursor: disabled ? "default" : "pointer", opacity: disabled ? 0.35 : 1 };
  }

  window.Templates = Templates;
  window.TemplateEditor = TemplateEditor;
})();
