/* =====================================================================
   ModalPedido (MPed) — Edicion de Pedido / Orden de Produccion
   Recibe via props: edt, setModal, setEdt, verPedPDF, D, up, openEmail
   ===================================================================== */

const MPed = ({ edt, setModal, setEdt, verPedPDF, D, up, openEmail }) => {
  const [p, setP] = useState(edt);
  const [newTalla, setNewTalla] = useState("");
  const [activeTab, setActiveTab] = useState(0);
  const u = (k, v) => setP(x => ({ ...x, [k]: v }));
  const ui = (idx, k, v) => { const items = [...p.items]; items[idx] = { ...items[idx], [k]: v }; setP(x => ({ ...x, items })); };
  const ut = (idx, t, v) => { const items = [...p.items]; items[idx] = { ...items[idx], tallasDetalle: { ...items[idx].tallasDetalle, [t]: parseInt(v) || 0 } }; setP(x => ({ ...x, items })); };
  const addT = (idx) => { if (!newTalla.trim()) return; const key = newTalla.trim().toUpperCase(); const items = [...p.items]; items[idx] = { ...items[idx], tallasDetalle: { ...items[idx].tallasDetalle, [key]: 0 }, tallasCustom: [...(items[idx].tallasCustom || []), key] }; setP(x => ({ ...x, items })); setNewTalla(""); };
  const rmT = (idx, t) => { const items = [...p.items]; const td = { ...items[idx].tallasDetalle }; delete td[t]; items[idx] = { ...items[idx], tallasDetalle: td, tallasCustom: (items[idx].tallasCustom || []).filter(x => x !== t) }; setP(x => ({ ...x, items })); };
  const handleImg = (idx, e) => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = (ev) => ui(idx, "renderImg", ev.target.result); reader.readAsDataURL(file); };
  const save = () => { up("pedidos", D.pedidos.map(x => x.id === p.id ? p : x)); setModal(null); setEdt(null); };
  const allT = it => [...new Set([...(D.tallas || []), ...(it.tallasCustom || [])])];
  return (
    <div style={S.modal} onMouseDown={e => { if (e.target === e.currentTarget) save(); }}><div style={{ ...S.mc, maxWidth: 1050 }} onMouseDown={e => e.stopPropagation()}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <div>
          <input style={{ ...S.inp, fontWeight: 700, fontSize: 15, width: 340, border: "none", background: "transparent", padding: 0, color: "#0a2540" }} value={p.nombrePed || ""} onChange={e => u("nombrePed", e.target.value)} placeholder={p.numero} />
          <div style={{ fontSize: 10.5, color: "#9ca3af", display: "flex", alignItems: "center", gap: 6 }}>{p.numero} <span style={S.badge(pedBadge(p.estado))}>{p.estado}</span></div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <select style={{ ...S.sel, width: 140, fontSize: 11, fontWeight: 600 }} value={p.estado} onChange={e => u("estado", e.target.value)}>
            {ESTADOS_PED.map(e => <option key={e} value={e}>{e}</option>)}
          </select>
          <button style={S.btnG} onClick={() => { save(); verPedPDF(p); }}>PDF</button>
          <button style={{ ...S.btn2, color: "#1e40af" }} onClick={() => openEmail("ped", p)}><Ic name="send" size={13} /></button>
          <button style={S.btn} onClick={save}><Ic name="check" size={13} /> Guardar</button>
        </div>
      </div>
      {/* Encabezado del pedido */}
      <div style={{ ...S.card, background: "#faf9f7" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr 1fr 1fr", gap: 8 }}>
          <F l="Fecha del pedido"><input style={{ ...S.inp, background: "#e5e1d8", fontWeight: 600 }} value={p.fecha} readOnly /></F>
          <F l="OC Cliente"><input style={S.inp} value={p.ocCliente} onChange={e => u("ocCliente", e.target.value)} placeholder="# orden de compra" /></F>
          <F l="Fecha compromiso"><input style={S.inp} type="date" value={p.fechaCompromiso} onChange={e => u("fechaCompromiso", e.target.value)} /></F>
          <F l="Responsable"><input style={S.inp} value={p.responsable} onChange={e => u("responsable", e.target.value)} /></F>
          <F l="Cliente"><input style={S.inp} value={p.clienteNombre} readOnly /></F>
          <F l="Tipo de negocio"><select style={{ ...S.sel, background: "#ede9fe", fontWeight: 600, color: "#5b21b6" }} value={p.tipoNegocio || ""} onChange={e => u("tipoNegocio", e.target.value)}>
            <option value="">— Seleccionar —</option>
            {TIPOS_NEGOCIO.map(t => <option key={t} value={t}>{t}</option>)}
          </select></F>
        </div>
        <div style={{ ...S.g4, marginTop: 7 }}>
          <F l="Dir. entrega"><input style={S.inp} value={p.dirEntrega} onChange={e => u("dirEntrega", e.target.value)} /></F>
          <F l="Dir. facturación"><input style={S.inp} value={p.dirFactura} onChange={e => u("dirFactura", e.target.value)} /></F>
          <F l="Contacto recibe"><input style={S.inp} value={p.contactoRecibe} onChange={e => u("contactoRecibe", e.target.value)} /></F>
          <F l="Tel. recibe"><input style={S.inp} value={p.telRecibe} onChange={e => u("telRecibe", e.target.value)} /></F>
        </div>
        <div style={{ marginTop: 7 }}>
          <F l="Archivo OC (adjuntar)">
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <input type="file" accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" onChange={e => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = ev => u("ocArchivo", { nombre: file.name, tipo: file.type, data: ev.target.result }); reader.readAsDataURL(file); }} style={{ fontSize: 11 }} />
              {p.ocArchivo && <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "4px 10px", background: "#d1fae5", borderRadius: 5, fontSize: 11, color: "#065f46" }}>
                <strong>{p.ocArchivo.nombre}</strong>
                <button style={{ background: "none", border: "none", cursor: "pointer", color: "#b91c1c", fontSize: 11, padding: 0 }} onClick={() => u("ocArchivo", null)}>x</button>
              </div>}
            </div>
            {p.ocArchivo && p.ocArchivo.tipo && p.ocArchivo.tipo.startsWith("image/") && <img src={p.ocArchivo.data} alt="OC" style={{ maxWidth: 300, maxHeight: 150, marginTop: 6, borderRadius: 6, border: "1px solid #e5e1d8" }} />}
          </F>
        </div>
      </div>
      {/* Item tabs */}
      {(p.items || []).length > 1 && <div style={{ ...S.tabs, flexWrap: "wrap", marginBottom: 6 }}>{p.items.map((it, i) => <div key={i} style={S.tab(activeTab === i)} onClick={() => setActiveTab(i)}>#{i + 1} {it.nombreComercial || it.tipoPrenda}</div>)}</div>}
      {/* Item detail */}
      {(p.items || []).map((it, idx) => activeTab === idx && (
        <div key={idx} style={{ ...S.card, borderLeft: "3px solid #0a2540" }}>
          <h4 style={{ margin: "0 0 10px", color: "#0a2540", fontSize: 13 }}>Ítem {idx + 1}: {it.nombreComercial || it.tipoPrenda} — <span style={{ fontWeight: 400, color: "#6b7280" }}>{it.cantidad} uds</span></h4>
          <div style={S.g4}>
            <F l="Textil"><input style={S.inp} value={it.textilNombre || ""} onChange={e => ui(idx, "textilNombre", e.target.value)} /></F>
            <F l="Color"><input style={S.inp} value={it.color || ""} onChange={e => ui(idx, "color", e.target.value)} placeholder="Ej: Azul marino, Blanco" /></F>
            <F l="Estampados"><input style={S.inp} value={(it.estampados || []).map(e => `${e.tecnica} (${e.ubicacion || ""})`).join(", ")} readOnly /></F>
            <F l="Empaque"><input style={S.inp} value={it.empaqueD || ""} onChange={e => ui(idx, "empaqueD", e.target.value)} /></F>
          </div>
          <div style={{ ...S.g2, marginTop: 7 }}>
            <F l="Imagen del diseño / render">
              <input type="file" accept="image/*" onChange={e => handleImg(idx, e)} style={{ fontSize: 11 }} />
              {it.renderImg && <img src={it.renderImg} alt="Render" style={{ maxWidth: 200, maxHeight: 120, marginTop: 6, borderRadius: 6, border: "1px solid #e5e1d8" }} />}
            </F>
            <div style={S.g2}><F l="Molde"><input style={S.inp} value={it.molde || ""} onChange={e => ui(idx, "molde", e.target.value)} /></F><F l="Patronista"><input style={S.inp} value={it.patronista || ""} onChange={e => ui(idx, "patronista", e.target.value)} /></F></div>
          </div>
          <F l="Insumos"><input style={{ ...S.inp, marginTop: 4 }} value={it.insumosD || ""} onChange={e => ui(idx, "insumosD", e.target.value)} /></F>
          {/* Tallas */}
          <div style={{ marginTop: 8 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={S.lb}>Tallas (Total: {it.cantidad})</div>
              <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
                <input style={{ ...S.inp, width: 70 }} value={newTalla} onChange={e => setNewTalla(e.target.value)} placeholder="Ej: 3XL" onKeyDown={e => { if (e.key === "Enter") addT(idx); }} />
                <button style={S.btn2} onClick={() => addT(idx)}><Ic name="plus" size={11} /> Talla</button>
              </div>
            </div>
            <div style={{ display: "flex", gap: 5, marginTop: 3, flexWrap: "wrap" }}>
              {allT(it).map(t => <div key={t} style={{ textAlign: "center" }}><div style={{ fontSize: 9.5, fontWeight: 600, color: "#6b7280", display: "flex", alignItems: "center", gap: 1 }}>{t}{(it.tallasCustom || []).includes(t) && <button style={{ background: "none", border: "none", cursor: "pointer", color: "#b91c1c", fontSize: 9, padding: 0 }} onClick={() => rmT(idx, t)}>x</button>}</div><input style={{ ...S.inp, width: 44, textAlign: "center" }} type="number" value={(it.tallasDetalle || {})[t] || ""} onChange={e => ut(idx, t, e.target.value)} /></div>)}
              <div style={{ textAlign: "center" }}><div style={{ fontSize: 9.5, fontWeight: 600 }}>Total</div><div style={{ padding: "6px 5px", fontWeight: 700, color: Object.values(it.tallasDetalle || {}).reduce((a, b) => a + b, 0) === it.cantidad ? "#065f46" : "#b91c1c" }}>{Object.values(it.tallasDetalle || {}).reduce((a, b) => a + b, 0)}/{it.cantidad}</div></div>
            </div>
          </div>
          {/* Proveedores */}
          <h5 style={{ margin: "10px 0 5px", fontSize: 10.5, textTransform: "uppercase", color: "#0a2540" }}>Proveedores por proceso</h5>
          <div style={S.g5}>
            <F l="Trazo"><SearchSel placeholder="Buscar..." value={it.provTrazo || ""}
              items={D.proveedores.filter(x => x.tipo === "Corte" || x.tipo === "Trazo")} labelKey="nombre"
              onChange={x => ui(idx, "provTrazo", x.nombre)} /></F>
            <F l="Corte"><SearchSel placeholder="Buscar..." value={it.provCorte || ""}
              items={D.proveedores.filter(x => x.tipo === "Corte")} labelKey="nombre"
              onChange={x => ui(idx, "provCorte", x.nombre)} /></F>
            <F l="Confección"><SearchSel placeholder="Buscar..." value={it.provConf || ""}
              items={D.proveedores.filter(x => x.tipo === "Confección")} labelKey="nombre"
              onChange={x => ui(idx, "provConf", x.nombre)} /></F>
            <F l="Estampado"><SearchSel placeholder="Buscar..." value={it.provEst || ""}
              items={D.proveedores.filter(x => ["Estampado", "Sublimación", "Bordado"].includes(x.tipo))} labelKey="nombre"
              onChange={x => ui(idx, "provEst", x.nombre)} /></F>
            <F l="Empaque"><select style={S.sel} value={it.provEmp || ""} onChange={e => ui(idx, "provEmp", e.target.value)}><option value="">—</option>{D.proveedores.filter(x => x.tipo === "Empaque").map(x => <option key={x.id} value={x.nombre}>{x.nombre}</option>)}</select></F>
          </div>
          <F l="Notas de producción"><textarea style={{ ...S.inp, minHeight: 36, marginTop: 5 }} value={it.notas || ""} onChange={e => ui(idx, "notas", e.target.value)} placeholder="Indicaciones especiales para este ítem..." /></F>
        </div>))}
      {/* Observaciones generales */}
      <div style={{ ...S.card, background: "#faf9f7", marginTop: 6 }}>
        <F l="Observaciones generales del pedido"><textarea style={{ ...S.inp, minHeight: 40 }} value={p.obs || ""} onChange={e => u("obs", e.target.value)} placeholder="Notas generales, acuerdos especiales..." /></F>
      </div>
    </div></div>
  );
};

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

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