/* =====================================================================
   PageCotizaciones.jsx (PgCot) — Listado de cotizaciones con filtros
   Render function: recibe app con state/setters/helpers de App
   ===================================================================== */

function PgCot(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,
    genCotNum, nuevaCot, saveCot, cotAPedido,
    tbl, verPDF, verPedPDF, openEmail, doLogin,
    puede, nivelLabel, nivelColor,
    menu, menuFull,
    showBulk, setShowBulk, bulkText, setBulkText,
    showBulkIns, setShowBulkIns, bulkTextIns, setBulkTextIns,
    showBulkProv, setShowBulkProv, bulkTextProv, setBulkTextProv,
    bulkMsg, setBulkMsg,
    splitLine, doBulkImport, doBulkImportIns, doBulkImportProv,
    mc,
  } = app;


    const cotNombre = c => c.clienteNombre || (D.clientes.find(x => x.id === c.clienteId) || {}).razon || "Sin cliente";
    const allClients = Array.from(new Set(D.cotizaciones.map(cotNombre))).sort();
    const s = search.trim().toLowerCase();
    const filtered = D.cotizaciones.filter(c => {
      if (cotFEstado && c.estado !== cotFEstado) return false;
      if (cotFCliente && cotNombre(c) !== cotFCliente) return false;
      if (s) {
        const hay = [c.numero, c.nombreCot, cotNombre(c), c.proyecto, c.estado, c.comercial].filter(Boolean).join(" ").toLowerCase();
        if (!hay.includes(s)) return false;
      }
      return true;
    });
    const grouped = {};
    filtered.forEach(c => {
      const cName = cotNombre(c);
      if (!grouped[cName]) grouped[cName] = [];
      grouped[cName].push(c);
    });
    const clients = Object.keys(grouped).sort();
    const filtersActive = !!(s || cotFEstado || cotFCliente);
    return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}><h2 style={{ margin: 0, color: "#0a2540", fontFamily: "Georgia,serif" }}>Cotizaciones</h2><button style={S.btn} onClick={nuevaCot}><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: 220 }} placeholder="Buscar por número, nombre, proyecto..." value={search} onChange={e => setSearch(e.target.value)} />
        <select style={{ ...S.sel, width: 160 }} value={cotFEstado} onChange={e => setCotFEstado(e.target.value)}>
          <option value="">Todos los estados</option>
          {ESTADOS_COT.map(e => <option key={e} value={e}>{e}</option>)}
        </select>
        <select style={{ ...S.sel, width: 200 }} value={cotFCliente} onChange={e => setCotFCliente(e.target.value)}>
          <option value="">Todos los clientes</option>
          {allClients.map(n => <option key={n} value={n}>{n}</option>)}
        </select>
        {filtersActive && <button style={S.btn2} onClick={() => { setSearch(""); setCotFEstado(""); setCotFCliente(""); }}>Limpiar</button>}
        <span style={{ marginLeft: "auto", fontSize: 11, color: "#6b7280" }}>{filtered.length} de {D.cotizaciones.length}</span>
      </div>
      {D.cotizaciones.length === 0 ? <div style={{ ...S.card, textAlign: "center", padding: 36, color: "#9ca3af" }}>Crea tu primera cotización.</div> :
        filtered.length === 0 ? <div style={{ ...S.card, textAlign: "center", padding: 36, color: "#9ca3af" }}>No hay cotizaciones que coincidan con los filtros.</div> :
        clients.map(cName => (
          <div key={cName} style={{ marginBottom: 16 }}>
            <h3 style={{ margin: "0 0 6px", fontSize: 13, color: "#0a2540", borderBottom: "1px solid #e5e1d8", paddingBottom: 4 }}>{cName} ({grouped[cName].length})</h3>
            <div style={S.card}>{tbl([{ l: "#" }, { l: "Nombre" }, { l: "Ítems" }, { l: "Subtotal", a: "right" }, { l: "Estado" }],
              grouped[cName].map(c => {
                const tots = (() => { const r = (c.items || []).reduce((a, it) => { const rc = motorCosteo(it, D.insumos); a.sub += rc._netoSinIVA * it.cantidad; return a; }, { sub: 0, iva: 0, total: 0 }); r.iva = Math.round(r.sub * 0.19); r.total = r.sub + r.iva; return r; })();
                const col = c.estado === "Pedido realizado" ? "green" : c.estado === "Aprobada" ? "green" : c.estado === "No aprobada" ? "red" : c.estado === "Enviada" ? "blue" : "gray";
                return (
                  <tr key={c.id}>
                    <td style={S.td}><strong>{c.numero}</strong><br /><span style={{ fontSize: 10, color: "#9ca3af" }}>{c.fecha}</span></td>
                    <td style={S.td}><strong style={{ color: "#0a2540" }}>{c.nombreCot || "—"}</strong>{c.proyecto && <div style={{ fontSize: 10, color: "#9ca3af" }}>{c.proyecto}</div>}</td>
                    <td style={S.td}>{(c.items || []).length}</td>
                    <td style={{ ...S.td, textAlign: "right" }}><div style={{ fontWeight: 600 }}>{fmt(tots.sub)}</div><div style={{ fontSize: 9, color: "#9ca3af" }}>+IVA {fmt(tots.total)}</div></td>
                    <td style={S.td}><span style={S.badge(col)}>{c.estado}</span>{c.estado === "No aprobada" && c.razonNo && <div style={{ fontSize: 10, color: "#b91c1c" }}>{c.razonNo}</div>}</td>
                    <td style={S.td}><div style={{ display: "flex", gap: 3, flexWrap: "wrap" }}>
                      <button style={S.btn2} onClick={() => { setEdt(c); setModal("cotizador"); }}><Ic name="edit" size={12} /></button>
                      <button style={S.btn2} onClick={() => verPDF(c)}><Ic name="download" size={12} /></button>
                      <button style={{ ...S.btn2, color: "#1e40af" }} onClick={() => openEmail("cot", c)} title="Enviar por correo"><Ic name="send" size={12} /></button>
                      {!["Aprobada", "Pedido realizado"].includes(c.estado) && <button style={S.btnG} onClick={() => { setConvertCot(c); setConvertTipo(TIPOS_NEGOCIO[0]); }}><Ic name="check" size={12} /></button>}
                      <button style={S.btnD} onClick={() => del("cotizaciones", c.id)}><Ic name="trash" size={12} /></button>
                    </div></td>
                  </tr>);
              }), true)}</div>
          </div>
        ))
      }
    </div>);

}

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