// LOLA Consola Web — Dashboard BI financiero
// Usa window.WC y las gráficas de charts.jsx. Todos los números llegan por props (dash),
// que vienen de GET /admin/dashboard — agregados reales de MongoDB, sin datos de ejemplo.
// Exporta window.DashboardView, window.KpiCard, window.Panel

function KpiCard({ label, value, delta, deltaUp, spark, sparkUp, icon, accent }) {
  const t = window.WC;
  return (
    <div style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 14, padding: '18px 20px',
      display: 'flex', flexDirection: 'column', gap: 12, boxShadow: '0 1px 2px rgba(16,32,46,.04)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 12, color: t.sec, fontWeight: 600, letterSpacing: .2 }}>{label}</span>
        <span style={{ width: 32, height: 32, borderRadius: 9, background: (accent || t.brand) + '14',
          color: accent || t.brand, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10 }}>
        <div>
          <div style={{ fontSize: 27, fontWeight: 800, color: t.text, letterSpacing: -1, lineHeight: 1, fontFamily: t.mono }}>{value}</div>
          {delta != null && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 8 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: deltaUp ? t.success : t.danger, fontFamily: t.mono }}>
                {deltaUp ? '▲' : '▼'} {delta}
              </span>
              <span style={{ fontSize: 11, color: t.ter }}>vs. mes anterior</span>
            </div>
          )}
        </div>
        {spark && <window.Sparkline data={spark} up={sparkUp !== false}/>}
      </div>
    </div>
  );
}

function Panel({ title, sub, action, children, pad = 22, style }) {
  const t = window.WC;
  return (
    <div style={{ background: '#fff', border: `1px solid ${t.border}`, borderRadius: 14,
      boxShadow: '0 1px 2px rgba(16,32,46,.04)', display: 'flex', flexDirection: 'column', ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '16px 22px', borderBottom: `1px solid ${t.border}` }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 700, color: t.text, letterSpacing: -.2 }}>{title}</div>
          {sub && <div style={{ fontSize: 12, color: t.ter, marginTop: 2 }}>{sub}</div>}
        </div>
        {action}
      </div>
      <div style={{ padding: pad, flex: 1 }}>{children}</div>
    </div>
  );
}

function Segmented({ options, value, onChange }) {
  const t = window.WC;
  return (
    <div style={{ display: 'flex', gap: 2, background: t.grid, borderRadius: 9, padding: 3 }}>
      {options.map(o => (
        <button key={o} onClick={() => onChange(o)} style={{
          border: 'none', cursor: 'pointer', padding: '5px 13px', borderRadius: 7,
          fontFamily: t.font, fontSize: 12, fontWeight: 600,
          background: value === o ? '#fff' : 'transparent',
          color: value === o ? t.text : t.sec,
          boxShadow: value === o ? '0 1px 3px rgba(16,32,46,.12)' : 'none' }}>{o}</button>
      ))}
    </div>
  );
}

