/* ============================================================
   PURE SPA — AGENDA · Dashboard  /admin/dashboard
   ============================================================ */
function StatCard({ label, value, sub, icon, tone }) {
  return (
    <Card pad={18} style={{ display: "flex", flexDirection: "column", gap: 10, minHeight: 116 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em",
          textTransform: "uppercase", color: C.taupe }}>{label}</span>
        <span style={{ width: 32, height: 32, borderRadius: 999, background: tone || C.gold15,
          display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name={icon} size={16} color={C.goldDeep} />
        </span>
      </div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 32, color: C.espresso, lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 300, color: C.taupe }}>{sub}</div>}
    </Card>
  );
}

function Dashboard() {
  const { version, navigate, openModal, can } = useApp();
  const todayBk = useMemo(() => PureApi.getBookings({ date: TODAY })
    .filter((b) => !["cancelled"].includes(b.status))
    .sort((a, b) => a.start.localeCompare(b.start)), [version]);
  const sales = todayBk.filter((b) => ["paid", "completed"].includes(b.status)).reduce((s, b) => s + b._price, 0);
  const pendingPay = PureApi.getBookings({ date: TODAY }).filter((b) => b.payStatus === "pending" && !["cancelled", "no_show"].includes(b.status));
  const now = new Date();
  const nowMin = now.getHours() * 60 + now.getMinutes();
  const next = todayBk.find((b) => { const [h, m] = b.start.split(":").map(Number); return h * 60 + m >= nowMin; }) || todayBk[0];
  const webCount = PureApi.getBookings({ date: TODAY }).filter((b) => b.origin === "Web").length;
  const weekCancels = PureApi.getReports().cancellations || 0;

  // ocupación por camilla (minutos ocupados hoy / minutos disponibles)
  const openMin = 10 * 60, closeMin = 19 * 60, total = closeMin - openMin;
  const occupancy = PureApi.getBeds().filter((b) => b.active).map((bed) => {
    const mins = todayBk.filter((b) => b.bedId === bed.id && ["confirmed", "paid", "completed", "pending_payment", "pending_confirmation"].includes(b.status))
      .reduce((s, b) => { const svc = svcOf(b); return s + (svc ? svc.duration + svc.cleanup : 0); }, 0);
    return { bed, pct: Math.min(100, Math.round((mins / total) * 100)) };
  });

  // servicios más vendidos
  const rep = PureApi.getReports();
  const topSvc = Object.entries(rep.bySvc).sort((a, b) => b[1] - a[1]);

  const alerts = [];
  if (pendingPay.length) alerts.push({ icon: "CreditCard", text: `Hay ${pendingPay.length} reserva${pendingPay.length > 1 ? "s" : ""} pendiente${pendingPay.length > 1 ? "s" : ""} de pago.` });
  const maint = PureApi.getBlocks({ date: TODAY }).find((b) => b.reason === "Mantencion" || b.reason === "Mantención");
  if (maint) alerts.push({ icon: "Wrench", text: `${bedName(maint.bedId)} tiene un bloqueo de mantención (${maint.start}–${maint.end}).` });
  const noPay16 = todayBk.find((b) => b.payStatus === "pending" && b.start >= "15:00");
  if (noPay16) alerts.push({ icon: "Clock", text: `La reserva de las ${noPay16.start} (${custName(noPay16)}) aún no tiene pago confirmado.` });

  return (
    <div>
      <PageHead eyebrow="Resumen del día" title="Buen día" sub={`Esto es lo que ocurre hoy · ${fullDate(TODAY)}`}>
        {can("booking:create") && <Button variant="primary" size="sm" onClick={() => openModal("newBooking", {})}><Icon name="Plus" size={14} color={C.espresso} style={{ marginRight: 4 }} />Nueva reserva</Button>}
      </PageHead>

      <div className="pu-stats" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 16 }}>
        <StatCard label="Reservas de hoy" value={todayBk.length} sub={`${todayBk.filter((b) => b.status === "confirmed" || b.status === "paid").length} confirmadas`} icon="CalendarCheck" />
        {can("payment:view")
          ? <StatCard label="Ventas del día" value={clp(sales)} sub={`${todayBk.filter((b) => ["paid", "completed"].includes(b.status)).length} pagadas`} icon="TrendingUp" />
          : <StatCard label="Atendidas" value={todayBk.filter((b) => b.status === "completed").length} sub="completadas hoy" icon="Check" />}
        {can("payment:view") && <StatCard label="Pagos pendientes" value={pendingPay.length} sub={clp(pendingPay.reduce((s, b) => s + b._price, 0))} icon="CreditCard" tone="#F8EFD2" />}
        <StatCard label="Reservas desde web" value={webCount} sub="canal online" icon="Globe" />
      </div>

      <div className="pu-dash-grid" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16 }}>
        {/* próximas reservas */}
        <Card pad={0}>
          <div style={{ padding: "18px 20px", borderBottom: `1px solid ${C.line}`, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 20, color: C.espresso }}>Próximas reservas</h3>
            <a href="#/admin/calendar" style={{ fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600, letterSpacing: "0.1em",
              textTransform: "uppercase", color: C.goldDeep, textDecoration: "none", borderBottom: `1px solid ${C.champagne}` }}>Ver agenda</a>
          </div>
          <div>
            {todayBk.length === 0 && <div style={{ padding: 28, textAlign: "center", color: C.taupe, fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13 }}>No hay reservas para hoy.</div>}
            {todayBk.slice(0, 6).map((b, i) => (
              <button key={b.id} onClick={() => openModal("detail", { id: b.id })} style={{ width: "100%", textAlign: "left", cursor: "pointer",
                display: "flex", alignItems: "center", gap: 14, padding: "13px 20px", background: next && next.id === b.id ? C.ivory : "transparent",
                border: "none", borderBottom: i < Math.min(6, todayBk.length) - 1 ? `1px solid ${C.line}` : "none" }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso, width: 52, flexShrink: 0 }}>{b.start}</div>
                <Avatar name={custName(b)} size={36} tone="champ" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, fontWeight: 500, color: C.espresso, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{custName(b)}</div>
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 300, color: C.taupe }}>{b._svcName} · {bedShort(b.bedId)}</div>
                </div>
                <StatusBadge status={b.status} />
              </button>
            ))}
          </div>
        </Card>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {/* alertas */}
          <Card pad={0}>
            <div style={{ padding: "16px 18px", borderBottom: `1px solid ${C.line}`, display: "flex", alignItems: "center", gap: 9 }}>
              <Icon name="Bell" size={16} color={C.goldDeep} />
              <h3 style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso }}>Alertas operativas</h3>
            </div>
            <div style={{ padding: "6px 0" }}>
              {alerts.length === 0 && <div style={{ padding: "16px 18px", color: C.taupe, fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13 }}>Todo en orden por ahora.</div>}
              {alerts.map((a, i) => (
                <div key={i} style={{ display: "flex", gap: 11, padding: "11px 18px", alignItems: "flex-start" }}>
                  <span style={{ width: 28, height: 28, borderRadius: 999, background: "#F8EFD2", flexShrink: 0,
                    display: "flex", alignItems: "center", justifyContent: "center", marginTop: 1 }}>
                    <Icon name={a.icon} size={14} color="#8A6A1E" />
                  </span>
                  <span style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 12.5, color: C.espresso, lineHeight: 1.5 }}>{a.text}</span>
                </div>
              ))}
            </div>
          </Card>

          {/* ocupación por camilla */}
          <Card pad={18}>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso, marginBottom: 14 }}>Ocupación por camilla</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {occupancy.map(({ bed, pct }) => (
                <div key={bed.id}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: C.espresso, fontWeight: 400 }}>{bed.name}</span>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: C.goldDeep, fontWeight: 600 }}>{pct}%</span>
                  </div>
                  <div style={{ height: 8, borderRadius: 999, background: C.ivoryDeep, overflow: "hidden" }}>
                    <div style={{ width: pct + "%", height: "100%", borderRadius: 999, background: `linear-gradient(90deg, ${C.champagne}, ${C.gold})`, transition: "width .6s ease" }} />
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>

      {/* fila inferior: servicios más vendidos + próxima reserva destacada */}
      <div className="pu-dash-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: 16, marginTop: 16 }}>
        <Card pad={18}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso }}>Próxima reserva</h3>
            <Icon name="Clock" size={16} color={C.taupe} />
          </div>
          {next ? (
            <button onClick={() => openModal("detail", { id: next.id })} style={{ width: "100%", textAlign: "left", cursor: "pointer", background: C.ivory, border: `1px solid ${C.line}`, borderRadius: 12, padding: 16 }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 30, color: C.espresso, lineHeight: 1 }}>{next.start} <span style={{ fontSize: 16, color: C.taupe }}>hrs</span></div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 500, color: C.espresso, marginTop: 8 }}>{custName(next)}</div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 300, color: C.taupe, marginBottom: 10 }}>{next._svcName} · {bedName(next.bedId)}</div>
              <StatusBadge status={next.status} />
            </button>
          ) : <div style={{ color: C.taupe, fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13 }}>Sin próximas reservas hoy.</div>}
        </Card>

        <Card pad={18}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <h3 style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso }}>Servicios más vendidos</h3>
            <span style={{ fontFamily: "var(--font-body)", fontSize: 10.5, color: C.taupe }}>histórico</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {topSvc.map(([name, count]) => {
              const max = topSvc[0][1];
              return (
                <div key={name}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: C.espresso }}>{name}</span>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: C.taupe }}>{count} ventas</span>
                  </div>
                  <div style={{ height: 8, borderRadius: 999, background: C.ivoryDeep, overflow: "hidden" }}>
                    <div style={{ width: (count / max * 100) + "%", height: "100%", background: C.espresso, opacity: 0.82, borderRadius: 999 }} />
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 20, marginTop: 18, paddingTop: 16, borderTop: `1px solid ${C.line}` }}>
            <div><div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: C.espresso }}>{weekCancels}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe }}>Cancelaciones (semana)</div></div>
            <div><div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: C.espresso }}>{rep.noShows}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe }}>No shows</div></div>
            {can("payment:view") && <div><div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: C.espresso }}>{clp(rep.avgTicket)}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe }}>Ticket promedio</div></div>}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
