// Home / Dashboard — monthly totals, quick actions, recent pedidos
function HomeScreen({ vendedora, pedidos, onNewOrder, onOpenPedido, onGoList, onOpenCatalog, onGoPagos, onLogout }) {
  const T = window.T;
  const { Icon, ProductTile, StatusPill } = window;

  // Debt — usa Supabase si está disponible (con fallback a loadBilling local)
  const billing = window.useBilling
    ? window.useBilling(vendedora?.id)
    : { state: window.loadBilling ? window.loadBilling() : { facturas: [], pagos: [] }, loading: false };
  const state = billing.state;
  const mine = { f: state.facturas, p: state.pagos };
  const deuda = window.totalDeuda ? window.totalDeuda(mine.f, mine.p) : 0;
  const vencida = window.totalDeudaVencida ? window.totalDeudaVencida(mine.f, mine.p) : 0;

  // stats
  const now = new Date();
  const thisMonth = pedidos.filter(p => p.fechaCreacion.getMonth() === now.getMonth() && p.fechaCreacion.getFullYear() === now.getFullYear());
  const totalMes = thisMonth.reduce((s, p) => s + p.productos.reduce((a, x) => a + x.precio * x.cantidad, 0), 0);
  const numMes = thisMonth.length;
  const commission = totalMes * 0.18; // mock commission
  const goal = 600;
  const pct = Math.min(100, Math.round((totalMes / goal) * 100));

  const firstName = (vendedora?.nombre || '').split(' ')[0] || '';

  const fmtMoney = (n) => '$' + n.toFixed(2);

  return (
    <div style={{ width: '100%', minHeight: '100%', background: T.paper, paddingBottom: 120 }}>
      {/* Header */}
      <div style={{ padding: '58px 24px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28 }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: T.inkMute }}>
            Inova · {vendedora?.zona}
          </div>
          <div style={{
            width: 32, height: 32, borderRadius: 999, background: T.accent,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: T.paper, fontFamily: T.serif, fontStyle: 'italic', fontSize: 15,
            cursor: 'pointer',
          }} onClick={onLogout} title="Cerrar sesión">{firstName[0]?.toUpperCase() || 'M'}</div>
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 34, lineHeight: 1, color: T.ink, letterSpacing: -0.8 }}>
          Hola, {firstName}{vendedora?.badge === 'puntual' && <span title="Vendedora Puntual" style={{ marginLeft: 8, fontSize: 24 }}>👑</span>}
        </div>
        <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 22, lineHeight: 1.2, color: T.inkSoft, letterSpacing: -0.3, marginTop: 6 }}>
          {new Date().toLocaleDateString('es', { weekday: 'long', day: 'numeric', month: 'long' })}
        </div>
      </div>

      {/* Deuda banner — aparece si tiene deuda */}
      {deuda > 0 && (
        <div style={{ padding: '0 24px 16px' }}>
          <button onClick={onGoPagos} style={{
            width: '100%', padding: 18, borderRadius: 18,
            background: vencida > 0 ? 'oklch(0.42 0.18 25)' : 'oklch(0.32 0.03 30)',
            color: '#fff', border: 'none', cursor: 'pointer', textAlign: 'left',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            boxShadow: vencida > 0 ? '0 10px 30px oklch(0.42 0.18 25 / 0.3)' : 'none',
          }}>
            <div>
              <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: 'rgba(255,255,255,0.65)', marginBottom: 2 }}>
                {vencida > 0 ? '⚠ Debes (vencido)' : 'Debes'}
              </div>
              <div style={{ fontFamily: T.serif, fontSize: 42, lineHeight: 0.95, letterSpacing: -1.5 }}>
                ${deuda.toFixed(2)}
              </div>
              <div style={{ fontFamily: T.sans, fontSize: 12, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>
                Tocar para ver y pagar
              </div>
            </div>
            <Icon name="chevronR" size={20} color="#fff" />
          </button>
        </div>
      )}

      {/* Hero metric card */}
      <div style={{ padding: '0 24px', marginBottom: 20 }}>
        <div style={{
          background: T.ink, color: T.paper, borderRadius: 24, padding: 24,
          position: 'relative', overflow: 'hidden',
        }}>
          {/* decorative serif mark */}
          <div style={{
            position: 'absolute', right: -30, top: -20, fontSize: 220, lineHeight: 1,
            fontFamily: T.serif, fontStyle: 'italic', color: 'rgba(255,255,255,0.04)',
            pointerEvents: 'none',
          }}>In</div>

          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)', marginBottom: 8 }}>
            Total del mes
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 56, lineHeight: 1, letterSpacing: -2, marginBottom: 4 }}>
            ${totalMes.toFixed(2)}
          </div>
          <div style={{ fontFamily: T.sans, fontSize: 13, color: 'rgba(255,255,255,0.55)', marginBottom: 24 }}>
            {numMes} {numMes === 1 ? 'pedido' : 'pedidos'} · comisión est. {fmtMoney(commission)}
          </div>

          {/* Progress to goal */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ fontFamily: T.sans, fontSize: 12, color: 'rgba(255,255,255,0.7)' }}>Meta {fmtMoney(goal)}</span>
              <span style={{ fontFamily: T.mono, fontSize: 11, color: T.paper, letterSpacing: 0.5 }}>{pct}%</span>
            </div>
            <div style={{ height: 4, background: 'rgba(255,255,255,0.12)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: `${pct}%`, height: '100%', background: T.accent, borderRadius: 999, transition: 'width 0.6s' }} />
            </div>
          </div>
        </div>
      </div>

      {/* Quick actions */}
      <div style={{ padding: '0 24px', marginBottom: 32 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 8 }}>
          <button onClick={onNewOrder} style={{
            padding: '18px 20px', borderRadius: 18, background: T.accent, color: T.paper,
            border: 'none', cursor: 'pointer', textAlign: 'left',
            display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <Icon name="plus" size={20} color={T.paper} />
            <div>
              <div style={{ fontFamily: T.serif, fontSize: 20, letterSpacing: -0.3, lineHeight: 1 }}>Nuevo pedido</div>
              <div style={{ fontFamily: T.sans, fontSize: 12, color: 'rgba(255,255,255,0.75)', marginTop: 4 }}>Armar ahora</div>
            </div>
          </button>
          <button onClick={onOpenCatalog} style={{
            padding: '18px 16px', borderRadius: 18, background: T.paperAlt, color: T.ink,
            border: `1px solid ${T.hairline}`, cursor: 'pointer', textAlign: 'left',
            display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <Icon name="book" size={20} color={T.ink} />
            <div>
              <div style={{ fontFamily: T.serif, fontSize: 16, letterSpacing: -0.3, lineHeight: 1 }}>Catálogo</div>
              <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkMute, marginTop: 4 }}>L'Bel · C07</div>
            </div>
          </button>
        </div>
      </div>

      {/* Recent orders */}
      <div>
        <window.SectionHead
          eyebrow="Actividad"
          title="Pedidos recientes"
          action={
            <button onClick={onGoList} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkSoft,
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>
              Ver todo <Icon name="chevronR" size={12} color={T.inkSoft} />
            </button>
          }
        />
        <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {pedidos.slice(0, 3).map(p => {
            const total = p.productos.reduce((s, x) => s + x.precio * x.cantidad, 0);
            const items = p.productos.reduce((s, x) => s + x.cantidad, 0);
            return (
              <button key={p.id} onClick={() => onOpenPedido(p)} style={{
                width: '100%', padding: 16, borderRadius: 18,
                background: T.paperAlt, border: `1px solid ${T.hairline}`,
                display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', textAlign: 'left',
              }}>
                {/* stack of up to 3 product tiles */}
                <div style={{ display: 'flex', position: 'relative', width: 60, height: 48, flexShrink: 0 }}>
                  {p.productos.slice(0, 3).map((pr, i) => (
                    <div key={i} style={{ position: 'absolute', left: i * 14, top: 0 }}>
                      <ProductTile tono={pr.tono} catalogo={pr.catalogo} imagen={pr.imagen} size={48} radius={10} />
                    </div>
                  ))}
                </div>
                <div style={{ flex: 1, minWidth: 0, marginLeft: Math.min(p.productos.length - 1, 2) * 14 }}>
                  <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1, color: T.inkMute, marginBottom: 3 }}>
                    {p.codigo}
                  </div>
                  <div style={{ fontFamily: T.serif, fontSize: 17, color: T.ink, letterSpacing: -0.2, lineHeight: 1.1, marginBottom: 4 }}>
                    ${total.toFixed(2)} <span style={{ fontFamily: T.sans, fontSize: 12, color: T.inkMute, fontStyle: 'normal' }}>· {items} ítems</span>
                  </div>
                  <StatusPill estado={p.estado} enviado={p.enviado} size="sm" />
                </div>
                <Icon name="chevronR" size={14} color={T.inkMute} />
              </button>
            );
          })}
        </div>
      </div>

      {/* Insight strip */}
      <div style={{ padding: '32px 24px 0' }}>
        <div style={{
          background: T.accentSoft, borderRadius: 18, padding: '16px 18px',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <Icon name="trending" size={18} color={T.accent} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.accentInk, fontWeight: 500 }}>
              Vas 23% arriba de abril pasado
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.accentInk, opacity: 0.75, marginTop: 2 }}>
              Esika lidera tus ventas este mes
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.HomeScreen = HomeScreen;
