/* =====================================================================
   PagePedidos.jsx (PgPed) — Listado de pedidos
   Render function: recibe app con state/setters/helpers de App
   ===================================================================== */

function PgPed(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 sP = search.trim().toLowerCase();
    const matchP = p => {
      if (!sP) return true;
      const hay = [p.numero, p.nombrePed, p.cotNum, p.clienteNombre, p.estado, p.ocCliente, p.responsable, p.dirEntrega, p.tipoNegocio].filter(Boolean).join(" ").toLowerCase();
      return hay.includes(sP);
    };
    const pedsBase = D.pedidos.filter(matchP);
    const peds = filtroEst === "todos" ? pedsBase : pedsBase.filter(p => p.estado === filtroEst);
    const hoyMs = new Date().getTime();
    const conteos = ESTADOS_PED.reduce((a, e) => ({ ...a, [e]: pedsBase.filter(p => p.estado === e).length }), {});
    return (
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <h2 style={{ margin: 0, color: "#0a2540", fontFamily: "Georgia,serif" }}>Pedidos ({D.pedidos.length})</h2>
        </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 por número, cliente, OC..." 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" }}>{peds.length} de {D.pedidos.length}</span>
        </div>
        <div style={{ display: "flex", gap: 5, marginBottom: 12, flexWrap: "wrap" }}>
          <button style={{ ...S.btn2, fontWeight: filtroEst === "todos" ? 700 : 400, background: filtroEst === "todos" ? "#0a2540" : undefined, color: filtroEst === "todos" ? "#e8d5b7" : undefined }} onClick={() => setFiltroEst("todos")}>Todos ({pedsBase.length})</button>
          {ESTADOS_PED.map(e => conteos[e] > 0 && <button key={e} style={{ ...S.btn2, fontWeight: filtroEst === e ? 700 : 400, background: filtroEst === e ? "#0a2540" : undefined, color: filtroEst === e ? "#e8d5b7" : undefined }} onClick={() => setFiltroEst(e)}>{e} ({conteos[e]})</button>)}
        </div>
        {peds.length === 0 ? <div style={{ ...S.card, textAlign: "center", padding: 36, color: "#9ca3af" }}>{D.pedidos.length === 0 ? "Aprueba una cotización para generar un pedido." : "No hay pedidos con este filtro."}</div> :
          peds.map(p => {
            const vencido = p.fechaCompromiso && new Date(p.fechaCompromiso).getTime() < hoyMs && p.estado !== "Entregado" && p.estado !== "Cancelado";
            const totalUds = (p.items || []).reduce((s, it) => s + (it.cantidad || 0), 0);
            return (
              <div key={p.id} style={{ ...S.card, borderLeft: `3px solid ${vencido ? "#ef4444" : p.estado === "Entregado" ? "#22c55e" : p.estado === "En producción" ? "#3b82f6" : p.estado === "En despacho" ? "#f59e0b" : "#d1cdc4"}` }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                  <div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <h3 style={{ margin: 0, color: "#0a2540", fontSize: 14 }}>{p.nombrePed || p.numero}</h3>
                      <span style={S.badge(pedBadge(p.estado))}>{p.estado}</span>
                      {vencido && <span style={{ ...S.badge("red"), fontSize: 9 }}>VENCIDO</span>}
                    </div>
                    <div style={{ fontSize: 11, color: "#6b7280", marginTop: 2 }}>
                      COT-{p.cotNum} · {p.clienteNombre} · {p.fecha}
                      {p.tipoNegocio && <span style={{ marginLeft: 8, padding: "1px 6px", borderRadius: 4, fontSize: 9, background: "#ede9fe", color: "#5b21b6", fontWeight: 600 }}>{p.tipoNegocio}</span>}
                      {p.fechaCompromiso && <span style={{ marginLeft: 8, color: vencido ? "#b91c1c" : "#065f46", fontWeight: 600 }}>Entrega: {p.fechaCompromiso}</span>}
                      {p.responsable && <span style={{ marginLeft: 8 }}>Resp: {p.responsable}</span>}
                    </div>
                    {p.dirEntrega && <div style={{ fontSize: 10.5, color: "#9ca3af" }}>Entrega: {p.dirEntrega}{p.contactoRecibe ? ` · ${p.contactoRecibe} ${p.telRecibe || ""}` : ""}</div>}
                  </div>
                  <div style={{ display: "flex", gap: 4, alignItems: "flex-start" }}>
                    <button style={S.btn} onClick={() => { setEdt(p); setModal("pedido"); }}><Ic name="edit" size={12} /></button>
                    <button style={{ ...S.btn2, color: "#1e40af" }} onClick={() => openEmail("ped", p)}><Ic name="send" size={12} /></button>
                    <button style={S.btnD} onClick={() => del("pedidos", p.id)}><Ic name="trash" size={12} /></button>
                  </div>
                </div>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead><tr><th style={S.th}>Prenda</th><th style={S.th}>Cant.</th><th style={S.th}>Textil</th><th style={S.th}>Color</th><th style={S.th}>Estampados</th><th style={S.th}>Tallas</th></tr></thead>
                  <tbody>{(p.items || []).map((it, i) => (
                    <tr key={i}>
                      <td style={S.td}><strong>{it.nombreComercial || it.tipoPrenda}</strong></td>
                      <td style={S.td}>{it.cantidad}</td>
                      <td style={S.td}>{it.textilNombre || "—"}</td>
                      <td style={S.td}>{it.color || "—"}</td>
                      <td style={S.td}>{(it.estampados || []).map(e => e.tecnica).join(", ") || "—"}</td>
                      <td style={S.td}>{it.tallasDetalle ? Object.entries(it.tallasDetalle).filter(([, v]) => v > 0).map(([t, v]) => `${t}:${v}`).join(", ") || "Pendiente" : "—"}</td>
                    </tr>
                  ))}</tbody>
                </table>
                <div style={{ display: "flex", justifyContent: "flex-end", gap: 12, marginTop: 6, fontSize: 10.5, color: "#6b7280" }}>
                  <span>{(p.items || []).length} ítem(s)</span>
                  <span>{totalUds} unidades</span>
                  {p.ocCliente && <span>OC: {p.ocCliente}</span>}
                </div>
              </div>
            );
          })
        }
      </div>
    );

}

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