/* ============================================================
   PURE SPA — AGENDA · Pagos /admin/payments + Reportes /admin/reports
   ============================================================ */
const METHOD_LABEL = { efectivo: "Efectivo", transferencia: "Transferencia", tarjeta: "Tarjeta", online: "Online", gift_card: "Gift Card", convenio: "Convenio", otro: "Otro" };

function PaymentsView() {
  const { version, can } = useApp();
  const [f, setF] = useState({ status: "", method: "" });
  let list = useMemo(() => PureApi.getPayments({}), [version]);
  list = list.filter((p) => (!f.status || p.status === f.status) && (!f.method || p.method === f.method));
  const totalPaid = list.filter((p) => p.status === "paid").reduce((s, p) => s + p.amount, 0);
  const totalPending = list.filter((p) => p.status === "pending").reduce((s, p) => s + p.amount, 0);

  const th = { fontFamily: "var(--font-body)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: C.taupe, padding: "13px 14px", textAlign: "left", whiteSpace: "nowrap" };
  const td = { padding: "13px 14px", fontFamily: "var(--font-body)", fontSize: 13, color: C.espresso, fontWeight: 300, verticalAlign: "middle" };
  const custOf = (p) => { const c = PureApi.getCustomerById(p.customerId); return c ? c.name : "Reserva web"; };

  return (
    <div>
      <PageHead eyebrow="Finanzas" title="Pagos" sub="Estado de cobros asociados a reservas." />
      <div className="pu-stats" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 18 }}>
        <Card pad={18}><div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: C.taupe, marginBottom: 8 }}>Recaudado</div><div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: C.espresso }}>{clp(totalPaid)}</div></Card>
        <Card pad={18}><div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: C.taupe, marginBottom: 8 }}>Pendiente</div><div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "#8A6A1E" }}>{clp(totalPending)}</div></Card>
        <Card pad={18}><div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: C.taupe, marginBottom: 8 }}>Transacciones</div><div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: C.espresso }}>{list.length}</div></Card>
      </div>

      <FilterBar>
        <div style={{ minWidth: 150 }}><Select value={f.status} onChange={(v) => setF({ ...f, status: v })} placeholder="Todos los estados" options={Object.keys(PAY_STATUS).map((s) => ({ value: s, label: PAY_STATUS[s].label }))} /></div>
        <div style={{ minWidth: 150 }}><Select value={f.method} onChange={(v) => setF({ ...f, method: v })} placeholder="Todos los métodos" options={Object.keys(METHOD_LABEL).map((m) => ({ value: m, label: METHOD_LABEL[m] }))} /></div>
      </FilterBar>

      <div className="pu-table-only">
        <TableWrap>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 820 }}>
            <thead><tr style={{ borderBottom: `1px solid ${C.line}` }}>
              <th style={th}>Fecha</th><th style={th}>Clienta</th><th style={th}>Servicio</th><th style={{ ...th, textAlign: "right" }}>Monto</th>
              <th style={th}>Estado</th><th style={th}>Método</th><th style={th}>Origen</th><th style={{ ...th, textAlign: "right" }}></th>
            </tr></thead>
            <tbody>
              {list.map((p, i) => (
                <tr key={p.id} style={{ borderBottom: i < list.length - 1 ? `1px solid ${C.line}` : "none" }}>
                  <td style={td}>{shortDate(p.date)}</td>
                  <td style={{ ...td, fontWeight: 500 }}>{custOf(p)}</td>
                  <td style={td}>{p.serviceName}</td>
                  <td style={{ ...td, textAlign: "right", fontFamily: "var(--font-display)", fontSize: 15 }}>{clp(p.amount)}</td>
                  <td style={td}><StatusBadge status={p.status} kind="pay" /></td>
                  <td style={td}><Tag>{METHOD_LABEL[p.method] || p.method}</Tag></td>
                  <td style={td}>{p.origin}</td>
                  <td style={{ ...td, textAlign: "right" }}>
                    {can("payment:update") && p.status === "pending"
                      ? <Button variant="ghost" size="sm" onClick={() => PureApi.markPaymentPaid(p.id)}>Marcar pagado</Button>
                      : <span style={{ color: C.taupe, fontSize: 18 }}>·</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </TableWrap>
      </div>

      <div className="pu-card-list" style={{ display: "none", flexDirection: "column", gap: 10 }}>
        {list.map((p) => (
          <Card key={p.id} pad={14}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <div><div style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 600, color: C.espresso }}>{custOf(p)}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: C.taupe }}>{p.serviceName} · {shortDate(p.date)}</div></div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso }}>{clp(p.amount)}</div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
              <StatusBadge status={p.status} kind="pay" /><Tag>{METHOD_LABEL[p.method]}</Tag>
              {can("payment:update") && p.status === "pending" && <Button variant="ghost" size="sm" onClick={() => PureApi.markPaymentPaid(p.id)} style={{ marginLeft: "auto" }}>Marcar pagado</Button>}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

/* ---------- REPORTES ---------- */
function ReportsView() {
  const { version } = useApp();
  const [range, setRange] = useState("all");
  const addDaysIso = (iso, days) => {
    const [y, m, d] = iso.split("-").map(Number);
    const date = new Date(y, m - 1, d);
    date.setDate(date.getDate() + days);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
  };
  const filters = useMemo(() => {
    if (range === "today") return { from: TODAY, to: TODAY };
    if (range === "week") return { from: addDaysIso(TODAY, -6), to: TODAY };
    if (range === "month") return {};
    return {};
  }, [range]);
  const rep = useMemo(() => PureApi.getReports(filters), [version, range, JSON.stringify(filters)]);
  const topSvc = Object.entries(rep.bySvc).sort((a, b) => b[1] - a[1]);
  const origins = Object.entries(rep.byOrigin).sort((a, b) => b[1] - a[1]);
  const maxOrigin = origins.length ? origins[0][1] : 1;

  const Stat = ({ label, value, accent }) => (
    <Card pad={18}><div style={{ fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: C.taupe, marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: accent || C.espresso }}>{value}</div></Card>
  );

  return (
    <div>
      <PageHead eyebrow="Análisis" title="Reportes" sub="Una mirada serena al negocio.">
        <div style={{ display: "flex", background: C.white, border: `1px solid ${C.line}`, borderRadius: 999, padding: 3 }}>
          {[["today", "Hoy"], ["week", "Semana"], ["month", "Mes"], ["all", "Todo"]].map(([k, l]) => (
            <button key={k} onClick={() => setRange(k)} style={{ border: "none", cursor: "pointer", borderRadius: 999, padding: "7px 15px", fontFamily: "var(--font-body)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", background: range === k ? C.espresso : "transparent", color: range === k ? C.ivory : C.taupe }}>{l}</button>
          ))}
        </div>
      </PageHead>

      <div className="pu-stats" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 16 }}>
        <Stat label="Ventas totales" value={clp(rep.sales)} accent={C.goldDeep} />
        <Stat label="Ticket promedio" value={clp(rep.avgTicket)} />
        <Stat label="Cancelaciones" value={rep.cancellations} />
        <Stat label="No shows" value={rep.noShows} />
      </div>

      <div className="pu-dash-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Card pad={20}>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso, marginBottom: 16 }}>Servicios más vendidos</h3>
          {topSvc.length === 0 && <div style={{ color: C.taupe, fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13 }}>Sin ventas en el período.</div>}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {topSvc.map(([name, count]) => (
              <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}</span></div>
                <div style={{ height: 8, borderRadius: 999, background: C.ivoryDeep, overflow: "hidden" }}><div style={{ width: (count / topSvc[0][1] * 100) + "%", height: "100%", background: `linear-gradient(90deg,${C.champagne},${C.gold})` }} /></div>
              </div>
            ))}
          </div>
        </Card>

        <Card pad={20}>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso, marginBottom: 16 }}>Reservas por origen</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {origins.map(([name, count]) => (
              <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}</span></div>
                <div style={{ height: 8, borderRadius: 999, background: C.ivoryDeep, overflow: "hidden" }}><div style={{ width: (count / maxOrigin * 100) + "%", height: "100%", background: C.espresso, opacity: 0.82 }} /></div>
              </div>
            ))}
          </div>
        </Card>

        <Card pad={20}>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 19, color: C.espresso, marginBottom: 16 }}>Ocupación por camilla</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {Object.entries(rep.byBed).map(([name, count]) => {
              const maxBed = Math.max(1, ...Object.values(rep.byBed));
              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} reservas</span></div>
                  <div style={{ height: 8, borderRadius: 999, background: C.ivoryDeep, overflow: "hidden" }}><div style={{ width: (count / maxBed * 100) + "%", height: "100%", background: `linear-gradient(90deg,${C.champagne},${C.gold})` }} /></div>
                </div>
              );
            })}
          </div>
        </Card>

        <Card pad={20} style={{ background: C.espresso, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 80% 0%, rgba(197,161,67,0.18), transparent 60%)" }} />
          <div style={{ position: "relative" }}>
            <Eyebrow color={C.champagne} style={{ marginBottom: 10 }}>Resumen del período</Eyebrow>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 300, fontSize: 26, color: C.ivory, lineHeight: 1.2, marginBottom: 18 }}>{rep.paidCount} rituales completados</div>
            <div style={{ display: "flex", gap: 24 }}>
              <div><div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: C.gold }}>{rep.count}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe }}>reservas totales</div></div>
              <div><div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: C.gold }}>{clp(rep.sales)}</div><div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe }}>ingresos</div></div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { PaymentsView, ReportsView, METHOD_LABEL });
