/* =====================================================================
   PageMaquila.jsx (PgMaquila) — Gestion de servicios de maquila (Trazo, Corte, Confeccion)
   Render function: recibe app con state/setters/helpers de App
   ===================================================================== */

function PgMaquila(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 provNames = (D.proveedores || []).map(p => p.nombre);
    const prendaNames = (D.tiposPrenda || []).map(p => p.nombre);
    const tiposMaq = ["Trazo", "Corte", "Confección"];
    const sMq = search.trim().toLowerCase();
    const matchMq = m => {
      if (!sMq) return true;
      const hay = [m.proveedor, m.tipo, m.obs, m.estado].filter(Boolean).join(" ").toLowerCase();
      return hay.includes(sMq);
    };
    const totalMq = (D.maquila || []).length;
    const visibleMq = (D.maquila || []).filter(matchMq).length;

    const newMaq = (tipo) => {
      const base = { id: nid(D.maquila || []), tipo, proveedor: "", obs: "", estado: "Activo" };
      if (tipo === "Trazo") base.precioMetro = 0;
      else if (tipo === "Corte") base.escalas = [{ desde: 1, hasta: 100, precio: 0 }];
      else if (tipo === "Confección") base.precios = prendaNames.map(p => ({ prenda: p, precio: 0 }));
      up("maquila", [...(D.maquila || []), base]);
      setEditMq(base);
    };

    return (
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <h2 style={{ margin: 0, color: "#0a2540", fontFamily: "Georgia,serif", fontSize: 18 }}>Servicios de Maquila</h2>
          <div style={{ display: "flex", gap: 4 }}>
            {tiposMaq.map(t => <button key={t} style={S.btn} onClick={() => newMaq(t)}><Ic name="plus" size={13} /> {t}</button>)}
          </div>
        </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 proveedor, tipo..." 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" }}>{visibleMq} de {totalMq}</span>
        </div>
        {totalMq > 0 && visibleMq === 0 && <div style={{ ...S.card, textAlign: "center", padding: 36, color: "#9ca3af" }}>No hay servicios que coincidan con la búsqueda.</div>}
        {tiposMaq.map(tipo => {
          const items = (D.maquila || []).filter(m => m.tipo === tipo).filter(matchMq);
          if (items.length === 0) return null;
          return (
            <div key={tipo}>
              <h3 style={{ margin: "14px 0 8px", color: "#0a2540", fontSize: 14, borderBottom: "1px solid #e5e1d8", paddingBottom: 4 }}>{tipo}</h3>
              {items.map(mq => {
                const isE = editMq && editMq.id === mq.id;
                const m = isE ? editMq : mq;
                return (
                  <div key={mq.id} style={{ ...S.card, borderLeft: isE ? "3px solid #0a2540" : "" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                      {isE ? (
                        <div style={{ ...S.g2, flex: 1, marginRight: 10 }}>
                          <F l="Proveedor"><select style={S.sel} value={m.proveedor} onChange={e => setEditMq({ ...m, proveedor: e.target.value })}><option value="">—</option>{provNames.map(p => <option key={p}>{p}</option>)}</select></F>
                          <F l="Estado"><select style={S.sel} value={m.estado} onChange={e => setEditMq({ ...m, estado: e.target.value })}><option>Activo</option><option>Inactivo</option></select></F>
                        </div>
                      ) : (
                        <div><strong>{mq.proveedor || "Sin proveedor"}</strong> <span style={S.badge(mq.estado === "Activo" ? "green" : "red")}>{mq.estado}</span></div>
                      )}
                      <div style={{ display: "flex", gap: 4 }}>
                        {isE ? <button style={S.btnG} onClick={() => { up("maquila", D.maquila.map(x => x.id === m.id ? m : x)); setEditMq(null); }}><Ic name="check" size={12} /></button> : <button style={S.btn2} onClick={() => setEditMq({ ...mq, escalas: mq.escalas ? [...mq.escalas] : undefined, precios: mq.precios ? mq.precios.map(p => ({ ...p })) : undefined })}><Ic name="edit" size={12} /></button>}
                        <button style={S.btnD} onClick={() => { up("maquila", D.maquila.filter(x => x.id !== mq.id)); if (isE) setEditMq(null); }}><Ic name="trash" size={12} /></button>
                      </div>
                    </div>

                    {/* Trazo: precio por metro */}
                    {tipo === "Trazo" && (
                      isE ? <F l="Precio por metro"><input style={S.inp} type="number" value={m.precioMetro || 0} onChange={e => setEditMq({ ...m, precioMetro: parseFloat(e.target.value) || 0 })} /></F>
                        : <div style={{ fontSize: 12 }}>Precio: <strong>{fmt(mq.precioMetro)}/metro</strong></div>
                    )}

                    {/* Corte: escalas por cantidad */}
                    {tipo === "Corte" && (<>
                      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                        <thead><tr><th style={S.th}>Desde</th><th style={S.th}>Hasta</th><th style={{ ...S.th, textAlign: "right" }}>$/ud</th>{isE && <th style={S.th}></th>}</tr></thead>
                        <tbody>{(m.escalas || []).map((esc, ei) => (
                          <tr key={ei}>{isE ? (<>
                            <td style={S.td}><input style={S.inp} type="number" value={esc.desde} onChange={e => { const es = [...m.escalas]; es[ei] = { ...es[ei], desde: parseInt(e.target.value) || 0 }; setEditMq({ ...m, escalas: es }); }} /></td>
                            <td style={S.td}><input style={S.inp} type="number" value={esc.hasta} onChange={e => { const es = [...m.escalas]; es[ei] = { ...es[ei], hasta: parseInt(e.target.value) || 0 }; setEditMq({ ...m, escalas: es }); }} /></td>
                            <td style={S.td}><input style={S.inp} type="number" value={esc.precio} onChange={e => { const es = [...m.escalas]; es[ei] = { ...es[ei], precio: parseFloat(e.target.value) || 0 }; setEditMq({ ...m, escalas: es }); }} /></td>
                            <td style={S.td}><button style={{ ...S.btnD, padding: "1px 6px" }} onClick={() => setEditMq({ ...m, escalas: m.escalas.filter((_, j) => j !== ei) })}>✕</button></td>
                          </>) : (<>
                            <td style={S.td}>{fmtN(esc.desde)}</td><td style={S.td}>{fmtN(esc.hasta)}</td><td style={{ ...S.td, textAlign: "right", fontWeight: 600 }}>{fmt(esc.precio)}</td>
                          </>)}</tr>
                        ))}</tbody>
                      </table>
                      {isE && <button style={{ ...S.btn2, marginTop: 4 }} onClick={() => setEditMq({ ...m, escalas: [...m.escalas, { desde: (m.escalas.length > 0 ? m.escalas[m.escalas.length - 1].hasta + 1 : 1), hasta: 9999, precio: 0 }] })}><Ic name="plus" size={11} /> Escala</button>}
                    </>)}

                    {/* Confección: precio por tipo de prenda */}
                    {tipo === "Confección" && (<>
                      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                        <thead><tr><th style={S.th}>Tipo de Prenda</th><th style={{ ...S.th, textAlign: "right" }}>Precio/ud</th></tr></thead>
                        <tbody>{(m.precios || []).map((pr, pi) => (
                          <tr key={pi}>
                            <td style={S.td}>{pr.prenda}</td>
                            <td style={S.td}>{isE ? <input style={{ ...S.inp, textAlign: "right" }} type="number" value={pr.precio} onChange={e => { const ps = m.precios.map((p, j) => j === pi ? { ...p, precio: parseFloat(e.target.value) || 0 } : p); setEditMq({ ...m, precios: ps }); }} /> : <strong style={{ float: "right" }}>{fmt(pr.precio)}</strong>}</td>
                          </tr>
                        ))}</tbody>
                      </table>
                      {isE && <div style={{ display: "flex", gap: 4, marginTop: 4 }}><select style={{ ...S.sel, width: "auto" }} value="" onChange={e => { if (e.target.value) setEditMq({ ...m, precios: [...m.precios, { prenda: e.target.value, precio: 0 }] }); e.target.value = ""; }}><option value="">+ Agregar prenda...</option>{(D.tiposPrenda || []).filter(tp => !(m.precios || []).some(pr => pr.prenda === tp.nombre)).map(tp => <option key={tp.id} value={tp.nombre}>{tp.nombre}</option>)}</select></div>}
                    </>)}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    );

}

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