function DashboardView({ dash, loading, error, reload, rangoDias, onRangoChange }) {
  const t = window.WC, I = window.WI;
  const isMobile = window.useIsMobile();
  const dias = rangoDias || 30;
  const rangoLabel = dias + ' días';

  if (loading) return <window.Loading label="Cargando analítica…"/>;
  if (error) return <window.ErrState error={error} onRetry={reload}/>;

  const d = dash || {}, k = d.kpis || {};
  const comision30 = d.comision30 || [];
  const estados = d.estados || [];
  const categorias = d.categorias || [];
  const topProv = d.topProv || [];
  const gmvSemana = d.gmvSemana || [];
  const funnel = d.funnel || [];
  const tx = d.tx || [];
  const totalServ = estados.reduce((s, x) => s + x.v, 0);
  const totalCat = categorias.reduce((s, x) => s + x.v, 0);
  const hasComision = comision30.some((x) => x.v > 0);
  const hasGmv = gmvSemana.some((x) => x.v > 0);
  const hasFunnel = funnel.length > 0 && funnel[0].v > 0;
  const com30total = comision30.reduce((s, x) => s + x.v, 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* KPIs (reales) */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4,1fr)', gap: isMobile ? 12 : 16 }}>
        <KpiCard label="Volumen transado (hoy)" value={window.fmtK(k.volumenHoy || 0)} icon={<I.Trend/>} accent={t.brand}/>
        <KpiCard label="Comisión LOLA (hoy)" value={window.fmtK(k.comisionHoy || 0)} icon={<I.Wallet/>} accent={t.success}
          spark={hasComision ? comision30.slice(-7).map((x) => x.v) : null}/>
        <KpiCard label="Servicios completados" value={window.fmtN(k.finalizados || 0)} icon={<I.Check/>} accent={t.accentDk}/>
        <KpiCard label="Ticket promedio" value={window.fmtQ(k.ticketPromedio || 0)} icon={<I.Tag/>} accent={t.purple}/>
      </div>

      {/* comisión + estados */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.65fr 1fr', gap: 18 }}>
        <Panel title="Ingreso por comisión" sub={`Neto de la plataforma · últimos ${dias} días`}
          action={<Segmented options={['7 días', '30 días', '90 días']} value={rangoLabel} onChange={(l) => onRangoChange && onRangoChange(parseInt(l, 10))}/>}>
          {hasComision ? (
            <React.Fragment>
              <window.AreaChart data={comision30} color={t.brand} labelEvery={dias <= 7 ? 1 : dias <= 30 ? 3 : 9} h={250}/>
              <div style={{ display: 'flex', gap: 26, marginTop: 6, paddingTop: 14, borderTop: `1px solid ${t.grid}` }}>
                <Stat label={`Total ${dias} días`} value={window.fmtK(com30total)}/>
                <Stat label="Promedio diario" value={window.fmtK(Math.round(com30total / dias))}/>
                <Stat label="Mejor día" value={window.fmtK(Math.max(...comision30.map((x) => x.v)))} pos/>
              </div>
            </React.Fragment>
          ) : <window.ChartEmpty h={250} label="Aún no hay comisiones registradas"/>}
        </Panel>
        <Panel title="Estado de servicios" sub="Distribución actual">
          {totalServ > 0 ? (
            <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
              <window.DonutChart data={estados} size={186} center={{ big: window.fmtN(totalServ), small: 'Total' }}/>
            </div>
          ) : <window.ChartEmpty h={200} label="Sin servicios todavía"/>}
        </Panel>
      </div>

      {/* GMV semana + funnel */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 18 }}>
        <Panel title="Volumen vs. comisión" sub="Servicios completados por día · GMV (azul) e ingreso LOLA (amarillo)">
          {hasGmv ? <window.BarChart data={gmvSemana} color={t.brand} color2={t.accent} h={230}/>
            : <window.ChartEmpty h={230} label="Sin viajes completados esta semana"/>}
        </Panel>
        <Panel title="Embudo de conversión" sub="De solicitud a pago">
          {hasFunnel ? <div style={{ paddingTop: 6 }}><window.Funnel data={funnel}/></div>
            : <window.ChartEmpty h={200} label="Sin solicitudes todavía"/>}
        </Panel>
      </div>

      {/* top proveedores + categorías */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr', gap: 18 }}>
        <Panel title="Top proveedores" sub="Por ingresos generados">
          {topProv.length ? <window.HBars data={topProv}/>
            : <window.ChartEmpty h={180} label="Sin pagos a proveedores todavía"/>}
        </Panel>
        <Panel title="Servicios por categoría" sub="Tipo de carga">
          {totalCat > 0 ? (
            <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 4 }}>
              <window.DonutChart data={categorias} size={176} center={{ big: window.fmtN(totalCat), small: 'Servicios' }}/>
            </div>
          ) : <window.ChartEmpty h={176} label="Sin servicios todavía"/>}
        </Panel>
      </div>

      {/* transacciones */}
      <Panel title="Movimientos recientes" sub="Libro mayor · billetera de la plataforma" pad={0}
        action={<button style={btnGhost(t)} onClick={reload}>Actualizar</button>}>
        {tx.length ? <TxTable rows={tx}/>
          : <div style={{ padding: '8px 0' }}><window.EmptyState icon="Wallet" title="Sin movimientos"
            sub="Los cobros, comisiones y pagos aparecerán aquí cuando haya operación."/></div>}
      </Panel>
    </div>
  );
}

function Stat({ label, value, pos }) {
  const t = window.WC;
  return (
    <div>
      <div style={{ fontSize: 11, color: t.ter, fontFamily: t.mono, textTransform: 'uppercase', letterSpacing: .8 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 800, color: pos ? t.success : t.text, fontFamily: t.mono, marginTop: 3, letterSpacing: -.5 }}>{value}</div>
    </div>
  );
}

function TxTable({ rows }) {
  const t = window.WC;
  const estadoColor = (e) => e === 'En revisión' ? t.warn : e === 'Liquidado' || e === 'Confirmado' ? t.success : t.brand;
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
        <thead>
          <tr style={{ background: '#FAFBFC' }}>
            {['ID', 'Tipo', 'Detalle', 'Usuario', 'Monto', 'Estado', 'Fecha'].map((h, i) => (
              <th key={h} style={{ textAlign: i === 4 ? 'right' : 'left', padding: '11px 22px', fontFamily: t.mono,
                fontSize: 10.5, letterSpacing: 1, textTransform: 'uppercase', color: t.ter, fontWeight: 700,
                borderBottom: `1px solid ${t.border}` }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={r.id} style={{ borderBottom: i < rows.length - 1 ? `1px solid ${t.grid}` : 'none' }}>
              <td style={{ padding: '12px 22px', fontFamily: t.mono, fontSize: 12, color: t.sec }}>{r.id}</td>
              <td style={{ padding: '12px 22px', fontWeight: 600, color: t.text }}>{r.tipo}</td>
              <td style={{ padding: '12px 22px', color: t.sec }}>{r.desc}</td>
              <td style={{ padding: '12px 22px', color: t.text }}>{r.usuario}</td>
              <td style={{ padding: '12px 22px', textAlign: 'right', fontFamily: t.mono, fontWeight: 700,
                color: r.signo === '+' ? t.success : t.danger }}>{r.signo}{window.fmtQ(r.monto)}</td>
              <td style={{ padding: '12px 22px' }}>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: estadoColor(r.estado),
                  background: estadoColor(r.estado) + '16', padding: '3px 10px', borderRadius: 999, fontFamily: t.mono }}>{r.estado}</span>
              </td>
              <td style={{ padding: '12px 22px', color: t.ter, fontFamily: t.mono, fontSize: 12, whiteSpace: 'nowrap' }}>{r.fecha}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function btnGhost(t) {
  return { border: `1px solid ${t.border}`, background: '#fff', color: t.sec, cursor: 'pointer',
    padding: '7px 14px', borderRadius: 8, fontFamily: t.font, fontSize: 12.5, fontWeight: 600 };
}

Object.assign(window, { DashboardView, KpiCard, Panel, Segmented, Stat, TxTable, btnGhost });
