﻿/* ============================================
   Admin Modules — Producción, Stock, Ventas, Terceros, Gastos, Rentabilidad, Maquinaria
   ============================================ */

/* ============================================
   Producción
   ============================================ */
function TabBtn({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding:"10px 18px", background:"none", border:"none", cursor:"pointer",
      fontWeight: active ? 600 : 400, fontSize:13,
      color: active ? "var(--green-800)" : "var(--admin-mute)",
      borderBottom: active ? "2px solid var(--green-800)" : "2px solid transparent",
      marginBottom:-1, whiteSpace:"nowrap",
    }}>{children}</button>
  );
}

function ModalDetalleLote({ lote, onClose, initialTab }) {
  const [tab,       setTab]     = useState(initialTab || "labores");
  const [labores,   setLabores] = useState([]);
  const [cortes,    setCortes]  = useState([]);
  const [fardos,    setFardos]  = useState([]);
  const [showNew,   setShowNew] = useState(false);
  const [loading,   setLoading] = useState(true);
  // Rendimiento tab state
  const [corteSelId, setCorteSelId] = useState("");
  const [rndCants,   setRndCants]   = useState({});
  const [rndKgTotal, setRndKgTotal] = useState("");
  const [rndMsg,     setRndMsg]     = useState("");
  const [rndSaving,  setRndSaving]  = useState(false);

  const tipoLabel = { rastrillado:"Rastrillado", fumigacion:"Fumigación", fertilizacion:"Fertilización", herbicida:"Herbicida", riego:"Riego", siembra:"Siembra", otro:"Otro" };
  const tipoIcon  = { rastrillado:"Tractor", fumigacion:"Wind", fertilizacion:"Leaf", herbicida:"Sprout", riego:"Droplets", siembra:"Wheat", otro:"MoreHorizontal" };
  const tipoCls   = { rastrillado:"b-info", fumigacion:"b-gold", fertilizacion:"b-green", herbicida:"b-mute", riego:"b-info", siembra:"b-green", otro:"b-mute" };

  const recargar = () => {
    setLoading(true);
    window.API.get(`/lotes/${lote.id}/detalle`).then(r => {
      setLabores(r.labores || []);
      setCortes(r.cortes  || []);
      if (r.cortes?.length && !corteSelId) setCorteSelId(String(r.cortes[0].id));
      setLoading(false);
    });
    window.API.get("/fardos").then(r => {
      if (r.data) {
        const destino = lote.destino_produccion || "ambos";
        setFardos(r.data.filter(f => {
          if (destino === "rollos") return f.tipo === "redondo";
          if (destino === "megas")  return f.tipo === "mega";
          return f.tipo === "redondo" || f.tipo === "mega"; // ambos
        }));
      }
    });
  };

  useEffect(() => { recargar(); }, [lote.id]);

  const guardarRendimiento = async () => {
    const ultimoId = cortes[0]?.id;
    const cant  = Object.values(rndCants).reduce((s, v) => s + (parseInt(v) || 0), 0);
    const kgTot = parseFloat(rndKgTotal) || null;
    if (!cant) { setRndMsg("Ingresá al menos una cantidad."); return; }
    const kgUnd = (cant && kgTot) ? parseFloat((kgTot / cant).toFixed(2)) : null;
    const kgHa  = (kgTot && lote.hectareas) ? parseFloat((kgTot / lote.hectareas).toFixed(2)) : null;
    setRndSaving(true); setRndMsg("");
    const cantidadesInt = {};
    Object.entries(rndCants).forEach(([id, v]) => { const n = parseInt(v); if (n > 0) cantidadesInt[id] = n; });
    const res = await window.API.post(`/cortes/${ultimoId}/rendimiento`, {
      cantidad_total: cant,
      kg_total:       kgTot,
      kg_por_unidad:  kgUnd,
      kg_por_ha:      kgHa,
      cantidades:     cantidadesInt,
    });
    setRndSaving(false);
    if (res.mensaje) {
      setRndMsg("✓ " + res.mensaje);
      setRndCants({}); setRndKgTotal("");
      recargar();
    } else { setRndMsg(res.message || "Error al guardar."); }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}
        style={{ maxWidth:760, width:"92vw", maxHeight:"88vh", display:"flex", flexDirection:"column" }}>

        <div className="modal__head">
          <div>
            <div style={{ fontSize:11, color:"var(--admin-mute)", fontWeight:600, textTransform:"uppercase", letterSpacing:"0.08em", marginBottom:2 }}>
              {lote.hectareas} ha · {lote.tenencia} · {lote.destino_produccion === "rollos" ? "Solo rollos" : lote.destino_produccion === "megas" ? "Solo megas" : "Rollos y megas"}
            </div>
            <div className="modal__title">{lote.nombre}</div>
          </div>
          <div style={{ display:"flex", gap:8, alignItems:"center" }}>
            {tab === "labores" && (
              <button className="btn btn-primary btn-sm" onClick={() => setShowNew(true)}>
                <I name="Plus" size={14} /> Registrar labor
              </button>
            )}
            <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
          </div>
        </div>

        <div style={{ display:"flex", borderBottom:"1px solid var(--admin-line)", padding:"0 22px" }}>
          <TabBtn active={tab==="labores"}    onClick={() => setTab("labores")}>Labores</TabBtn>
          <TabBtn active={tab==="cortes"}     onClick={() => setTab("cortes")}>Cortes</TabBtn>
          <TabBtn active={tab==="rendimiento"} onClick={() => setTab("rendimiento")}>Rendimiento</TabBtn>
        </div>

        <div style={{ flex:1, overflowY:"auto", padding:"16px 22px" }}>
          {loading ? (
            <div style={{ textAlign:"center", padding:32, color:"var(--admin-mute)" }}>Cargando...</div>

          ) : tab === "labores" ? (
            labores.length === 0
              ? <div style={{ textAlign:"center", padding:32, color:"var(--admin-mute)" }}>Sin labores. Usá "Registrar labor".</div>
              : <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
                  {labores.map(lb => (
                    <div key={lb.id} style={{ display:"flex", gap:12, alignItems:"flex-start", padding:"10px 12px", background:"var(--admin-bg)", borderRadius:8 }}>
                      <div style={{ width:34, height:34, borderRadius:8, background:"#fff", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>
                        <I name={tipoIcon[lb.tipo] || "MoreHorizontal"} size={15} style={{ color:"var(--green-800)" }} />
                      </div>
                      <div style={{ flex:1 }}>
                        <div style={{ display:"flex", gap:8, alignItems:"center", marginBottom:2 }}>
                          <span className={`b ${tipoCls[lb.tipo] || "b-mute"}`} style={{ fontSize:11 }}>{tipoLabel[lb.tipo] || lb.tipo}</span>
                          <span style={{ fontSize:12, color:"var(--admin-mute)" }}>{lb.fecha}</span>
                        </div>
                        {lb.producto      && <div style={{ fontSize:12, fontWeight:600 }}>{lb.producto}</div>}
                        {lb.observaciones && <div style={{ fontSize:12, color:"var(--admin-mute)" }}>{lb.observaciones}</div>}
                      </div>
                      <button className="icon-btn" style={{ width:28, height:28, color:"var(--bad)" }}
                        onClick={async () => { await window.API.del(`/labores/${lb.id}`); recargar(); }}>
                        <I name="Trash2" size={13} />
                      </button>
                    </div>
                  ))}
                </div>

          ) : tab === "cortes" ? (
            cortes.length === 0
              ? <div style={{ textAlign:"center", padding:32, color:"var(--admin-mute)" }}>Sin cortes registrados.</div>
              : (() => {
                  const cortesConRend = cortes.filter(c => c.cantidad_total > 0);
                  const totalFardos   = cortesConRend.reduce((s, c) => s + (c.cantidad_total || 0), 0);
                  const totalKg       = cortesConRend.reduce((s, c) => s + (c.kg_total || 0), 0);
                  return (
                    <table className="table">
                      <thead><tr><th>Corte</th><th>Fecha</th><th>Producto</th><th className="num">Fardos</th><th className="num">Kg total</th><th className="num">Kg/unidad</th><th className="num">Kg/ha</th><th>Observaciones</th></tr></thead>
                      <tbody>
                        {cortes.map(c => (
                          <tr key={c.id}>
                            <td><strong>{c.numero_corte}°</strong></td>
                            <td className="num">{c.fecha}</td>
                            <td>{c.producto ? <span className="b b-green" style={{ fontSize:11 }}>{c.producto}</span> : <span style={{ color:"var(--admin-mute)" }}>—</span>}</td>
                            <td className="num">{c.cantidad_total ?? <span style={{ color:"var(--admin-mute)" }}>—</span>}</td>
                            <td className="num">{c.kg_total ? c.kg_total.toLocaleString("es-AR") + " kg" : <span style={{ color:"var(--admin-mute)" }}>—</span>}</td>
                            <td className="num">{c.kg_por_unidad ? c.kg_por_unidad + " kg" : <span style={{ color:"var(--admin-mute)" }}>—</span>}</td>
                            <td className="num">{c.kg_por_ha ? c.kg_por_ha + " kg/ha" : <span style={{ color:"var(--admin-mute)" }}>—</span>}</td>
                            <td style={{ fontSize:12, color:"var(--admin-mute)" }}>{c.observaciones || "—"}</td>
                          </tr>
                        ))}
                      </tbody>
                      {cortesConRend.length > 1 && (
                        <tfoot>
                          <tr style={{ fontWeight:700, borderTop:"2px solid var(--admin-line)" }}>
                            <td colSpan="3" style={{ fontSize:12, color:"var(--admin-mute)" }}>Total campaña</td>
                            <td className="num">{totalFardos}</td>
                            <td className="num">{totalKg ? totalKg.toLocaleString("es-AR") + " kg" : "—"}</td>
                            <td className="num">—</td>
                            <td className="num">—</td>
                            <td></td>
                          </tr>
                        </tfoot>
                      )}
                    </table>
                  );
                })()

          ) : (
            /* ── TAB RENDIMIENTO ── */
            cortes.length === 0
              ? <div style={{ textAlign:"center", padding:32, color:"var(--admin-mute)" }}>Registrá un corte primero.</div>
              : (() => {
                  const ultimoCorte    = cortes[0];
                  const sinRendimiento = !ultimoCorte?.cantidad_total;
                  const rndCantN       = Object.values(rndCants).reduce((s, v) => s + (parseInt(v) || 0), 0);
                  const rndKgN         = parseFloat(rndKgTotal) || null;
                  const kgUnd          = (rndCantN && rndKgN) ? parseFloat((rndKgN / rndCantN).toFixed(2)) : null;
                  const kgHa           = (rndKgN && lote.hectareas) ? parseFloat((rndKgN / lote.hectareas).toFixed(2)) : null;

                  return (
                    <div style={{ display:"flex", flexDirection:"column", gap:20 }}>

                      {/* ── Cargar rendimiento del último corte ── */}
                      {sinRendimiento && (
                        <div style={{ display:"flex", flexDirection:"column", gap:12 }}>
                          <div style={{ fontSize:12, fontWeight:600, color:"var(--admin-mute)" }}>
                            Cargar rendimiento — {ultimoCorte.numero_corte}° corte · {ultimoCorte.fecha}
                          </div>
                          {fardos.length === 0 ? (
                            <div style={{ color:"var(--admin-mute)", fontSize:13 }}>Sin productos en Stock para este lote.</div>
                          ) : (
                            <>
                              <div style={{ background:"var(--admin-bg)", borderRadius:8, padding:"12px 14px" }}>
                                <div style={{ fontSize:11, fontWeight:600, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.07em", marginBottom:10 }}>
                                  ¿Qué se produjo en este corte?
                                </div>
                                <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
                                  {fardos.map(f => (
                                    <div key={f.id} style={{ display:"flex", gap:10, alignItems:"center" }}>
                                      <div style={{ flex:1 }}>
                                        <div style={{ fontSize:13, fontWeight:500 }}>
                                          <span className={`b ${f.tipo === "redondo" ? "b-info" : "b-gold"}`} style={{ fontSize:10, marginRight:6 }}>
                                            {f.tipo === "redondo" ? "Rollo" : "Mega"}
                                          </span>
                                          {f.nombre}
                                        </div>
                                        <div style={{ fontSize:11, color:"var(--admin-mute)" }}>stock actual: {f.stock} unidades</div>
                                      </div>
                                      <input className="form__input" type="number" min="0" step="1" placeholder="—"
                                        style={{ width:90, textAlign:"center" }}
                                        value={rndCants[f.id] || ""}
                                        onChange={e => setRndCants(prev => ({ ...prev, [f.id]: e.target.value }))}
                                      />
                                    </div>
                                  ))}
                                </div>
                              </div>

                              {rndCantN > 0 && (
                                <div className="form__field">
                                  <label>Total de kilos</label>
                                  <input className="form__input" type="number" min="0" step="0.01"
                                    value={rndKgTotal} onChange={e => setRndKgTotal(e.target.value)}
                                    placeholder="Ej: 60000" />
                                </div>
                              )}

                              {(kgUnd || kgHa) && (
                                <div style={{ display:"flex", gap:16, background:"var(--admin-bg)", borderRadius:8, padding:"8px 14px", fontSize:12 }}>
                                  {kgUnd && <span style={{ color:"var(--admin-mute)" }}>Promedio por unidad: <strong style={{ color:"var(--admin-text)" }}>{kgUnd} kg</strong></span>}
                                  {kgHa  && <span style={{ color:"var(--admin-mute)" }}>Kg por hectárea: <strong style={{ color:"var(--admin-text)" }}>{kgHa} kg/ha</strong></span>}
                                </div>
                              )}

                              <div style={{ display:"flex", gap:10, alignItems:"center" }}>
                                <button className="btn btn-primary btn-sm" onClick={guardarRendimiento} disabled={rndSaving}>
                                  {rndSaving ? "Guardando..." : <><I name="BarChart2" size={14} /> Guardar rendimiento</>}
                                </button>
                                {rndMsg && <span style={{ fontSize:12, color: rndMsg.startsWith("✓") ? "var(--good)" : "var(--bad)" }}>{rndMsg}</span>}
                              </div>
                            </>
                          )}
                        </div>
                      )}

                      {!sinRendimiento && rndMsg && (
                        <span style={{ fontSize:12, color:"var(--good)" }}>{rndMsg}</span>
                      )}

                    </div>
                  );
                })()
          )}
        </div>

        {showNew && (
          <ModalNuevaLabor loteId={lote.id} loteName={lote.nombre}
            onClose={() => setShowNew(false)}
            onSuccess={() => { setShowNew(false); recargar(); }}
          />
        )}
      </div>
    </div>
  );
}

function ModalNuevaLabor({ loteId, loteName, onClose, onSuccess }) {
  const tiposLabor = [
    { value:"rastrillado",   label:"Rastrillado" },
    { value:"fumigacion",    label:"Fumigación" },
    { value:"fertilizacion", label:"Fertilización" },
    { value:"herbicida",     label:"Herbicida" },
    { value:"riego",         label:"Riego" },
    { value:"siembra",       label:"Siembra" },
    { value:"otro",          label:"Otro" },
  ];
  const [tipo,     setTipo]    = useState("rastrillado");
  const [fecha,    setFecha]   = useState(new Date().toISOString().slice(0,10));
  const [producto, setProducto]= useState("");
  const [obs,      setObs]     = useState("");
  const [err,      setErr]     = useState("");
  const [loading,  setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const res = await window.API.post("/labores", {
      lote_id: loteId, tipo, fecha,
      producto: producto || null,
      observaciones: obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) { onSuccess(); }
    else { setErr(res.message || "Error al guardar."); }
  };

  return (
    <div className="modal-back" onClick={onClose} style={{ zIndex:1100 }}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth:420 }}>
        <div className="modal__head">
          <div className="modal__title">Registrar labor · {loteName}</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__row">
            <div className="form__field">
              <label>Tipo de labor</label>
              <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                {tiposLabor.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
              </select>
            </div>
            <div className="form__field">
              <label>Fecha</label>
              <input className="form__input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} required />
            </div>
          </div>
          <div className="form__field">
            <label>Producto / insumo <span style={{ color:"var(--admin-mute)", fontWeight:400 }}>(opcional)</span></label>
            <input className="form__input" value={producto} onChange={e => setProducto(e.target.value)}
              placeholder="Ej: Roundup 2L/ha, Urea 150kg/ha..." />
          </div>
          <div className="form__field">
            <label>Observaciones</label>
            <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)}
              placeholder="Condiciones, equipo utilizado, etc." />
          </div>
          {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
          <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf:"flex-end" }} disabled={loading}>
            {loading ? "Guardando..." : <><I name="Check" size={14} /> Guardar</>}
          </button>
        </form>
      </div>
    </div>
  );
}

function ModalNuevaCampana({ onClose, onSuccess }) {
  const hoy = new Date();
  const [nombre,  setNombre]  = useState("");
  const [inicio,  setInicio]  = useState("");
  const [fin,     setFin]     = useState("");
  const [activa,  setActiva]  = useState(true);
  const [obs,     setObs]     = useState("");
  const [err,     setErr]     = useState("");
  const [loading, setLoading] = useState(false);

  const autoCompletar = (nombreVal) => {
    setNombre(nombreVal);
    const match = nombreVal.match(/^(\d{4})\/(\d{2,4})$/);
    if (match) {
      const anio = parseInt(match[1]);
      setInicio(`${anio}-07-01`);
      setFin(`${anio + 1}-06-30`);
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const res = await window.API.post("/campanas", {
      nombre, fecha_inicio: inicio, fecha_fin: fin, activa, observaciones: obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      window.toast(`Campaña ${nombre} creada`);
      onSuccess();
      onClose();
    } else {
      setErr(res.message || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 440 }}>
        <div className="modal__head">
          <div className="modal__title">Nueva campaña</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__field">
            <label>Nombre de campaña <span style={{ color:"var(--admin-mute)", fontWeight:400 }}>(ej: 2025/26)</span></label>
            <input className="form__input" value={nombre} onChange={e => autoCompletar(e.target.value)}
              placeholder="2025/26" required autoFocus />
            {nombre.match(/^\d{4}\/\d{2,4}$/) && inicio && (
              <div style={{ fontSize:12, color:"var(--admin-mute)", marginTop:4 }}>
                Fechas autocompletadas: {inicio} → {fin}
              </div>
            )}
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Fecha inicio</label>
              <input className="form__input" type="date" value={inicio} onChange={e => setInicio(e.target.value)} required />
            </div>
            <div className="form__field">
              <label>Fecha fin</label>
              <input className="form__input" type="date" value={fin} onChange={e => setFin(e.target.value)} required />
            </div>
          </div>
          <label style={{ display:"flex", alignItems:"center", gap:8, fontSize:13, cursor:"pointer" }}>
            <input type="checkbox" checked={activa} onChange={e => setActiva(e.target.checked)} />
            Marcar como campaña activa
          </label>
          <div className="form__field">
            <label>Observaciones</label>
            <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} placeholder="Notas sobre esta campaña..." />
          </div>
          {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
          <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf:"flex-end" }} disabled={loading}>
            {loading ? "Guardando..." : <><I name="CalendarPlus" size={14} /> Crear campaña</>}
          </button>
        </form>
      </div>
    </div>
  );
}

