/* =====================================================================
   PagePlantillas.jsx (PgPl) — Plantillas de cargos comerciales
   Render function: recibe app con state/setters/helpers de App
   ===================================================================== */

function PgPl(app) {
const {
    D, setD, view, setView, modal, setModal, edt, setEdt, search, setSearch,
    cotFEstado, setCotFEstado, cotFCliente, setCotFCliente,
    catFTipo, setCatFTipo, catFTextil, setCatFTextil,
    eu, setEu, nu, setNu,
    dDesde, setDDesde, dHasta, setDHasta, filtroEst, setFiltroEst,
    editMq, setEditMq, ep, setEp, newPago, setNewPago, stab, setStab,
    saved, setSaved, ok,
    pdfCot, setPdfCot, pdfKind, setPdfKind, pdfPaperSize, setPdfPaperSize, pdfHtml,
    emailModal, setEmailModal, session, setSession, loginErr, setLoginErr,
    convertCot, setConvertCot, convertTipo, setConvertTipo,
    up, filt, del, openNew, openEd, saveForm,
    cotNombre, genCotNum, nuevaCot, saveCot, cotAPedido,
    tbl, verPDF, verPedPDF, openEmail, doLogin,
    menu, menuFull,
    showBulk, setShowBulk, bulkText, setBulkText,
    showBulkIns, setShowBulkIns, bulkTextIns, setBulkTextIns,
    showBulkProv, setShowBulkProv, bulkTextProv, setBulkTextProv,
    bulkMsg, setBulkMsg,
    splitLine, doBulkImport, doBulkImportIns, doBulkImportProv,
    mc,
  } = app;


    const sPl = search.trim().toLowerCase();
    const matchPl = pl => {
      if (!sPl) return true;
      const hay = [pl.nombre, ...(pl.cargos || []).map(c => c.nombre)].filter(Boolean).join(" ").toLowerCase();
      return hay.includes(sPl);
    };
    const plantillas = (D.plantillasCargos || []).filter(matchPl);
    return (
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}><h2 style={{ margin: 0, color: "#0a2540", fontFamily: "Georgia,serif" }}>Plantillas de Cargos</h2><button style={S.btn} onClick={() => { const np = { id: nid(D.plantillasCargos), nombre: "Nueva plantilla", cargos: [] }; up("plantillasCargos", [...D.plantillasCargos, np]); setEp(np); }}><Ic name="plus" size={14} /> Nueva</button></div>
        <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 12, padding: "8px 10px", background: "#faf9f7", border: "1px solid #e5e1d8", borderRadius: 6 }}>
          <input style={{ ...S.inp, width: 260 }} placeholder="Buscar plantilla o cargo..." value={search} onChange={e => setSearch(e.target.value)} />
          {search && <button style={S.btn2} onClick={() => setSearch("")}>Limpiar</button>}
          <span style={{ marginLeft: "auto", fontSize: 11, color: "#6b7280" }}>{plantillas.length} de {(D.plantillasCargos || []).length}</span>
        </div>
        {(D.plantillasCargos || []).length > 0 && plantillas.length === 0 && <div style={{ ...S.card, textAlign: "center", padding: 36, color: "#9ca3af" }}>No hay plantillas que coincidan con la búsqueda.</div>}
        {plantillas.map(pl => (
          <div key={pl.id} style={{ ...S.card, borderLeft: ep && ep.id === pl.id ? "3px solid #0a2540" : "" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
              {ep && ep.id === pl.id ? <input style={{ ...S.inp, fontWeight: 700, fontSize: 13, width: 280 }} value={ep.nombre} onChange={e => setEp({ ...ep, nombre: e.target.value })} /> : <h4 style={{ margin: 0, color: "#0a2540", fontSize: 13 }}>{pl.nombre}</h4>}
              <div style={{ display: "flex", gap: 4 }}>
                {ep && ep.id === pl.id ? <button style={S.btnG} onClick={() => { up("plantillasCargos", D.plantillasCargos.map(p => p.id === ep.id ? ep : p)); setEp(null); }}><Ic name="check" size={12} /></button> : <button style={S.btn2} onClick={() => setEp({ ...pl })}><Ic name="edit" size={12} /></button>}
                <button style={S.btnD} onClick={() => { up("plantillasCargos", D.plantillasCargos.filter(p => p.id !== pl.id)); if (ep && ep.id === pl.id) setEp(null); }}><Ic name="trash" size={12} /></button>
              </div>
            </div>
            {ep && ep.id === pl.id ? <div>{ep.cargos.map((c, i) => <div key={i} style={{ display: "flex", gap: 6, alignItems: "center", marginBottom: 4 }}><input style={{ ...S.inp, flex: 2 }} value={c.nombre} onChange={e => { const cg = [...ep.cargos]; cg[i] = { ...cg[i], nombre: e.target.value }; setEp({ ...ep, cargos: cg }); }} placeholder="Nombre" /><select style={{ ...S.sel, flex: 1 }} value={c.modo} onChange={e => { const cg = [...ep.cargos]; cg[i] = { ...cg[i], modo: e.target.value }; setEp({ ...ep, cargos: cg }); }}><option value="porcentaje">%</option><option value="fijo">$ Fijo</option></select><input style={{ ...S.inp, flex: 1 }} type="number" value={c.valor} onChange={e => { const cg = [...ep.cargos]; cg[i] = { ...cg[i], valor: parseFloat(e.target.value) || 0 }; setEp({ ...ep, cargos: cg }); }} /><button style={S.btnD} onClick={() => setEp({ ...ep, cargos: ep.cargos.filter((_, j) => j !== i) })}>✕</button></div>)}<button style={S.btn2} onClick={() => setEp({ ...ep, cargos: [...ep.cargos, { nombre: "", modo: "porcentaje", valor: 0 }] })}><Ic name="plus" size={11} /> Cargo</button></div> : <div style={{ fontSize: 11, color: "#6b7280" }}>{pl.cargos.length === 0 ? "Sin cargos" : pl.cargos.map(c => `${c.nombre}: ${c.modo === "porcentaje" ? c.valor + "%" : fmt(c.valor)}`).join(" · ")}</div>}
          </div>))}
        <div style={{ ...S.card, background: "#faf9f7" }}>
          <h4 style={{ margin: "0 0 6px", fontSize: 11, color: "#0a2540" }}>Métodos de Pago</h4>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {(D.metodosPago || []).map((m, i) => <div key={i} style={{ display: "flex", alignItems: "center", gap: 3, background: "#fff", border: "1px solid #d1cdc4", borderRadius: 5, padding: "3px 8px", fontSize: 11 }}>{m}<button style={{ background: "none", border: "none", cursor: "pointer", color: "#b91c1c", fontSize: 13, padding: 0 }} onClick={() => up("metodosPago", D.metodosPago.filter((_, j) => j !== i))}>✕</button></div>)}
            <button style={S.btn2} onClick={() => { const v = newPago.trim(); if (v) { up("metodosPago", [...(D.metodosPago || []), v]); setNewPago(""); } }}><Ic name="plus" size={11} /> Agregar</button>
            <input style={{ ...S.inp, width: 180 }} value={newPago} onChange={e => setNewPago(e.target.value)} placeholder="Nuevo método de pago" onKeyDown={e => { if (e.key === "Enter" && newPago.trim()) { up("metodosPago", [...(D.metodosPago || []), newPago.trim()]); setNewPago(""); } }} />
          </div>
        </div>
      </div>
    );

}

// ── Exports a global scope (Babel standalone aisla cada <script>) ──
window.PgPl        = PgPl;
