/* ============================================================
   PURE SPA — AGENDA · Reservas  /admin/bookings
   ============================================================ */
function ActionsMenu({ items }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => ref.current && !ref.current.contains(e.target) && setOpen(false);
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  const visible = items.filter((i) => i.show !== false);
  return (
    <div ref={ref} style={{ position: "relative", display: "inline-block" }}>
      <button onClick={() => setOpen(!open)} style={{ background: C.white, border: `1px solid ${C.line}`, borderRadius: 8,
        width: 34, height: 34, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
        <Icon name="MoreHorizontal" size={17} color={C.taupe} />
      </button>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 30, background: C.white,
          border: `1px solid ${C.line}`, borderRadius: 10, boxShadow: "0 14px 40px rgba(43,37,32,0.16)", padding: 5, minWidth: 184 }}>
          {visible.map((it, i) => (
            <button key={i} onClick={() => { setOpen(false); it.onClick(); }} style={{ width: "100%", textAlign: "left",
              display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: 7, border: "none", cursor: "pointer",
              background: "transparent", color: it.danger ? "#9C5048" : C.espresso, fontFamily: "var(--font-body)", fontSize: 13 }}
              onMouseEnter={(e) => e.currentTarget.style.background = C.ivory}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <Icon name={it.icon} size={15} color={it.danger ? "#9C5048" : C.taupe} />{it.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function bookingActions(b, openModal, can) {
  return [
    { icon: "Eye", label: "Ver detalle", onClick: () => openModal("detail", { id: b.id }) },
    { icon: "MoveRight", label: "Mover reserva", show: can("booking:move") && !["cancelled", "completed", "no_show"].includes(b.status), onClick: () => openModal("move", { id: b.id }) },
    { icon: "Check", label: "Marcar pagada", show: can("booking:complete") && b.payStatus !== "paid" && !["cancelled"].includes(b.status), onClick: () => { PureApi.setBookingStatus(b.id, "paid"); } },
    { icon: "CheckCheck", label: "Marcar completada", show: can("booking:complete") && !["cancelled", "completed", "no_show"].includes(b.status), onClick: () => PureApi.setBookingStatus(b.id, "completed") },
    { icon: "UserX", label: "No asistió", show: can("booking:no_show") && !["cancelled", "completed", "no_show"].includes(b.status), onClick: () => PureApi.setBookingStatus(b.id, "no_show") },
    { icon: "X", label: "Cancelar reserva", danger: true, show: can("booking:cancel") && !["cancelled"].includes(b.status), onClick: () => openModal("cancel", { id: b.id }) },
  ];
}

function FilterBar({ children }) {
  return <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 18, alignItems: "center" }}>{children}</div>;
}

function BookingsView() {
  const { version, openModal, can } = useApp();
  const [f, setF] = useState({ status: "", serviceId: "", bedId: "", origin: "", payStatus: "" });
  const beds = PureApi.getBeds();
  let list = useMemo(() => PureApi.getBookings({}).sort((a, b) => (b.date + b.start).localeCompare(a.date + a.start)), [version]);
  list = list.filter((b) => (!f.status || b.status === f.status) && (!f.serviceId || b.serviceId === f.serviceId)
    && (!f.bedId || b.bedId === f.bedId) && (!f.origin || b.origin === f.origin) && (!f.payStatus || b.payStatus === f.payStatus));

  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" };

  return (
    <div>
      <PageHead eyebrow="Listado" title="Reservas" sub={`${list.length} reservas en total`}>
        {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>

      <FilterBar>
        <div style={{ minWidth: 150 }}><Select value={f.status} onChange={(v) => setF({ ...f, status: v })} placeholder="Todos los estados" options={Object.keys(STATUS).filter((s) => s !== "blocked").map((s) => ({ value: s, label: STATUS[s].label }))} /></div>
        <div style={{ minWidth: 150 }}><Select value={f.serviceId} onChange={(v) => setF({ ...f, serviceId: v })} placeholder="Todos los servicios" options={PureApi.getServices().map((s) => ({ value: s.id, label: s.name }))} /></div>
        <div style={{ minWidth: 140 }}><Select value={f.bedId} onChange={(v) => setF({ ...f, bedId: v })} placeholder="Todas las camillas" options={beds.map((b) => ({ value: b.id, label: b.name }))} /></div>
        <div style={{ minWidth: 130 }}><Select value={f.origin} onChange={(v) => setF({ ...f, origin: v })} placeholder="Todos los orígenes" options={PureConstants.ORIGINS} /></div>
        <div style={{ minWidth: 130 }}><Select value={f.payStatus} onChange={(v) => setF({ ...f, payStatus: v })} placeholder="Cualquier pago" options={[{ value: "paid", label: "Pagado" }, { value: "pending", label: "Pendiente" }]} /></div>
        {(f.status || f.serviceId || f.bedId || f.origin || f.payStatus) && <button onClick={() => setF({ status: "", serviceId: "", bedId: "", origin: "", payStatus: "" })} style={{ background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: C.goldDeep }}>Limpiar</button>}
      </FilterBar>

      {/* tabla (desktop) */}
      <div className="pu-table-only">
        <TableWrap>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 880 }}>
            <thead><tr style={{ borderBottom: `1px solid ${C.line}` }}>
              <th style={th}>Fecha</th><th style={th}>Hora</th><th style={th}>Clienta</th><th style={th}>Servicio</th>
              <th style={th}>Camilla</th><th style={th}>Estado</th><th style={th}>Pago</th><th style={th}>Origen</th><th style={{ ...th, textAlign: "right" }}></th>
            </tr></thead>
            <tbody>
              {list.map((b, i) => (
                <tr key={b.id} style={{ borderBottom: i < list.length - 1 ? `1px solid ${C.line}` : "none" }}>
                  <td style={td}>{shortDate(b.date)}</td>
                  <td style={{ ...td, fontWeight: 500 }}>{b.start}</td>
                  <td style={td}><div style={{ display: "flex", alignItems: "center", gap: 9 }}><Avatar name={custName(b)} size={28} tone="champ" /><span style={{ fontWeight: 500 }}>{custName(b)}</span></div></td>
                  <td style={td}>{b._svcName}</td>
                  <td style={td}>{bedShort(b.bedId)}</td>
                  <td style={td}><StatusBadge status={b.status} /></td>
                  <td style={td}><StatusBadge status={b.payStatus} kind="pay" /></td>
                  <td style={td}><Tag>{b.origin}</Tag></td>
                  <td style={{ ...td, textAlign: "right" }}><ActionsMenu items={bookingActions(b, openModal, can)} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </TableWrap>
      </div>

      {/* cards (móvil) */}
      <div className="pu-card-list" style={{ display: "none", flexDirection: "column", gap: 10 }}>
        {list.map((b) => (
          <Card key={b.id} pad={14}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <Avatar name={custName(b)} size={36} tone="champ" />
                <div><div style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 600, color: C.espresso }}>{custName(b)}</div>
                  <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: C.taupe }}>{b._svcName}</div></div>
              </div>
              <ActionsMenu items={bookingActions(b, openModal, can)} />
            </div>
            <div style={{ display: "flex", gap: 14, fontFamily: "var(--font-body)", fontSize: 12, color: C.taupe, marginBottom: 10 }}>
              <span><Icon name="Calendar" size={12} color={C.taupe} style={{ marginRight: 4, verticalAlign: "-1px" }} />{shortDate(b.date)} · {b.start}</span>
              <span>{bedShort(b.bedId)}</span><span>{b.origin}</span>
            </div>
            <div style={{ display: "flex", gap: 8 }}><StatusBadge status={b.status} /><StatusBadge status={b.payStatus} kind="pay" /></div>
          </Card>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { BookingsView, ActionsMenu, bookingActions, FilterBar });