function Produccion() {
  const D = window.DATA;
  const [tab, setTab] = useState("todos");
  const [filter, setFilter] = useState("todos");
  const [showModal, setShowModal] = useState(false);
  const [showMapa, setShowMapa] = useState(false);
  const [showNuevoLote, setShowNuevoLote] = useState(false);
  const [showNuevaCampana, setShowNuevaCampana] = useState(false);
  const [loteSel,    setLoteSel]    = useState(null);
  const [loteSelTab, setLoteSelTab] = useState("labores");
  const [loteEditar, setLoteEditar] = useState(null);
  const [LOTES, setLOTES] = useState([]);
  const [campanas, setCampanas] = useState([]);
  const [campanaSelId, setCampanaSelId] = useState(null);

  const campanaActiva = campanas.find(c => c.activa) || campanas[0] || null;
  const campanaSel    = campanas.find(c => c.id === campanaSelId) || campanaActiva;

  const recargarCampanas = () => {
    window.API.get("/campanas").then(r => {
      if (r.data) {
        setCampanas(r.data);
        if (!campanaSelId) {
          const activa = r.data.find(c => c.activa);
          if (activa) setCampanaSelId(activa.id);
        }
      }
    });
  };

  const recargarLotes = () => {
    window.API.get("/lotes").then(r => {
      if (r.data) setLOTES(r.data.map(window.API_MAP.lote));
    });
  };

  useEffect(() => { recargarLotes(); recargarCampanas(); }, []);

  const lotesPorTenencia = (t) => LOTES.filter(l => l.tenencia === t);
  const totalHa = (t) => lotesPorTenencia(t).reduce((s, l) => s + l.hectareas, 0);

  const tabsData = [
    { id: "todos",     label: "Todos los campos", count: LOTES.length,                       has: LOTES.reduce((s,l) => s + l.hectareas, 0), color: "var(--green-700)", icon: "LayoutGrid" },
    { id: "propio",    label: "Propios",          count: lotesPorTenencia("propio").length,    has: totalHa("propio"),    color: "var(--green-800)", icon: "Home" },
    { id: "alquilado", label: "Alquilados",       count: lotesPorTenencia("alquilado").length, has: totalHa("alquilado"), color: "var(--gold-700)",  icon: "KeyRound" },
    { id: "sociedad",  label: "En sociedad",      count: lotesPorTenencia("sociedad").length,  has: totalHa("sociedad"),  color: "var(--earth-500)", icon: "Handshake" },
  ];

  const baseLotes = tab === "todos" ? LOTES : LOTES.filter(l => l.tenencia === tab);
  const filtered = baseLotes.filter(l => filter === "todos" ? true : l.estado === filter);

  const tenenciaLabel = { propio: "Propio", alquilado: "Alquilado", sociedad: "Sociedad" };
  const tenenciaCls   = { propio: "b-green", alquilado: "b-gold",  sociedad: "b-info" };

  return (
    <div className="page" data-screen-label="Produccion">
      <div className="page__header">
        <div>
          <div className="page__title">Producción de lotes</div>
          <div className="page__sub">{LOTES.length} lotes · {LOTES.reduce((s,l) => s + l.hectareas, 0)} ha totales · entre propios, alquilados y en sociedad</div>
        </div>
        <div className="page__actions">
          {campanaSel ? (
            <div style={{ display:"flex", alignItems:"center", gap:6 }}>
              <span style={{ fontSize:11, color:"var(--admin-mute)", fontWeight:600, textTransform:"uppercase", letterSpacing:"0.08em" }}>Campaña</span>
              <select className="form__select" style={{ padding:"4px 8px", fontSize:13, height:32 }}
                value={campanaSelId || ""}
                onChange={e => setCampanaSelId(Number(e.target.value))}>
                {campanas.map(c => (
                  <option key={c.id} value={c.id}>{c.nombre}{c.activa ? " ★" : ""}</option>
                ))}
              </select>
              <button className="btn btn-ghost btn-sm" style={{ padding:"0 8px" }} title="Nueva campaña"
                onClick={() => setShowNuevaCampana(true)}>
                <I name="CalendarPlus" size={14} />
              </button>
            </div>
          ) : (
            <button className="btn btn-secondary btn-sm" onClick={() => setShowNuevaCampana(true)}>
              <I name="CalendarPlus" size={14} /> Nueva campaña
            </button>
          )}
          <button className="btn btn-secondary btn-sm" onClick={() => setShowMapa(true)}><I name="Map" size={14} /> Ver mapa</button>
          <button className="btn btn-secondary btn-sm" onClick={() => setShowNuevoLote(true)}><I name="MapPin" size={14} /> Nuevo lote</button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowModal(true)}><I name="Plus" size={14} /> Registrar corte</button>
        </div>
      </div>

      <div className="kpi-grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))" }}>
        {tabsData.map(t => (
          <div key={t.id} className="kpi"
               onClick={() => setTab(t.id)}
               style={{ cursor: "pointer", borderColor: tab === t.id ? t.color : undefined, boxShadow: tab === t.id ? `0 0 0 2px ${t.color}30` : undefined, transition: "all 140ms" }}>
            <div className="kpi__head">
              <div className="kpi__icon" style={{ background: t.color + "22", color: t.color }}>
                <I name={t.icon} size={16} />
              </div>
              <span className="kpi__delta flat">{t.count} lotes</span>
            </div>
            <div className="kpi__label">{t.label}</div>
            <div className="kpi__value">{t.has} <span style={{ fontFamily: "Inter, sans-serif", fontSize: 13, color: "var(--admin-mute)", fontWeight: 500 }}>ha</span></div>
            <div className="kpi__hint">
              {t.id === "propio"    && "campos de la empresa"}
              {t.id === "alquilado" && "contratos vigentes"}
              {t.id === "sociedad"  && "con 2 empresas socias"}
              {t.id === "todos"     && "superficie en producción"}
            </div>
          </div>
        ))}
      </div>

      <div className="panel">
        <div className="panel__head">
          <div>
            <div className="panel__title">
              {tab === "todos" ? "Todos los lotes" : `Campos ${tab === "propio" ? "propios" : tab === "alquilado" ? "alquilados" : "en sociedad"}`}
            </div>
            <div className="panel__sub">{filtered.length} lotes · {filtered.reduce((s,l) => s + l.hectareas, 0)} ha</div>
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {[["todos","Todos"],["activo","Activos"],["descanso","En descanso"]].map(([k,l]) => (
              <button key={k} className={`chip ${filter===k?"is-active":""}`} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
        </div>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Lote</th><th>Uso</th><th>Tenencia</th><th className="num">Has</th><th>Último corte</th><th>Producción total</th><th>Estado</th><th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(l => (
                <tr key={l.nombre}>
                  <td>
                    <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                      <div style={{ width: 30, height: 30, borderRadius: 8, background: "var(--green-50)", color: "var(--green-800)", display: "grid", placeItems: "center" }}>
                        <I name="MapPin" size={14} />
                      </div>
                      <div>
                        <strong>Lote {l.nombre}</strong>
                        {l.tenencia === "alquilado" && <div style={{ fontSize: 11, color: "var(--admin-mute)" }}>de {l.dueño}</div>}
                        {l.tenencia === "sociedad"  && <div style={{ fontSize: 11, color: "var(--admin-mute)" }}>con {l.socio}</div>}
                      </div>
                    </div>
                  </td>
                  <td>
                    {(() => {
                      const d = l.destino_produccion || "ambos";
                      const label = d === "rollos" ? "Rollos" : d === "megas" ? "Megas" : "Rollos y megas";
                      const cls   = d === "rollos" ? "b-info" : d === "megas" ? "b-gold" : "b-green";
                      return <span className={`b ${cls}`}>{label}</span>;
                    })()}
                  </td>
                  <td>
                    <span className={`b ${tenenciaCls[l.tenencia]}`}>
                      <I name={l.tenencia === "propio" ? "Home" : l.tenencia === "alquilado" ? "KeyRound" : "Handshake"} size={11} />
                      {tenenciaLabel[l.tenencia]}
                    </span>
                    {l.participacion && <div style={{ fontSize: 11, color: "var(--admin-mute)", marginTop: 4 }}>{l.participacion}</div>}
                    {l.contrato && <div style={{ fontSize: 11, color: "var(--admin-mute)", marginTop: 4 }}>{l.contrato}</div>}
                  </td>
                  <td className="num">{l.hectareas}</td>
                  <td className="num">{l.ultCorte}</td>
                  <td>
                    {l.ultCorteFardos > 0
                      ? <button className="icon-btn" style={{ fontWeight:700, fontSize:14, color:"var(--green-800)", padding:"2px 6px" }}
                          onClick={() => { setLoteSelTab("rendimiento"); setLoteSel(l); }}>
                          {l.ultCorteFardos} <span style={{ fontSize:11, fontWeight:400, color:"var(--admin-mute)" }}>fardos</span>
                        </button>
                      : <span style={{ color:"var(--admin-mute)" }}>—</span>}
                  </td>
                  <td><EstadoBadge estado={l.estado} /></td>
                  <td>
                    <div style={{ display:"flex", gap:4 }}>
                      <button className="icon-btn" title="Editar lote" onClick={() => setLoteEditar(l)}>
                        <I name="Pencil" size={14} />
                      </button>
                      <button className="icon-btn" title="Eliminar lote" style={{ color:"var(--bad)" }}
                        onClick={async () => {
                          if (!confirm(`¿Eliminar el lote "${l.nombre}"? Esta acción no se puede deshacer.`)) return;
                          await window.API.del(`/lotes/${l.id}`);
                          recargarLotes();
                          window.toast(`Lote "${l.nombre}" eliminado`);
                        }}>
                        <I name="Trash2" size={14} />
                      </button>
                      <button className="icon-btn" title="Ver detalle" onClick={() => setLoteSel(l)}>
                        <I name="ChevronRight" size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan="9" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>No hay lotes con esos filtros.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {tab === "sociedad" && (
        <div className="grid-2">
          {lotesPorTenencia("sociedad").map(l => (
            <div key={l.nombre} className="panel">
              <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--earth-500)22", color: "var(--earth-500)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                  <I name="Handshake" size={22} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em" }}>Lote {l.nombre}</div>
                  <div style={{ color: "var(--admin-mute)", fontSize: 13, marginTop: 2 }}>Sociedad con <strong style={{ color: "var(--admin-ink)" }}>{l.socio}</strong></div>
                  <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
                    <span className="b b-green">{l.hectareas} ha</span>
                    <span className="b b-info">Participación {l.participacion}</span>
                    <EstadoBadge estado={l.estado} />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal        && <ModalRegistrarCorte lotes={LOTES} onClose={() => setShowModal(false)} onSuccess={recargarLotes} />}
      {showMapa         && <ModalMapaLotes lotes={LOTES} onClose={() => setShowMapa(false)} onSuccess={recargarLotes} />}
      {showNuevoLote    && <ModalNuevoLote onClose={() => setShowNuevoLote(false)} onSuccess={recargarLotes} />}
      {showNuevaCampana && <ModalNuevaCampana onClose={() => setShowNuevaCampana(false)} onSuccess={recargarCampanas} />}
      {loteSel          && <ModalDetalleLote lote={loteSel} initialTab={loteSelTab} onClose={() => setLoteSel(null)} />}
      {loteEditar      && <ModalEditarLote lote={loteEditar} onClose={() => setLoteEditar(null)} onSuccess={recargarLotes} />}
    </div>
  );
}

function ModalMapaLotes({ lotes, onClose, onSuccess }) {
  const mapRef   = React.useRef(null);
  const mapInst  = React.useRef(null);
  const lyrs     = React.useRef({});
  const drawLyr  = React.useRef(null);
  const pts      = React.useRef([]);

  const [modo,      setModo]      = useState(null);   // lote en edición
  const [nPts,      setNPts]      = useState(0);
  const [msg,       setMsg]       = useState("");
  const [guardando, setGuardando] = useState(false);
  const [lotesLocal,setLotesLocal]= useState(lotes);

  const renderLotes = (map, ls) => {
    Object.values(lyrs.current).forEach(l => { try { map.removeLayer(l); } catch {} });
    lyrs.current = {};
    const bounds = [];
    ls.forEach(lote => {
      if (!lote.poligono?.length) return;
      const colores = { propio:"#2d5016", alquilado:"#d97706", sociedad:"#7c5b3e" };
      const col = colores[lote.tenencia] || "#2d5016";
      const poly = window.Leaflet.polygon(lote.poligono, { color: col, fillColor: col, fillOpacity: 0.28, weight: 2.5 });
      poly.bindTooltip(
        `<b style="font-size:13px">${lote.nombre}</b><br><span style="font-size:11px;color:#888">${lote.hectareas} ha · ${lote.estado}</span>`,
        { sticky: true, direction:"top" }
      );
      poly.addTo(map);
      lyrs.current[lote.id] = poly;
      bounds.push(...lote.poligono);
    });
    if (bounds.length) { try { map.fitBounds(bounds, { padding:[30,30] }); } catch {} }
  };

  useEffect(() => {
    if (!mapRef.current || mapInst.current || !window.L) return;
    const map = window.Leaflet.map(mapRef.current, { center: [-31.6656, -63.2279], zoom: 14 });

    window.Leaflet.tileLayer(
      'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      { maxZoom: 19, attribution: '© Esri World Imagery' }
    ).addTo(map);
    window.Leaflet.tileLayer(
      'https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}',
      { maxZoom: 19, opacity: 0.6 }
    ).addTo(map);

    mapInst.current = map;
    renderLotes(map, lotes);

    return () => { map.remove(); mapInst.current = null; lyrs.current = {}; };
  }, []);

  const iniciarDibujo = (lote) => {
    const map = mapInst.current;
    if (!map) return;
    cancelarDibujo();
    setModo(lote);
    pts.current = [];
    setNPts(0);
    setMsg(`Hacé click en el campo para trazar los vértices de "${lote.nombre}"`);
    map.getContainer().style.cursor = "crosshair";

    const onClick = (e) => {
      pts.current.push([e.latlng.lat, e.latlng.lng]);
      setNPts(pts.current.length);
      if (drawLyr.current) map.removeLayer(drawLyr.current);
      drawLyr.current = pts.current.length >= 2
        ? window.Leaflet.polygon(pts.current, { color:"#22c55e", fillOpacity:0.15, dashArray:"6,4", weight:2 }).addTo(map)
        : window.Leaflet.circleMarker(e.latlng, { radius:5, color:"#22c55e", fillOpacity:1 }).addTo(map);
    };

    map._drawHandler = onClick;
    map.on("click", onClick);
  };

  const cancelarDibujo = () => {
    const map = mapInst.current;
    if (!map) return;
    if (map._drawHandler) { map.off("click", map._drawHandler); map._drawHandler = null; }
    if (drawLyr.current) { map.removeLayer(drawLyr.current); drawLyr.current = null; }
    if (map.getContainer()) map.getContainer().style.cursor = "";
    setModo(null); setNPts(0); pts.current = [];
  };

  const guardar = async () => {
    if (pts.current.length < 3) { setMsg("Mínimo 3 vértices."); return; }
    setGuardando(true);
    const lat = pts.current.reduce((s,p) => s+p[0], 0) / pts.current.length;
    const lng = pts.current.reduce((s,p) => s+p[1], 0) / pts.current.length;
    await window.API.post(`/lotes/${modo.id}/poligono`, { poligono: pts.current, lat_centro: lat, lng_centro: lng });
    const updated = lotesLocal.map(l => l.id === modo.id ? {...l, poligono: pts.current} : l);
    setLotesLocal(updated);
    renderLotes(mapInst.current, updated);
    cancelarDibujo();
    setMsg("✓ Polígono guardado");
    setGuardando(false);
    if (onSuccess) onSuccess();
  };

  const borrar = async (lote) => {
    await window.API.post(`/lotes/${lote.id}/poligono`, { poligono: null });
    const updated = lotesLocal.map(l => l.id === lote.id ? {...l, poligono: null} : l);
    setLotesLocal(updated);
    if (lyrs.current[lote.id]) { mapInst.current.removeLayer(lyrs.current[lote.id]); delete lyrs.current[lote.id]; }
  };

  return (
    <div className="modal-back" onClick={modo ? undefined : onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 860, width:"92vw" }}>
        <div className="modal__head">
          <div style={{ display:"flex", gap:10, alignItems:"center", flex:1 }}>
            <div className="modal__title">Mapa de lotes</div>
            {msg && <span style={{ fontSize:12, color: msg.startsWith("✓") ? "var(--good)" : "var(--admin-mute)" }}>{msg}</span>}
          </div>
          <div style={{ display:"flex", gap:8 }}>
            {modo && <>
              <span style={{ fontSize:12, color:"var(--admin-mute)", alignSelf:"center" }}>{nPts} vértices</span>
              {nPts >= 3 && <button className="btn btn-primary btn-sm" onClick={guardar} disabled={guardando}>{guardando ? "Guardando..." : <><I name="Save" size={13} /> Guardar campo</>}</button>}
              <button className="btn btn-secondary btn-sm" onClick={cancelarDibujo}>Cancelar</button>
            </>}
            {!modo && <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>}
          </div>
        </div>

        <div ref={mapRef} style={{ height: 490, borderRadius:8, zIndex:0, position:"relative" }} />

        <div style={{ paddingTop:10, display:"flex", gap:6, flexWrap:"wrap", alignItems:"center" }}>
          {!modo && <span style={{ fontSize:11, color:"var(--admin-mute)", fontWeight:600 }}>DIBUJAR:</span>}
          {!modo && lotesLocal.map(l => (
            <div key={l.id} style={{ display:"flex", gap:2 }}>
              <button className="btn btn-secondary btn-sm" style={{ fontSize:11, padding:"2px 8px" }} onClick={() => iniciarDibujo(l)}>
                <I name={l.poligono?.length ? "RefreshCw" : "PencilLine"} size={11} /> {l.nombre}{l.poligono?.length ? " ✓" : ""}
              </button>
              {l.poligono?.length > 0 && (
                <button className="btn btn-ghost btn-sm" style={{ fontSize:11, padding:"2px 6px", color:"var(--bad)" }} onClick={() => borrar(l)} title="Borrar polígono">
                  <I name="Trash2" size={11} />
                </button>
              )}
            </div>
          ))}
          <span style={{ marginLeft:"auto", fontSize:11, color:"var(--admin-mute)" }}>
            Imagen satelital ESRI · sin costo · sin API key
          </span>
        </div>

        <div style={{ display:"flex", gap:14, fontSize:11, color:"var(--admin-mute)", paddingTop:6 }}>
          <span><span style={{ display:"inline-block", width:10, height:10, background:"#22c55e", borderRadius:2, marginRight:4 }}></span>Propio</span>
          <span><span style={{ display:"inline-block", width:10, height:10, background:"#facc15", borderRadius:2, marginRight:4 }}></span>Alquilado</span>
          <span><span style={{ display:"inline-block", width:10, height:10, background:"#f472b6", borderRadius:2, marginRight:4 }}></span>Sociedad</span>
        </div>
      </div>
    </div>
  );
}

function ModalRegistrarCorte({ lotes, onClose, onSuccess }) {
  const lotesActivos = lotes.filter(l => l.estado !== "descanso" && l.estado !== "implantacion");
  const [loteId,   setLoteId]   = useState(String(lotesActivos[0]?.id || ""));
  const [fecha,    setFecha]    = useState(lotesActivos[0]?.proxCorteISO || new Date().toISOString().slice(0,10));

  // Cuando cambia el lote, autocompleta fecha con su próximo corte
  useEffect(() => {
    const lote = lotesActivos.find(l => String(l.id) === loteId);
    if (lote?.proxCorteISO) setFecha(lote.proxCorteISO);
  }, [loteId]);
  const [tipo,          setTipo]         = useState("");
  const [obs,           setObs]          = useState("");
  const [loading,  setLoading]  = useState(false);
  const [done,     setDone]     = useState(false);
  const [err,      setErr]      = useState("");

  const loteSeleccionado = lotesActivos.find(l => String(l.id) === loteId);
  const numeroCorte = (loteSeleccionado?.cortesCount || 0) + 1;

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!loteId) { setErr("Seleccioná un lote."); return; }
    if (!fecha)  { setErr("Ingresá la fecha del corte."); return; }
    if (!tipo)   { setErr("Seleccioná el tipo de corte (picado o entero)."); return; }
    if (loteSeleccionado?.ultCorteISO && fecha <= loteSeleccionado.ultCorteISO) {
      setErr(`La fecha debe ser posterior al último corte (${loteSeleccionado.ultCorte}).`); return;
    }
    setLoading(true);
    const res = await window.API.post("/cortes", {
      lote_id:      parseInt(loteId),
      numero_corte: numeroCorte,
      fecha_corte:  fecha,
      tipo:         tipo || null,
      observaciones: obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Registrar nuevo corte</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Corte registrado. Lote {loteSeleccionado?.nombre} actualizado.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__field">
              <label>Lote</label>
              <select className="form__select" value={loteId} onChange={e => setLoteId(e.target.value)} required>
                {lotesActivos.length === 0 && <option value="">Sin lotes activos</option>}
                {lotesActivos.map(l => (
                  <option key={l.id} value={l.id}>
                    {l.nombre} · {l.hectareas} ha
                    {l.proxCorte && l.proxCorte !== "—" ? ` · prox: ${l.proxCorte}` : ""}
                  </option>
                ))}
              </select>
            </div>

            {loteSeleccionado && (
              <div style={{ display:"flex", gap:16, background:"var(--admin-bg)", borderRadius:8, padding:"8px 14px", fontSize:12 }}>
                <span style={{ color:"var(--admin-mute)" }}>
                  Será el <strong style={{ color:"var(--admin-text)" }}>{numeroCorte}° corte</strong> de este lote
                </span>
                {loteSeleccionado.ultCorte && loteSeleccionado.ultCorte !== "—" && (
                  <span style={{ color:"var(--admin-mute)" }}>
                    <I name="History" size={11} /> Último: <strong style={{ color:"var(--admin-text)" }}>{loteSeleccionado.ultCorte}</strong>
                  </span>
                )}
              </div>
            )}

            <div className="form__field">
              <label>Fecha del corte</label>
              <input className="form__input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} required />
            </div>

            <div className="form__field">
              <label>Tipo de corte</label>
              <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                <option value="">Sin especificar</option>
                <option value="picados">Picados</option>
                <option value="enteros">Enteros</option>
              </select>
            </div>

            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} placeholder="Condiciones climáticas, calidad, etc." />
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={onClose} type="button">Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : "Registrar corte"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ModalEditarLote({ lote, onClose, onSuccess }) {
  const toDate = (str) => str ? str.split("/").reverse().join("-") : "";

  const [nombre,        setNombre]        = useState(lote.nombre || "");
  const [hectareas,     setHectareas]     = useState(String(lote.hectareas || ""));
  const [tenencia,      setTenencia]      = useState(lote.tenencia || "propio");
  const [estado,        setEstado]        = useState(lote.estado || "activo");
  const [destino,       setDestino]       = useState(lote.destino_produccion || "ambos");
  const [dueno,         setDueno]         = useState(lote.dueño || "");
  const [contratoHasta, setContratoHasta] = useState(toDate(lote.contrato?.replace("Hasta ", "")));
  const [socio,         setSocio]         = useState(lote.socio || "");
  const [participacion, setParticipacion] = useState(lote.participacion || "");
  const [obs,           setObs]           = useState(lote.observaciones || "");
  const [loading,       setLoading]       = useState(false);
  const [err,           setErr]           = useState("");

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const body = {
      nombre, hectareas: parseFloat(hectareas), tenencia, estado,
      destino_produccion: destino,
      observaciones: obs || null,
    };
    if (tenencia === "alquilado") { body.dueno = dueno; body.contrato_hasta = contratoHasta || null; }
    if (tenencia === "sociedad")  { body.socio = socio; body.participacion = participacion; }

    const res = await window.API.put(`/lotes/${lote.id}`, body);
    setLoading(false);
    if (res.data?.id || res.id) {
      window.toast(`Lote "${nombre}" actualizado`);
      onSuccess && onSuccess();
      onClose();
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Editar lote · {lote.nombre}</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__row">
            <div className="form__field">
              <label>Nombre del lote</label>
              <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required autoFocus />
            </div>
            <div className="form__field">
              <label>Hectáreas</label>
              <input className="form__input" type="number" step="0.01" min="0.01" value={hectareas} onChange={e => setHectareas(e.target.value)} required />
            </div>
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Tenencia</label>
              <select className="form__select" value={tenencia} onChange={e => setTenencia(e.target.value)}>
                <option value="propio">Propio</option>
                <option value="alquilado">Alquilado</option>
                <option value="sociedad">En sociedad</option>
              </select>
            </div>
            <div className="form__field">
              <label>Uso del lote</label>
              <select className="form__select" value={destino} onChange={e => setDestino(e.target.value)}>
                <option value="ambos">Rollos y megas</option>
                <option value="rollos">Solo rollos</option>
                <option value="megas">Solo megas</option>
              </select>
            </div>
          </div>
          <div className="form__field">
            <label>Estado actual</label>
            <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
              <option value="activo">Activo</option>
              <option value="proximo">Próx. corte</option>
              <option value="descanso">En descanso</option>
              <option value="implantacion">Implantación</option>
            </select>
          </div>
          {tenencia === "alquilado" && (
            <div className="form__row">
              <div className="form__field">
                <label>Dueño del campo</label>
                <input className="form__input" value={dueno} onChange={e => setDueno(e.target.value)} />
              </div>
              <div className="form__field">
                <label>Contrato hasta</label>
                <input className="form__input" type="date" value={contratoHasta} onChange={e => setContratoHasta(e.target.value)} />
              </div>
            </div>
          )}
          {tenencia === "sociedad" && (
            <div className="form__row">
              <div className="form__field">
                <label>Empresa socia</label>
                <input className="form__input" value={socio} onChange={e => setSocio(e.target.value)} />
              </div>
              <div className="form__field">
                <label>Participación</label>
                <input className="form__input" value={participacion} onChange={e => setParticipacion(e.target.value)} placeholder="Ej: 50% / 50%" />
              </div>
            </div>
          )}
          <div className="form__field">
            <label>Observaciones</label>
            <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} />
          </div>
          {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
          <div style={{ display:"flex", gap:8, justifyContent:"flex-end" }}>
            <button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>Cancelar</button>
            <button type="submit" className="btn btn-primary btn-sm" disabled={loading}>
              {loading ? "Guardando..." : <><I name="Save" size={14} /> Guardar cambios</>}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function ModalNuevoLote({ onClose, onSuccess }) {
  const [nombre,       setNombre]       = useState("");
  const [hectareas,    setHectareas]    = useState("");
  const [tenencia,     setTenencia]     = useState("propio");
  const [estado,       setEstado]       = useState("activo");
  const [destino,      setDestino]      = useState("ambos");
  const [dueno,        setDueno]        = useState("");
  const [contratoHasta,setContratoHasta]= useState("");
  const [socio,        setSocio]        = useState("");
  const [participacion,setParticipacion]= useState("");
  const [obs,          setObs]          = useState("");
  const [sociosDB,     setSociosDB]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [done,    setDone]    = useState(false);
  const [err,     setErr]     = useState("");

  useEffect(() => {
    window.API.get("/proveedores").then(r => {
      if (r.data) setSociosDB(r.data.map(s => s.nombre));
    });
  }, []);

  const toISO = (str) => {
    if (!str) return null;
    const [d, m, y] = str.split("/");
    return y ? `${y}-${m}-${d}` : null;
  };

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const body = {
      nombre,
      hectareas:           parseFloat(hectareas),
      tenencia,
      estado,
      destino_produccion:  destino,
      observaciones: obs || null,
    };
    if (tenencia === "alquilado") { body.dueno = dueno; body.contrato_hasta = toISO(contratoHasta); }
    if (tenencia === "sociedad")  { body.socio = socio; body.participacion = participacion; }

    const res = await window.API.post("/lotes", body);
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Agregar nuevo lote</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Lote "{nombre}" agregado correctamente.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__row">
              <div className="form__field">
                <label>Nombre del lote</label>
                <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required placeholder="Ej: La Cañada" autoFocus />
              </div>
              <div className="form__field">
                <label>Hectáreas</label>
                <input className="form__input" type="number" step="0.01" min="0.01" value={hectareas} onChange={e => setHectareas(e.target.value)} required placeholder="Ej: 120" />
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Tenencia</label>
                <select className="form__select" value={tenencia} onChange={e => setTenencia(e.target.value)}>
                  <option value="propio">Propio</option>
                  <option value="alquilado">Alquilado</option>
                  <option value="sociedad">En sociedad</option>
                </select>
              </div>
              <div className="form__field">
                <label>Uso del lote</label>
                <select className="form__select" value={destino} onChange={e => setDestino(e.target.value)}>
                  <option value="ambos">Rollos y megas</option>
                  <option value="rollos">Solo rollos</option>
                  <option value="megas">Solo megas</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Estado actual</label>
                <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
                  <option value="activo">Activo</option>
                  <option value="descanso">En descanso</option>
                </select>
              </div>
            </div>
            {tenencia === "alquilado" && (
              <div className="form__row">
                <div className="form__field">
                  <label>Dueño del campo</label>
                  <input className="form__input" value={dueno} onChange={e => setDueno(e.target.value)} placeholder="Nombre del propietario" required />
                </div>
                <div className="form__field">
                  <label>Contrato hasta</label>
                  <input className="form__input" value={contratoHasta} onChange={e => setContratoHasta(e.target.value)} placeholder="dd/mm/aaaa" />
                </div>
              </div>
            )}
            {tenencia === "sociedad" && (
              <div className="form__row">
                <div className="form__field">
                  <label>Empresa socia</label>
                  {sociosDB.length > 0 ? (
                    <select className="form__select" value={socio} onChange={e => setSocio(e.target.value)} required>
                      <option value="">— seleccionar socio —</option>
                      {sociosDB.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  ) : (
                    <input className="form__input" value={socio} onChange={e => setSocio(e.target.value)}
                      placeholder="Registrá primero el socio en Asociación" required />
                  )}
                </div>
                <div className="form__field">
                  <label>Participación</label>
                  <input className="form__input" value={participacion} onChange={e => setParticipacion(e.target.value)} placeholder="Ej: 50% / 50%" />
                </div>
              </div>
            )}
            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} placeholder="Notas adicionales..." />
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={onClose} type="button">Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : <><I name="MapPin" size={13} /> Agregar lote</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ============================================
   Stock
   ============================================ */
function Stock() {
  const D = window.DATA;
  const [showMov,    setShowMov]    = useState(false);
  const [showNuevo,  setShowNuevo]  = useState(false);
  const [PRODUCTS,   setPRODUCTS]   = useState([]);
  const [movTipo,    setMovTipo]    = useState("ingreso");
  const [movProdId,  setMovProdId]  = useState("");
  const [movCant,    setMovCant]    = useState("");
  const [asignarLote,setAsignarLote]= useState(null);
  const [LOTES_STOCK,setLOTES_STOCK]= useState([]);
  const [prodSel,    setProdSel]    = useState(null);

  const recargarFardos = () => {
    window.API.get("/fardos").then(r => {
      if (r.data) setPRODUCTS(r.data.map(window.API_MAP.fardo));
    });
    window.API.get("/lotes").then(r => {
      if (r.data) setLOTES_STOCK(r.data.map(l => ({ id: l.id, nombre: l.nombre })));
    });
  };

  useEffect(() => { recargarFardos(); }, []);

  const totalChico   = PRODUCTS.filter(p => p.tipo === "chico").reduce((s,p) => s + p.stock, 0);
  const totalRedondo = PRODUCTS.filter(p => p.tipo === "redondo").reduce((s,p) => s + p.stock, 0);
  const totalMega    = PRODUCTS.filter(p => p.tipo === "mega").reduce((s,p) => s + p.stock, 0);
  const valorTotal   = PRODUCTS.reduce((s,p) => s + p.stock * p.precio, 0);

  return (
    <div className="page" data-screen-label="Stock">
      <div className="page__header">
        <div>
          <div className="page__title">Stock de fardos</div>
          <div className="page__sub">Stock de fardos activo</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-secondary btn-sm" onClick={() => window.toast("Stock exportado a Excel")}><I name="Download" size={14} /> Exportar</button>
          <button className="btn btn-secondary btn-sm" onClick={() => setShowMov(true)}><I name="ArrowRightLeft" size={14} /> Movimiento</button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowNuevo(true)}><I name="Plus" size={14} /> Nuevo fardo</button>
        </div>
      </div>

      <div className="kpi-grid">
        <StockTotal title="Rollos"    value={D.fmtNum(totalRedondo)} hint={`${PRODUCTS.filter(p=>p.tipo==='redondo').length} productos`} icon="Circle" />
        <StockTotal title="Megas"     value={D.fmtNum(totalMega)}    hint={`${PRODUCTS.filter(p=>p.tipo==='mega').length} productos`}    icon="Package" />
      </div>

      <div className="panel">
        <div className="panel__head">
          <div className="panel__title">Detalle por tipo y corte</div>
          <span className="b b-mute">{PRODUCTS.length} SKUs</span>
        </div>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Producto</th><th>Tipo</th><th>Peso</th><th>Proteína</th><th>Galpón</th><th className="num">Stock</th><th className="num">Precio</th><th>Estado</th>
              </tr>
            </thead>
            <tbody>
              {PRODUCTS.map(p => {
                const niv = p.stock <= 15 ? "bad" : p.stock <= 50 ? "warn2" : p.stock <= 120 ? "warn" : "ok";
                return (
                  <tr key={p.id} style={{ cursor:"pointer" }}
                    onClick={() => setProdSel(p)}
                    onMouseEnter={e => e.currentTarget.style.background="var(--admin-bg)"}
                    onMouseLeave={e => e.currentTarget.style.background=""}>
                    <td><strong>{p.nombre}</strong></td>
                    <td><span className={`b ${p.tipo==="redondo"?"b-info":"b-gold"}`}>{p.tipo==="redondo"?"Rollo":"Mega"}</span></td>
                    <td className="num">{p.peso}</td>
                    <td className="num"><strong>{p.proteina}</strong></td>
                    <td>{p.galpon}</td>
                    <td className="num"><strong>{D.fmtNum(p.stock)}</strong></td>
                    <td className="num">{p.precio > 0 ? D.fmtARS(p.precio) : "—"}</td>
                    <td>
                      <span className={`b b-${niv}`}>
                        <span className={`dot dot-${niv}`}></span>
                        {niv === "ok" ? "Stock alto" : niv === "warn" ? "Stock medio" : niv === "warn2" ? "Stock casi bajo" : "Stock bajo"}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {showMov && (
        <div className="modal-back" onClick={() => setShowMov(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal__head">
              <div className="modal__title">Movimiento de stock</div>
              <button className="modal__close" onClick={() => setShowMov(false)}><I name="X" size={18} /></button>
            </div>
            <form className="form" onSubmit={async (e) => {
              e.preventDefault();
              const prod = PRODUCTS.find(p => p.id === movProdId);
              if (!prod) { window.toast("Seleccioná un producto", "warn"); return; }
              const cant = parseInt(movCant) || 0;
              const nuevoStock = movTipo === "ajuste" ? cant : movTipo === "ingreso" ? prod.stock + cant : Math.max(0, prod.stock - cant);
              const realId = prod.id.replace("p","");
              const res = await window.API.patch(`/fardos/${realId}`, { stock: nuevoStock });
              if (res.data?.id || res.id) {
                window.toast("Movimiento registrado"); recargarFardos(); setShowMov(false); setMovCant(""); setMovProdId("");
              } else { window.toast(res.message || "Error al registrar movimiento", "warn"); }
            }}>
              <div className="form__row">
                <div className="form__field">
                  <label>Tipo de movimiento</label>
                  <select className="form__select" value={movTipo} onChange={e => setMovTipo(e.target.value)}>
                    <option value="ingreso">Ingreso (producción)</option>
                    <option value="egreso">Egreso (venta)</option>
                    <option value="ajuste">Ajuste de inventario</option>
                  </select>
                </div>
                <div className="form__field">
                  <label>Cantidad</label>
                  <input className="form__input" type="number" min="0" value={movCant} onChange={e => setMovCant(e.target.value)} required placeholder="0" />
                </div>
              </div>
              <div className="form__field">
                <label>Producto</label>
                <select className="form__select" value={movProdId} onChange={e => setMovProdId(e.target.value)} required>
                  <option value="">Seleccioná un producto</option>
                  {PRODUCTS.map(p => <option key={p.id} value={p.id}>{p.nombre} · {p.tipo} · stock: {p.stock}</option>)}
                </select>
              </div>
              <div className="form__field">
                <label>Observaciones</label>
                <textarea className="form__textarea" />
              </div>
              <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf: "flex-end" }}>Confirmar movimiento</button>
            </form>
          </div>
        </div>
      )}

      {showNuevo   && <ModalNuevoFardo onClose={() => setShowNuevo(false)} onSuccess={recargarFardos} />}
      {prodSel     && <ModalEditarFardo fardo={prodSel} onClose={() => setProdSel(null)} onSuccess={() => { setProdSel(null); recargarFardos(); }} />}
      {asignarLote && (
        <div className="modal-back" onClick={() => setAsignarLote(null)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth:380 }}>
            <div className="modal__head">
              <div className="modal__title">Lote de origen · {asignarLote.nombre}</div>
              <button className="modal__close" onClick={() => setAsignarLote(null)}><I name="X" size={18} /></button>
            </div>
            <div className="form" style={{ gap:12 }}>
              <div className="form__field">
                <label>Lote que produjo este fardo</label>
                <select className="form__select" defaultValue={asignarLote.origen !== "—" ? asignarLote.origen : ""}
                  onChange={async (e) => {
                    const loteNombre = e.target.value;
                    const realId = asignarLote.id.replace("p","");
                    await window.API.patch(`/fardos/${realId}`, { origen: loteNombre || null });
                    recargarFardos();
                    setAsignarLote(null);
                    window.toast("Lote de origen asignado");
                  }}>
                  <option value="">Sin asignar</option>
                  {LOTES_STOCK.map(l => <option key={l.id} value={l.nombre}>{l.nombre}</option>)}
                </select>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => setAsignarLote(null)}>Cancelar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function ModalEditarFardo({ fardo, onClose, onSuccess }) {
  const D = window.DATA;
  const realId = fardo.id.replace("p", "");

  const [nombre,    setNombre]    = useState(fardo.nombre || "");
  const [tipo,      setTipo]      = useState(fardo.tipo || "redondo");
  const [peso,      setPeso]      = useState(String(parseFloat(fardo.peso) || ""));
  const [proteina,  setProteina]  = useState(parseFloat(fardo.proteina) || "");
  const [calidad,   setCalidad]   = useState(fardo.calidad || "Estándar");
  const [galpon,    setGalpon]    = useState(fardo.galpon !== "—" ? fardo.galpon : "");
  const [stock,     setStock]     = useState(String(fardo.stock || 0));
  const [precio,    setPrecio]    = useState(String(fardo.precio || 0));
  const [corteId,   setCorteId]   = useState(fardo.corte_id || "");
  const [cortes,    setCortes]    = useState([]);
  const [tab,       setTab]       = useState("info");
  const [err,       setErr]       = useState("");
  const [loading,   setLoading]   = useState(false);
  const [confirmar, setConfirmar] = useState(false);

  useEffect(() => {
    // Cargar fardo fresco para tener corte_id actualizado
    window.API.get(`/fardos/${realId}`).then(r => {
      if (r.data) setCorteId(r.data.corte_id || "");
    });
    window.API.get("/cortes").then(r => {
      if (r.data) setCortes(r.data);
    });
  }, [realId]);

  const corteSeleccionado = cortes.find(c => String(c.id) === String(corteId));

  const guardar = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const body = {
      nombre, tipo,
      peso_kg:      parseFloat(peso),
      proteina_pct: proteina ? parseFloat(proteina) : null,
      calidad,
      galpon:       galpon || null,
      stock:        parseInt(stock) || 0,
      precio:       parseFloat(precio) || 0,
      corte_id:     corteId ? parseInt(corteId) : null,
    };
    const res = await window.API.patch(`/fardos/${realId}`, body);
    setLoading(false);
    if (res.data?.id || res.id) { window.toast("Fardo actualizado"); onSuccess(); }
    else { setErr(res.message || "Error al guardar."); }
  };

  const eliminar = async () => {
    await window.API.del(`/fardos/${realId}`);
    window.toast(`"${fardo.nombre}" eliminado`);
    onSuccess();
  };

  const TabBtn2 = ({ id, label }) => (
    <button type="button" onClick={() => setTab(id)} style={{
      padding:"8px 16px", background:"none", border:"none", cursor:"pointer",
      fontWeight: tab===id ? 600 : 400, fontSize:13,
      color: tab===id ? "var(--green-800)" : "var(--admin-mute)",
      borderBottom: tab===id ? "2px solid var(--green-800)" : "2px solid transparent",
      marginBottom:-1,
    }}>{label}</button>
  );

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth:500 }}>
        <div className="modal__head">
          <div>
            <div style={{ fontSize:11, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.08em", marginBottom:2 }}>
              {tipo === "redondo" ? "Rollo" : "Mega"} · stock: {fardo.stock}
            </div>
            <div className="modal__title">{fardo.nombre}</div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        <div style={{ display:"flex", borderBottom:"1px solid var(--admin-line)", padding:"0 22px" }}>
          <TabBtn2 id="info" label="Datos" />
          <TabBtn2 id="origen" label="Origen / Corte" />
        </div>

        <div style={{ padding:"16px 22px" }}>
          {tab === "info" ? (
            <form className="form" onSubmit={guardar}>
              <div className="form__field">
                <label>Nombre del producto</label>
                <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required autoFocus />
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label>Tipo</label>
                  <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                    <option value="redondo">Rollo</option>
                    <option value="mega">Mega</option>
                  </select>
                </div>
                <div className="form__field">
                  <label>Calidad</label>
                  <select className="form__select" value={calidad} onChange={e => setCalidad(e.target.value)}>
                    <option value="Estándar">Estándar</option>
                    <option value="Premium">Premium</option>
                  </select>
                </div>
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label>Galpón</label>
                  <select className="form__select" value={galpon} onChange={e => setGalpon(e.target.value)}>
                    <option value="">— seleccionar —</option>
                    <option>Galpón A</option><option>Galpón B</option><option>Galpón C</option><option>Galpón D</option>
                  </select>
                </div>
                <div className="form__field">
                  <label>Stock actual</label>
                  <input className="form__input" type="number" min="0" value={stock} onChange={e => setStock(e.target.value)} required />
                </div>
              </div>
              <div className="form__field">
                <label>Precio por kilo ($)</label>
                <div style={{ position:"relative" }}>
                  <span style={{ position:"absolute", left:14, top:"50%", transform:"translateY(-50%)", color:"var(--admin-mute)", fontWeight:600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01" value={precio} onChange={e => setPrecio(e.target.value)} style={{ paddingLeft:28 }} placeholder="0" />
                </div>
              </div>
              {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
              <div style={{ display:"flex", gap:8, justifyContent:"space-between" }}>
                {!confirmar
                  ? <button type="button" className="btn btn-ghost btn-sm" style={{ color:"var(--bad)" }} onClick={() => setConfirmar(true)}>
                      <I name="Trash2" size={13} /> Eliminar
                    </button>
                  : <div style={{ display:"flex", gap:6, alignItems:"center" }}>
                      <span style={{ fontSize:12, color:"var(--bad)" }}>¿Eliminar?</span>
                      <button type="button" className="btn btn-secondary btn-sm" onClick={() => setConfirmar(false)}>No</button>
                      <button type="button" className="btn btn-primary btn-sm" style={{ background:"var(--bad)" }} onClick={eliminar}>Sí, eliminar</button>
                    </div>
                }
                <button type="submit" className="btn btn-primary btn-sm" disabled={loading}>
                  {loading ? "Guardando..." : <><I name="Save" size={13} /> Guardar</>}
                </button>
              </div>
            </form>
          ) : (
            <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
              <div style={{ fontSize:12, color:"var(--admin-mute)", marginBottom:4 }}>
                Hacé click en el corte al que pertenece este fardo
              </div>
              {(() => {
                const cortesFiltrados = cortes.filter(c => {
                  if (tipo === "redondo") return c.cantidad_rollos > 0;
                  if (tipo === "mega")    return c.cantidad_megas  > 0;
                  return true;
                });
                if (cortesFiltrados.length === 0) {
                  return <div style={{ textAlign:"center", padding:24, color:"var(--admin-mute)", fontSize:13 }}>
                    Sin cortes con producción de {tipo === "redondo" ? "rollos" : "megas"}.
                  </div>;
                }
                return cortesFiltrados.map(c => {
                    const sel = String(c.id) === String(corteId);
                    const rend = [];
                    if (c.cantidad_rollos > 0) rend.push(c.cantidad_rollos + " rollos");
                    if (c.cantidad_megas  > 0) rend.push(c.cantidad_megas  + " megas");
                    return (
                      <div key={c.id}
                        onClick={async () => {
                          const newId = sel ? "" : c.id;
                          setCorteId(newId);
                          await window.API.patch(`/fardos/${realId}`, { corte_id: newId ? parseInt(newId) : null });
                          window.toast(newId ? "Corte asignado" : "Corte desvinculado");
                        }}
                        style={{
                          display:"flex", alignItems:"center", gap:12, padding:"10px 14px",
                          borderRadius:8, cursor:"pointer", border:"2px solid",
                          borderColor: sel ? "var(--green-800)" : "var(--admin-line)",
                          background:  sel ? "#f0f7eb" : "#fff",
                          transition:"all 120ms",
                        }}>
                        <div style={{ width:32, height:32, borderRadius:8,
                          background: sel ? "var(--green-800)" : "var(--admin-bg)",
                          color: sel ? "#fff" : "var(--admin-mute)",
                          display:"flex", alignItems:"center", justifyContent:"center",
                          fontWeight:700, fontSize:13, flexShrink:0 }}>
                          {c.numero_corte}°
                        </div>
                        <div style={{ flex:1 }}>
                          <div style={{ fontWeight:600, fontSize:13 }}>{c.lote_nombre || "—"}</div>
                          <div style={{ fontSize:11, color:"var(--admin-mute)", display:"flex", gap:10, marginTop:2 }}>
                            <span><I name="Calendar" size={10} /> {c.fecha_corte}</span>
                            {rend.length > 0 && <span><I name="Package" size={10} /> {rend.join(" / ")}</span>}
                            {rend.length === 0 && <span style={{ fontStyle:"italic" }}>sin rendimiento registrado</span>}
                          </div>
                        </div>
                        {sel && <I name="CheckCircle2" size={16} style={{ color:"var(--green-800)", flexShrink:0 }} />}
                      </div>
                    );
                  });
              })()}
              {corteId && (
                <button type="button" className="btn btn-ghost btn-sm" style={{ alignSelf:"flex-start", fontSize:11 }}
                  onClick={async () => {
                    setCorteId("");
                    await window.API.patch(`/fardos/${realId}`, { corte_id: null });
                    window.toast("Corte desvinculado");
                  }}>
                  <I name="X" size={11} /> Quitar asignación
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ModalNuevoFardo({ onClose, onSuccess }) {
  const [nombre,     setNombre]     = useState("");
  const [tipo,       setTipo]       = useState("redondo");
  const [peso,       setPeso]       = useState("");
  const [proteina,   setProteina]   = useState("");
  const [calidad,    setCalidad]    = useState("Estándar");
  const [galpon,     setGalpon]     = useState("");
  const [stock,      setStock]      = useState("0");
  const [precio,     setPrecio]     = useState("");
  const [destacado,  setDestacado]  = useState(false);
  const [loading, setLoading] = useState(false);
  const [done,    setDone]    = useState(false);
  const [err,     setErr]     = useState("");

  const pesoDefault = { redondo: "350", mega: "500" };

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.post("/fardos", {
      nombre,
      tipo,
      peso_kg:      parseFloat(peso || pesoDefault[tipo]),
      proteina_pct: proteina ? parseFloat(proteina) : null,
      calidad,
      galpon:       galpon  || null,
      stock:        parseInt(stock) || 0,
      precio:       parseFloat(precio) || 0,
      destacado,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Agregar fardo al stock</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Fardo "{nombre}" agregado al stock.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__field">
              <label>Nombre del producto</label>
              <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required placeholder="Ej: Fardo Prismático Chico" autoFocus />
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Tipo</label>
                <select className="form__select" value={tipo} onChange={e => { setTipo(e.target.value); setPeso(pesoDefault[e.target.value]); }}>
                  <option value="redondo">Rollo</option>
                  <option value="mega">Mega</option>
                </select>
              </div>
              <div className="form__field">
                <label>Calidad</label>
                <select className="form__select" value={calidad} onChange={e => setCalidad(e.target.value)}>
                  <option value="Estándar">Estándar</option>
                  <option value="Premium">Premium</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Galpón</label>
                <select className="form__select" value={galpon} onChange={e => setGalpon(e.target.value)}>
                  <option value="">— seleccionar —</option>
                  <option>Galpón A</option><option>Galpón B</option><option>Galpón C</option><option>Galpón D</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Stock inicial</label>
                <input className="form__input" type="number" min="0" value={stock} onChange={e => setStock(e.target.value)} required />
              </div>
              <div className="form__field">
                <label>Precio por kilo ($)</label>
                <div style={{ position:"relative" }}>
                  <span style={{ position:"absolute", left:14, top:"50%", transform:"translateY(-50%)", color:"var(--admin-mute)", fontWeight:600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01" value={precio} onChange={e => setPrecio(e.target.value)} style={{ paddingLeft:28 }} placeholder="0" />
                </div>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field" style={{ justifyContent: "flex-end" }}>
                <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", paddingTop: 28 }}>
                  <input type="checkbox" checked={destacado} onChange={e => setDestacado(e.target.checked)} style={{ width: 16, height: 16 }} />
                  Destacado en catálogo
                </label>
              </div>
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={onClose} type="button">Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : <><I name="Package" size={13} /> Agregar al stock</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function StockTotal({ title, value, hint, icon, gold }) {
  return (
    <div className="kpi">
      <div className="kpi__head">
        <div className="kpi__icon" style={gold ? { background: "var(--gold-100)", color: "var(--gold-700)" } : null}><I name={icon} size={16} /></div>
      </div>
      <div className="kpi__label">{title}</div>
      <div className="kpi__value">{value}</div>
      <div className="kpi__hint">{hint}</div>
    </div>
  );
}

/* ============================================
   Ventas y clientes
   ============================================ */
function ModalNuevaVenta({ clientes, fardos, onClose, onSuccess }) {
  const D = window.DATA;
  const [clienteId,   setClienteId]   = useState("");
  const [clienteNom,  setClienteNom]  = useState("");
  const [fardoId,     setFardoId]     = useState("");
  const [producto,    setProducto]    = useState("");
  const [cantidad,    setCantidad]    = useState("");
  const [precio,      setPrecio]      = useState("");
  const [fecha,       setFecha]       = useState(new Date().toISOString().slice(0,10));
  const [formaPago,   setFormaPago]   = useState("transferencia");
  const [estado,      setEstado]      = useState("pagado");
  const [err,         setErr]         = useState("");
  const [loading,     setLoading]     = useState(false);

  const onClienteChange = (e) => {
    const id  = e.target.value;
    const cli = clientes.find(c => String(c.id) === id);
    setClienteId(id);
    setClienteNom(cli ? cli.nombre : "");
  };

  const onFardoChange = (e) => {
    const id = e.target.value;
    const f  = fardos.find(x => String(x.id) === id);
    setFardoId(id);
    setProducto(f ? f.nombre : "");
    if (f && f.precio > 0) setPrecio(String(f.precio));
  };

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const body = {
      cliente_id:      clienteId || null,
      cliente_nombre:  clienteNom || "Sin cliente",
      fardo_id:        fardoId || null,
      producto:        producto || "Producto sin especificar",
      cantidad:        parseInt(cantidad),
      precio_unitario: parseFloat(precio),
      fecha,
      forma_pago:      formaPago,
      estado,
    };
    const res = await window.API.post("/ventas", body);
    setLoading(false);
    if (res.data?.id || res.id) {
      window.toast("Venta registrada correctamente");
      onSuccess();
      onClose();
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" · ") : (res.message || "Error al guardar.");
      setErr(msgs);
    }
  };

  const monto = (parseFloat(cantidad) || 0) * (parseFloat(precio) || 0);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 520 }}>
        <div className="modal__head">
          <div className="modal__title">Registrar nueva venta</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__row">
            <div className="form__field">
              <label>Cliente</label>
              <select className="form__select" value={clienteId} onChange={onClienteChange} required>
                <option value="">Seleccioná un cliente</option>
                {clientes.map(c => <option key={c.id} value={c.id}>{c.nombre}</option>)}
              </select>
            </div>
            <div className="form__field">
              <label>Estado</label>
              <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
                <option value="pagado">Pagado</option>
                <option value="pendiente">Pendiente</option>
                <option value="parcial">Parcial</option>
              </select>
            </div>
          </div>
          <div className="form__field">
            <label>Producto</label>
            <select className="form__select" value={fardoId} onChange={onFardoChange} required>
              <option value="">Seleccioná un fardo</option>
              {fardos.map(f => (
                <option key={f.id} value={f.id}>
                  {f.nombre} · {f.tipo === "redondo" ? "Rollo" : "Mega"} · stock: {f.stock}
                  {f.precio > 0 ? ` · ${D.fmtARS(f.precio)}` : ""}
                </option>
              ))}
            </select>
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Cantidad</label>
              <input className="form__input" type="number" min="1" value={cantidad} onChange={e => setCantidad(e.target.value)} required placeholder="0" />
            </div>
            <div className="form__field">
              <label>Precio unitario ($)</label>
              <input className="form__input" type="number" min="0" step="0.01" value={precio} onChange={e => setPrecio(e.target.value)} required placeholder="0" />
            </div>
          </div>
          {monto > 0 && (
            <div style={{ fontSize: 13, color: "var(--admin-mute)", textAlign: "right", marginTop: -8 }}>
              Total: <strong style={{ color: "var(--admin-text)" }}>{D.fmtARS(monto)}</strong>
            </div>
          )}
          <div className="form__row">
            <div className="form__field">
              <label>Fecha</label>
              <input className="form__input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} required />
            </div>
            <div className="form__field">
              <label>Forma de pago</label>
              <select className="form__select" value={formaPago} onChange={e => setFormaPago(e.target.value)}>
                <option value="transferencia">Transferencia</option>
                <option value="cheque_diferido">Cheque diferido</option>
                <option value="efectivo">Efectivo</option>
                <option value="cuenta_corriente">Cuenta corriente</option>
              </select>
            </div>
          </div>
          {err && <div style={{ fontSize: 13, color: "var(--bad)", display: "flex", gap: 6 }}><I name="AlertCircle" size={14} />{err}</div>}
          <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf: "flex-end" }} disabled={loading}>
            {loading ? "Guardando..." : <><I name="Save" size={14} /> Guardar venta</>}
          </button>
        </form>
      </div>
    </div>
  );
}

function VentasModulo() {
  const D = window.DATA;
  const [showVenta,   setShowVenta]   = useState(false);
  const [showCliente, setShowCliente] = useState(false);
  const [CLIENTES,    setCLIENTES]    = useState([]);
  const [clienteSel,  setClienteSel]  = useState(null);
  const [VENTAS,      setVENTAS]      = useState([]);
  const [FARDOS,      setFARDOS]      = useState([]);
  const [resumen,     setResumen]     = useState({ total_mes: 0, total_mes_ant: 0, pendiente: 0, ticket_promedio: 0, count_mes: 0 });

  const recargar = () => {
    window.API.get("/clientes").then(r => {
      if (r.data) setCLIENTES(r.data.map(c => ({
        id: String(c.id), nombre: c.nombre, tipo: c.tipo || "—", ciudad: c.ciudad || "—",
        email: c.email || "", telefono: c.telefono || "", cuit: c.cuit || "",
        saldo: c.saldo_pendiente || 0, total: c.total_facturado || 0,
        ventasCount: c.ventas_count || 0, observaciones: c.observaciones || "",
      })));
    });
    window.API.get("/ventas").then(r => {
      if (r.data) setVENTAS(r.data);
    });
    window.API.get("/ventas-resumen").then(r => {
      if (r.total_mes !== undefined) setResumen(r);
    });
    window.API.get("/fardos").then(r => {
      if (r.data) setFARDOS(r.data);
    });
  };

  useEffect(() => { recargar(); }, []);

  const topData = VENTAS.reduce((acc, v) => {
    const key = v.cliente;
    acc[key] = (acc[key] || 0) + v.monto;
    return acc;
  }, {});
  const topClientes = Object.entries(topData).sort((a,b) => b[1]-a[1]).slice(0,6)
    .map(([name, total]) => ({ name: name.length > 18 ? name.slice(0,17)+"…" : name, total }));

  const deltasMes = resumen.total_mes_ant > 0
    ? Math.round(((resumen.total_mes - resumen.total_mes_ant) / resumen.total_mes_ant) * 100)
    : null;

  return (
    <div className="page" data-screen-label="Ventas">
      <div className="page__header">
        <div>
          <div className="page__title">Ventas y clientes</div>
          <div className="page__sub">{CLIENTES.length} clientes · {VENTAS.length} ventas registradas</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-secondary btn-sm" onClick={() => window.toast("Exportar ventas — próximamente")}><I name="Download" size={14} /> Exportar</button>
          <button className="btn btn-secondary btn-sm" onClick={() => setShowCliente(true)}><I name="UserPlus" size={14} /> Nuevo cliente</button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowVenta(true)}><I name="Plus" size={14} /> Nueva venta</button>
        </div>
      </div>

      <div className="kpi-grid">
        <Kpi icon="Receipt"    label="Ventas del mes" value={D.fmtARS(resumen.total_mes)} delta={deltasMes !== null ? `${deltasMes > 0 ? "+" : ""}${deltasMes}%` : ""} deltaDir={deltasMes > 0 ? "up" : "down"} hint="vs. mes anterior" />
        <Kpi icon="Users"      label="Clientes activos" value={String(CLIENTES.length)} delta="" deltaDir="flat" hint="registrados en el sistema" />
        <Kpi icon="Clock"      label="A cobrar" value={D.fmtARS(resumen.pendiente)} delta="" deltaDir="info" hint="pendiente + parcial" />
        <Kpi icon="TrendingUp" label="Ticket promedio" value={D.fmtARS(resumen.ticket_promedio)} delta="" deltaDir="flat" hint="ventas del mes" />
      </div>

      <div className="grid-2">
        <div className="panel" style={{ overflow: "hidden" }}>
          <div className="panel__head">
            <div className="panel__title">Ventas recientes</div>
            <span className="b b-mute">{VENTAS.length} ventas</span>
          </div>
          <div className="table-wrap" style={{ maxHeight: 460, overflow: "auto" }}>
            <table className="table">
              <thead>
                <tr><th>Fecha</th><th>Cliente</th><th>Producto</th><th className="num">Cant.</th><th className="num">Monto</th><th>Estado</th></tr>
              </thead>
              <tbody>
                {VENTAS.length === 0 && (
                  <tr><td colSpan="6" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>Sin ventas cargadas. Usá "Nueva venta" para registrar.</td></tr>
                )}
                {VENTAS.map(v => (
                  <tr key={v.id}>
                    <td className="num">{v.fecha}</td>
                    <td><strong>{v.cliente}</strong></td>
                    <td style={{ fontSize: 12.5, color: "var(--admin-mute)" }}>{v.producto}</td>
                    <td className="num">{v.cant}</td>
                    <td className="num money">{D.fmtARS(v.monto)}</td>
                    <td><EstadoBadge estado={v.estado} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="panel">
          <div className="panel__head">
            <div>
              <div className="panel__title">Top clientes</div>
              <div className="panel__sub">Por monto facturado</div>
            </div>
            <span className="b b-mute">{topClientes.length}</span>
          </div>
          <div style={{ padding:"6px 18px 18px", display:"flex", flexDirection:"column", gap:10 }}>
            {topClientes.length === 0
              ? <div style={{ textAlign:"center", padding:30, color:"var(--admin-mute)", fontSize:13 }}>Sin ventas aún</div>
              : (() => {
                  const max = Math.max(...topClientes.map(c => c.total));
                  const medals = ["#facc15", "#94a3b8", "#b45309"];
                  return topClientes.map((c, i) => {
                    const pct = max > 0 ? (c.total / max) * 100 : 0;
                    const medal = medals[i];
                    return (
                      <div key={c.name} style={{ display:"flex", alignItems:"center", gap:10 }}>
                        <div style={{
                          width:24, height:24, borderRadius:"50%", flexShrink:0,
                          background: medal || "var(--admin-bg)",
                          color: medal ? "#fff" : "var(--admin-mute)",
                          display:"grid", placeItems:"center",
                          fontSize:11, fontWeight:700,
                        }}>{i+1}</div>
                        <div style={{ flex:1, minWidth:0 }}>
                          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:4, gap:8 }}>
                            <span style={{ fontSize:13, fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{c.name}</span>
                            <span style={{ fontSize:13, fontWeight:600, color:"var(--green-800)", whiteSpace:"nowrap" }}>{D.fmtARS(c.total)}</span>
                          </div>
                          <div style={{ background:"var(--admin-bg)", borderRadius:999, height:6, overflow:"hidden" }}>
                            <div style={{
                              width:`${pct}%`, height:"100%",
                              background:`linear-gradient(90deg, var(--green-800), var(--green-700,#3d6b1f))`,
                              borderRadius:999, transition:"width 600ms ease",
                            }} />
                          </div>
                        </div>
                      </div>
                    );
                  });
                })()
            }
          </div>
        </div>
      </div>

      <div className="panel">
        <div className="panel__head">
          <div>
            <div className="panel__title">Listado de clientes</div>
            <div className="panel__sub">Registrados en el sistema</div>
          </div>
          {resumen.pendiente > 0 && (
            <div style={{ background: "var(--bad)", color: "#fff", padding: "6px 14px", borderRadius: 999, fontSize: 12, fontWeight: 600 }}>
              Total a cobrar: {D.fmtARS(resumen.pendiente)}
            </div>
          )}
        </div>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr><th>Cliente</th><th>Tipo</th><th>Ciudad</th><th>Teléfono</th><th>Email</th><th className="num">Cuenta corriente</th></tr>
            </thead>
            <tbody>
              {CLIENTES.length === 0 && (
                <tr><td colSpan="6" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>Sin clientes cargados. Usá "Nuevo cliente" para agregar.</td></tr>
              )}
              {CLIENTES.map(c => (
                <tr key={c.id} style={{ cursor:"pointer" }}
                  onClick={() => setClienteSel(c)}
                  onMouseEnter={e => e.currentTarget.style.background="var(--admin-bg)"}
                  onMouseLeave={e => e.currentTarget.style.background=""}>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--green-800)", color: "#fff", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 600 }}>
                        {c.nombre.split(" ").map(s=>s[0]).slice(0,2).join("")}
                      </div>
                      <strong>{c.nombre}</strong>
                    </div>
                  </td>
                  <td><span className={`b ${c.tipo === "tambo" ? "b-green" : c.tipo === "haras" ? "b-gold" : c.tipo === "cria" ? "b-info" : "b-mute"}`}>{c.tipo}</span></td>
                  <td>{c.ciudad}</td>
                  <td style={{ fontSize: 12.5 }}>{c.telefono || "—"}</td>
                  <td style={{ fontSize: 12.5 }}>{c.email || "—"}</td>
                  <td className="num">
                    {c.saldo > 0
                      ? <span className="b b-bad"><I name="AlertCircle" size={11} /> {D.fmtARS(c.saldo)}</span>
                      : <span style={{ color:"var(--admin-mute)", fontSize:12 }}>Al día</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showCliente && <ModalNuevoCliente onClose={() => setShowCliente(false)} onSuccess={recargar} />}
      {showVenta   && <ModalNuevaVenta clientes={CLIENTES} fardos={FARDOS} onClose={() => setShowVenta(false)} onSuccess={recargar} />}
      {clienteSel  && <ModalDetalleCliente cliente={clienteSel} onClose={() => setClienteSel(null)} onSuccess={() => { setClienteSel(null); recargar(); }} onRefresh={recargar} />}
    </div>
  );
}
function ModalDetalleCliente({ cliente, onClose, onSuccess, onRefresh }) {
  const D = window.DATA;
  const [tab,       setTab]       = useState("datos");
  const [nombre,    setNombre]    = useState(cliente.nombre || "");
  const [tipo,      setTipo]      = useState(cliente.tipo || "tambo");
  const [ciudad,    setCiudad]    = useState(cliente.ciudad !== "—" ? cliente.ciudad : "");
  const [telefono,  setTelefono]  = useState(cliente.telefono || "");
  const [email,     setEmail]     = useState(cliente.email || "");
  const [cuit,      setCuit]      = useState(cliente.cuit || "");
  const [obs,       setObs]       = useState(cliente.observaciones || "");
  const [historial, setHistorial] = useState({ ventas: [], cliente: null });
  const [loading,   setLoading]   = useState(false);
  const [err,       setErr]       = useState("");
  const [confirmar, setConfirmar] = useState(false);
  const [pagoSel,   setPagoSel]   = useState(null); // venta a marcar pagada

  useEffect(() => {
    window.API.get(`/clientes/${cliente.id}/historial`).then(r => {
      if (r.ventas) setHistorial(r);
    });
  }, [cliente.id]);

  const guardar = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const body = {
      nombre, tipo,
      ciudad:        ciudad   || null,
      telefono:      telefono || null,
      email:         email    || null,
      cuit:          cuit     || null,
      observaciones: obs      || null,
    };
    const res = await window.API.put(`/clientes/${cliente.id}`, body);
    setLoading(false);
    if (res.data?.id || res.id) {
      window.toast(`Cliente "${nombre}" actualizado`);
      onSuccess && onSuccess();
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" · ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  const eliminar = async () => {
    await window.API.del(`/clientes/${cliente.id}`);
    window.toast(`"${cliente.nombre}" eliminado`);
    onSuccess && onSuccess();
  };

  const TabBtnC = ({ id, label, badge }) => (
    <button type="button" onClick={() => setTab(id)} style={{
      padding:"10px 18px", background:"none", border:"none", cursor:"pointer",
      fontWeight: tab===id ? 600 : 400, fontSize:13,
      color: tab===id ? "var(--green-800)" : "var(--admin-mute)",
      borderBottom: tab===id ? "2px solid var(--green-800)" : "2px solid transparent",
      marginBottom:-1, display:"flex", alignItems:"center", gap:6,
    }}>
      {label}
      {badge !== undefined && badge !== null && <span className="b b-mute" style={{ fontSize:10 }}>{badge}</span>}
    </button>
  );

  const estadoBadge = (estado) => {
    const cls = estado === "pagado" ? "b-green" : estado === "parcial" ? "b-gold" : "b-bad";
    const lbl = estado === "pagado" ? "Pagado" : estado === "parcial" ? "Parcial" : "Pendiente";
    return <span className={`b ${cls}`}>{lbl}</span>;
  };

  const saldo = historial.cliente?.saldo_pendiente ?? cliente.saldo ?? 0;
  const total = historial.cliente?.total_facturado ?? cliente.total ?? 0;

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}
        style={{ maxWidth:900, width:"95vw", maxHeight:"90vh", display:"flex", flexDirection:"column" }}>

        <div className="modal__head">
          <div style={{ display:"flex", gap:12, alignItems:"center" }}>
            <div style={{ width:42, height:42, borderRadius:"50%", background:"var(--green-800)", color:"#fff", display:"grid", placeItems:"center", fontSize:14, fontWeight:600 }}>
              {cliente.nombre.split(" ").map(s=>s[0]).slice(0,2).join("")}
            </div>
            <div>
              <div style={{ fontSize:11, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.08em" }}>
                {cliente.tipo} {cliente.ciudad && cliente.ciudad !== "—" ? "· " + cliente.ciudad : ""}
              </div>
              <div className="modal__title">{cliente.nombre}</div>
            </div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        {/* Resumen rápido */}
        <div style={{ display:"flex", gap:0, padding:"12px 22px", background:"var(--admin-bg)", borderBottom:"1px solid var(--admin-line)" }}>
          <div style={{ flex:1, borderRight:"1px solid var(--admin-line)" }}>
            <div style={{ fontSize:10, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.08em" }}>Cuenta corriente</div>
            <div style={{ fontSize:18, fontWeight:600, color: saldo > 0 ? "var(--bad)" : "var(--good)" }}>
              {saldo > 0 ? D.fmtARS(saldo) : "Al día"}
            </div>
          </div>
          <div style={{ flex:1, paddingLeft:16, borderRight:"1px solid var(--admin-line)" }}>
            <div style={{ fontSize:10, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.08em" }}>Total facturado</div>
            <div style={{ fontSize:18, fontWeight:600 }}>{D.fmtARS(total)}</div>
          </div>
          <div style={{ flex:1, paddingLeft:16 }}>
            <div style={{ fontSize:10, color:"var(--admin-mute)", textTransform:"uppercase", letterSpacing:"0.08em" }}>Ventas</div>
            <div style={{ fontSize:18, fontWeight:600 }}>{historial.ventas?.length || 0}</div>
          </div>
        </div>

        <div style={{ display:"flex", borderBottom:"1px solid var(--admin-line)", padding:"0 22px" }}>
          <TabBtnC id="datos"   label="Datos" />
          <TabBtnC id="ventas"  label="Historial de ventas" badge={historial.ventas?.length || 0} />
        </div>

        <div style={{ flex:1, overflowY:"auto", padding:"16px 22px" }}>
          {tab === "datos" ? (
            <form className="form" onSubmit={guardar}>
              <div className="form__row">
                <div className="form__field">
                  <label>Nombre / Establecimiento</label>
                  <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required autoFocus />
                </div>
                <div className="form__field">
                  <label>Tipo</label>
                  <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                    <option value="tambo">Tambo</option>
                    <option value="haras">Haras</option>
                    <option value="cria">Cría</option>
                    <option value="otro">Otro</option>
                  </select>
                </div>
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label>Ciudad</label>
                  <input className="form__input" value={ciudad} onChange={e => setCiudad(e.target.value)} />
                </div>
                <div className="form__field">
                  <label>Teléfono</label>
                  <input className="form__input" value={telefono} onChange={e => setTelefono(e.target.value)} />
                </div>
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label>Email</label>
                  <input className="form__input" type="email" value={email} onChange={e => setEmail(e.target.value)} />
                </div>
                <div className="form__field">
                  <label>CUIT</label>
                  <input className="form__input" value={cuit} onChange={e => {
                    const digits = e.target.value.replace(/\D/g, "").slice(0, 11);
                    let fmt = digits;
                    if (digits.length > 2)  fmt = digits.slice(0,2) + "-" + digits.slice(2);
                    if (digits.length > 10) fmt = digits.slice(0,2) + "-" + digits.slice(2,10) + "-" + digits.slice(10);
                    setCuit(fmt);
                  }} placeholder="Ej: 20-12345678-9" maxLength={13} />
                </div>
              </div>
              <div className="form__field">
                <label>Observaciones</label>
                <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} />
              </div>
              {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
              <div style={{ display:"flex", justifyContent:"space-between", gap:8 }}>
                {!confirmar
                  ? <button type="button" className="btn btn-ghost btn-sm" style={{ color:"var(--bad)" }} onClick={() => setConfirmar(true)}>
                      <I name="Trash2" size={13} /> Eliminar cliente
                    </button>
                  : <div style={{ display:"flex", gap:6, alignItems:"center" }}>
                      <span style={{ fontSize:12, color:"var(--bad)" }}>¿Eliminar "{cliente.nombre}"?</span>
                      <button type="button" className="btn btn-secondary btn-sm" onClick={() => setConfirmar(false)}>No</button>
                      <button type="button" className="btn btn-primary btn-sm" style={{ background:"var(--bad)" }} onClick={eliminar}>Sí, eliminar</button>
                    </div>
                }
                <button type="submit" className="btn btn-primary btn-sm" disabled={loading}>
                  {loading ? "Guardando..." : <><I name="Save" size={13} /> Guardar cambios</>}
                </button>
              </div>
            </form>
          ) : (
            historial.ventas?.length === 0
              ? <div style={{ textAlign:"center", padding:32, color:"var(--admin-mute)" }}>Sin ventas registradas para este cliente.</div>
              : <table className="table">
                  <thead>
                    <tr><th>Fecha</th><th>Producto</th><th className="num">Cant.</th><th className="num">Monto</th><th>Pago</th><th>Estado</th><th></th></tr>
                  </thead>
                  <tbody>
                    {historial.ventas.map(v => (
                      <tr key={v.id}>
                        <td className="num">{v.fecha}</td>
                        <td style={{ fontSize:12.5 }}>{v.producto}</td>
                        <td className="num">{v.cantidad}</td>
                        <td className="num money"><strong>{D.fmtARS(v.monto)}</strong></td>
                        <td style={{ fontSize:11, color:"var(--admin-mute)" }}>{v.forma_pago?.replace("_", " ")}</td>
                        <td>{estadoBadge(v.estado)}</td>
                        <td>
                          {v.estado !== "pagado" && (
                            <button className="btn btn-secondary btn-sm" style={{ fontSize:11, padding:"4px 10px", color:"var(--good)", borderColor:"var(--good)" }}
                              onClick={() => setPagoSel(v)}>
                              <I name="CheckCircle2" size={12} /> Marcar pagado
                            </button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
          )}
        </div>

        {pagoSel && (
          <div className="modal-back" onClick={() => setPagoSel(null)} style={{ zIndex:1100 }}>
            <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth:400 }}>
              <div className="modal__head">
                <div className="modal__title">Confirmar pago</div>
                <button className="modal__close" onClick={() => setPagoSel(null)}><I name="X" size={18} /></button>
              </div>
              <div style={{ padding:"4px 22px 18px" }}>
                <p style={{ fontSize:14, marginBottom:14 }}>
                  ¿Estás seguro que <strong>{cliente.nombre}</strong> entregó el dinero de esta venta?
                </p>
                <div style={{ background:"var(--admin-bg)", borderRadius:8, padding:"10px 14px", marginBottom:16, fontSize:13 }}>
                  <div><strong>Producto:</strong> {pagoSel.producto}</div>
                  <div><strong>Fecha:</strong> {pagoSel.fecha}</div>
                  <div><strong>Monto:</strong> <span style={{ color:"var(--good)", fontWeight:600 }}>{D.fmtARS(pagoSel.monto)}</span></div>
                  <div><strong>Estado actual:</strong> {pagoSel.estado}</div>
                </div>
                <div style={{ display:"flex", gap:8, justifyContent:"flex-end" }}>
                  <button className="btn btn-secondary btn-sm" onClick={() => setPagoSel(null)}>Cancelar</button>
                  <button className="btn btn-primary btn-sm"
                    onClick={async () => {
                      await window.API.post(`/ventas/${pagoSel.id}/marcar-pagado`, {});
                      window.toast(`Pago de ${D.fmtARS(pagoSel.monto)} registrado`);
                      const r = await window.API.get(`/clientes/${cliente.id}/historial`);
                      if (r.ventas) setHistorial(r);
                      onRefresh && onRefresh();
                      setPagoSel(null);
                    }}>
                    <I name="CheckCircle2" size={14} /> Sí, confirmar pago
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ModalNuevoCliente({ onClose, onSuccess }) {
  const [nombre,  setNombre]  = useState("");
  const [tipo,    setTipo]    = useState("tambo");
  const [ciudad,  setCiudad]  = useState("");
  const [telefono,setTelefono]= useState("");
  const [email,   setEmail]   = useState("");
  const [cuit,    setCuit]    = useState("");
  const [obs,     setObs]     = useState("");
  const [loading, setLoading] = useState(false);
  const [done,    setDone]    = useState(false);
  const [err,     setErr]     = useState("");

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.post("/clientes", {
      nombre,
      tipo,
      ciudad:       ciudad   || null,
      telefono:     telefono || null,
      email:        email    || null,
      cuit:         cuit     || null,
      observaciones:obs      || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Nuevo cliente</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Cliente "{nombre}" guardado correctamente.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__row">
              <div className="form__field">
                <label>Nombre / Establecimiento</label>
                <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required placeholder="Ej: Tambo La Esperanza" autoFocus />
              </div>
              <div className="form__field">
                <label>Tipo</label>
                <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                  <option value="tambo">Tambo</option>
                  <option value="haras">Haras</option>
                  <option value="cria">Cría</option>
                  <option value="otro">Otro</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Ciudad</label>
                <input className="form__input" value={ciudad} onChange={e => setCiudad(e.target.value)} placeholder="Ej: Las Varillas, Cba" />
              </div>
              <div className="form__field">
                <label>Teléfono</label>
                <input className="form__input" value={telefono} onChange={e => setTelefono(e.target.value)} placeholder="Ej: (03562) 15-678-2341" />
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Email</label>
                <input className="form__input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="cliente@ejemplo.com" />
              </div>
              <div className="form__field">
                <label>CUIT</label>
                <input className="form__input" value={cuit} onChange={e => {
                  const digits = e.target.value.replace(/\D/g, "").slice(0, 11);
                  let fmt = digits;
                  if (digits.length > 2)  fmt = digits.slice(0,2) + "-" + digits.slice(2);
                  if (digits.length > 10) fmt = digits.slice(0,2) + "-" + digits.slice(2,10) + "-" + digits.slice(10);
                  setCuit(fmt);
                }} placeholder="Ej: 20-12345678-9" maxLength={13} />
              </div>
            </div>
            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} placeholder="Notas adicionales..." />
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={onClose} type="button">Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : <><I name="UserPlus" size={13} /> Guardar cliente</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ModalNuevoServicio({ direccion, onClose, onSuccess }) {
  const D = window.DATA;
  const tiposSrv = direccion === "prestado"
    ? ["Siembra de alfalfa","Corte y rastrillado","Enfardado redondo","Enfardado prismático","Megaenfardado","Otro"]
    : ["Fumigación","Pulverización","Cosecha","Transporte","Reparación maquinaria","Veterinario","Otro"];

  const [contraparte, setContraparte] = useState("");
  const [servicio,    setServicio]    = useState(tiposSrv[0]);
  const [hectareas,   setHectareas]   = useState("");
  const [fecha,       setFecha]       = useState(new Date().toISOString().slice(0,10));
  const [monto,       setMonto]       = useState("");
  const [estado,      setEstado]      = useState("pendiente");
  const [obs,         setObs]         = useState("");
  const [err,         setErr]         = useState("");
  const [loading,     setLoading]     = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const res = await window.API.post("/servicios", {
      direccion, contraparte, servicio,
      hectareas: hectareas ? parseFloat(hectareas) : null,
      fecha, monto: parseFloat(monto) || 0, estado,
      observaciones: obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) { window.toast("Servicio registrado"); onSuccess(); onClose(); }
    else { setErr(res.message || "Error al guardar."); }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth:520 }}>
        <div className="modal__head">
          <div className="modal__title">
            {direccion === "prestado" ? "Nuevo servicio prestado" : "Nuevo servicio contratado"}
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__field">
            <label>{direccion === "prestado" ? "Cliente" : "Proveedor / Contratista"}</label>
            <input className="form__input" value={contraparte} onChange={e => setContraparte(e.target.value)} required autoFocus
              placeholder={direccion === "prestado" ? "Ej: Tambo Don José" : "Ej: Pulverizadora Sacanta"} />
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Tipo de servicio</label>
              <select className="form__select" value={servicio} onChange={e => setServicio(e.target.value)}>
                {tiposSrv.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
            </div>
            <div className="form__field">
              <label>Hectáreas <span style={{ color:"var(--admin-mute)", fontWeight:400 }}>(opcional)</span></label>
              <input className="form__input" type="number" step="0.01" min="0" value={hectareas} onChange={e => setHectareas(e.target.value)} placeholder="0" />
            </div>
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Fecha</label>
              <input className="form__input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} required />
            </div>
            <div className="form__field">
              <label>Monto ($)</label>
              <input className="form__input" type="number" min="0" step="0.01" value={monto} onChange={e => setMonto(e.target.value)} required />
            </div>
          </div>
          <div className="form__field">
            <label>Estado</label>
            <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
              <option value="pendiente">Pendiente — sin {direccion === "prestado" ? "cobrar" : "pagar"}</option>
              <option value="parcial">Parcial — {direccion === "prestado" ? "cobrado" : "pagado"} en parte</option>
              <option value="completado">Completado — {direccion === "prestado" ? "cobrado total" : "pagado total"}</option>
            </select>
          </div>
          <div className="form__field">
            <label>Observaciones</label>
            <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} />
          </div>
          {err && <div style={{ fontSize:13, color:"var(--bad)" }}>{err}</div>}
          <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf:"flex-end" }} disabled={loading}>
            {loading ? "Guardando..." : <><I name="Save" size={14} /> Guardar</>}
          </button>
        </form>
      </div>
    </div>
  );
}

function ServiciosTerceros() {
  const D = window.DATA;
  const [tab,         setTab]         = useState("prestado");
  const [showNuevo,   setShowNuevo]   = useState(false);
  const [servicios,   setServicios]   = useState([]);
  const [resumen,     setResumen]     = useState({ prestados: { total:0, cobrado:0, pendiente:0, count:0 }, contratados: { total:0, pagado:0, pendiente:0, count:0 } });

  const recargar = () => {
    window.API.get("/servicios").then(r => { if (r.data) setServicios(r.data); });
    window.API.get("/servicios-resumen").then(r => { if (r.prestados) setResumen(r); });
  };

  useEffect(() => { recargar(); }, []);

  const listado = servicios.filter(s => s.direccion === tab);
  const estatusLabel = (estado, dir) => {
    if (estado === "completado") return dir === "prestado" ? "Cobrado" : "Pagado";
    if (estado === "parcial")    return "Parcial";
    return "Pendiente";
  };
  const estatusCls = (estado) => estado === "completado" ? "b-green" : estado === "parcial" ? "b-gold" : "b-bad";

  const totalHa = listado.reduce((s, r) => s + (r.hectareas || 0), 0);
  const stats = tab === "prestado" ? resumen.prestados : resumen.contratados;
  const colorAccion = tab === "prestado" ? "var(--good)" : "var(--bad)";
  const labelAccion = tab === "prestado" ? "Cobrado"    : "Pagado";
  const labelPendiente = tab === "prestado" ? "A cobrar" : "A pagar";
  const valorAccion = tab === "prestado" ? stats.cobrado : stats.pagado;

  const eliminarServicio = async (id) => {
    if (!confirm("¿Eliminar este servicio?")) return;
    await window.API.del(`/servicios/${id}`);
    window.toast("Servicio eliminado");
    recargar();
  };

  const marcarCompletado = async (id) => {
    await window.API.patch(`/servicios/${id}`, { estado: "completado" });
    window.toast(tab === "prestado" ? "Marcado como cobrado" : "Marcado como pagado");
    recargar();
  };

  return (
    <div className="page" data-screen-label="Terceros">
      <div className="page__header">
        <div>
          <div className="page__title">Servicios a terceros</div>
          <div className="page__sub">Servicios que damos a clientes y servicios que contratamos a terceros</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-primary btn-sm" onClick={() => setShowNuevo(true)}>
            <I name="Plus" size={14} /> Nuevo {tab === "prestado" ? "servicio" : "contratado"}
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display:"flex", gap:0, borderBottom:"2px solid var(--admin-line)", marginBottom:18 }}>
        <button onClick={() => setTab("prestado")} style={{
          padding:"12px 22px", background:"none", border:"none", cursor:"pointer",
          fontWeight: tab==="prestado" ? 600 : 400, fontSize:14,
          color: tab==="prestado" ? "var(--green-800)" : "var(--admin-mute)",
          borderBottom: tab==="prestado" ? "3px solid var(--green-800)" : "3px solid transparent",
          marginBottom:-2, display:"flex", alignItems:"center", gap:8,
        }}>
          <I name="ArrowUpRight" size={15} /> Servicios que damos
          <span className="b b-mute" style={{ fontSize:11 }}>{resumen.prestados.count}</span>
        </button>
        <button onClick={() => setTab("contratado")} style={{
          padding:"12px 22px", background:"none", border:"none", cursor:"pointer",
          fontWeight: tab==="contratado" ? 600 : 400, fontSize:14,
          color: tab==="contratado" ? "var(--gold-700)" : "var(--admin-mute)",
          borderBottom: tab==="contratado" ? "3px solid var(--gold-700)" : "3px solid transparent",
          marginBottom:-2, display:"flex", alignItems:"center", gap:8,
        }}>
          <I name="ArrowDownLeft" size={15} /> Servicios que contratamos
          <span className="b b-mute" style={{ fontSize:11 }}>{resumen.contratados.count}</span>
        </button>
      </div>

      <div className="kpi-grid">
        <Kpi icon="ListChecks" label={`${tab === "prestado" ? "Trabajos" : "Contrataciones"}`} value={String(stats.count)} delta="" deltaDir="flat" hint="total registrados" />
        <Kpi icon="Map" label="Hectáreas" value={totalHa > 0 ? totalHa.toFixed(0) + " ha" : "—"} delta="" deltaDir="info" hint="acumuladas" />
        <Kpi icon="CheckCircle2" label={labelAccion} value={D.fmtARS(valorAccion)} delta="" deltaDir="up" hint="finalizados" />
        <Kpi icon="Clock" label={labelPendiente} value={D.fmtARS(stats.pendiente)} delta="" deltaDir="flat" hint="por liquidar" />
      </div>

      <div className="panel">
        <div className="panel__head">
          <div className="panel__title">
            {tab === "prestado" ? "Servicios prestados" : "Servicios contratados"}
          </div>
          <span className="b b-mute">{listado.length} registros</span>
        </div>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>{tab === "prestado" ? "Cliente" : "Proveedor"}</th>
                <th>Servicio</th>
                <th className="num">Has</th>
                <th>Fecha</th>
                <th className="num">Monto</th>
                <th>Estado</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {listado.length === 0 && (
                <tr><td colSpan="7" style={{ textAlign:"center", padding:30, color:"var(--admin-mute)" }}>
                  Sin servicios {tab === "prestado" ? "prestados" : "contratados"} registrados.
                </td></tr>
              )}
              {listado.map(s => (
                <tr key={s.id}>
                  <td><strong>{s.contraparte}</strong></td>
                  <td style={{ fontSize:13 }}>{s.servicio}</td>
                  <td className="num">{s.hectareas ? s.hectareas : "—"}</td>
                  <td className="num">{s.fecha}</td>
                  <td className="num money">{D.fmtARS(s.monto)}</td>
                  <td><span className={`b ${estatusCls(s.estado)}`}>{estatusLabel(s.estado, s.direccion)}</span></td>
                  <td>
                    <div style={{ display:"flex", gap:4 }}>
                      {s.estado !== "completado" && (
                        <button className="icon-btn" title={tab === "prestado" ? "Marcar cobrado" : "Marcar pagado"}
                          style={{ color:"var(--good)" }} onClick={() => marcarCompletado(s.id)}>
                          <I name="CheckCircle2" size={14} />
                        </button>
                      )}
                      <button className="icon-btn" title="Eliminar" style={{ color:"var(--bad)" }} onClick={() => eliminarServicio(s.id)}>
                        <I name="Trash2" size={14} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showNuevo && <ModalNuevoServicio direccion={tab} onClose={() => setShowNuevo(false)} onSuccess={recargar} />}
    </div>
  );
}

/* ============================================
   Gastos y costos
   ============================================ */
/* ── Configuración de categorías de gastos ── */
const CATS_GASTO = [
  { key: "combustible",   label: "Combustible",       icon: "Fuel",       color: "#2d5016" },
  { key: "mantenimiento", label: "Mantenimiento",      icon: "Wrench",     color: "#3b82f6" },
  { key: "insumos",       label: "Insumos",            icon: "Package",    color: "#d4a574" },
  { key: "personal",      label: "Personal",           icon: "Users",      color: "#f59e0b" },
  { key: "servicios",     label: "Servicios",          icon: "Zap",        color: "#8b5cf6" },
  { key: "logistica",     label: "Logística",          icon: "Truck",      color: "#0891b2" },
  { key: "compra_fardos", label: "Compra de fardos",   icon: "Building2",  color: "#8b6f47" },
  { key: "uso_personal",  label: "Uso personal",       icon: "UserCircle", color: "#ef4444" },
  { key: "otros",         label: "Otros",              icon: "Receipt",    color: "#6b7280" },
];

function Gastos() {
  const D = window.DATA;
  const [gastos,     setGastos]     = useState([]);
  const [catSel,     setCatSel]     = useState("todas");
  const [tabModo,    setTabModo]    = useState("gastos");
  const [showNuevo,  setShowNuevo]  = useState(false);
  const [gastoSel,   setGastoSel]   = useState(null);  // gasto abierto en detalle/edición
  const [loading,    setLoading]    = useState(true);

  const recargar = () => {
    setLoading(true);
    window.API.get("/gastos").then(r => {
      if (r.data) setGastos(r.data);
      setLoading(false);
    }).catch(() => setLoading(false));
  };

  useEffect(() => { recargar(); }, []);

  // ── totales ──────────────────────────────────────────────────────
  const gastosConMonto = gastos.filter(g => g.monto != null);
  const totalGeneral   = gastosConMonto.reduce((s, g) => s + g.monto, 0);

  const totalPorCat = (key) =>
    gastosConMonto.filter(g => g.categoria === key).reduce((s, g) => s + g.monto, 0);

  // gastos filtrados para la tabla
  const gastosBase      = gastos.filter(g => g.categoria !== "uso_personal");
  const gastosPersonal  = gastos.filter(g => g.categoria === "uso_personal");

  const gastosFiltrados = catSel === "todas"
    ? gastosBase
    : gastosBase.filter(g => g.categoria === catSel);
  const totalFiltrado   = gastosFiltrados.filter(g => g.monto).reduce((s, g) => s + g.monto, 0);
  const totalPersonal   = gastosPersonal.filter(g => g.monto).reduce((s, g) => s + g.monto, 0);

  // datos para el gráfico de torta
  const pieData = CATS_GASTO.map(c => ({
    cat:   c.label,
    monto: totalPorCat(c.key),
    color: c.color,
  })).filter(c => c.monto > 0);

  return (
    <div className="page" data-screen-label="Gastos">
      <div className="page__header">
        <div>
          <div className="page__title">Gastos y costos</div>
          <div className="page__sub">
            {gastos.length} movimientos · total {D.fmtARS(totalGeneral)}
            {gastosPersonal.length > 0 && ` · uso personal ${D.fmtARS(totalPersonal)}`}
          </div>
        </div>
        <div className="page__actions">
          <button className="btn btn-secondary btn-sm"
            onClick={() => window.toast("Exportando gastos...")}>
            <I name="Download" size={14} /> Exportar
          </button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowNuevo(true)}>
            <I name="Plus" size={14} /> Cargar gasto
          </button>
        </div>
      </div>

      {/* ── Tabs: Gastos / Uso personal ── */}
      <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
        {[["gastos", "Gastos generales"], ["personal", "Uso personal"]].map(([k, l]) => (
          <button key={k} className={`chip ${tabModo === k ? "is-active" : ""}`}
            onClick={() => setTabModo(k)}>
            {k === "personal" && <I name="UserCircle" size={12} />} {l}
            {k === "personal" && gastosPersonal.length > 0 &&
              <span style={{ marginLeft: 6, background: "var(--bad)", color: "#fff", borderRadius: 999, padding: "0 6px", fontSize: 10 }}>
                {gastosPersonal.length}
              </span>}
          </button>
        ))}
      </div>

      {/* ════════════════════════════════════════════════════════════
          TAB: GASTOS GENERALES
          ════════════════════════════════════════════════════════════ */}
      {tabModo === "gastos" && (
        <>
          {/* KPI por categoría (excluyendo uso_personal) */}
          <div className="kpi-grid">
            {/* Card "Todas" */}
            <div className="kpi" onClick={() => setCatSel("todas")} style={{
              cursor: "pointer",
              borderColor:  catSel === "todas" ? "var(--green-700)" : undefined,
              boxShadow:    catSel === "todas" ? "0 0 0 2px var(--green-100)" : undefined,
              transition: "all 140ms",
            }}>
              <div className="kpi__head">
                <div className="kpi__icon" style={{ background: "var(--green-50)", color: "var(--green-800)" }}>
                  <I name="LayoutGrid" size={16} />
                </div>
              </div>
              <div className="kpi__label">Todas</div>
              <div className="kpi__value" style={{ fontSize: 22 }}>
                {D.fmtARS(gastosBase.filter(g => g.monto).reduce((s,g) => s + g.monto, 0))}
              </div>
              <div className="kpi__hint">{gastosBase.length} movimientos</div>
            </div>

            {/* Card por categoría */}
            {CATS_GASTO.filter(c => c.key !== "uso_personal").map(c => {
              const total = totalPorCat(c.key);
              const cant  = gastos.filter(g => g.categoria === c.key).length;
              const isActive = catSel === c.key;
              return (
                <div key={c.key} className="kpi" onClick={() => setCatSel(c.key)} style={{
                  cursor: "pointer",
                  borderColor: isActive ? c.color : undefined,
                  boxShadow:   isActive ? `0 0 0 2px ${c.color}30` : undefined,
                  transition: "all 140ms",
                }}>
                  <div className="kpi__head">
                    <div className="kpi__icon" style={{ background: c.color + "22", color: c.color }}>
                      <I name={c.icon} size={16} />
                    </div>
                  </div>
                  <div className="kpi__label">{c.label}</div>
                  <div className="kpi__value" style={{ fontSize: 22 }}>{D.fmtARS(total)}</div>
                  <div className="kpi__hint">{cant} mov.</div>
                </div>
              );
            })}
          </div>

          {/* Gráfico + tabla */}
          {pieData.length > 0 && (
            <ChartCard title="Distribución de gastos" sub={`Total: ${D.fmtARS(totalGeneral)}`} height={280}>
              <RC.PieChart>
                <RC.Pie data={pieData} dataKey="monto" nameKey="cat"
                  innerRadius={60} outerRadius={100} paddingAngle={2} animationDuration={900}>
                  {pieData.map((e, i) => <RC.Cell key={i} fill={e.color} stroke="#fff" strokeWidth={2} />)}
                </RC.Pie>
                <RC.Tooltip
                  contentStyle={{ background: "#0e1f0a", border: "none", borderRadius: 10, color: "#fff", fontSize: 12 }}
                  formatter={(v) => [D.fmtARS(v), ""]}
                />
                <RC.Legend wrapperStyle={{ fontSize: 11.5 }} iconType="circle" />
              </RC.PieChart>
            </ChartCard>
          )}

          {/* Tabla detalle */}
          <div className="panel">
            <div className="panel__head">
              <div>
                <div className="panel__title">
                  {catSel === "todas" ? "Todos los gastos" : `Gastos — ${CATS_GASTO.find(c=>c.key===catSel)?.label}`}
                </div>
                <div className="panel__sub">{gastosFiltrados.length} movimientos · {D.fmtARS(totalFiltrado)}</div>
              </div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                <button className={`chip ${catSel === "todas" ? "is-active" : ""}`} onClick={() => setCatSel("todas")}>Todas</button>
                {CATS_GASTO.filter(c => c.key !== "uso_personal").map(c => (
                  <button key={c.key} className={`chip ${catSel === c.key ? "is-active" : ""}`} onClick={() => setCatSel(c.key)}>{c.label}</button>
                ))}
              </div>
            </div>
            <div className="table-wrap">
              <table className="table">
                <thead>
                  <tr><th>Fecha</th><th>Categoría</th><th>Detalle</th><th>Proveedor / A quién</th><th>Método</th><th className="num">Monto</th><th>Estado</th></tr>
                </thead>
                <tbody>
                  {loading && (
                    <tr><td colSpan="7" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>Cargando...</td></tr>
                  )}
                  {!loading && gastosFiltrados.length === 0 && (
                    <tr><td colSpan="7" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>
                      No hay gastos registrados.{catSel === "todas" ? ' Usá "Cargar gasto" para agregar.' : " Cambiá el filtro de categoría."}
                    </td></tr>
                  )}
                  {gastosFiltrados.map((g, i) => {
                    const cat = CATS_GASTO.find(c => c.key === g.categoria);
                    return (
                      <tr key={g.id || i} style={{ cursor: "pointer" }} onClick={() => setGastoSel(g)}
                        onMouseEnter={e => e.currentTarget.style.background = "var(--green-50)"}
                        onMouseLeave={e => e.currentTarget.style.background = ""}>
                        <td className="num">{g.fecha}</td>
                        <td>
                          <span className="b" style={{ background: (cat?.color || "#888") + "22", color: cat?.color || "#888" }}>
                            <I name={cat?.icon || "Receipt"} size={11} /> {cat?.label || g.categoria}
                          </span>
                        </td>
                        <td><strong>{g.detalle}</strong></td>
                        <td style={{ fontSize: 12.5, color: "var(--admin-mute)" }}>{g.proveedor_persona || "—"}</td>
                        <td style={{ fontSize: 12.5 }}>{g.metodo_pago || "—"}</td>
                        <td className="num money">{g.monto != null ? D.fmtARS(g.monto) : <span style={{ color: "var(--admin-mute)" }}>—</span>}</td>
                        <td>
                          <span className={`b ${g.estado === "pagado" ? "b-ok" : "b-warn"}`}>{g.estado}</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
                {gastosFiltrados.length > 0 && totalFiltrado > 0 && (
                  <tfoot>
                    <tr style={{ background: "var(--admin-bg)" }}>
                      <td colSpan="5" style={{ textAlign: "right", fontWeight: 600, fontSize: 12.5, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Subtotal</td>
                      <td className="num money" style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 18, fontWeight: 500 }}>{D.fmtARS(totalFiltrado)}</td>
                      <td></td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>
        </>
      )}

      {/* ════════════════════════════════════════════════════════════
          TAB: USO PERSONAL
          ════════════════════════════════════════════════════════════ */}
      {tabModo === "personal" && (
        <>
          {/* Banner resumen uso personal */}
          <div style={{ background: "var(--green-900)", color: "#fff", borderRadius: 14, padding: "22px 28px", marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div style={{ fontSize: 11, color: "var(--gold-300)", textTransform: "uppercase", letterSpacing: "0.12em", fontWeight: 600 }}>Total uso personal</div>
              <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 40, fontWeight: 500, letterSpacing: "-0.025em", marginTop: 4 }}>
                {D.fmtARS(totalPersonal)}
              </div>
              <div style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>
                {gastosPersonal.length} {gastosPersonal.length === 1 ? "movimiento registrado" : "movimientos registrados"}
              </div>
            </div>
            <button className="btn btn-sm" style={{ background: "rgba(255,255,255,0.15)", color: "#fff", border: "1px solid rgba(255,255,255,0.2)" }}
              onClick={() => { setShowNuevo(true); }}>
              <I name="Plus" size={14} /> Registrar uso personal
            </button>
          </div>

          {/* Tabla uso personal */}
          <div className="panel">
            <div className="panel__head">
              <div>
                <div className="panel__title">Detalle de uso personal</div>
                <div className="panel__sub">En qué se usó el dinero · registros completos</div>
              </div>
            </div>
            <div className="table-wrap">
              <table className="table">
                <thead>
                  <tr><th>Fecha</th><th>Persona</th><th>En qué se gastó</th><th>Método</th><th className="num">Monto</th><th>Estado</th></tr>
                </thead>
                <tbody>
                  {gastosPersonal.length === 0 && (
                    <tr><td colSpan="6" style={{ textAlign: "center", padding: 30, color: "var(--admin-mute)" }}>
                      Sin registros de uso personal. Usá "Registrar uso personal" para agregar.
                    </td></tr>
                  )}
                  {gastosPersonal.map((g, i) => (
                    <tr key={g.id || i} style={{ cursor: "pointer" }} onClick={() => setGastoSel(g)}
                      onMouseEnter={e => e.currentTarget.style.background = "var(--green-50)"}
                      onMouseLeave={e => e.currentTarget.style.background = ""}>
                      <td className="num">{g.fecha}</td>
                      <td>
                        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                          <div style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--bad)22", color: "var(--bad)", display: "grid", placeItems: "center" }}>
                            <I name="User" size={14} />
                          </div>
                          <strong>{g.proveedor_persona || "—"}</strong>
                        </div>
                      </td>
                      <td>{g.detalle}</td>
                      <td style={{ fontSize: 12.5 }}>{g.metodo_pago || "—"}</td>
                      <td className="num money">{g.monto != null ? D.fmtARS(g.monto) : "—"}</td>
                      <td><span className={`b ${g.estado === "pagado" ? "b-ok" : "b-warn"}`}>{g.estado}</span></td>
                    </tr>
                  ))}
                </tbody>
                {gastosPersonal.length > 0 && totalPersonal > 0 && (
                  <tfoot>
                    <tr style={{ background: "var(--admin-bg)" }}>
                      <td colSpan="4" style={{ textAlign: "right", fontWeight: 600, fontSize: 12.5, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Total uso personal</td>
                      <td className="num money" style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 18, fontWeight: 500, color: "var(--bad)" }}>{D.fmtARS(totalPersonal)}</td>
                      <td></td>
                    </tr>
                  </tfoot>
                )}
              </table>
            </div>
          </div>
        </>
      )}

      {showNuevo && (
        <ModalNuevoGasto
          defaultCat={tabModo === "personal" ? "uso_personal" : "combustible"}
          onClose={() => setShowNuevo(false)}
          onSuccess={() => { recargar(); setShowNuevo(false); }}
        />
      )}

      {gastoSel && (
        <ModalDetalleGasto
          gasto={gastoSel}
          onClose={() => setGastoSel(null)}
          onSuccess={() => { recargar(); setGastoSel(null); }}
        />
      )}
    </div>
  );
}

/* ── Modal: ver detalle, editar o eliminar un gasto ── */
function ModalDetalleGasto({ gasto, onClose, onSuccess }) {
  const D = window.DATA;
  const [modo,      setModo]      = useState("ver");   // "ver" | "editar"
  const [confirmar, setConfirmar] = useState(false);
  const [loading,   setLoading]   = useState(false);
  const [err,       setErr]       = useState("");

  // Campos editables
  const [categoria,  setCategoria]  = useState(gasto.categoria);
  const [detalle,    setDetalle]    = useState(gasto.detalle);
  const [fecha,      setFecha]      = useState(gasto.fecha || "");
  const [monto,      setMonto]      = useState(gasto.monto != null ? String(gasto.monto) : "");
  const [persona,    setPersona]    = useState(gasto.proveedor_persona || "");
  const [metodo,     setMetodo]     = useState(gasto.metodo_pago || "Transferencia");
  const [estado,     setEstado]     = useState(gasto.estado || "pagado");
  const [obs,        setObs]        = useState(gasto.observaciones || "");

  const esPersonal = categoria === "uso_personal";
  const cat        = CATS_GASTO.find(c => c.key === categoria);

  const toISO = (str) => {
    const [d, m, y] = (str || "").split("/");
    return y ? `${y}-${m}-${d}` : str; // si ya es ISO lo deja
  };

  const guardar = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.put(`/gastos/${gasto.id}`, {
      fecha:              toISO(fecha),
      categoria,
      detalle:            detalle.trim(),
      proveedor_persona:  persona || null,
      metodo_pago:        metodo  || null,
      monto:              monto   ? parseFloat(monto) : null,
      estado,
      observaciones:      obs     || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      onSuccess && onSuccess();
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  const eliminar = async () => {
    setLoading(true);
    const res = await window.API.del(`/gastos/${gasto.id}`);
    setLoading(false);
    if (res.mensaje || res.message) {
      onSuccess && onSuccess();
    } else {
      setErr("No se pudo eliminar.");
      setConfirmar(false);
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 540 }}>

        {/* Header */}
        <div className="modal__head">
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: (cat?.color || "#888") + "22", color: cat?.color || "#888", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <I name={cat?.icon || "Receipt"} size={18} />
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>
                {cat?.label || gasto.categoria}
              </div>
              <div className="modal__title" style={{ fontSize: 18, lineHeight: 1.2 }}>{gasto.detalle}</div>
            </div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        {/* ══ MODO VER ══ */}
        {modo === "ver" && (
          <>
            {/* Box principal con monto */}
            <div style={{ background: "var(--green-900)", color: "#fff", borderRadius: 12, padding: "20px 22px", marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontSize: 11, color: "var(--gold-300)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>Monto</div>
                <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 36, fontWeight: 500, letterSpacing: "-0.02em", marginTop: 4 }}>
                  {gasto.monto != null ? D.fmtARS(gasto.monto) : <span style={{ opacity: 0.5, fontSize: 20 }}>Sin monto</span>}
                </div>
              </div>
              <span className={`b ${gasto.estado === "pagado" ? "b-ok" : "b-warn"}`} style={{ fontSize: 13 }}>
                {gasto.estado === "pagado" ? "Pagado" : "Pendiente"}
              </span>
            </div>

            {/* Grilla de datos */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
              {[
                { label: "Fecha",               val: gasto.fecha },
                { label: "Método de pago",      val: gasto.metodo_pago || "—" },
                { label: esPersonal ? "Persona" : "Proveedor / beneficiario",
                                                val: gasto.proveedor_persona || "—" },
                { label: "Categoría",           val: cat?.label || gasto.categoria },
              ].map(({ label, val }) => (
                <div key={label} style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10 }}>
                  <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600, marginBottom: 4 }}>{label}</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{val}</div>
                </div>
              ))}
            </div>

            {gasto.observaciones && (
              <div style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10, marginBottom: 16 }}>
                <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600, marginBottom: 4 }}>Observaciones</div>
                <div style={{ fontSize: 13.5 }}>{gasto.observaciones}</div>
              </div>
            )}

            {/* Confirmación de eliminación */}
            {confirmar ? (
              <div style={{ background: "#fee2e2", border: "1px solid #fca5a5", borderRadius: 10, padding: 14, marginBottom: 12 }}>
                <div style={{ fontWeight: 600, color: "var(--bad)", marginBottom: 8 }}>¿Seguro que querés eliminar este gasto?</div>
                <div style={{ fontSize: 12.5, color: "#7f1d1d", marginBottom: 12 }}>Esta acción mueve el registro a la papelera. Se puede recuperar desde el panel admin.</div>
                <div style={{ display: "flex", gap: 8 }}>
                  <button className="btn btn-secondary btn-sm" onClick={() => setConfirmar(false)}>Cancelar</button>
                  <button className="btn btn-sm" style={{ background: "var(--bad)", color: "#fff" }} onClick={eliminar} disabled={loading}>
                    {loading ? "Eliminando..." : <><I name="Trash2" size={13} /> Sí, eliminar</>}
                  </button>
                </div>
              </div>
            ) : null}

            {err && <div style={{ color: "var(--bad)", fontSize: 13, marginBottom: 8 }}>{err}</div>}

            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button className="btn btn-secondary btn-sm" onClick={() => setConfirmar(true)} style={{ color: "var(--bad)" }}>
                <I name="Trash2" size={14} /> Eliminar
              </button>
              <button className="btn btn-secondary btn-sm" onClick={() => setModo("editar")}>
                <I name="Pencil" size={14} /> Editar
              </button>
              <button className="btn btn-primary btn-sm" onClick={onClose}>Cerrar</button>
            </div>
          </>
        )}

        {/* ══ MODO EDITAR ══ */}
        {modo === "editar" && (
          <form className="form" onSubmit={guardar}>

            {/* Selector de categoría */}
            <div className="form__field">
              <label>Categoría</label>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {CATS_GASTO.map(c => (
                  <button key={c.key} type="button" onClick={() => setCategoria(c.key)}
                    style={{
                      padding: "5px 10px", borderRadius: 8, fontSize: 12, fontWeight: 600,
                      display: "flex", gap: 5, alignItems: "center",
                      background: categoria === c.key ? c.color : "var(--admin-bg)",
                      color:      categoria === c.key ? "#fff"   : "var(--admin-mute)",
                      border:     `1px solid ${categoria === c.key ? c.color : "var(--admin-line)"}`,
                      cursor: "pointer", transition: "all 120ms",
                    }}>
                    <I name={c.icon} size={11} /> {c.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Persona (uso personal) */}
            {esPersonal && (
              <div className="form__field">
                <label>Persona</label>
                <input className="form__input" value={persona} onChange={e => setPersona(e.target.value)} placeholder="Quién usó el dinero" />
              </div>
            )}

            <div className="form__field">
              <label>{esPersonal ? "¿En qué se gastó?" : "Detalle"}</label>
              <input className="form__input" value={detalle} onChange={e => setDetalle(e.target.value)} required />
            </div>

            {!esPersonal && (
              <div className="form__field">
                <label>Proveedor / a quién se le pagó</label>
                <input className="form__input" value={persona} onChange={e => setPersona(e.target.value)} />
              </div>
            )}

            <div className="form__row">
              <div className="form__field">
                <label>Monto ($)</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01" value={monto} onChange={e => setMonto(e.target.value)} style={{ paddingLeft: 28, fontWeight: 700 }} placeholder="0" />
                </div>
              </div>
              <div className="form__field">
                <label>Fecha</label>
                <input className="form__input" value={fecha} onChange={e => setFecha(e.target.value)} placeholder="dd/mm/aaaa" required />
              </div>
            </div>

            <div className="form__row">
              <div className="form__field">
                <label>Método de pago</label>
                <select className="form__select" value={metodo} onChange={e => setMetodo(e.target.value)}>
                  <option>Transferencia</option><option>Cheque diferido</option><option value="Cheque recibido">Cheque recibido (endosado)</option><option>Efectivo</option><option>Cuenta corriente</option><option>Débito automático</option>
                </select>
              </div>
              <div className="form__field">
                <label>Estado</label>
                <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
                  <option value="pagado">Pagado</option><option value="pendiente">Pendiente</option>
                </select>
              </div>
            </div>

            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} />
            </div>

            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}

            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
              <button type="button" className="btn btn-secondary btn-sm" onClick={() => setModo("ver")}>
                <I name="ArrowLeft" size={13} /> Volver
              </button>
              <button type="submit" className="btn btn-primary btn-sm" disabled={loading}>
                {loading ? "Guardando..." : <><I name="Check" size={13} /> Guardar cambios</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ── Modal para cargar cualquier gasto ── */
function ModalNuevoGasto({ defaultCat, onClose, onSuccess }) {
  const D = window.DATA;
  const [categoria,    setCategoria]    = useState(defaultCat || "combustible");
  const [detalle,      setDetalle]      = useState("");
  const [fecha,        setFecha]        = useState(new Date().toLocaleDateString("es-AR"));
  const [monto,        setMonto]        = useState("");
  const [persona,      setPersona]      = useState("");
  const [proveedor,    setProveedor]    = useState("");
  const [metodo,       setMetodo]       = useState("Transferencia");
  const [estado,       setEstado]       = useState("pagado");
  const [obs,          setObs]          = useState("");
  // Campos específicos de cheque recibido
  const [chequeNum,     setChequeNum]     = useState("");
  const [chequeBanco,   setChequeBanco]   = useState("");
  const [chequeSucursal,setChequeSucursal]= useState("");
  const [chequeOrigen,  setChequeOrigen]  = useState("");   // quién lo libró (cliente)
  const [chequeCuit,    setChequeCuit]    = useState("");   // CUIT del librador
  const [chequeDestino, setChequeDestino] = useState("");   // a quién va (proveedor que lo cobra)
  const [chequeCobro,   setChequeCobro]   = useState("");   // fecha de cobro / vencimiento
  const [loading,      setLoading]      = useState(false);
  const [done,         setDone]         = useState(false);
  const [err,          setErr]          = useState("");

  const esPersonal      = categoria === "uso_personal";
  const esFardo         = categoria === "compra_fardos";
  const esChequeRecibido= metodo === "Cheque recibido";

  const toISO = (str) => {
    if (!str) return null;
    const parts = str.split("/");
    if (parts.length === 3) return `${parts[2]}-${parts[1]}-${parts[0]}`;
    return str; // si ya es ISO
  };

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");

    // 1. Guardar el gasto
    const resGasto = await window.API.post("/gastos", {
      fecha:              toISO(fecha),
      categoria,
      detalle:            detalle.trim(),
      proveedor_persona:  esPersonal ? (persona || null) : (proveedor || null),
      metodo_pago:        metodo || null,
      monto:              monto ? parseFloat(monto) : null,
      estado,
      observaciones:      obs || null,
    });

    if (!resGasto.id) {
      setLoading(false);
      const msgs = resGasto.errors ? Object.values(resGasto.errors).flat().join(" ") : resGasto.message;
      setErr(msgs || "Error al guardar el gasto.");
      return;
    }

    // 2. Si el método es "Cheque recibido", también guardarlo en cheques
    if (esChequeRecibido) {
      await window.API.post("/cheques", {
        tipo:             "recibido",
        numero:           chequeNum      || null,
        banco:            chequeBanco    || null,
        sucursal:         chequeSucursal || null,
        origen:           chequeOrigen   || null,
        cuit:             chequeCuit     || null,
        destino:          chequeDestino  || proveedor || null,
        concepto:         detalle.trim(),
        monto:            monto ? parseFloat(monto) : null,
        fecha_recepcion:  toISO(fecha),
        fecha_cobro:      toISO(chequeCobro) || null,
        estado:           chequeDestino || proveedor ? "endosado" : "en_cartera",
        gasto_id:         resGasto.id,
        observaciones:    obs || null,
      });
    }

    setLoading(false);
    setDone(true);
    onSuccess && onSuccess();
  };

  const cat = CATS_GASTO.find(c => c.key === categoria);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}
        style={{ maxHeight: "92dvh", display: "flex", flexDirection: "column" }}>
        <div className="modal__head" style={{ flexShrink: 0 }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>
              {esPersonal ? "Uso personal" : "Nuevo gasto"}
            </div>
            <div className="modal__title">
              {esPersonal ? "Registrar uso personal" : "Cargar gasto"}
            </div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        <div style={{ overflowY: "auto", flex: 1 }}>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Gasto registrado correctamente.</div>
        ) : (
          <form className="form" onSubmit={submit}>

            {/* Categoría */}
            <div className="form__field">
              <label>Categoría</label>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {CATS_GASTO.map(c => (
                  <button key={c.key} type="button"
                    onClick={() => setCategoria(c.key)}
                    style={{
                      padding: "6px 12px", borderRadius: 8, fontSize: 12.5, fontWeight: 600,
                      display: "flex", gap: 6, alignItems: "center",
                      background: categoria === c.key ? c.color : "var(--admin-bg)",
                      color:      categoria === c.key ? "#fff"   : "var(--admin-mute)",
                      border:     `1px solid ${categoria === c.key ? c.color : "var(--admin-line)"}`,
                      cursor: "pointer", transition: "all 120ms",
                    }}>
                    <I name={c.icon} size={12} /> {c.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Uso personal — quién */}
            {esPersonal && (
              <div className="form__field">
                <label>Persona</label>
                <input className="form__input" value={persona} onChange={e => setPersona(e.target.value)}
                  placeholder="Ej: Lucas, Rubén, socio..." autoFocus />
              </div>
            )}

            {/* Detalle */}
            <div className="form__field">
              <label>{esPersonal ? "¿En qué se gastó?" : esFardo ? "Producto / cantidad" : "Detalle"}</label>
              <input className="form__input" value={detalle} onChange={e => setDetalle(e.target.value)}
                required
                placeholder={
                  esPersonal ? "Ej: Nafta, supermercado, ropa..." :
                  esFardo    ? "Ej: 40 × Fardo redondo 350 kg · 2° corte" :
                               "Ej: Gasoil 2.400 lts, Service JD 6110..."
                }
                autoFocus={!esPersonal} />
            </div>

            {/* Proveedor (no en uso personal) */}
            {!esPersonal && (
              <div className="form__field">
                <label>{esFardo ? "Empresa / socio proveedor" : "Proveedor / a quién se le pagó"}</label>
                <input className="form__input" value={proveedor} onChange={e => setProveedor(e.target.value)}
                  placeholder={esFardo ? "Ej: La Pampita SA" : "Ej: YPF Sacanta, Repuestos Rivero..."} />
              </div>
            )}

            {/* Método, Estado, Monto, Fecha — todos juntos, adaptables */}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 12 }}>
              <div className="form__field" style={{ flex: "1 1 200px", margin: 0 }}>
                <label>Método de pago</label>
                <select className="form__select" value={metodo} onChange={e => setMetodo(e.target.value)}>
                  <option>Transferencia</option>
                  <option>Cheque diferido</option>
                  <option value="Cheque recibido">Cheque recibido (endosado)</option>
                  <option>Efectivo</option>
                  <option>Cuenta corriente</option>
                  <option>Débito automático</option>
                </select>
              </div>
              <div className="form__field" style={{ flex: "1 1 140px", margin: 0 }}>
                <label>Estado del pago</label>
                <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
                  <option value="pagado">Pagado</option>
                  <option value="pendiente">Pendiente</option>
                </select>
              </div>
              <div className="form__field" style={{ flex: "1 1 140px", margin: 0 }}>
                <label>Monto ($)</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01"
                    value={monto} onChange={e => setMonto(e.target.value)}
                    style={{ paddingLeft: 28, fontWeight: 700, fontSize: 16 }}
                    placeholder="0" />
                </div>
              </div>
              <div className="form__field" style={{ flex: "1 1 140px", margin: 0 }}>
                <label>Fecha</label>
                <input className="form__input" value={fecha} onChange={e => setFecha(e.target.value)} placeholder="dd/mm/aaaa" required />
              </div>
            </div>

            {/* ── Campos extra para Cheque Recibido ── */}
            {esChequeRecibido && (
              <div style={{ background: "#fffbeb", border: "1px solid #f59e0b55", borderRadius: 10, padding: 16 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: "#92400e", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 12, display: "flex", gap: 6, alignItems: "center" }}>
                  <I name="ScrollText" size={13} /> Datos del cheque recibido
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 12 }}>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 150px" }}>
                    <label>N° de cheque</label>
                    <input className="form__input" value={chequeNum} onChange={e => setChequeNum(e.target.value)} placeholder="Ej: 00045821" />
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 180px" }}>
                    <label>Banco</label>
                    <select className="form__select" value={chequeBanco} onChange={e => setChequeBanco(e.target.value)}>
                      <option value="">— banco —</option>
                      <option>Banco Galicia</option><option>Banco Macro</option><option>Banco Nación</option>
                      <option>Banco Santander</option><option>Banco Provincia</option><option>Banco BBVA</option>
                      <option>Banco ICBC</option><option>Banco Credicoop</option><option>Otro</option>
                    </select>
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 150px" }}>
                    <label>Sucursal</label>
                    <input className="form__input" value={chequeSucursal} onChange={e => setChequeSucursal(e.target.value)} placeholder="Ej: Córdoba Centro" />
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 160px" }}>
                    <label>Fecha de cobro</label>
                    <input className="form__input" value={chequeCobro} onChange={e => setChequeCobro(e.target.value)} placeholder="dd/mm/aaaa" />
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 200px" }}>
                    <label>Librador (quién lo emitió)</label>
                    <input className="form__input" value={chequeOrigen} onChange={e => setChequeOrigen(e.target.value)} placeholder="Ej: Tambo La Esperanza" />
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 170px" }}>
                    <label>CUIT del librador</label>
                    <input className="form__input" value={chequeCuit} onChange={e => setChequeCuit(e.target.value)} placeholder="Ej: 30-71456823-4" />
                  </div>
                  <div className="form__field" style={{ margin: 0, flex: "1 1 100%" }}>
                    <label>Endosado a (a quién le entregás el cheque)</label>
                    <input className="form__input" value={chequeDestino} onChange={e => setChequeDestino(e.target.value)} placeholder="Ej: YPF Sacanta, Repuestos Rivero..." />
                  </div>
                </div>
                <div style={{ marginTop: 10, fontSize: 12, color: "#78350f" }}>
                  <I name="Info" size={12} /> Este cheque se guardará automáticamente en la sección <strong>Cheques Recibidos</strong> con el destino indicado.
                </div>
              </div>
            )}

            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)}
                placeholder="Notas adicionales..." />
            </div>

            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}

            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" type="button" onClick={onClose}>Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}
                style={cat ? { background: cat.color, borderColor: cat.color } : {}}>
                {loading ? "Guardando..." : <>
                  <I name={cat?.icon || "Receipt"} size={13} />
                  {esPersonal ? "Registrar uso" : esChequeRecibido ? "Guardar gasto + cheque" : "Guardar gasto"}
                </>}
              </button>
            </div>
          </form>
        )}
        </div>
      </div>
    </div>
  );
}

/* ── Etiquetas de categorías ── */
const CAT_INGRESO = {
  venta_fardos:       { label: "Venta de fardos",      icon: "Package",    color: "#2d5016" },
  servicios_terceros: { label: "Servicios a terceros",  icon: "Tractor",    color: "#0891b2" },
  asociacion:         { label: "Asociación",            icon: "Handshake",  color: "#8b6f47" },
  otros:              { label: "Otros ingresos",        icon: "Receipt",    color: "#6b7280" },
};

/* ============================================
   Rentabilidad
   ============================================ */
function Rentabilidad() {
  const D = window.DATA;
  const [resumen,     setResumen]     = useState(null);
  const [ingresosList,setIngresosList]= useState([]);
  const [showNuevo,   setShowNuevo]   = useState(false);
  const [ingresoSel,  setIngresoSel]  = useState(null);
  const [tab,         setTab]         = useState("resumen"); // "resumen" | "ingresos"

  const recargar = () => {
    window.API.get("/rentabilidad-resumen").then(r => { if (!r.error) setResumen(r); });
    window.API.get("/ingresos").then(r => { if (r.data) setIngresosList(r.data); });
  };

  useEffect(() => { recargar(); }, []);

  const totalIngresos = resumen?.total_ingresos || 0;
  const totalGastos   = resumen?.total_gastos   || 0;
  const utilidad      = totalIngresos - totalGastos;
  const margen        = totalIngresos > 0 ? ((utilidad / totalIngresos) * 100).toFixed(1) : 0;

  // Datos del gráfico por mes
  const chartData = (resumen?.por_mes || []).map(m => ({
    mes:      m.mes.slice(5) + "/" + m.mes.slice(2,4), // "05/26"
    Ingresos: m.total_ingresos,
    Gastos:   m.total_gastos,
  }));

  // Desglose: ingresos por categoría vs gastos por categoría
  const ingCat  = resumen?.ingresos_por_cat || [];
  const gastCat = resumen?.gastos_por_cat   || [];

  return (
    <div className="page" data-screen-label="Rentabilidad">
      <div className="page__header">
        <div>
          <div className="page__title">Rentabilidad</div>
          <div className="page__sub">Ingresos y costos reales · acumulado total</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-secondary btn-sm" onClick={recargar}>
            <I name="RefreshCw" size={14} /> Actualizar
          </button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowNuevo(true)}>
            <I name="Plus" size={14} /> Registrar ingreso
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 8, marginBottom: 4 }}>
        {[["resumen","Resumen"],["ingresos","Ingresos cargados"]].map(([k,l]) => (
          <button key={k} className={`chip ${tab===k?"is-active":""}`} onClick={() => setTab(k)}>{l}</button>
        ))}
      </div>

      {/* ── TAB RESUMEN ── */}
      {tab === "resumen" && (
        <>
          {/* KPIs principales */}
          <div className="grid-3">
            <div className="panel">
              <div className="panel__sub">Ingresos totales</div>
              <div className="bignum" style={{ color: "var(--green-800)" }}>
                {D.fmtARS(totalIngresos)}
                <small>{ingresosList.length} registros cargados</small>
              </div>
            </div>
            <div className="panel">
              <div className="panel__sub">Costos totales</div>
              <div className="bignum">
                {D.fmtARS(totalGastos)}
                <small>desde módulo Gastos</small>
              </div>
            </div>
            <div className="panel" style={{ background: utilidad >= 0 ? "var(--green-900)" : "var(--bad)", color: "#fff" }}>
              <div className="panel__sub" style={{ color: "rgba(255,255,255,0.6)" }}>Utilidad neta</div>
              <div className="bignum" style={{ color: "#fff" }}>
                {D.fmtARS(utilidad)}
                <small style={{ color: utilidad >= 0 ? "var(--gold-300)" : "#fca5a5" }}>
                  Margen {margen}%
                </small>
              </div>
            </div>
          </div>

          {totalIngresos === 0 && totalGastos === 0 ? (
            <div className="panel" style={{ padding: 40, textAlign: "center", color: "var(--admin-mute)" }}>
              <I name="TrendingUp" size={40} style={{ opacity: 0.2, display: "block", margin: "0 auto 16px" }} />
              Sin datos todavía. Registrá ingresos con el botón "Registrar ingreso" y cargá gastos en el módulo de Gastos.
            </div>
          ) : (
            <div className="grid-2">
              {/* Gráfico ingresos vs costos por mes */}
              {chartData.length > 0 ? (
                <ChartCard title="Ingresos vs Costos por mes" sub="Evolución mensual" height={300}>
                  <RC.BarChart data={chartData} margin={{ top: 10, right: 12, left: 0, bottom: 0 }}>
                    <RC.CartesianGrid stroke="#efece3" vertical={false} />
                    <RC.XAxis dataKey="mes" stroke="#7a766c" fontSize={11} tickLine={false} axisLine={false} />
                    <RC.YAxis stroke="#7a766c" fontSize={11} tickLine={false} axisLine={false}
                      tickFormatter={(v) => `$${(v/1e6).toFixed(1)}M`} width={55} />
                    <RC.Tooltip
                      contentStyle={{ background: "#0e1f0a", border: "none", borderRadius: 10, color: "#fff", fontSize: 12 }}
                      formatter={(v) => [D.fmtARS(v), ""]}
                    />
                    <RC.Legend wrapperStyle={{ fontSize: 11.5 }} iconType="circle" />
                    <RC.Bar dataKey="Ingresos" fill="#2d5016" radius={[6,6,0,0]} animationDuration={900} />
                    <RC.Bar dataKey="Gastos"   fill="#d4a574" radius={[6,6,0,0]} animationDuration={900} />
                  </RC.BarChart>
                </ChartCard>
              ) : (
                <div className="panel" style={{ display: "flex", alignItems: "center", justifyContent: "center", color: "var(--admin-mute)" }}>
                  Cargá ingresos de distintos meses para ver el gráfico.
                </div>
              )}

              {/* Desglose costos vs ingresos por categoría */}
              <div className="panel">
                <div className="panel__head">
                  <div className="panel__title">Desglose por categoría</div>
                </div>

                {ingCat.length > 0 && (
                  <>
                    <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600, marginBottom: 8 }}>Ingresos</div>
                    {ingCat.map(c => {
                      const info = CAT_INGRESO[c.categoria] || { label: c.categoria, color: "#888", icon: "Receipt" };
                      const pct  = totalIngresos > 0 ? (c.total / totalIngresos * 100).toFixed(0) : 0;
                      return (
                        <div key={c.categoria} style={{ marginBottom: 10 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 4 }}>
                            <span style={{ display: "flex", gap: 6, alignItems: "center" }}>
                              <I name={info.icon} size={12} style={{ color: info.color }} /> {info.label}
                            </span>
                            <span style={{ fontWeight: 600 }}>{D.fmtARS(c.total)} <span style={{ color: "var(--admin-mute)", fontWeight: 400 }}>({pct}%)</span></span>
                          </div>
                          <div style={{ height: 6, background: "var(--admin-bg)", borderRadius: 999 }}>
                            <div style={{ width: `${pct}%`, height: "100%", background: info.color, borderRadius: 999 }} />
                          </div>
                        </div>
                      );
                    })}
                    <div className="divider" />
                  </>
                )}

                {gastCat.length > 0 && (
                  <>
                    <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600, marginBottom: 8 }}>Costos</div>
                    {gastCat.map(c => {
                      const pct = totalGastos > 0 ? (c.total / totalGastos * 100).toFixed(0) : 0;
                      return (
                        <div key={c.categoria} style={{ marginBottom: 10 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 4 }}>
                            <span>{c.categoria}</span>
                            <span style={{ fontWeight: 600 }}>{D.fmtARS(c.total)} <span style={{ color: "var(--admin-mute)", fontWeight: 400 }}>({pct}%)</span></span>
                          </div>
                          <div style={{ height: 6, background: "var(--admin-bg)", borderRadius: 999 }}>
                            <div style={{ width: `${pct}%`, height: "100%", background: "var(--gold-700)", borderRadius: 999 }} />
                          </div>
                        </div>
                      );
                    })}
                  </>
                )}

                {ingCat.length === 0 && gastCat.length === 0 && (
                  <div style={{ color: "var(--admin-mute)", fontSize: 13, padding: "20px 0" }}>Sin datos aún.</div>
                )}
              </div>
            </div>
          )}
        </>
      )}

      {/* ── TAB INGRESOS CARGADOS ── */}
      {tab === "ingresos" && (
        <div className="panel">
          <div className="panel__head">
            <div>
              <div className="panel__title">Ingresos registrados</div>
              <div className="panel__sub">{ingresosList.length} registros · total {D.fmtARS(totalIngresos)}</div>
            </div>
            <button className="btn btn-primary btn-sm" onClick={() => setShowNuevo(true)}>
              <I name="Plus" size={14} /> Nuevo
            </button>
          </div>
          {ingresosList.length === 0 ? (
            <div style={{ padding: 40, textAlign: "center", color: "var(--admin-mute)" }}>
              Sin ingresos registrados. Usá "Registrar ingreso" para agregar.
            </div>
          ) : (
            <div className="table-wrap">
              <table className="table">
                <thead>
                  <tr><th>Período</th><th>Categoría</th><th>Descripción</th><th className="num">Monto</th><th></th></tr>
                </thead>
                <tbody>
                  {ingresosList.map(i => {
                    const info = CAT_INGRESO[i.categoria] || { label: i.categoria, color: "#888", icon: "Receipt" };
                    return (
                      <tr key={i.id} style={{ cursor: "pointer" }}
                        onClick={() => setIngresoSel(i)}
                        onMouseEnter={e => e.currentTarget.style.background = "var(--green-50)"}
                        onMouseLeave={e => e.currentTarget.style.background = ""}>
                        <td style={{ fontWeight: 600 }}>{i.periodo_label || i.periodo}</td>
                        <td>
                          <span className="b" style={{ background: info.color + "22", color: info.color }}>
                            <I name={info.icon} size={11} /> {info.label}
                          </span>
                        </td>
                        <td style={{ fontSize: 12.5, color: "var(--admin-mute)" }}>{i.descripcion || "—"}</td>
                        <td className="num money" style={{ fontWeight: 700 }}>{D.fmtARS(i.monto)}</td>
                        <td>
                          <button className="icon-btn" onClick={e => { e.stopPropagation(); setIngresoSel(i); }}>
                            <I name="Pencil" size={15} />
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {showNuevo  && <ModalNuevoIngreso onClose={() => setShowNuevo(false)} onSuccess={() => { recargar(); setShowNuevo(false); }} />}
      {ingresoSel && <ModalEditarIngreso ingreso={ingresoSel} onClose={() => setIngresoSel(null)} onSuccess={() => { recargar(); setIngresoSel(null); }} />}
    </div>
  );
}

/* ── Modal: registrar ingreso mensual ── */
function ModalNuevoIngreso({ onClose, onSuccess }) {
  const [periodo,    setPeriodo]    = useState(() => {
    const hoy = new Date();
    return `${hoy.getFullYear()}-${String(hoy.getMonth()+1).padStart(2,"0")}`;
  });
  const [monto,      setMonto]      = useState("");
  const [categoria,  setCategoria]  = useState("venta_fardos");
  const [descripcion,setDescripcion]= useState("");
  const [obs,        setObs]        = useState("");
  const [loading,    setLoading]    = useState(false);
  const [done,       setDone]       = useState(false);
  const [err,        setErr]        = useState("");

  const D = window.DATA;

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.post("/ingresos", {
      periodo:      `${periodo}-01`,   // primer día del mes
      monto:        parseFloat(monto),
      categoria,
      descripcion:  descripcion || null,
      observaciones:obs         || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  const info = CAT_INGRESO[categoria];

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div>
            <div style={{ fontSize: 12, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>Nuevo ingreso</div>
            <div className="modal__title">Registrar ingreso del período</div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Ingreso registrado correctamente.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__field">
              <label>Categoría</label>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {Object.entries(CAT_INGRESO).map(([k, v]) => (
                  <button key={k} type="button" onClick={() => setCategoria(k)}
                    style={{
                      padding: "6px 12px", borderRadius: 8, fontSize: 12.5, fontWeight: 600,
                      display: "flex", gap: 6, alignItems: "center",
                      background: categoria === k ? v.color : "var(--admin-bg)",
                      color:      categoria === k ? "#fff"   : "var(--admin-mute)",
                      border:     `1px solid ${categoria === k ? v.color : "var(--admin-line)"}`,
                      cursor: "pointer", transition: "all 120ms",
                    }}>
                    <I name={v.icon} size={12} /> {v.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="form__row">
              <div className="form__field">
                <label>Período (mes)</label>
                <input className="form__input" type="month" value={periodo} onChange={e => setPeriodo(e.target.value)} required />
              </div>
              <div className="form__field">
                <label>Monto total del período</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01"
                    value={monto} onChange={e => setMonto(e.target.value)}
                    style={{ paddingLeft: 28, fontWeight: 700, fontSize: 16 }}
                    placeholder="0" required autoFocus />
                </div>
              </div>
            </div>

            <div className="form__field">
              <label>Descripción (opcional)</label>
              <input className="form__input" value={descripcion} onChange={e => setDescripcion(e.target.value)}
                placeholder="Ej: 320 fardos redondos · 3 servicios de corte" />
            </div>

            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)}
                placeholder="Notas adicionales..." />
            </div>

            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}

            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button type="button" className="btn btn-secondary btn-sm" onClick={onClose}>Cancelar</button>
              <button type="submit" className="btn btn-primary btn-sm" disabled={loading}
                style={info ? { background: info.color, borderColor: info.color } : {}}>
                {loading ? "Guardando..." : <><I name="TrendingUp" size={13} /> Registrar ingreso</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ── Modal: editar / eliminar ingreso ── */
function ModalEditarIngreso({ ingreso, onClose, onSuccess }) {
  const D = window.DATA;
  const [modo,      setModo]      = useState("ver");
  const [confirmar, setConfirmar] = useState(false);
  const [monto,     setMonto]     = useState(String(ingreso.monto));
  const [categoria, setCategoria] = useState(ingreso.categoria);
  const [descripcion,setDescripcion]= useState(ingreso.descripcion || "");
  const [loading,   setLoading]   = useState(false);
  const [err,       setErr]       = useState("");

  const info = CAT_INGRESO[ingreso.categoria] || { label: ingreso.categoria, color: "#888" };

  const guardar = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.put(`/ingresos/${ingreso.id}`, {
      periodo:    `${ingreso.periodo}-01`,
      monto:      parseFloat(monto),
      categoria,
      descripcion:descripcion || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) onSuccess && onSuccess();
    else setErr(res.message || "Error al guardar.");
  };

  const eliminar = async () => {
    setLoading(true);
    await window.API.del(`/ingresos/${ingreso.id}`);
    setLoading(false);
    onSuccess && onSuccess();
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: info.color + "22", color: info.color, display: "grid", placeItems: "center" }}>
              <I name={CAT_INGRESO[ingreso.categoria]?.icon || "Receipt"} size={18} />
            </div>
            <div>
              <div style={{ fontSize: 11, color: "var(--admin-mute)", fontWeight: 600, textTransform: "uppercase" }}>{info.label}</div>
              <div className="modal__title" style={{ fontSize: 18 }}>{ingreso.periodo_label || ingreso.periodo}</div>
            </div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        {modo === "ver" ? (
          <>
            <div style={{ background: "var(--green-900)", color: "#fff", borderRadius: 12, padding: "20px 22px", marginBottom: 16 }}>
              <div style={{ fontSize: 11, color: "var(--gold-300)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>Monto registrado</div>
              <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 40, fontWeight: 500, letterSpacing: "-0.025em", marginTop: 4 }}>
                {D.fmtARS(ingreso.monto)}
              </div>
            </div>
            {ingreso.descripcion && (
              <div style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10, marginBottom: 14, fontSize: 13.5 }}>
                {ingreso.descripcion}
              </div>
            )}
            {confirmar ? (
              <div style={{ background: "#fee2e2", border: "1px solid #fca5a5", borderRadius: 10, padding: 14, marginBottom: 12 }}>
                <div style={{ fontWeight: 600, color: "var(--bad)", marginBottom: 8 }}>¿Eliminar este ingreso?</div>
                <div style={{ display: "flex", gap: 8 }}>
                  <button className="btn btn-secondary btn-sm" onClick={() => setConfirmar(false)}>Cancelar</button>
                  <button className="btn btn-sm" style={{ background: "var(--bad)", color: "#fff" }} onClick={eliminar}>
                    <I name="Trash2" size={13} /> Eliminar
                  </button>
                </div>
              </div>
            ) : null}
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button className="btn btn-secondary btn-sm" style={{ color: "var(--bad)" }} onClick={() => setConfirmar(true)}><I name="Trash2" size={14} /> Eliminar</button>
              <button className="btn btn-secondary btn-sm" onClick={() => setModo("editar")}><I name="Pencil" size={14} /> Editar</button>
              <button className="btn btn-primary btn-sm" onClick={onClose}>Cerrar</button>
            </div>
          </>
        ) : (
          <form className="form" onSubmit={guardar}>
            <div className="form__row">
              <div className="form__field">
                <label>Monto</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600 }}>$</span>
                  <input className="form__input" type="number" min="0" step="0.01" value={monto} onChange={e => setMonto(e.target.value)} style={{ paddingLeft: 28, fontWeight: 700 }} required />
                </div>
              </div>
              <div className="form__field">
                <label>Categoría</label>
                <select className="form__select" value={categoria} onChange={e => setCategoria(e.target.value)}>
                  {Object.entries(CAT_INGRESO).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
                </select>
              </div>
            </div>
            <div className="form__field">
              <label>Descripción</label>
              <input className="form__input" value={descripcion} onChange={e => setDescripcion(e.target.value)} />
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
              <button type="button" className="btn btn-secondary btn-sm" onClick={() => setModo("ver")}><I name="ArrowLeft" size={13} /> Volver</button>
              <button type="submit" className="btn btn-primary btn-sm" disabled={loading}>{loading ? "Guardando..." : <><I name="Check" size={13} /> Guardar</>}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ============================================
   Maquinaria
   ============================================ */
function Maquinaria() {
  const D = window.DATA;
  const [showService,    setShowService]    = useState(false);
  const [showNuevaMaq,   setShowNuevaMaq]   = useState(false);
  const [showUso,        setShowUso]        = useState(null); // maquina para registrar uso
  const [detail,         setDetail]         = useState(null);
  const [showFuel,       setShowFuel]       = useState(null);
  const [MAQUINAS,       setMAQUINAS]       = useState([]);
  const [LOTES_MAQUINAS, setLOTES_MAQUINAS] = useState([]);

  const recargarMaquinas = () => {
    window.API.get("/maquinas").then(r => {
      if (r.data) setMAQUINAS(r.data.map(window.API_MAP.maquina));
    });
  };

  useEffect(() => {
    recargarMaquinas();
    window.API.get("/lotes").then(r => {
      if (r.data) setLOTES_MAQUINAS(r.data.map(l => l.nombre));
    });
  }, []);

  const totalLitrosMes = MAQUINAS.reduce((s, m) => s + (m.cargas || []).filter(c => c.fecha && c.fecha.endsWith("/05/2026")).reduce((a, c) => a + c.litros, 0), 0);
  const totalGastoMes  = MAQUINAS.reduce((s, m) => s + (m.cargas || []).filter(c => c.fecha && c.fecha.endsWith("/05/2026")).reduce((a, c) => a + (c.costo || 0), 0), 0);

  return (
    <div className="page" data-screen-label="Maquinaria">
      <div className="page__header">
        <div>
          <div className="page__title">Maquinaria</div>
          <div className="page__sub">{MAQUINAS.length} unidades en flota · tocá una para ver combustible e historial</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-secondary btn-sm" onClick={() => window.toast("Generando historial PDF de la flota...")}><I name="History" size={14} /> Historial</button>
          <button className="btn btn-secondary btn-sm" onClick={() => MAQUINAS.length > 0 && setShowFuel(MAQUINAS[0])}><I name="Fuel" size={14} /> Cargar combustible</button>
          <button className="btn btn-secondary btn-sm" onClick={() => setShowService(true)}><I name="Wrench" size={14} /> Programar service</button>
          <button className="btn btn-primary btn-sm" onClick={() => setShowNuevaMaq(true)}><I name="Plus" size={14} /> Nueva máquina</button>
        </div>
      </div>

      {/* hidden — botón legacy removido */}

      <div className="kpi-grid">
        <Kpi icon="Tractor"       label="Unidades activas"       value={`${MAQUINAS.filter(m=>m.estado!=='service').length} / ${MAQUINAS.length}`} delta="" deltaDir="info" hint="unidades en operación" />
        <Kpi icon="Fuel"          label="Gasoil cargado (mes)"   value={`${D.fmtNum(totalLitrosMes)} L`} delta={D.fmtARS(totalGastoMes)} deltaDir="info" hint="total gastado en mayo" />
        <Kpi icon="AlertTriangle" label="Service próximos"       value="3" delta="< 30 días" deltaDir="flat" hint="ver bandera roja abajo" />
        <Kpi icon="Wallet"        label="Mantenimiento (mes)"    value={D.fmtARS(1820000)} delta="−13%" deltaDir="up" hint="vs. abril" />
      </div>

      {MAQUINAS.length === 0 && (
        <div className="panel" style={{ padding: 40, textAlign: "center", color: "var(--admin-mute)" }}>
          <I name="Tractor" size={40} style={{ opacity: 0.2, display: "block", margin: "0 auto 16px" }} />
          No hay máquinas cargadas. Usá "Nueva máquina" para agregar equipos a la flota.
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
        {MAQUINAS.map(m => {
          const pct = (m.serviceUsado / m.serviceTotal) * 100;
          const barClass = pct >= 100 ? "bad" : pct >= 75 ? "warn" : "";
          const icon = m.tipo === "Tractor" ? "Tractor" : m.tipo === "Logística" ? "Truck" : m.tipo === "Segadora" ? "Scissors" : m.tipo === "Rastrillo" ? "Rake" : m.tipo === "Sembradora" ? "Sprout" : "Cog";
          return (
            <div className="machine-card" key={m.nombre} style={{ cursor: "pointer" }} onClick={() => setDetail(m)}>
              <div className="machine-card__head">
                <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <div className="machine-card__icon"><I name={icon} size={20} /></div>
                  <div>
                    <div className="machine-card__name">{m.nombre}</div>
                    <div className="machine-card__model">{m.tipo} · año {m.año}</div>
                  </div>
                </div>
                <EstadoBadge estado={m.estado} />
              </div>
              <div className="machine-card__rows">
                <div>
                  <span>Uso acumulado</span>
                  <strong>{m.km ? `${D.fmtNum(m.km)} km` : `${D.fmtNum(m.horas)} hs`}</strong>
                </div>
                <div>
                  <span>Próximo service</span>
                  <strong style={{ color: m.warn ? "var(--bad)" : "var(--admin-ink)" }}>{m.proxService}</strong>
                </div>
                {m.ultCarga && (
                  <div style={{ gridColumn: "1 / -1", paddingTop: 8, borderTop: "1px dashed var(--admin-line)", marginTop: 4 }}>
                    <span><I name="Fuel" size={10} style={{ verticalAlign: "-1px", marginRight: 3 }} /> Última carga</span>
                    <strong>{m.ultCarga.fecha} · {m.ultCarga.litros} L · {D.fmtARS(m.ultCarga.costo)}</strong>
                  </div>
                )}
                <div style={{ gridColumn: "1 / -1" }}>
                  <span>Último uso</span>
                  <strong style={{ fontSize: 12.5 }}>{m.usos[0] ? `${m.usos[0].fecha} · ${m.usos[0].lote}` : "—"}</strong>
                </div>
              </div>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--admin-mute)", marginBottom: 4 }}>
                  <span>Ciclo de service</span>
                  <span>{Math.min(100, Math.round(pct))}%</span>
                </div>
                <div className={`machine-card__bar ${barClass}`}>
                  <span style={{ width: `${Math.min(100, pct)}%` }}></span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {showNuevaMaq && <ModalNuevaMaquina onClose={() => setShowNuevaMaq(false)} onSuccess={recargarMaquinas} />}
      {showUso      && <ModalRegistrarUso maquina={showUso} lotes={LOTES_MAQUINAS} onClose={() => setShowUso(null)} onSuccess={recargarMaquinas} />}

      {/* DETALLE de máquina */}
      {detail && <MaquinaDetail maquina={detail} onClose={() => setDetail(null)} onLoadFuel={(m) => { setDetail(null); setShowFuel(m); }} onRegistrarUso={(m) => { setDetail(null); setShowUso(m); }} />}

      {/* MODAL cargar combustible */}
      {showFuel && <CombustibleModal maquina={showFuel} maquinas={MAQUINAS} onClose={() => setShowFuel(null)} onSuccess={recargarMaquinas} />}

      {/* MODAL programar service */}
      {showService && (
        <div className="modal-back" onClick={() => setShowService(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal__head">
              <div className="modal__title">Programar service</div>
              <button className="modal__close" onClick={() => setShowService(false)}><I name="X" size={18} /></button>
            </div>
            <form className="form" onSubmit={async (e) => {
              e.preventDefault();
              const maq = MAQUINAS.find(m => m.nombre === e.target.maqNombre.value);
              if (!maq) return;
              const res = await window.API.patch('/maquinas/' + maq.id, { estado: 'service', observaciones: e.target.tareas.value || null });
              if (res.data?.id || res.id) { window.toast('Service programado para ' + maq.nombre); recargarMaquinas(); setShowService(false); }
              else { window.toast('Error al programar service', 'warn'); }
            }}>
              <div className="form__field">
                <label>Maquinaria</label>
                <select className="form__select" name="maqNombre" defaultValue={MAQUINAS[0]?.nombre || ""}>
                  {MAQUINAS.map(m => <option key={m.nombre}>{m.nombre}</option>)}
                </select>
              </div>
              <div className="form__row">
                <div className="form__field">
                  <label>Fecha programada</label>
                  <input className="form__input" defaultValue="20/05/2026" />
                </div>
                <div className="form__field">
                  <label>Taller</label>
                  <select className="form__select"><option>Servicio oficial Kuhn</option><option>Taller propio</option><option>Mecánica Rivero</option></select>
                </div>
              </div>
              <div className="form__field">
                <label>Tareas</label>
                <textarea className="form__textarea" name="tareas" placeholder="Cambio de aceite, cuchillas, filtros..." />
              </div>
              <button className="btn btn-primary btn-sm" type="submit" style={{ alignSelf: "flex-end" }}>Programar</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

/* Detalle de una máquina — combustible + uso */
function MaquinaDetail({ maquina, onClose, onLoadFuel, onRegistrarUso }) {
  const D = window.DATA;
  const m = maquina;
  const [tab, setTab] = useState("uso");
  const [usos, setUsos] = useState(m.usos || []);

  useEffect(() => {
    if (!m.id) return;
    window.API.get("/usos-maquina").then(r => {
      if (r.data) {
        const propios = r.data
          .filter(u => u.maquina_id === m.id)
          .map(u => ({
            fecha: u.fecha,
            lote:  u.lote  || u.observaciones || "—",
            tarea: u.tarea,
            horas: u.horas,
            km:    u.km,
          }));
        if (propios.length > 0) setUsos(propios);
      }
    });
  }, [m.id]);

  const totalLitros = (m.cargas || []).reduce((s, c) => s + c.litros, 0);
  const totalGasto  = (m.cargas || []).reduce((s, c) => s + c.costo, 0);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 720, padding: 0, overflow: "hidden" }}>
        {/* Header */}
        <div style={{ padding: "22px 24px 18px", borderBottom: "1px solid var(--admin-line)", display: "flex", gap: 14, alignItems: "flex-start" }}>
          <div style={{ width: 52, height: 52, borderRadius: 12, background: "var(--green-50)", color: "var(--green-800)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <I name={m.tipo === "Tractor" ? "Tractor" : m.tipo === "Logística" ? "Truck" : "Cog"} size={26} />
          </div>
          <div style={{ flex: 1 }}>
            <div className="modal__title">{m.nombre}</div>
            <div style={{ color: "var(--admin-mute)", fontSize: 13, marginTop: 2 }}>{m.tipo} · año {m.año} · {m.km ? D.fmtNum(m.km) + " km" : D.fmtNum(m.horas) + " hs"}</div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", borderBottom: "1px solid var(--admin-line)", padding: "0 24px", gap: 8 }}>
          <DetailTab active={tab === "uso"}          onClick={() => setTab("uso")}          label="Historial de uso"   count={m.usos.length} />
          <DetailTab active={tab === "combustible"}  onClick={() => setTab("combustible")}  label="Combustible"        count={(m.cargas || []).length} disabled={m.ultCarga === null} />
        </div>

        {/* Body */}
        <div style={{ padding: 22, maxHeight: 480, overflow: "auto" }}>
          {tab === "uso" && (
            <>
              {usos.length === 0 ? (
                <div style={{ padding: 30, textAlign: "center", color: "var(--admin-mute)" }}>
                  Sin registros de uso aún.
                  <br />
                  <button className="btn btn-primary btn-sm" style={{ marginTop: 12 }}
                    onClick={() => { onClose(); onRegistrarUso && onRegistrarUso(m); }}>
                    <I name="ClipboardList" size={13} /> Registrar primer uso
                  </button>
                </div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {usos.map((u, i) => (
                    <div key={i} style={{
                      display: "grid", gridTemplateColumns: "80px 1fr auto",
                      gap: 14, alignItems: "center",
                      padding: 12, borderRadius: 10,
                      background: i === 0 ? "var(--green-50)" : "var(--admin-bg)",
                      border: i === 0 ? "1px solid var(--green-400)" : "1px solid transparent",
                    }}>
                      <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, fontWeight: 600, color: "var(--admin-ink)" }}>{u.fecha}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13.5, lineHeight: 1.3 }}>{u.tarea}</div>
                        <div style={{ display: "flex", gap: 6, marginTop: 6, flexWrap: "wrap" }}>
                          <span className="b b-info" style={{ fontSize: 11 }}><I name="MapPin" size={11} /> {u.lote}</span>
                          {i === 0 && <span className="b b-ok" style={{ fontSize: 11 }}>último uso</span>}
                        </div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", color: "var(--green-800)" }}>
                          {u.km ? u.km : u.horas}
                        </div>
                        <div style={{ fontSize: 10.5, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>
                          {u.km ? "km" : "horas"}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}

          {tab === "combustible" && (
            <>
              {(m.cargas || []).length === 0 ? (
                <div style={{ padding: 30, textAlign: "center", color: "var(--admin-mute)" }}>
                  Esta máquina no consume gasoil directamente.
                </div>
              ) : (
                <>
                  {/* Resumen */}
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 16 }}>
                    <div style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10 }}>
                      <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>Última carga</div>
                      <div style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{m.ultCarga.fecha}</div>
                      <div style={{ fontSize: 12, color: "var(--admin-mute)" }}>{m.ultCarga.litros} L · {D.fmtARS(m.ultCarga.costo)}</div>
                    </div>
                    <div style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10 }}>
                      <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>Total cargado</div>
                      <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 22, fontWeight: 500, color: "var(--green-800)", marginTop: 2 }}>{D.fmtNum(totalLitros)} L</div>
                    </div>
                    <div style={{ padding: 14, background: "var(--admin-bg)", borderRadius: 10 }}>
                      <div style={{ fontSize: 11, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600 }}>Total gastado</div>
                      <div style={{ fontFamily: "'Fraunces', Georgia, serif", fontSize: 22, fontWeight: 500, color: "var(--green-800)", marginTop: 2 }}>{D.fmtARS(totalGasto)}</div>
                    </div>
                  </div>

                  {/* Lista */}
                  <div style={{ fontSize: 12, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 600, marginBottom: 10 }}>
                    Cargas registradas
                  </div>
                  <div className="table-wrap" style={{ border: "1px solid var(--admin-line)", borderRadius: 10 }}>
                    <table className="table">
                      <thead><tr><th>Fecha</th><th>Surtidor</th><th className="num">Litros</th><th className="num">Costo</th><th className="num">$/L</th></tr></thead>
                      <tbody>
                        {m.cargas.map((c, i) => (
                          <tr key={i}>
                            <td className="num">{c.fecha}</td>
                            <td>{c.surtidor}</td>
                            <td className="num"><strong>{c.litros} L</strong></td>
                            <td className="num money">{D.fmtARS(c.costo)}</td>
                            <td className="num" style={{ color: "var(--admin-mute)" }}>{D.fmtARS(Math.round(c.costo / c.litros))}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--admin-line)", display: "flex", gap: 8, justifyContent: "flex-end" }}>
          {m.ultCarga !== null && (
            <button className="btn btn-secondary btn-sm" onClick={() => onLoadFuel(m)}>
              <I name="Fuel" size={14} /> Cargar gasoil
            </button>
          )}
          <button className="btn btn-secondary btn-sm" onClick={() => { onClose(); onRegistrarUso && onRegistrarUso(m); }}>
            <I name="ClipboardList" size={14} /> Registrar uso
          </button>
          <button className="btn btn-primary btn-sm" onClick={onClose}>Cerrar</button>
        </div>
      </div>
    </div>
  );
}

function DetailTab({ active, onClick, label, count, disabled }) {
  return (
    <button onClick={!disabled ? onClick : undefined} disabled={disabled} style={{
      padding: "14px 4px",
      borderBottom: active ? "2px solid var(--green-800)" : "2px solid transparent",
      color: disabled ? "var(--admin-line)" : (active ? "var(--admin-ink)" : "var(--admin-mute)"),
      fontWeight: active ? 600 : 500,
      fontSize: 13.5,
      display: "flex", gap: 8, alignItems: "center",
      cursor: disabled ? "not-allowed" : "pointer",
    }}>
      {label}
      <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 999, background: active ? "var(--green-50)" : "var(--admin-bg)", color: active ? "var(--green-800)" : "var(--admin-mute)" }}>{count}</span>
    </button>
  );
}

/* Modal: cargar combustible */
function CombustibleModal({ maquina, maquinas = [], onClose, onSuccess }) {
  const D = window.DATA;
  const [maqSel,   setMaqSel]   = useState(maquina.nombre);
  const [litros,   setLitros]   = useState(180);
  const [costo,    setCosto]    = useState(0);
  const [fecha,    setFecha]    = useState(new Date().toISOString().slice(0,10));
  const [surtidor, setSurtidor] = useState("Cisterna propia");
  const [surtOtro, setSurtOtro] = useState("");
  const [done,     setDone]     = useState(false);
  const [err,      setErr]      = useState("");
  const [loading,  setLoading]  = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const maq = maquinas.find(m => m.nombre === maqSel) || maquina;
    const surtFinal = surtidor === "Otro" ? (surtOtro || "Otro") : surtidor;
    const res = await window.API.post("/cargas-combustible", {
      maquina_id: maq.id,
      fecha,
      litros,
      surtidor: surtFinal,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" · ") : (res.message || "Error al guardar.");
      setErr(msgs);
    }
  };

  const maqsConCombustible = maquinas.filter(m => m.consume_combustible !== false);

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div>
            <div style={{ fontSize: 12, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>Carga de combustible</div>
            <div className="modal__title">Registrar nueva carga</div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        <form className="form" onSubmit={submit}>
          <div className="form__field">
            <label>Maquinaria</label>
            <select className="form__select" value={maqSel} onChange={e => setMaqSel(e.target.value)}>
              {maqsConCombustible.map(m => <option key={m.nombre}>{m.nombre}</option>)}
            </select>
          </div>
          <div className="form__row">
            <div className="form__field">
              <label>Litros cargados</label>
              <div style={{ position: "relative" }}>
                <input className="form__input" type="number" value={litros} onChange={e => setLitros(+e.target.value)} required style={{ paddingRight: 36 }} />
                <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600, fontSize: 13 }}>L</span>
              </div>
            </div>
            {surtidor !== "Cisterna propia" && (
              <div className="form__field">
                <label>Costo total</label>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600 }}>$</span>
                  <input className="form__input" type="number" value={costo} onChange={e => setCosto(+e.target.value)} style={{ paddingLeft: 28 }} />
                </div>
              </div>
            )}
          </div>
          {surtidor !== "Cisterna propia" && litros > 0 && costo > 0 && (
            <div style={{ background: "var(--admin-bg)", borderRadius: 8, padding: 10, fontSize: 12.5, color: "var(--admin-mute)", textAlign: "center" }}>
              Precio por litro: <strong style={{ color: "var(--admin-ink)" }}>{D.fmtARS(Math.round(costo / litros))}</strong>
            </div>
          )}
          <div className="form__row">
            <div className="form__field">
              <label>Fecha</label>
              <input className="form__input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} />
            </div>
            <div className="form__field">
              <label>Surtidor / origen</label>
              <select className="form__select" value={surtidor} onChange={e => setSurtidor(e.target.value)}>
                <option>Cisterna propia</option>
                <option>YPF Calchin</option>
                <option>Shell Luque</option>
                <option>Shell Sacanta</option>
                <option>Otro</option>
              </select>
              {surtidor === "Otro" && (
                <input className="form__input" style={{ marginTop: 6 }} value={surtOtro} onChange={e => setSurtOtro(e.target.value)} placeholder="Nombre del surtidor / proveedor" autoFocus />
              )}
            </div>
          </div>
          {err && <div style={{ fontSize: 13, color: "var(--bad)", display: "flex", gap: 6 }}><I name="AlertCircle" size={14} />{err}</div>}
          {done && <div className="form-toast"><I name="CheckCircle2" size={18} /> Carga registrada · {litros} L en {maqSel}.</div>}
          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
            <button className="btn btn-secondary btn-sm" onClick={onClose} type="button">Cancelar</button>
            <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>{loading ? "Guardando..." : "Confirmar carga"}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

/* ============================================================
   MODAL: Nueva máquina
   ============================================================ */
function ModalNuevaMaquina({ onClose, onSuccess }) {
  const [nombre,    setNombre]    = useState("");
  const [tipo,      setTipo]      = useState("Tractor");
  const [anio,      setAnio]      = useState(new Date().getFullYear().toString());
  const [estado,    setEstado]    = useState("operativo");
  const [medicion,  setMedicion]  = useState("horas");
  const [usoAcum,   setUsoAcum]   = useState("0");
  const [servTotal, setServTotal] = useState("");
  const [servUsado, setServUsado] = useState("0");
  const [proxServ,  setProxServ]  = useState("");
  const [combustible,setCombustible]= useState(true);
  const [obs,       setObs]       = useState("");
  const [loading, setLoading] = useState(false);
  const [done,    setDone]    = useState(false);
  const [err,     setErr]     = useState("");

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.post("/maquinas", {
      nombre,
      tipo,
      anio:                parseInt(anio),
      estado,
      medicion,
      uso_acumulado:       parseInt(usoAcum) || 0,
      service_total:       servTotal ? parseInt(servTotal) : null,
      service_usado:       parseInt(servUsado) || 0,
      proximo_service:     proxServ || null,
      alerta_service:      false,
      consume_combustible: combustible,
      observaciones:       obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  const tiposIcono = { Tractor: "Tractor", Segadora: "Scissors", Enfardadora: "Package", Megaenfardadora: "Package", Rastrillo: "Rake", Sembradora: "Sprout", Logística: "Truck", Otro: "Cog" };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__title">Agregar máquina a la flota</div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> "{nombre}" agregada a la flota.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__row">
              <div className="form__field">
                <label>Nombre / Identificación</label>
                <input className="form__input" value={nombre} onChange={e => setNombre(e.target.value)} required placeholder="Ej: Tractor John Deere 6110" autoFocus />
              </div>
              <div className="form__field">
                <label>Tipo de equipo</label>
                <select className="form__select" value={tipo} onChange={e => setTipo(e.target.value)}>
                  {Object.keys(tiposIcono).map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Año</label>
                <input className="form__input" type="number" min="1970" max="2030" value={anio} onChange={e => setAnio(e.target.value)} required />
              </div>
              <div className="form__field">
                <label>Estado actual</label>
                <select className="form__select" value={estado} onChange={e => setEstado(e.target.value)}>
                  <option value="operativo">Operativo</option>
                  <option value="service">En service</option>
                  <option value="reparacion">En reparación</option>
                  <option value="baja">Baja</option>
                </select>
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Medir uso en</label>
                <select className="form__select" value={medicion} onChange={e => setMedicion(e.target.value)}>
                  <option value="horas">Horas de trabajo</option>
                  <option value="km">Kilómetros</option>
                </select>
              </div>
              <div className="form__field">
                <label>Uso acumulado actual ({medicion === "horas" ? "hs" : "km"})</label>
                <input className="form__input" type="number" min="0" value={usoAcum} onChange={e => setUsoAcum(e.target.value)} />
              </div>
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Service cada ({medicion === "horas" ? "hs" : "km"})</label>
                <input className="form__input" type="number" min="0" value={servTotal} onChange={e => setServTotal(e.target.value)} placeholder="Ej: 500" />
              </div>
              <div className="form__field">
                <label>Próximo service</label>
                <input className="form__input" value={proxServ} onChange={e => setProxServ(e.target.value)} placeholder="Ej: 240 hs" />
              </div>
            </div>
            <div className="form__field" style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
              <label style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: 8 }}>
                <input type="checkbox" checked={combustible} onChange={e => setCombustible(e.target.checked)} style={{ width: 16, height: 16 }} />
                Esta máquina consume gasoil (habilita el registro de cargas)
              </label>
            </div>
            <div className="form__field">
              <label>Observaciones</label>
              <textarea className="form__textarea" value={obs} onChange={e => setObs(e.target.value)} placeholder="Marca, modelo exacto, historial de compra..." />
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" type="button" onClick={onClose}>Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : <><I name="Plus" size={13} /> Agregar a la flota</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   MODAL: Registrar uso de máquina
   ============================================================ */
function ModalRegistrarUso({ maquina, lotes, onClose, onSuccess }) {
  const D = window.DATA;
  const [loteNombre, setLoteNombre] = useState("");
  const [tarea,      setTarea]      = useState("");
  const [fecha,      setFecha]      = useState(new Date().toLocaleDateString("es-AR"));
  const [horas,      setHoras]      = useState("");
  const [km,         setKm]         = useState("");
  const [obs,        setObs]        = useState("");
  const [loading, setLoading] = useState(false);
  const [done,    setDone]    = useState(false);
  const [err,     setErr]     = useState("");

  const toISO = (str) => {
    const [d, m, y] = (str || "").split("/");
    return y ? `${y}-${m}-${d}` : null;
  };

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr("");
    const res = await window.API.post("/usos-maquina", {
      maquina_id:    maquina.id || null,
      lote_id:       null, // por nombre, no ID — se puede mejorar
      fecha:         toISO(fecha),
      tarea,
      horas:         maquina.medicion === "horas" && horas ? parseFloat(horas) : null,
      km:            maquina.medicion === "km"    && km    ? parseInt(km)       : null,
      observaciones: obs || null,
    });
    setLoading(false);
    if (res.data?.id || res.id) {
      setDone(true);
      onSuccess && onSuccess();
      setTimeout(onClose, 1400);
    } else {
      const msgs = res.errors ? Object.values(res.errors).flat().join(" ") : res.message;
      setErr(msgs || "Error al guardar.");
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal__head">
          <div>
            <div style={{ fontSize: 12, color: "var(--admin-mute)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 600 }}>Registrar uso</div>
            <div className="modal__title">{maquina.nombre}</div>
          </div>
          <button className="modal__close" onClick={onClose}><I name="X" size={18} /></button>
        </div>
        {done ? (
          <div className="form-toast"><I name="CheckCircle2" size={18} /> Uso registrado en {maquina.nombre}.</div>
        ) : (
          <form className="form" onSubmit={submit}>
            <div className="form__field">
              <label>Descripción de la tarea</label>
              <input className="form__input" value={tarea} onChange={e => setTarea(e.target.value)} required placeholder="Ej: Corte y rastrillado · 2° corte" autoFocus />
            </div>
            <div className="form__row">
              <div className="form__field">
                <label>Lote / Campo</label>
                {lotes.length > 0 ? (
                  <select className="form__select" value={loteNombre} onChange={e => setLoteNombre(e.target.value)}>
                    <option value="">— sin lote específico —</option>
                    {lotes.map(l => <option key={l} value={l}>{l}</option>)}
                    <option value="Galpón A">Galpón A</option>
                    <option value="Galpón B">Galpón B</option>
                    <option value="Galpón C">Galpón C</option>
                    <option value="Ruta / Traslado">Ruta / Traslado</option>
                    <option value="Taller propio">Taller propio</option>
                  </select>
                ) : (
                  <input className="form__input" value={loteNombre} onChange={e => setLoteNombre(e.target.value)} placeholder="Ej: Lote La Cañada" />
                )}
              </div>
              <div className="form__field">
                <label>Fecha</label>
                <input className="form__input" value={fecha} onChange={e => setFecha(e.target.value)} required placeholder="dd/mm/aaaa" />
              </div>
            </div>
            <div className="form__row">
              {maquina.medicion === "horas" ? (
                <div className="form__field">
                  <label>Horas trabajadas</label>
                  <div style={{ position: "relative" }}>
                    <input className="form__input" type="number" step="0.5" min="0" value={horas} onChange={e => setHoras(e.target.value)} required placeholder="Ej: 8" style={{ paddingRight: 36 }} />
                    <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600, fontSize: 12 }}>hs</span>
                  </div>
                </div>
              ) : (
                <div className="form__field">
                  <label>Kilómetros recorridos</label>
                  <div style={{ position: "relative" }}>
                    <input className="form__input" type="number" min="0" value={km} onChange={e => setKm(e.target.value)} required placeholder="Ej: 120" style={{ paddingRight: 36 }} />
                    <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--admin-mute)", fontWeight: 600, fontSize: 12 }}>km</span>
                  </div>
                </div>
              )}
              <div className="form__field">
                <label>Observaciones</label>
                <input className="form__input" value={obs} onChange={e => setObs(e.target.value)} placeholder="Condiciones, incidencias..." />
              </div>
            </div>
            {err && <div style={{ color: "var(--bad)", fontSize: 13 }}>{err}</div>}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
              <button className="btn btn-secondary btn-sm" type="button" onClick={onClose}>Cancelar</button>
              <button className="btn btn-primary btn-sm" type="submit" disabled={loading}>
                {loading ? "Guardando..." : <><I name="ClipboardList" size={13} /> Registrar uso</>}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Produccion, Stock, VentasModulo, ServiciosTerceros, Gastos, Rentabilidad, Maquinaria });
