/* ============================================
   Admin — Login + Shell + Dashboard
   ============================================ */

/* ============================================
   Login
   ============================================ */
function Login({ onLogin, onBack, resetToken, resetEmail }) {
  // step: "login" | "forgot" | "reset" | "reset-ok"
  const [step,     setStep]    = useState(() => resetToken ? "reset" : "login");
  const [email,    setEmail]   = useState(resetEmail || "admin@msamoro.com");
  const [pass,     setPass]    = useState("");
  const [passConf, setPassConf]= useState("");
  const [err,      setErr]     = useState("");
  const [msg,      setMsg]     = useState("");
  const [loading,  setLoading] = useState(false);

  const submitLogin = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const r = await window.API.login(email, pass);
    if (r.ok) { onLogin(r.user); }
    else { setErr(r.error || "Credenciales incorrectas."); setLoading(false); }
  };

  const submitForgot = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const r = await window.API.forgotPassword(email);
    setLoading(false);
    if (r.ok) setMsg(r.mensaje);
    else setErr(r.error);
  };

  const submitReset = async (e) => {
    e.preventDefault();
    if (pass !== passConf) { setErr("Las contraseñas no coinciden."); return; }
    setErr(""); setLoading(true);
    const r = await window.API.resetPassword(resetToken, email, pass, passConf);
    setLoading(false);
    if (r.ok) { setStep("reset-ok"); setMsg(r.mensaje); }
    else setErr(r.error);
  };

  const Left = () => (
    <div className="login__left">
      <div className="login__brand-row">
        <BrandMark />
        <div className="brand__name" style={{ color: "#fff" }}>MSA <span style={{ color: "var(--gold-300)" }}>Moro</span></div>
      </div>
      <div className="login__quote" style={{ position: "relative", zIndex: 1 }}>
        Producir alfalfa premium no es solo plantar — es medir, registrar y mejorar cada lote, año tras año.
        <div style={{ marginTop: 28, fontSize: 14, color: "var(--gold-300)", fontFamily: "Inter, sans-serif", fontStyle: "normal", letterSpacing: 0 }}>
          — Hermanos Bertoldi, fundadores
        </div>
      </div>
      <div className="login__foot">Panel de gestión interna · v2.4.1 · campaña 2025/26</div>
    </div>
  );

  const ErrMsg = () => err ? (
    <div style={{ fontSize: 13, color: "var(--bad)", display: "flex", gap: 6, alignItems: "center" }}>
      <I name="AlertCircle" size={14} />{err}
    </div>
  ) : null;

  if (step === "forgot") return (
    <div className="login">
      <Left />
      <div className="login__right">
        <div className="login-card">
          <button type="button" onClick={() => { setStep("login"); setErr(""); setMsg(""); }}
            style={{ display:"flex", alignItems:"center", gap:6, background:"none", border:"none", cursor:"pointer", fontSize:13, color:"var(--text-muted)", marginBottom:20, padding:0 }}>
            <I name="ArrowLeft" size={15} /> Volver al inicio de sesión
          </button>
          <div className="login-card__eyebrow">Recuperar acceso</div>
          <h2>¿Olvidaste tu<br/>contraseña?</h2>
          <p className="login-card__sub">Te enviamos un enlace para restablecerla.</p>
          {msg ? (
            <div style={{ fontSize:14, color:"var(--good)", display:"flex", gap:8, alignItems:"center", marginTop:8 }}>
              <I name="CheckCircle2" size={16} />{msg}
            </div>
          ) : (
            <form className="form" onSubmit={submitForgot}>
              <div className="form__field">
                <label>Email</label>
                <input className="form__input" type="email" value={email} onChange={e => setEmail(e.target.value)} autoFocus required />
              </div>
              <ErrMsg />
              <button className="btn btn-primary btn-lg" type="submit" style={{ marginTop:8, justifyContent:"center" }} disabled={loading}>
                {loading ? "Enviando..." : <><I name="Mail" size={16} /> Enviar enlace</>}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  );

  if (step === "reset") return (
    <div className="login">
      <Left />
      <div className="login__right">
        <div className="login-card">
          <div className="login-card__eyebrow">Nueva contraseña</div>
          <h2>Restablecer<br/>contraseña.</h2>
          <p className="login-card__sub">Ingresá tu nueva contraseña para {email}.</p>
          <form className="form" onSubmit={submitReset}>
            <div className="form__field">
              <label>Nueva contraseña</label>
              <input className="form__input" type="password" value={pass} onChange={e => setPass(e.target.value)} autoFocus required minLength={8} placeholder="Mínimo 8 caracteres" />
            </div>
            <div className="form__field">
              <label>Confirmar contraseña</label>
              <input className="form__input" type="password" value={passConf} onChange={e => setPassConf(e.target.value)} required minLength={8} />
            </div>
            <ErrMsg />
            <button className="btn btn-primary btn-lg" type="submit" style={{ marginTop:8, justifyContent:"center" }} disabled={loading}>
              {loading ? "Guardando..." : <><I name="KeyRound" size={16} /> Guardar contraseña</>}
            </button>
          </form>
        </div>
      </div>
    </div>
  );

  if (step === "reset-ok") return (
    <div className="login">
      <Left />
      <div className="login__right">
        <div className="login-card">
          <div className="login-card__eyebrow">Listo</div>
          <h2>Contraseña<br/>actualizada.</h2>
          <div style={{ display:"flex", flexDirection:"column", gap:16, marginTop:8 }}>
            <div style={{ fontSize:14, color:"var(--good)", display:"flex", gap:8, alignItems:"center" }}>
              <I name="CheckCircle2" size={16} />{msg}
            </div>
            <button className="btn btn-primary btn-lg" style={{ justifyContent:"center" }} onClick={() => { setStep("login"); setPass(""); setPassConf(""); setMsg(""); }}>
              Ir al inicio de sesión <I name="ArrowRight" size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  // step === "login"
  return (
    <div className="login">
      <Left />
      <div className="login__right">
        <div className="login-card">
          <div className="login-card__eyebrow">Acceso exclusivo</div>
          <h2>Bienvenido<br/>al panel directivo.</h2>
          <p className="login-card__sub">Acceso exclusivo para directivos y administración.</p>
          <form className="form" onSubmit={submitLogin}>
            <div className="form__field">
              <label>Email</label>
              <input className="form__input" type="email" value={email} onChange={e => setEmail(e.target.value)} autoFocus />
            </div>
            <div className="form__field">
              <label>Contraseña</label>
              <input className="form__input" type="password" value={pass} onChange={e => setPass(e.target.value)} />
            </div>
            <ErrMsg />
            <button className="btn btn-primary btn-lg" type="submit" style={{ marginTop:8, justifyContent:"center" }} disabled={loading}>
              {loading ? "Ingresando..." : <>Ingresar <I name="ArrowRight" size={16} /></>}
            </button>
            <button type="button" style={{ background:"none", border:"none", cursor:"pointer", fontSize:13, color:"var(--text-muted)", alignSelf:"center", marginTop:2 }}
              onClick={() => { setStep("forgot"); setErr(""); }}>
              ¿Olvidaste tu contraseña?
            </button>
            {onBack && (
              <button type="button" className="btn btn-ghost btn-sm" style={{ alignSelf:"center", marginTop:2 }} onClick={onBack}>
                <I name="ArrowLeft" size={14} /> Volver al sitio
              </button>
            )}
          </form>
        </div>
      </div>
    </div>
  );
}

/* ============================================
   Sidebar
   ============================================ */
function Sidebar({ active, onNav, onExit, onLogout, open, onClose }) {
  const items = [
    { section: "Principal" },
    { id: "dashboard",   label: "Inicio",           icon: "LayoutDashboard" },
    { id: "produccion",  label: "Producción",      icon: "Sprout" },
    { id: "stock",       label: "Stock de fardos", icon: "Package", badge: "12.8k" },
    { section: "Comercial" },
    { id: "ventas",      label: "Ventas y clientes", icon: "Receipt" },
    { id: "asociacion",  label: "Asociación",         icon: "Handshake" },
    { id: "terceros",    label: "Servicios a terceros", icon: "Tractor" },
    { section: "Finanzas" },
    { id: "gastos",      label: "Gastos y costos", icon: "Wallet" },
    { id: "cheques",     label: "Cheques",         icon: "ScrollText", badge: "22" },
    { id: "rent",        label: "Rentabilidad",    icon: "TrendingUp" },
    { section: "Operaciones" },
    { id: "logistica",   label: "Logística",       icon: "Truck", badge: String(window.DATA?.VIAJES?.filter(v => v.estado === "programado" || v.estado === "en curso").length ?? 0) },
    { id: "empleados",   label: "Empleados",       icon: "Users", badge: "3" },
    { id: "maquinaria",  label: "Maquinaria",      icon: "Wrench", badge: "8" },
  ];

  const handleNav = (id) => { onNav(id); onClose && onClose(); };

  return (
    <>
      <div className={`sidebar-backdrop ${open ? "is-open" : ""}`} onClick={onClose}></div>
      <aside className={`sidebar ${open ? "is-open" : ""}`}>
        <div className="sidebar__brand">
          <BrandMark />
          <div>
            <div className="sidebar__brand-name">MSA Moro Servicios Agropecuarios</div>
            <div className="sidebar__brand-meta">Panel directivo</div>
          </div>
          <button className="sidebar__close" onClick={onClose} aria-label="Cerrar menú">
            <I name="X" size={20} />
          </button>
        </div>

        {items.map((it, i) =>
          it.section ? (
            <div key={"s"+i} className="sidebar__section">{it.section}</div>
          ) : (
            <button key={it.id} className={`sidebar__link ${active === it.id ? "is-active" : ""}`} onClick={() => handleNav(it.id)}>
              <I name={it.icon} size={17} />
              <span>{it.label}</span>
              {it.badge && <span className="sidebar__badge">{it.badge}</span>}
            </button>
          )
        )}

        <div className="sidebar__footer">
          <button className="sidebar__exit" onClick={onExit}>
            <I name="ExternalLink" size={15} /> Ver sitio público
          </button>
          <button className="sidebar__exit" onClick={onLogout}>
            <I name="LogOut" size={15} /> Cerrar sesión
          </button>
        </div>
      </aside>
    </>
  );
}

/* ============================================
   Topbar
   ============================================ */
function NotifDropdown({ notifs, onNav, onClose }) {
  const ref = React.useRef(null);

  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [onClose]);

  const iconMap = { cheque:"ScrollText", maquinaria:"Wrench", viaje:"Truck", gasto:"Wallet", stock:"Package", corte:"Scissors" };
  const moduloMap = { produccion:"produccion", cheques:"cheques", maquinaria:"maquinaria", logistica:"logistica", gastos:"gastos", stock:"stock" };
  const colorUrg  = (u) => u === "alta" ? "var(--bad)" : u === "media" ? "#d97706" : "var(--admin-mute)";
  const labelUrg  = (u) => u === "alta" ? "Urgente" : u === "media" ? "Importante" : "Info";

  const fmtFecha = (f) => {
    if (!f) return null;
    const d = new Date(f + "T00:00:00");
    return d.toLocaleDateString("es-AR", { day:"2-digit", month:"short" });
  };

  return (
    <div ref={ref} style={{
      position:"absolute", top:"calc(100% + 10px)", right:0, width:340, maxHeight:480,
      background:"#fff", border:"1px solid var(--admin-line)", borderRadius:12,
      boxShadow:"0 8px 32px rgba(0,0,0,.18)", zIndex:1000, overflow:"hidden", display:"flex", flexDirection:"column"
    }}>
      <div style={{ padding:"14px 16px 10px", borderBottom:"1px solid var(--admin-line)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
        <span style={{ fontWeight:600, fontSize:14 }}>Notificaciones</span>
        {notifs.length > 0
          ? <span style={{ fontSize:12, background:"var(--bad)", color:"#fff", borderRadius:10, padding:"2px 8px" }}>{notifs.length}</span>
          : <span style={{ fontSize:12, color:"var(--admin-mute)" }}>Sin alertas</span>
        }
      </div>
      <div style={{ overflowY:"auto", flex:1 }}>
        {notifs.length === 0 ? (
          <div style={{ padding:"32px 16px", textAlign:"center", color:"var(--admin-mute)", fontSize:13 }}>
            <I name="CheckCircle2" size={28} style={{ marginBottom:8, opacity:.4 }} />
            <div>Todo al día</div>
          </div>
        ) : notifs.map(n => (
          <button key={n.id} onClick={() => { onNav(moduloMap[n.modulo] || n.modulo); onClose(); }}
            style={{ width:"100%", display:"flex", gap:10, padding:"10px 16px", background:"none", border:"none",
              borderBottom:"1px solid var(--admin-line)", cursor:"pointer", textAlign:"left", alignItems:"flex-start" }}
            onMouseEnter={e => e.currentTarget.style.background="var(--admin-bg)"}
            onMouseLeave={e => e.currentTarget.style.background="none"}
          >
            <div style={{ width:32, height:32, borderRadius:8, background: colorUrg(n.urgencia) + "18",
              display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0, marginTop:1 }}>
              <I name={iconMap[n.tipo] || "Bell"} size={15} style={{ color: colorUrg(n.urgencia) }} />
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:13, fontWeight:600, marginBottom:2, color:"var(--admin-text)" }}>{n.titulo}</div>
              <div style={{ fontSize:12, color:"var(--admin-mute)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{n.detalle}</div>
            </div>
            <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-end", gap:4, flexShrink:0 }}>
              <span style={{ fontSize:10, fontWeight:600, color: colorUrg(n.urgencia),
                background: colorUrg(n.urgencia) + "18", borderRadius:6, padding:"2px 6px" }}>
                {labelUrg(n.urgencia)}
              </span>
              {n.fecha && <span style={{ fontSize:10, color:"var(--admin-mute)" }}>{fmtFecha(n.fecha)}</span>}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function Topbar({ user, onMenuClick, notificaciones = [], onNav }) {
  const nombre   = user?.nombre || "Admin";
  const initials = nombre.split(" ").map(w => w[0]).slice(0, 2).join("").toUpperCase();
  const [showNotif, setShowNotif] = useState(false);
  const count = notificaciones.length;

  return (
    <div className="topbar">
      <button className="topbar__menu" onClick={onMenuClick} aria-label="Menú">
        <I name="Menu" size={20} />
      </button>
      <div className="topbar__search">
        <I name="Search" size={16} />
        <input placeholder="Buscar lote, cliente, fardo, venta..." />
        <kbd style={{ fontSize: 10, color: "var(--admin-mute)", padding: "2px 6px", border: "1px solid var(--admin-line)", borderRadius: 4 }}>⌘K</kbd>
      </div>
      <div className="topbar__actions">
        <button className="icon-btn" onClick={() => window.toast("Centro de ayuda — soporte@msamoro.com.ar", "info")}><I name="HelpCircle" size={18} /></button>
        <div style={{ position:"relative" }}>
          <button className="icon-btn" onClick={() => setShowNotif(v => !v)} style={{ position:"relative" }}>
            <I name="Bell" size={18} />
            {count > 0 && (
              <span className="badge" style={{ position:"absolute", top:-4, right:-4, minWidth:16, height:16,
                background:"var(--bad)", color:"#fff", borderRadius:8, fontSize:10, fontWeight:700,
                display:"flex", alignItems:"center", justifyContent:"center", padding:"0 4px" }}>
                {count > 9 ? "9+" : count}
              </span>
            )}
          </button>
          {showNotif && <NotifDropdown notifs={notificaciones} onNav={onNav} onClose={() => setShowNotif(false)} />}
        </div>
        <div className="user-chip">
          <div className="user-chip__avatar">{initials}</div>
          <div>
            <div className="user-chip__name">{nombre}</div>
            <div className="user-chip__role">{user?.email || ""}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================
   Recharts shorthand
   ============================================ */
const RC = window.Recharts;

function ChartCard({ title, sub, right, height = 260, children }) {
  return (
    <div className="panel">
      <div className="panel__head">
        <div>
          <div className="panel__title">{title}</div>
          {sub && <div className="panel__sub">{sub}</div>}
        </div>
        {right}
      </div>
      <div style={{ height, marginLeft: -8, marginRight: -8 }}>
        <RC.ResponsiveContainer width="100%" height="100%">
          {children}
        </RC.ResponsiveContainer>
      </div>
    </div>
  );
}

/* ============================================
   Dashboard
   ============================================ */
function Dashboard() {
  const D = window.DATA;
  const [stats,  setStats]  = useState(null);
  const [alerts, setAlerts] = useState([]);

  useEffect(() => {
    window.API.get("/dashboard").then(data => { if (!data.error) setStats(data); });
    window.API.get("/notificaciones").then(data => { if (Array.isArray(data)) setAlerts(data); });
  }, []);

  const ha      = stats ? Number(stats.lotes.hectareas).toLocaleString("es-AR") : "…";
  const lotesN  = stats ? stats.lotes.total : "…";
  const fardos  = stats ? Number(stats.stock.total_fardos).toLocaleString("es-AR") : "…";
  const clientes= stats ? stats.clientes.total : "…";
  const empN    = stats ? stats.empleados.total : "…";
  const viajesP = stats ? stats.viajes.programados + stats.viajes.en_curso : "…";
  const ventasMes = stats ? D.fmtARS(stats.ventas_mes) : "…";

  const alertIcon  = { cheque:"Clock", maquinaria:"Wrench", viaje:"Truck", gasto:"DollarSign", stock:"Package", corte:"Sprout" };
  const alertClass = { alta:"bad", media:"warn", baja:"info" };

  const ventasMensuales = stats?.ventas_mensuales || [];
  const produccionLotes = stats?.produccion_lotes  || [];
  const ventasPorTipo   = stats?.ventas_por_tipo   || [];
  const ultimasVentas   = stats?.ultimas_ventas    || [];

  return (
    <div className="page" data-screen-label="Inicio">
      <div className="page__header">
        <div>
          <div className="page__title">Buen día. <span style={{ color: "var(--admin-mute)" }}>Resumen actualizado.</span></div>
          <div className="page__sub">Datos en tiempo real · Campaña 2025/26</div>
        </div>
        <div className="page__actions">
          <button className="btn btn-primary btn-sm" onClick={() => window.navTo("ventas")}><I name="Plus" size={14} /> Registrar venta</button>
        </div>
      </div>

      {/* KPIs */}
      <div className="kpi-grid">
        <Kpi icon="Package"      label="Fardos en stock"   value={String(fardos)}   delta="" deltaDir="flat" hint="inventario actual" />
        <Kpi icon="DollarSign"   label="Ventas del mes"    value={ventasMes}         delta="" deltaDir="flat" hint="mes en curso" />
        <Kpi icon="Map"          label="Hectáreas activas" value={ha + " ha"}        delta={lotesN + " lotes"} deltaDir="info" hint="en producción" />
        <Kpi icon="Users"        label="Clientes"          value={String(clientes)}  delta="" deltaDir="flat" hint="registrados" />
        <Kpi icon="UserCheck"    label="Empleados"         value={String(empN)}      delta="" deltaDir="flat" hint="en plantilla" />
        <Kpi icon="Truck"        label="Viajes activos"    value={String(viajesP)}   delta="programados / en curso" deltaDir="info" hint="logística" />
      </div>

      {/* Ventas mensuales + Alertas */}
      <div className="grid-2">
        <ChartCard
          title="Ventas mensuales"
          sub="Últimos 12 meses"
          height={280}
        >
          {ventasMensuales.length === 0
            ? <div style={{ display:"flex", alignItems:"center", justifyContent:"center", height:"100%", color:"var(--admin-mute)", fontSize:13 }}>Sin datos de ventas aún</div>
            : <RC.AreaChart data={ventasMensuales} margin={{ top: 10, right: 20, left: 10, bottom: 0 }}>
                <defs>
                  <linearGradient id="gradVentas" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#2d5016" stopOpacity={0.35} />
                    <stop offset="100%" stopColor="#2d5016" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <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(0)}M`} width={50} />
                <RC.Tooltip
                  contentStyle={{ background: "#0e1f0a", border: "none", borderRadius: 10, color: "#fff", fontSize: 12 }}
                  formatter={(v) => [D.fmtARS(v), "Ventas"]}
                />
                <RC.Area type="monotone" dataKey="ventas" stroke="#2d5016" strokeWidth={2.5} fill="url(#gradVentas)" animationDuration={900} />
              </RC.AreaChart>
          }
        </ChartCard>

        <div className="panel">
          <div className="panel__head">
            <div className="panel__title">Alertas</div>
            {alerts.length > 0 && <span className="b b-warn">{alerts.length} pendientes</span>}
          </div>
          {alerts.length === 0
            ? <div style={{ padding:"24px 0", textAlign:"center", color:"var(--admin-mute)", fontSize:13 }}>Sin alertas activas</div>
            : alerts.slice(0, 6).map(a => (
                <div className="alert" key={a.id} style={{ cursor:"pointer" }} onClick={() => window.navTo(a.modulo)}>
                  <div className={`alert__icon ${alertClass[a.urgencia] || "info"}`}>
                    <I name={alertIcon[a.tipo] || "Bell"} size={16} />
                  </div>
                  <div>
                    <div className="alert__title">{a.titulo}</div>
                    <div className="alert__meta">{a.detalle}</div>
                  </div>
                </div>
              ))
          }
        </div>
      </div>

      {/* Producción por lote + Ventas por producto */}
      <div className="grid-2">
        <ChartCard
          title="Producción por lote"
          sub="Toneladas acumuladas"
          right={<span style={{ fontSize: 11, color: "var(--admin-mute)" }}>{lotesN} lotes</span>}
          height={280}
        >
          {produccionLotes.length === 0
            ? <div style={{ display:"flex", alignItems:"center", justifyContent:"center", height:"100%", color:"var(--admin-mute)", fontSize:13 }}>Sin cortes registrados</div>
            : <RC.BarChart data={produccionLotes} margin={{ top: 10, right: 12, left: 0, bottom: 0 }}>
                <RC.CartesianGrid stroke="#efece3" vertical={false} />
                <RC.XAxis dataKey="lote" stroke="#7a766c" fontSize={10.5} tickLine={false} axisLine={false} interval={0} angle={-18} textAnchor="end" height={56} />
                <RC.YAxis stroke="#7a766c" fontSize={11} tickLine={false} axisLine={false} tickFormatter={(v) => `${v}t`} width={42} />
                <RC.Tooltip
                  contentStyle={{ background: "#0e1f0a", border: "none", borderRadius: 10, color: "#fff", fontSize: 12 }}
                  formatter={(v) => [`${v} t`, "Producción"]}
                />
                <RC.Bar dataKey="toneladas" fill="#7cb342" radius={[6,6,0,0]} animationDuration={900} />
              </RC.BarChart>
          }
        </ChartCard>

        <ChartCard title="Ventas por producto" sub="Distribución por monto total" height={280}>
          {ventasPorTipo.length === 0
            ? <div style={{ display:"flex", alignItems:"center", justifyContent:"center", height:"100%", color:"var(--admin-mute)", fontSize:13 }}>Sin ventas registradas</div>
            : <RC.PieChart>
                <RC.Pie data={ventasPorTipo} dataKey="valor" nameKey="tipo" innerRadius={56} outerRadius={92} paddingAngle={2} animationDuration={900}>
                  {ventasPorTipo.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) => [`${v}%`, ""]}
                />
                <RC.Legend wrapperStyle={{ fontSize: 11.5 }} iconType="circle" />
              </RC.PieChart>
          }
        </ChartCard>
      </div>

      {/* Últimas ventas */}
      <div className="panel">
        <div className="panel__head">
          <div className="panel__title">Últimas ventas</div>
          <button className="btn btn-ghost btn-sm" onClick={() => window.navTo("ventas")}>Ver todas <I name="ArrowRight" size={14} /></button>
        </div>
        <div className="table-wrap">
          {ultimasVentas.length === 0
            ? <div style={{ padding:"24px", textAlign:"center", color:"var(--admin-mute)", fontSize:13 }}>Sin ventas registradas</div>
            : <table className="table">
                <thead>
                  <tr><th>Fecha</th><th>Cliente</th><th>Producto</th><th className="num">Cantidad</th><th className="num">Monto</th><th>Estado</th></tr>
                </thead>
                <tbody>
                  {ultimasVentas.map((v, i) => (
                    <tr key={i}>
                      <td className="num">{v.fecha}</td>
                      <td><strong>{v.cliente}</strong></td>
                      <td>{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>
  );
}

function Kpi({ icon, label, value, delta, deltaDir, hint }) {
  const dirClass = deltaDir === "up" ? "up" : deltaDir === "down" ? "down" : "flat";
  const arrow = deltaDir === "up" ? "ArrowUp" : deltaDir === "down" ? "ArrowDown" : null;
  return (
    <div className="kpi">
      <div className="kpi__head">
        <div className="kpi__icon"><I name={icon} size={16} /></div>
        {delta && (
          <div className={`kpi__delta ${dirClass}`}>
            {arrow && <I name={arrow} size={11} />} {delta}
          </div>
        )}
      </div>
      <div className="kpi__label">{label}</div>
      <div className="kpi__value">{value}</div>
      {hint && <div className="kpi__hint">{hint}</div>}
    </div>
  );
}

function EstadoBadge({ estado }) {
  const map = {
    pagado:    ["b-ok",   "Pagado"],
    parcial:   ["b-warn", "Parcial"],
    pendiente: ["b-bad",  "Pendiente"],
    cobrado:   ["b-ok",   "Cobrado"],
    activo:    ["b-ok",   "Activo"],
    proximo:   ["b-warn", "Próximo corte"],
    descanso:  ["b-mute", "En descanso"],
    implantacion: ["b-info", "Implantación"],
    operativo: ["b-ok",   "Operativo"],
    service:   ["b-bad",  "Service"],
  };
  const [cls, label] = map[estado] || ["b-mute", estado];
  return <span className={`b ${cls}`}><span className={`dot ${cls === "b-ok" ? "dot-ok" : cls === "b-warn" ? "dot-warn" : cls === "b-bad" ? "dot-bad" : ""}`}></span>{label}</span>;
}

Object.assign(window, { Login, Sidebar, Topbar, Dashboard, Kpi, EstadoBadge, ChartCard, RC });
