/* =====================================================================
   ModalCotizacion (MCot) — Edicion de Cotizacion
   Recibe via props: edt, setD, setModal, setSaved, D, saveCot,
   genCotNum, verPDF, openEmail
   ===================================================================== */

const MCot = ({ edt, setD, setModal, setSaved, D, saveCot, genCotNum, verPDF, openEmail }) => {
  const [c, setC] = useState(edt);
  const [itab, setItab] = useState(0);
  const [qa, setQa] = useState(null);
  const [showImport, setShowImport] = useState(null); // "catalogo" | "cotizacion" | null
  const u = (k, v) => setC(x => ({ ...x, [k]: v }));

  const getTecs = () => (D.tecnicas || []).filter(t => t.estado === "Activo");
  const getTecInfo = n => (D.tecnicas || []).find(x => x.nombre === n) || {};

  // ─── Import from catalog or previous cotización ───
  const addFromCatalog = (prod) => {
    setC(prev => {
      const items = [...(prev.items || []), { ...prod, _id: uid(), cantidad: 1 }];
      setItab(items.length - 1); setShowImport(null);
      return { ...prev, items };
    });
  };
  const addFromCot = (cotId, itemIdx) => {
    const cot = D.cotizaciones.find(x => x.id === cotId);
    if (!cot || !cot.items[itemIdx]) return;
    const src = cot.items[itemIdx];
    setC(prev => {
      const items = [...(prev.items || []), { ...src, _id: uid(), cantidad: src.cantidad }];
      setItab(items.length - 1); setShowImport(null);
      return { ...prev, items };
    });
  };
  const saveToCatalog = (idx) => {
    const it = c.items[idx];
    const { _id, cantidad, ...rest } = it;
    const prod = { ...rest, id: nid(D.catalogo || []) };
    setD(d => ({ ...d, catalogo: [...(d.catalogo || []), prod] }));
    setSaved("✓ Guardado en catálogo"); setTimeout(() => setSaved(""), 3000);
  };

  // ─── Quick-add helpers ───
  const qaCliente = () => setQa({ type: "cliente", data: { razon: "", nit: "", contacto: "", correo: "", tel: "", ciudad: "Cali" } });
  const qaSaveCliente = () => { const cl = { ...qa.data, id: nid(D.clientes), tipo: "Empresa", comercial: qa.data.razon, dir: "", dirFactura: "", dirEntrega: "", condiciones: "", obs: "", estado: "Activo" }; const num = genCotNum(cl.id, cl.razon); setQa(null); setD(d => ({ ...d, clientes: [...d.clientes, cl] })); setC(prev => ({ ...prev, clienteId: cl.id, clienteNombre: cl.razon, numero: num })); };
  const qaPrenda = () => setQa({ type: "prenda", data: { nombre: "", consumoDefault: 0.65 } });
  const qaSavePrenda = (idx) => { const tp = { id: nid(D.tiposPrenda), codigo: "TP-" + String(D.tiposPrenda.length + 1).padStart(3, "0"), nombre: qa.data.nombre, cat: "Superior", desc: "", consumoDefault: qa.data.consumoDefault, insumosDefault: [], procesosDefault: { corte: 1500, confeccion: 6500, empaque: 800 }, estado: "Activo" }; setQa(null); setD(d => ({ ...d, tiposPrenda: [...d.tiposPrenda, tp] })); if (idx !== undefined) urc(idx, { tipoPrenda: tp.nombre, consumoTextil: tp.consumoDefault }); };
  const qaTextil = () => setQa({ type: "textil", data: { nombre: "", precio: 0, proveedor: "" } });
  const qaSaveTextil = (idx) => { const tx = { id: nid(D.textiles), codigo: "TX-" + String(D.textiles.length + 1).padStart(3, "0"), nombre: qa.data.nombre, proveedor: qa.data.proveedor, precio: qa.data.precio, composicion: "", gramaje: 0, ancho: 150, unidad: "Metro", iva: 19, dctoPP: 0, dctoVol: 0, volMin: 0, diasAbast: 5, colores: "", ref: "", obs: "", estado: "Activo" }; setQa(null); setD(d => ({ ...d, textiles: [...d.textiles, tx] })); if (idx !== undefined) urc(idx, { textilId: tx.id, textilNombre: tx.nombre, precioTextil: tx.precio, dctoTextil: 0 }); };
  const qaMaquila = () => setQa({ type: "maquila", data: { tipo: "Trazo", proveedor: "", precioMetro: 0 } });
  const qaSaveMaquila = () => { const mq = { id: nid(D.maquila || []), tipo: qa.data.tipo, proveedor: qa.data.proveedor, precioMetro: qa.data.precioMetro || 0, escalas: qa.data.tipo === "Corte" ? [{ desde: 1, hasta: 9999, precio: 0 }] : undefined, precios: qa.data.tipo === "Confección" ? [] : undefined, obs: "", estado: "Activo" }; setQa(null); setD(d => ({ ...d, maquila: [...(d.maquila || []), mq] })); };

  // Constructor de ítems
  const addItem = () => {
    setC(prev => {
      const newItem = { _id: uid(), tipoPrenda: "", nombreComercial: "", desc: "", cantidad: 1, textilId: null, textilNombre: "", consumoTextil: 0.65, precioTextil: 0, dctoTextil: 0, insumosItems: [], estampados: [], costoCorte: 1500, costoConfeccion: 6500, costoEmpaque: 800, costoOtros: 0, margenBruto: prev.margenGlobal || 35, ivaRate: 19, cargos: [], empaque: "Individual" };
      const items = [...(prev.items || []), newItem];
      setItab(items.length - 1);
      return { ...prev, items };
    });
  };
  const urc = (idx, ch) => { setC(prev => { const items = [...prev.items]; items[idx] = motorCosteo({ ...items[idx], ...ch }, D.insumos); return { ...prev, items }; }); };
  const selTipo = (idx, nombre) => {
    const tp = D.tiposPrenda.find(x => x.nombre === nombre);
    if (tp) urc(idx, { tipoPrenda: nombre, consumoTextil: tp.consumoDefault || 0.65, insumosItems: (tp.insumosDefault || []).map(id => ({ id, qty: 1 })), costoCorte: (tp.procesosDefault || {}).corte || 1500, costoConfeccion: (tp.procesosDefault || {}).confeccion || 6500, costoEmpaque: (tp.procesosDefault || {}).empaque || 800 });
    else urc(idx, { tipoPrenda: nombre });
  };
  const selTex = (idx, tid) => { const t = D.textiles.find(x => x.id === tid); if (t) urc(idx, { textilId: t.id, textilNombre: t.nombre, precioTextil: t.precio, dctoTextil: t.dctoPP }); };
  const addEst = idx => { const tecs = getTecs(); const f = tecs[0] || { nombre: "DTF", costoBase: 35, unidadCobro: "cm²", proveedor: "" }; const est = [...(c.items[idx].estampados || []), { _id: uid(), tecnica: f.nombre, unidadCobro: f.unidadCobro || "cm²", costoUnitario: f.costoBase || 0, proveedor: f.proveedor || "", anchoCm: f.unidadCobro === "cm²" ? 10 : 0, altoCm: f.unidadCobro === "cm²" ? 10 : 0, metros: 0, cantidadUds: 1, puntadasMiles: 0, pliegos: 1, ubicacion: "Frente" }]; urc(idx, { estampados: est }); };
  const rmEst = (ii, ei) => urc(ii, { estampados: c.items[ii].estampados.filter((_, i) => i !== ei) });
  const upEst = (ii, ei, ch) => { const est = [...c.items[ii].estampados]; est[ei] = { ...est[ei], ...ch }; if (ch.tecnica) { const ti = getTecInfo(ch.tecnica); est[ei].unidadCobro = ti.unidadCobro || est[ei].unidadCobro; est[ei].costoUnitario = ti.costoBase || est[ei].costoUnitario; est[ei].proveedor = ti.proveedor || est[ei].proveedor; if ((ti.unidadCobro || "").toLowerCase() === "metro") { est[ei].metros = c.items[ii].consumoTextil || 0; } } urc(ii, { estampados: est }); };
  const rmItem = idx => { setC(prev => { const items = prev.items.filter((_, i) => i !== idx); if (itab >= items.length) setItab(Math.max(0, items.length - 1)); return { ...prev, items }; }); };
  const dupItem = idx => { setC(prev => { const src = prev.items[idx]; const items = [...prev.items, { ...src, _id: uid(), estampados: (src.estampados || []).map(e => ({ ...e, _id: uid() })), cargos: (src.cargos || []).map(x => ({ ...x })) }]; setItab(items.length - 1); return { ...prev, items }; }); };
  const addCargo = idx => urc(idx, { cargos: [...(c.items[idx].cargos || []), { nombre: "", modo: "porcentaje", valor: 0 }] });
  const rmCargo = (ii, ci) => urc(ii, { cargos: c.items[ii].cargos.filter((_, i) => i !== ci) });
  const upCargo = (ii, ci, ch) => { const cg = [...c.items[ii].cargos]; cg[ci] = { ...cg[ci], ...ch }; urc(ii, { cargos: cg }); };
  const applyPl = (idx, plId) => { const pl = D.plantillasCargos.find(p => p.id === plId); if (pl) urc(idx, { cargos: pl.cargos.map(x => ({ ...x })) }); };

  const ci = c.items && c.items[itab];
  const tots = (() => { const r = (c.items || []).reduce((a, it) => { const rc = motorCosteo(it, D.insumos); a.n += rc._netoSinIVA * it.cantidad; a.u += rc._utilidad * it.cantidad; return a; }, { n: 0, i: 0, f: 0, u: 0 }); r.i = Math.round(r.n * 0.19); r.f = r.n + r.i; return r; })();

  return (
    <div style={S.modal} onMouseDown={e => { if (e.target === e.currentTarget) saveCot(c); }}>
      <div style={{ ...S.mc, maxWidth: 1100, width: "96%" }} onMouseDown={e => e.stopPropagation()} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 10, color: "#9ca3af", marginBottom: 2 }}>Nombre de la cotización (editable)</div>
            <input style={{ ...S.inp, fontWeight: 700, fontSize: 15, width: 380, background: "#faf9f7", padding: "4px 8px", color: "#0a2540" }} value={c.nombreCot || ""} onChange={e => u("nombreCot", e.target.value)} placeholder="Escribe un nombre para esta cotización..." />
            <div style={{ fontSize: 10.5, color: "#9ca3af", marginTop: 2 }}>COT-{c.numero}</div>
          </div>
          <div style={{ display: "flex", gap: 6 }}><button style={S.btn2} onClick={() => verPDF(c)}><Ic name="download" size={13} /> PDF</button><button style={{ ...S.btn2, color: "#1e40af" }} onClick={() => openEmail("cot", c)}><Ic name="send" size={13} /> Correo</button><button style={S.btn} onClick={() => saveCot(c)}><Ic name="check" size={13} /> Guardar</button></div>
        </div>
        {/* C.1 Encabezado */}
        <div style={{ ...S.card, background: "#faf9f7" }}>
          <div style={S.g4}>
            <F l="Fecha"><input style={S.inp} type="date" value={c.fecha} onChange={e => u("fecha", e.target.value)} /></F>
            <F l="Vigencia"><input style={S.inp} value={c.vigencia} onChange={e => u("vigencia", e.target.value)} /></F>
            <F l="Comercial"><input style={S.inp} value={c.comercial} onChange={e => u("comercial", e.target.value)} /></F>
            <F l="Estado"><select style={S.sel} value={c.estado} onChange={e => u("estado", e.target.value)}>{ESTADOS_COT.map(e => <option key={e}>{e}</option>)}</select></F>
          </div>
          {c.estado === "No aprobada" && <div style={{ marginTop: 7, display: "flex", flexWrap: "wrap", gap: 4 }}><span style={{ ...S.lb, marginBottom: 0, marginRight: 4 }}>Razón:</span>{RAZONES_NO.map(r => <button key={r} style={{ ...S.btn2, fontSize: 10.5, padding: "3px 8px", ...(c.razonNo === r ? { background: "#fee2e2", borderColor: "#fca5a5", color: "#991b1b" } : {}) }} onClick={() => u("razonNo", r)}>{r}</button>)}</div>}
          <div style={{ ...S.g3, marginTop: 7 }}>
            <F l="Cliente">
              <div style={{ position: "relative" }}>
                <input style={S.inp} placeholder="Buscar cliente..." value={c._clienteSearch !== undefined ? c._clienteSearch : (D.clientes.find(x => x.id === c.clienteId)?.razon || c.clienteNombre || "")}
                  onChange={e => { u("_clienteSearch", e.target.value); }}
                  onFocus={e => { if (!c._clienteSearch && c._clienteSearch !== "") u("_clienteSearch", ""); }}
                  onBlur={() => { setTimeout(() => u("_clienteSearch", undefined), 200); }}
                />
                {c._clienteSearch !== undefined && (() => {
                  const q = (c._clienteSearch || "").toLowerCase();
                  const matches = D.clientes.filter(x => !q || x.razon.toLowerCase().includes(q) || (x.comercial||"").toLowerCase().includes(q) || (x.nit||"").toLowerCase().includes(q)).slice(0, 12);
                  return (
                    <div style={{ position: "absolute", top: "100%", left: 0, right: 0, background: "#fff", border: "1px solid #d1cdc4", borderRadius: "0 0 5px 5px", maxHeight: 200, overflowY: "auto", zIndex: 50, boxShadow: "0 4px 12px rgba(0,0,0,0.12)" }}>
                      {matches.map(x => <div key={x.id} style={{ padding: "6px 9px", fontSize: 12, cursor: "pointer", borderBottom: "1px solid #f0ece4" }}
                        onMouseDown={() => { const num = genCotNum(x.id, x.razon); u("clienteId", x.id); u("clienteNombre", x.razon); u("numero", num); u("_clienteSearch", undefined); }}>
                        <strong>{x.razon}</strong>{x.comercial ? <span style={{ color: "#9ca3af" }}> · {x.comercial}</span> : ""}{x.nit ? <span style={{ color: "#9ca3af" }}> · {x.nit}</span> : ""}
                      </div>)}
                      <div style={{ padding: "6px 9px", fontSize: 11, cursor: "pointer", color: "#1e40af", fontWeight: 600, background: "#f0f9ff" }}
                        onMouseDown={() => { qaCliente(); u("_clienteSearch", undefined); }}>
                        + Nuevo Cliente...
                      </div>
                    </div>
                  );
                })()}
              </div>
            </F>
            <F l="Proyecto"><input style={S.inp} value={c.proyecto} onChange={e => u("proyecto", e.target.value)} /></F>
            <F l="Margen bruto global %"><input style={S.inp} type="number" value={c.margenGlobal} onChange={e => u("margenGlobal", parseFloat(e.target.value) || 0)} /></F>
          </div>
          <div style={{ ...S.g4, marginTop: 7 }}>
            <F l="Flete"><select style={S.sel} value={c.flete} onChange={e => u("flete", e.target.value)}><option>No incluido</option><option>Incluido</option></select></F>
            <F l="Método pago"><select style={S.sel} value={c.metodoPago} onChange={e => u("metodoPago", e.target.value)}><option value="">—</option>{(D.metodosPago || []).map(m => <option key={m}>{m}</option>)}</select></F>
            <F l="Días entrega"><select style={S.sel} value={c.diasEntrega} onChange={e => u("diasEntrega", parseInt(e.target.value))}>{DIAS_ENT.map(d => <option key={d} value={d}>{d} días</option>)}</select></F>
            <F l="Garantía"><select style={S.sel} value={c.garantiaMeses} onChange={e => u("garantiaMeses", parseInt(e.target.value))}>{GARANTIA.map(m => <option key={m} value={m}>{m} mes(es)</option>)}</select></F>
          </div>
          <div style={{ ...S.g2, marginTop: 7 }}>
            <F l="Obs. interna"><textarea style={{ ...S.inp, minHeight: 28 }} value={c.obsInt} onChange={e => u("obsInt", e.target.value)} /></F>
            <F l="Obs. externa (PDF)"><textarea style={{ ...S.inp, minHeight: 28 }} value={c.obsExt} onChange={e => u("obsExt", e.target.value)} /></F>
          </div>
        </div>

        {/* C.2 Constructor ítems */}
        <div style={S.card}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <h4 style={{ margin: 0, fontSize: 11, textTransform: "uppercase", letterSpacing: 1, color: "#0a2540" }}>Constructor de Ítems</h4>
            <div style={{ display: "flex", gap: 4 }}>
              <button style={S.btn} onClick={addItem}><Ic name="plus" size={13} /> Nuevo</button>
              <button style={S.btn2} onClick={() => setShowImport(showImport === "catalogo" ? null : "catalogo")}>Catálogo</button>
              <button style={S.btn2} onClick={() => setShowImport(showImport === "cotizacion" ? null : "cotizacion")}>Desde Cotización</button>
            </div>
          </div>
          {/* Import panels */}
          {showImport === "catalogo" && (
            <div style={{ background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 7, padding: 10, marginBottom: 8 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "#065f46", marginBottom: 6 }}>Seleccionar producto del catálogo</div>
              {(D.catalogo || []).length === 0 ? <p style={{ fontSize: 11, color: "#9ca3af" }}>Catálogo vacío. Guarda ítems desde el cotizador.</p> :
                (D.catalogo || []).map(p => <div key={p.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "4px 0", borderBottom: "1px solid #d1fae5", fontSize: 11 }}><span><strong>{p.nombreComercial || p.tipoPrenda}</strong> — {p.textilNombre || "—"} · {(p.estampados || []).length} est.</span><button style={S.btn2} onClick={() => addFromCatalog(p)}>Agregar</button></div>)
              }
            </div>
          )}
          {showImport === "cotizacion" && (
            <div style={{ background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 7, padding: 10, marginBottom: 8, maxHeight: 250, overflow: "auto" }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "#1e40af", marginBottom: 6 }}>Importar ítem desde cotización anterior</div>
              {D.cotizaciones.filter(ct => ct.id !== c.id && (ct.items || []).length > 0).length === 0 ? <p style={{ fontSize: 11, color: "#9ca3af" }}>No hay cotizaciones previas con ítems.</p> :
                D.cotizaciones.filter(ct => ct.id !== c.id && (ct.items || []).length > 0).map(ct => (
                  <div key={ct.id} style={{ marginBottom: 6 }}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: "#1e40af" }}>{ct.numero} — {ct.clienteNombre || "—"} ({ct.fecha})</div>
                    {ct.items.map((it, ii) => <div key={ii} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "2px 0 2px 10px", fontSize: 11 }}><span>{it.nombreComercial || it.tipoPrenda} · {it.cantidad}ud · {it.textilNombre || "—"}</span><button style={S.btn2} onClick={() => addFromCot(ct.id, ii)}>Importar</button></div>)}
                  </div>
                ))
              }
            </div>
          )}
          {(c.items || []).length === 0 ? <p style={{ color: "#9ca3af", textAlign: "center", padding: 18, fontSize: 12 }}>Agrega ítems</p> : (<>
            <div style={{ ...S.tabs, flexWrap: "wrap" }}>{c.items.map((it, i) => <div key={it._id || i} style={S.tab(itab === i)} onClick={() => setItab(i)}>#{i + 1}{it.nombreComercial ? ` ${it.nombreComercial}` : ""}</div>)}</div>
            {ci && (() => { const idx = itab; const it = motorCosteo(ci, D.insumos);
              const estCost = e => { const uc = e.unidadCobro || "cm²"; if (uc === "cm²") return ((e.anchoCm || 0) * (e.altoCm || 0)) * (e.costoUnitario || 0); if (uc === "metro") return (e.metros || 0) * (e.costoUnitario || 0); if (uc === "unidad") return (e.cantidadUds || 1) * (e.costoUnitario || 0); if (uc === "puntadas(miles)") return (e.puntadasMiles || 0) * (e.costoUnitario || 0); if (uc === "pliego") return (e.pliegos || 1) * (e.costoUnitario || 0); return 0; };
              const estLabel = e => { const uc = e.unidadCobro || "cm²"; if (uc === "cm²") return `${((e.anchoCm || 0) * (e.altoCm || 0)).toFixed(1)} cm²`; if (uc === "metro") return `${e.metros || 0} m`; if (uc === "unidad") return `${e.cantidadUds || 1} ud`; if (uc === "puntadas(miles)") return `${e.puntadasMiles || 0} mil punt.`; if (uc === "pliego") return `${e.pliegos || 1} pliego(s)`; return ""; };
            return (
              <div>
                <div style={{ display: "flex", gap: 5, marginBottom: 8 }}><button style={S.btn2} onClick={() => dupItem(idx)}><Ic name="copy" size={12} /> Duplicar</button><button style={{ ...S.btn2, color: "#92400e" }} onClick={() => saveToCatalog(idx)}>★ Catálogo</button><button style={S.btnD} onClick={() => rmItem(idx)}><Ic name="trash" size={11} /></button></div>
                <div style={S.g3}>
                  <F l="Tipo prenda"><SearchSel placeholder="Buscar tipo prenda..." value={it.tipoPrenda}
                    items={D.tiposPrenda.filter(x => x.estado === "Activo")}
                    labelKey="nombre"
                    renderItem={tp => <span>{tp.nombre} <span style={{color:"#9ca3af"}}>({tp.consumoDefault}m)</span></span>}
                    onChange={tp => selTipo(idx, tp.nombre)}
                    onNew={() => qaPrenda()} newLabel="Nuevo Tipo..."
                  /></F>
                  <F l="Nombre comercial"><input style={S.inp} value={it.nombreComercial} onChange={e => urc(idx, { nombreComercial: e.target.value })} /></F>
                  <F l="Cantidad"><input style={S.inp} type="number" value={it.cantidad} onChange={e => urc(idx, { cantidad: parseInt(e.target.value) || 0 })} /></F>
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 6, marginBottom: 6 }}>
                  <F l="Imagen / Mockup del producto">
                    <input type="file" accept="image/*" onChange={e => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = ev => urc(idx, { mockupImg: ev.target.result }); reader.readAsDataURL(file); }} style={{ fontSize: 11 }} />
                  </F>
                  {it.mockupImg && <div style={{ position: "relative" }}>
                    <img src={it.mockupImg} alt="Mockup" style={{ maxWidth: 180, maxHeight: 120, borderRadius: 8, border: "1px solid #e5e1d8", objectFit: "cover" }} />
                    <button style={{ position: "absolute", top: 2, right: 2, background: "#fee2e2", border: "none", borderRadius: "50%", width: 18, height: 18, fontSize: 10, cursor: "pointer", color: "#991b1b", fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }} onClick={() => urc(idx, { mockupImg: null })}>x</button>
                  </div>}
                </div>

                {/* B1: Costos directos */}
                <h5 style={S.secT}>1. Costos Directos</h5>
                <div style={S.g4}>
                  <F l="Textil"><SearchSel placeholder="Buscar textil..." value={it.textilNombre || ""}
                    items={D.textiles.filter(x => x.estado === "Activo")}
                    labelKey="nombre"
                    renderItem={t => <span>{t.nombre} <span style={{color:"#9ca3af"}}>— {fmt(t.precio)}/m</span></span>}
                    onChange={t => selTex(idx, t.id)}
                    onNew={() => qaTextil()} newLabel="Nuevo Textil..."
                  /></F>
                  <F l="Consumo (m)"><input style={S.inp} type="number" step="0.01" value={it.consumoTextil || ""} onChange={e => urc(idx, { consumoTextil: parseFloat(e.target.value) || 0 })} /></F>
                  <F l="Precio/m"><input style={S.inp} type="number" value={it.precioTextil || ""} onChange={e => urc(idx, { precioTextil: parseFloat(e.target.value) || 0 })} /></F>
                  <F l="Dcto %"><input style={S.inp} type="number" value={it.dctoTextil || ""} onChange={e => urc(idx, { dctoTextil: parseFloat(e.target.value) || 0 })} /></F>
                </div>
                <F l="Insumos"><div style={{ display: "flex", flexWrap: "wrap", gap: 3, marginTop: 3 }}>{D.insumos.map(ins => { const items = it.insumosItems || it.insumosIds || []; const entry = items.find(x => (typeof x === "object" ? x.id : x) === ins.id); const sel = !!entry; const qty = sel && typeof entry === "object" ? entry.qty : 1; return <div key={ins.id} style={{ display: "flex", alignItems: "center", gap: 2, padding: "2px 7px", borderRadius: 5, background: sel ? "#dbeafe" : "#f3f4f6", fontSize: 10.5 }}><input type="checkbox" checked={sel} onChange={() => { const cur = (it.insumosItems || []).filter(x => (typeof x === "object" ? x.id : x) !== ins.id); if (!sel) cur.push({ id: ins.id, qty: 1 }); urc(idx, { insumosItems: cur }); }} /><span>{ins.nombre} ({fmt(ins.costo)})</span>{sel && <input style={{ ...S.inp, width: 36, textAlign: "center", padding: "1px 2px", marginLeft: 3 }} type="number" min="1" value={qty} onChange={e => { const cur = (it.insumosItems || []).map(x => (typeof x === "object" ? x.id : x) === ins.id ? { id: ins.id, qty: parseInt(e.target.value) || 1 } : x); urc(idx, { insumosItems: cur }); }} />}</div>; })}</div></F>

                {/* Estampados */}
                <div style={{ margin: "10px 0 5px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontSize: 10.5, fontWeight: 600, color: "#6b7280" }}>ESTAMPADOS ({(it.estampados || []).length})</span>
                  <button style={S.btn2} onClick={() => addEst(idx)}><Ic name="plus" size={11} /> Agregar</button>
                </div>
                {(it.estampados || []).map((est, ei) => { const uc = est.unidadCobro || "cm²"; const cE = estCost(est); return (
                  <div key={est._id || ei} style={{ background: "#fefce8", border: "1px solid #fde68a", borderRadius: 7, padding: 9, marginBottom: 5 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 3 }}>
                      <span style={{ fontSize: 10.5, fontWeight: 700, color: "#92400e" }}>#{ei + 1} · {uc}</span>
                      <button style={{ ...S.btnD, padding: "1px 7px", fontSize: 10 }} onClick={() => rmEst(idx, ei)}>✕</button>
                    </div>
                    <div style={S.g3}>
                      <F l="Técnica"><SearchSel placeholder="Buscar técnica..." value={est.tecnica}
                        items={getTecs()} labelKey="nombre"
                        renderItem={t => <span>{t.nombre} <span style={{color:"#9ca3af"}}>{t.costoBase ? fmt(t.costoBase)+"/" + (t.unidadCobro||"ud") : ""}</span></span>}
                        onChange={t => upEst(idx, ei, { tecnica: t.nombre })}
                      /></F>
                      <F l="Proveedor"><SearchSel placeholder="Buscar proveedor..." value={est.proveedor || ""}
                        items={D.proveedores || []} labelKey="nombre"
                        renderItem={p => <span>{p.nombre} <span style={{color:"#9ca3af"}}>{p.tipo||""}</span></span>}
                        onChange={p => upEst(idx, ei, { proveedor: p.nombre })}
                      /></F>
                      <F l="Ubicación"><input style={S.inp} value={est.ubicacion || ""} onChange={e => upEst(idx, ei, { ubicacion: e.target.value })} placeholder="Frente, Espalda..." /></F>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: uc === "cm²" ? "1fr 1fr 1fr 1fr" : "1fr 1fr 1fr", gap: 7, marginTop: 5 }}>
                      {uc === "cm²" && <F l="Ancho cm"><input style={S.inp} type="number" step="0.5" value={est.anchoCm || ""} onChange={e => upEst(idx, ei, { anchoCm: parseFloat(e.target.value) || 0 })} /></F>}
                      {uc === "cm²" && <F l="Alto cm"><input style={S.inp} type="number" step="0.5" value={est.altoCm || ""} onChange={e => upEst(idx, ei, { altoCm: parseFloat(e.target.value) || 0 })} /></F>}
                      {uc === "metro" && <F l="Metros"><input style={S.inp} type="number" step="0.01" value={est.metros || 0} onChange={e => upEst(idx, ei, { metros: parseFloat(e.target.value) || 0 })} /></F>}
                      {uc === "unidad" && <F l="Cantidad"><input style={S.inp} type="number" value={est.cantidadUds || 1} onChange={e => upEst(idx, ei, { cantidadUds: parseInt(e.target.value) || 1 })} /></F>}
                      {uc === "puntadas(miles)" && <F l="Miles punt."><input style={S.inp} type="number" step="0.5" value={est.puntadasMiles || 0} onChange={e => upEst(idx, ei, { puntadasMiles: parseFloat(e.target.value) || 0 })} /></F>}
                      {uc === "pliego" && <F l="Pliegos"><input style={S.inp} type="number" value={est.pliegos || 1} onChange={e => upEst(idx, ei, { pliegos: parseInt(e.target.value) || 1 })} /></F>}
                      <F l={`$/${uc}`}><input style={S.inp} type="number" value={est.costoUnitario || 0} onChange={e => upEst(idx, ei, { costoUnitario: parseFloat(e.target.value) || 0 })} /></F>
                      <F l="Unidad"><select style={S.sel} value={uc} onChange={e => upEst(idx, ei, { unidadCobro: e.target.value })}>{UNIDADES_EST.map(x => <option key={x}>{x}</option>)}</select></F>
                    </div>
                    <div style={{ marginTop: 3, fontSize: 10.5, color: "#6b7280" }}><strong>{estLabel(est)}</strong> × {fmt(est.costoUnitario || 0)}/{uc} = <strong style={{ color: "#0a2540" }}>{fmt(cE)}</strong>/ud{est.proveedor ? ` · ${est.proveedor}` : ""}</div>
                  </div>); })}

                {/* Maquila / Transformación */}
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}><h5 style={{ ...S.secT, margin: "10px 0 4px" }}>Maquila / Transformación</h5><button style={{ ...S.btn2, fontSize: 10 }} onClick={() => qaMaquila()}>+ Proveedor Maquila</button></div>
                <div style={S.g3}>
                  <F l="Proveedor Trazo"><SearchSel placeholder="Buscar trazo..." value={it._provTrazo || ""}
                    items={maqProvs(D, "Trazo").map(p => ({ id: p, nombre: p, precio: maqTrazo(D, p, it.consumoTextil, it.cantidad) }))}
                    labelKey="nombre"
                    renderItem={p => <span>{p.nombre} — <span style={{color:"#9ca3af"}}>{fmt(p.precio)}/ud</span></span>}
                    onChange={p => { urc(idx, { _provTrazo: p.nombre, costoTrazo: p.precio }); }}
                    onNew={() => qaMaquila()} newLabel="Nuevo Proveedor Maquila"
                  /></F>
                  <F l="Proveedor Corte"><SearchSel placeholder="Buscar corte..." value={it._provCorte || ""}
                    items={maqProvs(D, "Corte").map(p => ({ id: p, nombre: p, precio: maqCorte(D, p, it.cantidad) }))}
                    labelKey="nombre"
                    renderItem={p => <span>{p.nombre} — <span style={{color:"#9ca3af"}}>{fmt(p.precio)}/ud</span></span>}
                    onChange={p => { urc(idx, { _provCorte: p.nombre, costoCorte: p.precio }); }}
                    onNew={() => qaMaquila()} newLabel="Nuevo Proveedor Maquila"
                  /></F>
                  <F l="Proveedor Confección"><SearchSel placeholder="Buscar confección..." value={it._provConf || ""}
                    items={maqProvs(D, "Confección").map(p => ({ id: p, nombre: p, precio: maqConfeccion(D, p, it.tipoPrenda) }))}
                    labelKey="nombre"
                    renderItem={p => <span>{p.nombre} — <span style={{color:"#9ca3af"}}>{fmt(p.precio)}/ud</span></span>}
                    onChange={p => { urc(idx, { _provConf: p.nombre, costoConfeccion: p.precio }); }}
                    onNew={() => qaMaquila()} newLabel="Nuevo Proveedor Maquila"
                  /></F>
                </div>
                <div style={{ ...S.g4, marginTop: 6 }}>
                  <F l="Trazo"><input style={S.inp} type="number" value={it.costoTrazo || ""} onChange={e => urc(idx, { costoTrazo: parseFloat(e.target.value) || 0 })} /></F>
                  <F l="Corte"><input style={S.inp} type="number" value={it.costoCorte} onChange={e => urc(idx, { costoCorte: parseFloat(e.target.value) || 0 })} /></F>
                  <F l="Confección"><input style={S.inp} type="number" value={it.costoConfeccion} onChange={e => urc(idx, { costoConfeccion: parseFloat(e.target.value) || 0 })} /></F>
                  <F l="Empaque"><input style={S.inp} type="number" value={it.costoEmpaque} onChange={e => urc(idx, { costoEmpaque: parseFloat(e.target.value) || 0 })} /></F>
                </div>
                <div style={{ background: "#f9f7f3", padding: 8, borderRadius: 5, marginTop: 6, fontSize: 12 }}>
                  <strong>Subtotal directo: {fmt(it._subDirecto)}</strong>
                  <span style={{ marginLeft: 10, fontSize: 10.5, color: "#6b7280" }}>Tex {fmt(it._cTextil)} + Ins {fmt(it._cInsumos)} + Est {fmt(it._cEstampados)} + Maquila {fmt((it.costoTrazo||0)+(it.costoCorte||0)+(it.costoConfeccion||0)+(it.costoEmpaque||0))}</span>
                </div>

                {/* B2: Margen / Precio */}
                <h5 style={S.secT}>2. Margen y Precio</h5>
                <div style={S.g4}>
                  <F l="Margen bruto %"><input style={{ ...S.inp, fontWeight: 700, fontSize: 14 }} type="number" value={it.margenBruto || ""} onChange={e => urc(idx, { margenBruto: parseFloat(e.target.value) || 0, precioManual: 0 })} /></F>
                  <F l="Precio venta manual (sin IVA)"><input style={{ ...S.inp, fontWeight: 700, fontSize: 14, background: it.precioManual > 0 ? "#fefce8" : "#faf9f7" }} type="number" value={it.precioManual || ""} onChange={e => urc(idx, { precioManual: parseFloat(e.target.value) || 0 })} placeholder="Dejar vacío = por margen" /></F>
                  <div><div style={S.lb}>Precio base resultante</div><div style={{ fontSize: 16, fontWeight: 700, color: "#0a2540", padding: "4px 0" }}>{fmt(it._precioBase)}</div>{it.precioManual > 0 && <div style={{ fontSize: 10, color: "#92400e" }}>Precio fijado manualmente</div>}</div>
                  <div><div style={S.lb}>Margen bruto real</div><div style={{ fontSize: 14, fontWeight: 700, color: it._subDirecto > 0 ? ((it._precioBase - it._subDirecto) / it._precioBase * 100 < 15 ? "#b91c1c" : "#065f46") : "#0a2540", padding: "4px 0" }}>{it._precioBase > 0 ? ((it._precioBase - it._subDirecto) / it._precioBase * 100).toFixed(1) : "0.0"}%</div></div>
                </div>

                {/* B3: Cargos */}
                <h5 style={S.secT}>3. Cargos Adicionales</h5>
                <div style={{ display: "flex", gap: 6, marginBottom: 6, flexWrap: "wrap" }}>
                  <button style={S.btn2} onClick={() => addCargo(idx)}><Ic name="plus" size={11} /> Manual</button>
                  <div style={{ display: "inline-block", width: 180 }}><SearchSel placeholder="Plantilla cargos..." value=""
                    items={D.plantillasCargos} labelKey="nombre"
                    onChange={p => applyPl(idx, p.id)}
                  /></div>
                </div>
                {(it._cargosC || it.cargos || []).map((cg, ci) => (
                  <div key={ci} style={{ display: "flex", gap: 6, alignItems: "center", marginBottom: 3 }}>
                    <input style={{ ...S.inp, flex: 2 }} value={cg.nombre} onChange={e => upCargo(idx, ci, { nombre: e.target.value })} placeholder="Nombre" />
                    <select style={{ ...S.sel, flex: 1 }} value={cg.modo} onChange={e => upCargo(idx, ci, { modo: e.target.value })}><option value="porcentaje">%</option><option value="fijo">$ Fijo</option></select>
                    <input style={{ ...S.inp, flex: 1 }} type="number" value={cg.valor} onChange={e => upCargo(idx, ci, { valor: parseFloat(e.target.value) || 0 })} />
                    <span style={{ fontSize: 11, fontWeight: 600, minWidth: 70, textAlign: "right" }}>{fmt(cg._calc || 0)}</span>
                    <button style={{ ...S.btnD, padding: "1px 5px" }} onClick={() => rmCargo(idx, ci)}>✕</button>
                  </div>))}
                {it._totalCargos > 0 && <div style={{ textAlign: "right", fontWeight: 600, fontSize: 12, marginTop: 3 }}>Subtotal cargos: {fmt(it._totalCargos)}</div>}

                {/* B4: Precio final */}
                <h5 style={S.secT}>4. Precio Final</h5>
                <div style={{ ...S.g4, background: "#f0fdf4", padding: 12, borderRadius: 7, border: "1px solid #bbf7d0" }}>
                  <div><div style={S.lb}>Neto sin IVA</div><div style={{ fontSize: 14, fontWeight: 700 }}>{fmt(it._netoSinIVA)}</div></div>
                  <div><div style={S.lb}>IVA {it.ivaRate || 19}%</div><div style={{ fontSize: 14, fontWeight: 600 }}>{fmt(it._iva)}</div></div>
                  <div><div style={S.lb}>Precio final</div><div style={{ fontSize: 17, fontWeight: 800, color: "#065f46" }}>{fmt(it._precioFinal)}</div></div>
                  <div><div style={S.lb}>Total ítem</div><div style={{ fontSize: 15, fontWeight: 700, color: "#0a2540" }}>{fmt(it._precioFinal * it.cantidad)}</div></div>
                </div>
                <div style={{ ...S.g4, marginTop: 6, background: "#faf9f7", padding: 8, borderRadius: 5, fontSize: 10.5 }}>
                  <div><span style={{ color: "#6b7280" }}>Costo directo:</span><br /><strong>{fmt(it._subDirecto)}</strong></div>
                  <div><span style={{ color: "#6b7280" }}>Utilidad:</span><br /><strong style={{ color: it._utilidad > 0 ? "#065f46" : "#b91c1c" }}>{fmt(it._utilidad)}</strong></div>
                  <div><span style={{ color: "#6b7280" }}>Margen real:</span><br /><strong style={{ color: it._margenReal < 10 ? "#b91c1c" : it._margenReal < 20 ? "#92400e" : "#065f46" }}>{it._margenReal.toFixed(1)}%</strong></div>
                  <div><span style={{ color: "#6b7280" }}>Precio mín:</span><br /><strong>{fmt(it._netoSinIVA)}</strong></div>
                </div>
                {it._margenReal < 10 && <div style={S.alertB("red")}><Ic name="alert" size={13} /> Margen real &lt; 10%</div>}
                {it._utilidad < 0 && <div style={S.alertB("red")}><Ic name="alert" size={13} /> Utilidad NEGATIVA</div>}
                {it._totalCargos > it._precioBase * 0.15 && <div style={S.alertB("yellow")}><Ic name="alert" size={13} /> Cargos &gt; 15% del precio base</div>}
              </div>); })()}
          </>)}
        </div>
        {/* C.5 Resumen económico */}
        <div style={{ ...S.card, background: "#0a2540", color: "#e8d5b7" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div><div style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: 1 }}>Resumen</div><div style={{ fontSize: 10.5, color: "#8faabe", marginTop: 1 }}>{(c.items || []).length} ítem(s) · {(c.items || []).reduce((s, it) => s + it.cantidad, 0)} uds</div></div>
            <div style={{ textAlign: "right" }}><div style={{ fontSize: 11.5 }}>Neto: {fmt(tots.n)} · IVA: {fmt(tots.i)}</div><div style={{ fontSize: 22, fontWeight: 800, fontFamily: "Georgia,serif" }}>{fmt(tots.f)}</div><div style={{ fontSize: 10.5, color: "#8faabe" }}>Utilidad: {fmt(tots.u)}</div></div>
          </div>
        </div>
      </div>
      {/* Quick-add popup */}
      {qa && (
        <div style={{ position: "fixed", inset: 0, zIndex: 1500, background: "rgba(0,0,0,0.35)", display: "flex", alignItems: "center", justifyContent: "center" }} onMouseDown={e => { if (e.target === e.currentTarget) setQa(null); }}>
          <div style={{ background: "#fff", borderRadius: 12, padding: 20, width: qa.type === "cliente" ? 480 : 400, boxShadow: "0 12px 40px rgba(0,0,0,.2)", border: "2px solid #e8d5b7" }} onMouseDown={e => e.stopPropagation()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
              <h3 style={{ margin: 0, fontSize: 14, color: "#0a2540", fontFamily: "Georgia,serif" }}>
                {qa.type === "cliente" && "Nuevo cliente"}
                {qa.type === "prenda" && "Nuevo tipo de prenda"}
                {qa.type === "textil" && "Nuevo textil"}
                {qa.type === "maquila" && "Nuevo servicio maquila"}
              </h3>
              <button style={{ background: "none", border: "none", fontSize: 18, cursor: "pointer", color: "#9ca3af" }} onClick={() => setQa(null)}>✕</button>
            </div>

            {qa.type === "cliente" && <>
              <div style={S.g2}>
                <F l="Razón Social"><input style={S.inp} value={qa.data.razon} onChange={e => setQa({ ...qa, data: { ...qa.data, razon: e.target.value } })} autoFocus /></F>
                <F l="NIT"><input style={S.inp} value={qa.data.nit} onChange={e => setQa({ ...qa, data: { ...qa.data, nit: e.target.value } })} /></F>
              </div>
              <div style={{ ...S.g3, marginTop: 6 }}>
                <F l="Contacto"><input style={S.inp} value={qa.data.contacto} onChange={e => setQa({ ...qa, data: { ...qa.data, contacto: e.target.value } })} /></F>
                <F l="Correo"><input style={S.inp} value={qa.data.correo} onChange={e => setQa({ ...qa, data: { ...qa.data, correo: e.target.value } })} /></F>
                <F l="Tel"><input style={S.inp} value={qa.data.tel} onChange={e => setQa({ ...qa, data: { ...qa.data, tel: e.target.value } })} /></F>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                <button style={S.btnG} onClick={qaSaveCliente}><Ic name="check" size={12} /> Crear cliente</button>
                <button style={S.btn2} onClick={() => setQa(null)}>Cancelar</button>
              </div>
            </>}

            {qa.type === "prenda" && <>
              <div style={{ display: "flex", gap: 8 }}>
                <F l="Nombre de prenda"><input style={S.inp} value={qa.data.nombre} onChange={e => setQa({ ...qa, data: { ...qa.data, nombre: e.target.value } })} autoFocus /></F>
                <F l="Consumo default (m)"><input style={S.inp} type="number" step="0.01" value={qa.data.consumoDefault || ""} onChange={e => setQa({ ...qa, data: { ...qa.data, consumoDefault: parseFloat(e.target.value) || 0 } })} /></F>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                <button style={S.btnG} onClick={() => qaSavePrenda(itab)}><Ic name="check" size={12} /> Crear prenda</button>
                <button style={S.btn2} onClick={() => setQa(null)}>Cancelar</button>
              </div>
            </>}

            {qa.type === "textil" && <>
              <div style={{ display: "flex", gap: 8 }}>
                <F l="Nombre textil"><input style={S.inp} value={qa.data.nombre} onChange={e => setQa({ ...qa, data: { ...qa.data, nombre: e.target.value } })} autoFocus /></F>
                <F l="Precio/m"><input style={S.inp} type="number" value={qa.data.precio || ""} onChange={e => setQa({ ...qa, data: { ...qa.data, precio: parseFloat(e.target.value) || 0 } })} /></F>
                <F l="Proveedor"><select style={S.sel} value={qa.data.proveedor} onChange={e => setQa({ ...qa, data: { ...qa.data, proveedor: e.target.value } })}><option value="">—</option>{(D.proveedores || []).map(p => <option key={p.id} value={p.nombre}>{p.nombre}</option>)}</select></F>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                <button style={S.btnG} onClick={() => qaSaveTextil(itab)}><Ic name="check" size={12} /> Crear textil</button>
                <button style={S.btn2} onClick={() => setQa(null)}>Cancelar</button>
              </div>
            </>}

            {qa.type === "maquila" && <>
              <div style={{ display: "flex", gap: 8 }}>
                <F l="Tipo"><select style={S.sel} value={qa.data.tipo} onChange={e => setQa({ ...qa, data: { ...qa.data, tipo: e.target.value } })}><option>Trazo</option><option>Corte</option><option>Confección</option></select></F>
                <F l="Proveedor"><select style={S.sel} value={qa.data.proveedor} onChange={e => setQa({ ...qa, data: { ...qa.data, proveedor: e.target.value } })}><option value="">—</option>{(D.proveedores || []).map(p => <option key={p.id} value={p.nombre}>{p.nombre}</option>)}</select></F>
                {qa.data.tipo === "Trazo" && <F l="$/metro"><input style={S.inp} type="number" value={qa.data.precioMetro || ""} onChange={e => setQa({ ...qa, data: { ...qa.data, precioMetro: parseFloat(e.target.value) || 0 } })} /></F>}
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                <button style={S.btnG} onClick={qaSaveMaquila}><Ic name="check" size={12} /> Crear servicio</button>
                <button style={S.btn2} onClick={() => setQa(null)}>Cancelar</button>
              </div>
            </>}
          </div>
        </div>
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════
// GENERIC FORM MODAL (module-level — no remount on parent re-render)

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