You are iteration 8 of a 10-step Ballbox accessibility loop.

Read these files first:
- /home/sebas/runtime/ralph-loops/ballbox-a11y-20260517-120638/TASKS.md
- /home/sebas/runtime/ralph-loops/ballbox-a11y-20260517-120638/STATE.md

Then do exactly this:
1. Pick the highest-value pending task from TASKS.md.
2. Mark it in_progress in TASKS.md and briefly note it in STATE.md.
3. Implement the work in /home/sebas/work/projects/ballbox.
4. Run appropriate validation commands for your change.
5. Update TASKS.md with done/pending state changes.
6. Update STATE.md with a concise result, validation outcome, and next suggested task.
7. Do not use chat-style handoff; communicate only by editing those files.
8. Do not push, merge, or ask the user anything.
9. If blocked, write the blocker clearly in STATE.md and TASKS.md, then stop.

Be decisive. Prefer semantic HTML-first accessibility improvements.


bash

cd /home/sebas/work/projects/ballbox && git status --short && printf '\n---PLAN---\n' && sed -n '1,220p' PLAN.md && printf '\n---QUEUE---\n' && sed -n '1,220p' docs/next-steps-queue.md


# Ballbox accessibility tasks

Status legend: pending | in_progress | done

1. done - coach-settings-page-client: package format and active state controls to semantic grouped controls.
2. done - coach-settings-page-client: students table contact save/error/status semantics and grouping.
3. done - coach-settings-page-client: availability section audit for html-first labels/help/status.
4. done - club-coaches-page-client: calendar grid action text/status cleanup and explicit helper copy.
5. done - payments-admin-client: CRUD/session forms now use semantic form/fieldset structure, explicit labels, helper copy, and stronger status/live messaging.
6. done - authenticated/public nav final keyboard/a11y polish audit: public/workspace navs now expose explicit nav labels, `aria-current` or pressed state, and screen-reader labels on menu/profile triggers.
7. done - cross-flow pass: `/coaches`, `/classes/[offerId]`, and `/clubs/venues/[venueId]` now expose semantic live-region error/status messaging for auth submit, class request submit, and venue autosave/update flows.
8. pending - add or adjust tests for changed semantics where useful, especially keyboard interaction for weekly availability grid and new live-region semantics.
9. done - validation run: `pnpm exec eslint components/coach-settings-page-client.tsx components/weekly-availability-grid.tsx components/club-coaches-page-client.tsx` and `pnpm typecheck` passed.
10. pending - write final summary and remaining backlog.


# Ralph loop state

Status: running
Iteration: 8/10
Rule: each agent must read TASKS.md and STATE.md first, then update both before exit.
Rule: communicate only through files in this directory.
Rule: work only in /home/sebas/work/projects/ballbox.
Rule: do not push or merge.

Current owner: agent-8
Current focus: iteration 8
Last result: updated `components/coach-access-page-client.tsx`, `components/classes-request-form.tsx`, and `components/club-venue-page-client.tsx` so auth errors announce with `role="alert"`, class-request success/error messages announce semantically, and venue autosave now exposes a live status plus alert semantics for errors; synced `PLAN.md`, `docs/implemented-host-app.md`, and `docs/implemented-sports.md`. Validation: `pnpm exec eslint components/coach-access-page-client.tsx components/classes-request-form.tsx components/club-venue-page-client.tsx` and `pnpm typecheck` passed. Next suggested task: task 8, add or adjust tests around weekly-availability keyboard semantics and the new live-region feedback.


 M PLAN.md
 M components/authenticated-workspace-navbar.tsx
 M components/classes-request-form.tsx
 M components/club-coaches-page-client.tsx
 M components/club-venue-page-client.tsx
 M components/coach-access-page-client.tsx
 M components/coach-settings-page-client.tsx
 M components/navbar.tsx
 M components/payments-admin-client.tsx
 M components/weekly-availability-grid.tsx
 M docs/implemented-host-app.md
 M docs/implemented-sports.md

---PLAN---
# Ballbox Host App Plan

## Goal
- Convert `ballbox` into the host app for Ballbox platform.
- Preserve the current marketing home at `/`.
- Add a shared admin shell at `/admin`.
- Keep product boundaries explicit with dedicated subroutes.
- Converge on a shared `network` core model that all product domains reference.

## Current State
- Ballbox overall is still in validation stage for padel centers; there are no customers yet and near-term proof still depends on pilots with the first machines.
- `/` remains the marketing home.
- `/admin` is live as the shared Ballbox admin shell.
- Product-separated admin areas exist for `tvs`, `payments`, `network`, `sports`, and `players`.
- `/admin/screens` exists as the runtime entry area for TVs.
- `/player/[screenId]` is the lightweight TV runtime route served as plain HTML + JavaScript inside Ballbox.
- `/player/[screenId]` now exists as the lightweight TV runtime route served as plain HTML + JavaScript inside Ballbox.
- TVs are internal to Ballbox as a module, not a separate app.
- TVs admin and `/api/tvs/*` use an internal Ballbox ownership model for clubs, venues, screens, and campaigns.
- TVs runtime/admin already read Ballbox Postgres directly through Prisma.
- TVs runtime heartbeats and impressions already write to Ballbox DB-backed flows.
- TVs manifest/admin scheduling now respects campaign and assignment time windows.
- TVs now expose a strict Zod-backed API contract plus contract tests.
- TVs runtime now exposes on-screen diagnostics for cache/object-URL/manual parity verification on real devices.
- TVs runtime diagnostics now also support a one-click parity snapshot JSON export (playback/cache/network/reporting state + user agent + capture timestamp) to standardize real-device evidence capture.
- OPS-2 local parity rerun on 2026-04-19 identified two machine-local issues: stale TV seed scheduling and unstable repo Playwright `webServer` behavior on this Pi. TV seed scheduling is now fixed in `prisma/seed-data.ts`; remaining OPS-2 closure work is local parity rerun plus real-device parity capture.
- TVs player runtime cache/media/impression/heartbeat/manifest-refresh logic now lives in one shared core used by both the React player and the lightweight plain-JS player shell.
- Maintainability review for the next refactor cycle is documented in `docs/maintainability-priorities-2026-03.md`.
- Payments are now owned inside Ballbox host app: native MercadoPago webhook intake exists under `/notification/mercadopago` and resolves QR notifications by fetching the upstream order.
- Payments host app now also exposes native QR order creation under `/api/integrations/payments/orders`, generating canonical `externalReference` values required for approved-session persistence correlation.
- `/admin/payments` now also generates live MercadoPago QR orders for arbitrary amounts or per-product prices, with money inputs expressed in major units (for example `15.00` or `1000.00`), then shows the QR preview/order id for scan-and-pay validation.
- That admin QR surface is now positioned as a provider test/debug harness; production vending-machine payments should integrate through the TCN machine protocol and let the machine render the buyer-facing QR.
- Club revenue share is currently handled with scheduled manual settlements/bookkeeping; Mercado Pago native split stays deferred until the machine flow and club count justify it.
- Legacy approved-callback compatibility has been removed from operations; `/api/integrations/payments/approved` now returns `410` so only the native MercadoPago path remains active.
- `/admin/payments` now exposes Ballbox-local CRUD/reconciliation for approved payment sessions plus correlation checks against canonical `payment-vm_{vendingMachineId}-txn_{machineTxnId}` references.
- Payments admin session routes now read Prisma error helpers from `lib/prisma-errors.ts` instead of importing them via `lib/ballbox-store.ts`.
- Network core now has DB-backed admin CRUD for ATC-linked clubs, venues, and vending machines inside Ballbox.
- Prisma `Club.atcSportclubId` now matches live nullable data to prevent admin loader `P2032` crashes on legacy clubs without ATC linkage (`/admin/network`, `/admin/players`, `/admin/sports`, `/admin/tvs`).
- Clubs keep nullable `atcSportclubId` support for legacy/local rows, and repo now ships `db:backfill-atc-clubs` to reconcile local club names with ATC summary data when ids exist.
- Network club list/detail/admin query shaping has started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- Network club create/update/delete helpers have now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- Network venue mutation/delete helpers have also started moving out of `lib/ballbox-store.ts` into dedicated backend modules.
- Network vending-machine route callers now import `lib/network-backend-vending-machines.ts` directly and read unique-constraint classification from `lib/prisma-errors.ts`.
- Network club/venue route callers and `/admin/network` page now import direct network backend modules (`lib/network-backend-clubs.ts`, `lib/network-backend-club-mutations.ts`, `lib/network-backend-venues.ts`) plus `lib/prisma-errors.ts`.
- Network route handlers now share `lib/http/network-route-helpers.ts` for JSON parsing plus success/error envelopes across club, venue, and vending-machine contract routes.
- Players, sports, and payments route handlers now also share `lib/http/*-route-helpers.ts` so public/admin contract surfaces no longer depend on deep route-local helper imports.
- Network admin frontend view extraction has started moving venue-level and club-level rendering blocks out of `components/network-admin-client.tsx` into smaller components.
- Network admin frontend section composition has now also started moving club-list rendering, create-club section wiring, and derived venue-form wiring out of `components/network-admin-client.tsx` so it trends further toward a shell.
- Network admin frontend client-state, mutation orchestration, and local form-state wiring have started moving out of `components/network-admin-client.tsx` into dedicated hooks so the client trends toward a shell.
- Network admin frontend form defaults and status-option constants now live in a shared client config so shell and child components consume one source of truth.
- Network admin frontend layout/class wiring now also lives in a dedicated shell component so `components/network-admin-client.tsx` is closer to trivial hook composition.
- Network admin frontend shell chrome styles now also live in a tiny shared helper so the shell stays closer to pure composition/wiring.
- Players admin frontend client-state, form defaults, shell composition, and presentational stats/create/list-card seams now live in dedicated frontend modules so the client follows the same maintainable pattern already used by network.
- Sports admin frontend client-state, form defaults, shell composition, and coach/event section rendering now live in dedicated frontend seams so `components/sports-admin-client.tsx` is closer to pure wiring.
- Final naming direction is `network` core with `Club`, `Venue`, `VendingMachine`, `Screen`, and `TvDevice`.
- Post-`pnpm db:push` plus `pnpm db:seed` verification confirms physical DB columns stay canonical as `vendingMachineId` and `tvDeviceId`, with no `machineId`, `deviceId`, `/devices`, or `PaymentSessionRef` persistence aliases reintroduced.
- TVs admin now has DB-backed CRUD for screens and tv devices inside Ballbox.
- TV device admin mutations have started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV screen admin mutations have now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV campaign admin mutations have now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV creative admin mutations have now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV assignment admin mutations have now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV admin venue-option query shaping has now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV admin device/screen/campaign operations query shaping has now also started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- TV runtime source/manifest/heartbeat/impression helpers now also delegate from `lib/ballbox-store.ts` into a dedicated TV runtime backend module.
- TVs admin now has DB-backed CRUD for campaigns, creatives, and screen assignments inside Ballbox.
- Admin now supports a simple shared-password access layer when `BALLBOX_ADMIN_PASSWORD` is configured.
- TVs impressions now reject creatives that are not active for the target screen.
- Players API now reads Ballbox Postgres for `Player` and `Membership` rollups.
- Player backend read/admin query+mutation helpers have now started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- Sports coach backend helpers have now started moving out of `lib/ballbox-store.ts` into a dedicated backend module.
- Sports events plus classes offer/request backend helpers have now also started moving out of `lib/ballbox-store.ts` into dedicated backend modules.
- Sports now has DB-backed entities and admin/read APIs for coaches, open matches, and classes.
- `/classes` now exists as the first non-admin public Ballbox surface.
- `/classes` now lists Ballbox-local `ClassOffer` records, shows offer detail, surfaces visible ATC public-read slots, and accepts local `ClassRequest` submissions with either a concrete selected slot or a flexible any-schedule/any-location fallback.
- `/classes-by-date` now ships as a zone-first reservation calendar driven by coach availability plus ATC club availability, including explicit “coach disponible, pero sin canchas” slots and a required first zone selection based on the club's public location label when available.
- `/classes/me` now ships as a lightweight read-only student follow-up view (email-filtered request history) so demos can show the request loop without claiming full reservation confirmation.
- `/classes` initial HTML now renders from Ballbox-local offer data first and resolves ATC public-read context asynchronously after paint, with a short shared server cache to avoid repeating the same ATC lookup per visitor.
- `/classes` SSR no longer waits on ATC sportclub-summary hydration just to print club names, and `/classes-by-date` now parallelizes club/date ATC availability lookups behind a short shared server cache so first-byte time stays materially lower under production-like loads.
- Rapid demo execution now follows `docs/demo-iteration-mode.md` (`L1 story` / `L2 contracted demo` / `L3 production candidate`) so pivots stay fast without leaking demo shortcuts into core modules.
- `/coaches` now acts as the Ballbox account hub where the first differentiation is `Coach` vs `Club`.
- `/coaches` now defaults to `Sign in`, and `Sign up` is the fallback path for new accounts.
- `/coaches/settings` now lands on a coach workspace split into `Calendar`, `Performance`, `Alumnos`, and `Horarios y Clases`: calendar shows the current week in an hour-by-hour matrix centered on the coach's real student classes, grouping simultaneous reservations into one class card, surfacing participant basics (name, sexo, edad, categoria), and marking paid vs pending reservations, and now starts with a large `Agregar clase` CTA that jumps into `Alumnos`; `Performance` shows per-club performance plus weekly earnings and student consistency/review rows, `Alumnos` keeps roster + taken-hour management with the student table visible by default and `Agregar clase` opening a wide inline composer instead of a right-side summary panel, and `Horarios y Clases` now auto-saves club selection, availability, packages, and Mercado Pago setup without explicit save buttons while no longer exposing the club's court-fee pricing to the coach; pending autosave writes are now also flushed if the user leaves the page before the debounce finishes.
- `/clubs` now exists as the club-only service home that opens right after club sign-in/sign-up and groups the operational surfaces into service cards, with `Entrenadores` as the active entry point into the existing coaches workspace and the remaining services marked as `Proximamente`.
- `/clubs/coaches` now lands on a club workspace with top-level `Calendar`, `Analytics`, `Sedes`, and `Profesores` sections: calendar shows the current week's coach availability and reservations with sede/coach/court filters plus in-place manual class loading, analytics shows professor/reservation money splits and review placeholders, `Sedes` groups venue creation plus venue quick settings, and `Profesores` groups invite links plus the club coach table.
- `/clubs/coaches` now also enforces the club session at the page boundary before rendering the workspace, preventing the `Entrenadores` service-card hop from dropping users back into the shared `/coaches` access hub after a valid club login.
- `/clubs/coaches` now lands on a club workspace with top-level `Calendar`, `Analytics`, `Sedes`, and `Profesores` sections: calendar now works one sede at a time, switches between `Disponibilidad` and `Reservas`, uses clickable tag filters for sede/day/club-owned coaches instead of dropdowns, assigns a persistent color to each coach-enabled court, and shows the selected day with all coach-enabled courts as columns so clubs can see coverage or reservation gaps per court without selecting a court filter; coaches assigned with `Asignar todas las canchas` are treated as flexible coverage and occupy one free court per half-hour, not every court at once; manual class loading and pending requests open from dedicated action buttons above the calendar, and manual class creation now requires selecting an active coach package so clubs cannot create classes for coaches without packages; analytics shows professor/reservation money splits and review placeholders, `Sedes` now starts from a large `Agregar sede` CTA, keeps venue creation behind that action, and lists every venue in an editable table with a deep edit action, and `Profesores` groups invite links plus the club coach table.
- The `/clubs/coaches` calendar cells now avoid repeating redundant court-color bars or per-slot coverage counts inside each block; court color remains visible in the column header and the empty/cubierto cell state carries the coverage signal.
- Club workspace clickable actions are now visually distinguished with stronger accent borders, CTA chips, and hover/focus states, while venue detail edits auto-save in place instead of requiring explicit `Guardar` buttons or reloading the user back to the top, and pending autosave writes now also flush on navigation/unmount so venue/price/schedule edits are not lost when switching screens quickly.
- Club roster reads now tolerate production databases that have not yet received the newest coach/student schema additions: missing `Coach.assignedCourtId`, `CoachStudentBooking`, player contact columns, or coach package tables degrade to empty/null data instead of turning `/api/clubs/coaches` into a 500.
- `/api/coaches/students` now lets a coach load existing Ballbox players into concrete occupied time slots, validating availability, venue fit, and overlap rules, and the coach workspace now surfaces those students in a dedicated `Alumnos` section with WhatsApp / Telegram contact fields.
- `/api/coaches/students` now also supports weekly recurring student bookings, and the coach workspace `Alumnos` section can create new students directly before assigning them to one-off or recurring classes.
- `/api/clubs/players` now lets a club create its own students and auto-membership them into that club before assigning them to a professor from the club workspace manual class flow.
- External-coach availability now excludes venue slots already absorbed by club-coach availability, so external coaches only see residual hours after club coaches take priority.
- `/clubs/venues/[venueId]` now exists as the dedicated venue detail view for configuring venue opening/closing time, coach hours, external-coach availability, reservation settings, courts, and the coaches assigned to that venue, including which fixed court each coach covers in that sede; the page is now structured as a visible step-by-step workspace with quick jump cards so coach hours and court selection are no longer hidden inside collapsed panels.
- `CoachAvailability` weekly ranges and `CoachClub` selections now model coach intent separately from ATC court availability, while coach-side editing is clamped to the hours enabled by the assigned venue or the selected external clubs.
- Clubs now carry optional ATC sportclub ids to query availability at the club level.
- Clubs now also carry an optional contact email used for demo-grade club access and roster management.
- Venues now also store one opening time, one closing time, weekly coach-availability ranges, an external-coach availability flag, coach-enabled courts per venue, a special reservation price for coach classes, a club-coach-only discount on that fee, and a configurable late-cancellation window in hours.
- Coaches now can also be assigned to one venue inside their club.
- Coaches now also persist a Mercado Pago placeholder handle plus reusable sales-package rows for pricing, duration, class format, and max-student setup.
- Coaches and clubs now also store per-account password hashes for sign-in.
- Clubs now also persist coach invite tokens for generic join links, while still tolerating older email-bound invites.
- Local development now has a first-class Docker Postgres path via `docker-compose.yml` plus `.env.local`, and the seed now provisions demo coach/club passwords for local sign-in.
- Auth/session routes now return explicit database-unavailable errors when Prisma cannot reach or borrow a DB connection, instead of surfacing those failures as generic bad-login states.
- `/admin` overview now reads lightweight aggregate counts instead of hydrating full product datasets during SSR.
- Coach experience discovery is still early: current research input is an online form, so Ballbox does not yet have enough real-world coach workflow evidence to lock the sports product thesis.
- ATC admin/write is still not integrated; only a small public-read availability boundary now exists for `/classes` offer context and must degrade cleanly when unavailable.
- Local quality gate now includes `pnpm lint`, `pnpm typecheck`, `pnpm test:contracts`, `pnpm test:e2e`, and `pnpm build`.
- On `ballbox-first`, repo Playwright now uses a stable production-style `webServer` path for e2e (`pnpm build:e2e && pnpm start:e2e` on port `3020`), replacing the unstable Next 16 dev-server setup previously used on this Pi.
- Vitest taxonomy now includes layered includes for `tests/contracts`, `tests/unit`, and `tests/integration`, with dedicated scripts for each layer.
- Isolated backend/helper tests for classes, network client helpers, players client helpers, sports backend modules, and TVs runtime invariants now live under `tests/unit`, while route/schema surfaces stay under `tests/contracts`.

## Route Map
- `/`: marketing home
- `/admin`: admin overview
- `/admin/tvs`: TV and screen operations
- `/admin/payments`: payment operations and reconciliation
- `/admin/network`: clubs, venues, vending machines
- `/admin/sports`: open matches, coaches, academy
- `/admin/players`: players y memberships
- `/admin/screens`: screen runtime admin surface hosted inside Ballbox
- `/classes`: public class discovery + request surface
- `/classes/[offerId]`: public offer detail + request form
- `/classes-by-date`: zone-first reservation discovery calendar
- `/coaches`: account hub for coach vs club
- `/classes/me`: read-only student request follow-up
- `/coaches/settings`: coach workspace with `Calendar` / `Performance` / `Alumnos` / `Horarios y Clases`
- `/clubs`: club service home
- `/clubs/coaches`: club workspace with `Calendar` / `Analytics` / `Sedes` / `Profesores`
- authenticated coach/club workspace routes now use a shared top navbar with section tabs and an avatar-triggered sign-out menu instead of top-corner text links or standalone explainer hero panels; the workspace tabs now expose explicit nav labels, `aria-current`/pressed state, and a screen-reader label on the profile trigger.
- coach workspace now also includes student follow-up and manually occupied-hour management using existing `Player` records, including coach-editable WhatsApp and Telegram contact data
- `/clubs/venues/[venueId]`: dedicated venue setup and venue roster

## Backend Split
- Ballbox Next.js host:
  - app shell
  - admin UI
  - shared auth/RBAC foundation
  - low-complexity CRUD
  - BFF aggregation and integration routes
  - shared `network` core entities
  - internal TVs module and runtime
- External specialized services:
  - none required for current native MercadoPago payments flow in Ballbox host app

## Implemented
- Shared admin shell and product-separated routes are in place.
- Admin shell copy now adapts per route instead of repeating one generic hero across every module.
- TVs now resolve admin/runtime state from a canonical internal Ballbox model with explicit club, venue, screen, and campaign ownership.
- TVs runtime now has a per-screen route and manifest-driven player UI.
- TVs now also expose a lightweight non-React runtime at `/player/[screenId]` for constrained devices.
- Prisma/Postgres foundation now exists in Ballbox for the durable replacement.
- Ballbox Postgres has the TVs schema pushed and seeded with current local fixture data.
- Network APIs now read/write Ballbox Postgres through Prisma.
- TVs source/manifest/impression/heartbeat paths already read/write against Ballbox Postgres.
- TVs admin now exposes direct runtime and manifest links per screen for operations.
- TVs errors now use a shared strict shape and the contract is validated by `pnpm test:contracts`.
- Payments integration health and sessions routes now report Ballbox-internal native MercadoPago status plus webhook/order metadata.
- Payments native MercadoPago webhook flow now lands in Ballbox, validates canonical payment correlation from fetched orders, and persists approved payments as `PaymentSession` records.
- For the current Ballbox Mercado Pago account/API surface, QR order creation now relies on the account-level webhook configuration instead of sending inline `notification_url`, because Mercado Pago rejects that field on `POST /v1/orders` for this setup.
- Unsupported merchant-order notification topics are ignored so only QR order events drive persistence.
- Replay testing with two older live `ORD...` ids returned `MERCADOPAGO_ORDER_NOT_APPROVED_expired`; see `docs/mercadopago-webhook-replay-notes-2026-04-23.md` for the current blocker and next resume point.
- Payments now have an admin CRUD/reconciliation surface over local `PaymentSession` rows via `/api/admin/payments/*`.
- Final target model is documented in `docs/domain-model-target.md`; end state does not keep retro-compatibility shims.
- ESLint is now wired and the repo exposes an explicit `typecheck` script.
- `/admin` and current admin-only APIs can now be gated by a shared password cookie session.
- `/admin/tvs` now performs admin CRUD for screens and tv devices through admin-only APIs under `/api/admin/tvs/*`.
- `/admin/tvs` now performs admin CRUD for campaigns, creatives, and assignments through admin-only APIs under `/api/admin/tvs/*`.
- TVs impression writes now validate creative-to-screen activity windows before persisting telemetry.
- Players now have DB-backed read/admin APIs for `Player` and `Membership`.
- Players route + page callers now import `lib/players-backend.ts` (and `lib/network-backend-clubs.ts` for club lists) directly instead of relying on `lib/ballbox-store.ts` for runtime access.
- Sports now have DB-backed read/admin APIs for `Coach`, `OpenMatch`, and `Class`.
- Classes MVP now also has DB-backed public APIs for `ClassOffer` and `ClassRequest`.
- `/classes/me` now provides a lightweight student request-history surface over Ballbox-local `ClassRequest` records (read-only, demo-grade email lookup).
- `ClassRequest` now snapshots the student's selected visible slot when they choose one, and otherwise persists an explicit flexible-selection fallback mode.
- Coach availability now ships as weekly ranges with 90-minute slots, filtered by coach club selection and ATC club availability.
- Coach and club account entry now starts at `/coaches`, with `Sign in` first and `Sign up` only for users without an account.
- Coaches and clubs now sign in with per-account email + password credentials, and `/api/account/session` routes each session to the correct dashboard.
- Coach sign-up now asks only for name, email, and password; if a club invited that coach, the invite link auto-links the account to that club.
- `/coaches/settings` now opens on a coach workspace split into `Calendar`, `Performance`, `Alumnos`, and `Horarios y Clases`, with the calendar rendered as a weekly class matrix for the coach's students and reservation payment status, `Performance` dedicated to club-level results and weekly analytics, and `Horarios y Clases` handling external clubs, weekly availability inside allowed venue/club windows, reusable class packages, and a Mercado Pago placeholder handle with per-section auto-save, but without showing venue fee/court-price internals to the coach.
- `/clubs/venues/[venueId]` now also supports recurring hourly price overrides on top of the venue base reservation price, and `/clubs/coaches` calendar cells now surface the effective slot price so clubs can see both coverage/reservations and what that half-hour costs.
- `/coaches/settings` now also lets coaches attach existing Ballbox players to concrete booked slots in their active venues, so taken hours, weekly earnings, consistency tracking, and lightweight student follow-up live inside the coach workspace.
- Club venue management now persists an optional assigned court per coach inside the venue: a specific court pins coverage to that court, while the default `Asignar todas las canchas` mode lets that coach float across enabled courts and be placed into one free court per half-hour in the club calendar.
- Club sign-in/sign-up now lands on `/clubs`, a service home that separates the club's operational modules before entering the detailed coaches workspace.
- Club accounts now have a dedicated workspace at `/clubs/coaches` split into `Calendar`, `Analytics`, `Sedes`, and `Profesores`, while venue-by-venue deep setup still lives at `/clubs/venues/[venueId]`, all under the same shared navbar/profile chrome.
- Venue setup now uses two simple fields for opening and closing time plus a collapsible weekly half-hour grid for coach hours, shows closed periods in red while editing coach availability, lets clubs mark whether external coaches are allowed, keeps coach-enabled courts in a dedicated selection panel, and includes reservation pricing/cancellation settings both in the venue detail and as quick settings on `/clubs/coaches`, including a discount that applies only to coaches assigned to that club.
- ATC lookups for class surfaces now resolve by club (no court coupling), and class request validation rechecks the selected slot date/time against ATC public-read.
- `/classes` SSR now avoids blocking first paint on ATC public-read fetches; the page paints local offer data first, then hydrates ATC availability from cached API responses.
- `/coaches`, `/classes/[offerId]`, and `/clubs/venues/[venueId]` now expose stronger live-region semantics for submit/save errors and status updates, so auth, request, and venue autosave flows announce failures/success to screen-reader users instead of relying only on visual toast-style text.
- `/admin` overview SSR now uses direct aggregate counts instead of loading full admin datasets only to derive metrics.
- Sports/classes facade exports in `lib/ballbox-store.ts` now delegate to dedicated sports-events and classes backend modules instead of keeping that slice inline.
- Classes route/page callers now also import `lib/classes-backend.ts` directly for offer/request reads and writes, so class surfaces no longer depend on `lib/ballbox-store.ts` as their runtime entrypoint.
- Sports route + page callers now import `lib/sports-backend-events.ts` and `lib/sports-backend-coaches.ts` directly, so `lib/ballbox-store.ts` is no longer the primary sports entrypoint.
- TV runtime/backend facade exports in `lib/ballbox-store.ts` now delegate to `lib/tvs-backend-runtime.ts` instead of keeping source/manifest/heartbeat/impression logic inline.
- TVs admin/runtime route and page callers now import direct TVs backend modules plus shared TV types from `lib/tvs-backend-types.ts`, so `lib/ballbox-store.ts` is now a compatibility facade instead of the primary TVs entrypoint.
- UI color/system tokens are split between landing (`app/styles/landing-tokens.css`) and admin (`app/styles/admin-tokens.css`).

## Streetcast Migration Check
- Source of truth for parity review: `/Users/sebas/Code/street-cast-pwa`.
- Covered in Ballbox today:
  - manifest polling exists in `components/screen-player.tsx`
  - sequential creative playback exists in `components/screen-player.tsx`
  - impression writes exist in `components/screen-player.tsx`
  - runtime health signaling exists via heartbeats in `components/screen-player.tsx`
- Missing or not yet verified against Streetcast behavior:
  - no manual real-device verification yet proves CacheStorage/object-URL playback outside local browser automation

## Next Steps (Priority + Dependency Queue)
- Source of truth for task backlog and dependencies: `docs/next-steps-queue.md`.
- Selection rule for the next agent: pick the highest-priority task marked `ready` in that doc.
- Current pick (`P0`, `ready`): `OPS-2` TVs runtime parity closure.
- Immediately after `OPS-2`: continue with `P1` dependency order.
- Then continue with `P1` in dependency order: `ARCH-2` and `ARCH-3` -> `PERF-1` -> `PAY-3`.
- Club revenue share is currently handled with scheduled manual settlements; `PAY-4` stays behind the TCN machine-facing adapter work as a future Mercado Pago split option.
- Keep detailed backlog/status only in `docs/next-steps-queue.md` to avoid drift.

## Ordered Payments Track
1. Provider-level Mercado Pago proof without TCN hardware is now closed.
   - result: Ballbox created a real production order, received the public webhook at `/notification/mercadopago`, fetched the approved order, and persisted the payment with visible reconciliation evidence in `/admin/payments`

---QUEUE---
# Next Steps Queue

## Purpose
- Keep `PLAN.md` actionable without turning it into a long unordered backlog.
- Let any agent pick the next best task quickly using priority + dependency.

## Picking Rule
- Pick the highest-priority task with `Status: ready`.
- If a task is `blocked`, unblock its dependency first.
- After shipping, update this file, `PLAN.md`, and relevant `docs/implemented-*.md` in the same work.

## Recently Completed (2026-04-14)

### DOC-1 Docs normalization baseline
- Priority: P0
- Status: completed
- Depends on: none
- Scope shipped:
  - docs navigation/categories normalized in `docs/index.md`
  - `docs/repo-map.md` maintained as a fast entrypoint map
  - stale/missing references removed from active docs surfaces (`README.md`, `PLAN.md`, `docs/index.md`)
- Evidence: `node scripts/check-doc-references.mjs` passes

### DOC-2 PLAN execution hygiene
- Priority: P0
- Status: completed
- Depends on: none
- Scope shipped:
  - `PLAN.md` next-steps section reduced to queue pointer + explicit pick order
  - active queue wording avoids mixing done narrative
  - handoff wording keeps one clear "pick this next" target
- Expected payoff: next-agent selection is immediate

### DOC-3 Docs drift CI guard
- Priority: P0
- Status: completed
- Depends on: none
- Scope shipped:
  - CI check validates docs references in `README.md`, `PLAN.md`, and `docs/index.md`
  - CI fails on broken/missing local doc references
- Evidence: `.github/workflows/docs-drift-guard.yml`, `scripts/check-doc-references.mjs`

### ARCH-1 Route helper boundary cleanup
- Priority: P1
- Status: completed
- Depends on: DOC-1 (done)
- Scope shipped:
  - route helper/envelope parsing moved to shared `lib/http/*`
  - deep relative helper imports removed from network, players, sports, and payments route handlers
- Evidence: route handlers now import `@/lib/http/*-route-helpers`

### OPS-0 Admin surface 500 fix (`/admin/tvs`, `/admin/network`, `/admin/sports`, `/admin/players`)
- Priority: P0
- Status: completed
- Depends on: none
- Scope shipped:
  - aligned Prisma `Club.atcSportclubId` with live nullable data to prevent runtime `P2032` decode failures
  - regenerated Prisma client after schema alignment
  - added `db:backfill-atc-clubs` to sync local club names with ATC summary by `atcSportclubId` while keeping null-ATC clubs supported
- Evidence: Prisma `club.findMany` now handles rows with `atcSportclubId = null`

## P0 Ready

### OPS-1 Payments real-world validation closure
- Priority: P0
- Status: completed
- Depends on: none
- Scope shipped:
  - public webhook smoke against the native MercadoPago webhook path
  - real payment persisted as approved in `/admin/payments`
  - observed payload quirks identified and handled
- Progress (2026-04-14): payments migration to host app started in one feature branch; health/sessions now expose internal MercadoPago mode, Ballbox ships `/notification/mercadopago` intake with order fetch verification, and native order creation now exists at `/api/integrations/payments/orders`.
- Progress (2026-04-19): PAY-2 cleanup removed bridge-oriented operational status from host-app health/docs; OPS-1 is now focused on validating the native MercadoPago order-create + webhook-persist path only.
- Progress (2026-04-23): TCN protocol review shows the `additional hardware devices` note is about machine-side QR scanning, while the machine payment flow (`FunCode=8000`) already returns `CodeUrl` for machine-screen QR display. This means the admin QR page should be treated as a provider test harness, and production integration should move to a TCN adapter layer.
- Progress (2026-05-05): first production order-create attempt against `https://ballbox.app/api/integrations/payments/orders` failed before buyer payment with Mercado Pago `400 unsupported_properties` because `notification_url` was rejected (`additionalProperties '$.notification_url' not allowed`). Ballbox should stop sending inline `notification_url` for this account/API surface and rely on the existing account-level Mercado Pago webhook configuration before rerunning the real-payment check.
- Closure (2026-05-13): a real approved payment now persists locally and is visible in `/admin/payments`. Mercado Pago webhook noise from `topic_merchant_order_wh` remains intentionally ignored. Closure required two Ballbox compatibility fixes for live provider payloads: product id fallback from `items[0].external_code` and robust parsing of `total_amount` when Mercado Pago returns a string.
- Expected payoff: closes highest-risk integration uncertainty

### OPS-2 TVs runtime parity closure
- Priority: P0
- Status: ready
- Depends on: none
- Scope:
  - manually verify real-device CacheStorage/object-URL behavior on `/player/[screenId]`
  - update `docs/streetcast-parity.md` with concrete evidence
- Progress (2026-04-14): runtime now exports a JSON parity snapshot from `/player/[screenId]` to standardize evidence capture; remaining work is one real-device run and doc evidence entry.
- Progress (2026-04-19): machine-local Playwright setup is now standardized outside the repo at `/mnt/rpi/repos/browser-harness`; repo Playwright now uses a stable production-style e2e server path on this Pi, and stock TV seed data now keeps `screen_001` actively programmed after `pnpm db:seed`.
- Remaining closure needs:
  - run `pnpm db:seed`, then rerun local parity/e2e on `screen_001`
  - run the documented real-device parity capture (online snapshot, offline snapshot, reconnect recovery)
  - then update this queue item and `PLAN.md` to completed
- Expected payoff: de-risks constrained-device production behavior

## P1 After P0

### ARCH-2 Continue `ballbox-store` caller migration
- Priority: P1
- Status: completed
- Depends on: ARCH-1 (done)
- Scope shipped:
  - TVs admin/runtime pages and routes now import direct TVs backend modules instead of `lib/ballbox-store.ts`
  - classes pages/routes/helpers now import `lib/classes-backend.ts` directly for offer/request reads and writes
  - shared TV types now live in `lib/tvs-backend-types.ts`, keeping `lib/ballbox-store.ts` as a compatibility facade instead of the primary entrypoint
- Evidence:
  - `app/admin/tvs/page.tsx`
  - `app/api/admin/tvs/*`
  - `app/api/tvs/heartbeat/route.ts`
  - `app/api/classes/requests/route.ts`
  - `lib/classes.ts`
  - `lib/tvs-source.ts`
- Expected payoff: less coupling and better module discoverability

### ARCH-3 Test taxonomy split
- Priority: P1
- Status: completed
- Depends on: DOC-1 (done)
- Scope shipped:
  - isolated backend/helper tests moved out of `tests/contracts` into `tests/unit`
  - route/schema contract coverage stayed in `tests/contracts`
  - `vitest` layered scripts/includes remain aligned with `contracts`, `unit`, and `integration`
- Evidence:
  - `tests/unit/classes/backend.test.ts`
  - `tests/unit/network/backend-mappers.test.ts`
  - `tests/unit/network/use-network-admin-client-state.test.tsx`
  - `tests/unit/players/use-players-admin-client-state.test.tsx`
  - `tests/unit/sports/backend-events.test.ts`
  - `tests/unit/tvs/runtime.test.ts`
- Expected payoff: faster debugging and more intentional coverage growth

### PERF-1 TTFB focused pass
- Priority: P1
- Status: completed
- Depends on: OPS-1
- Scope shipped:
  - measured production-like local server timings for `/admin`, `/classes`, and `/classes-by-date`
  - removed ATC summary hydration from `/classes` SSR club-name shaping
  - parallelized `/classes-by-date` ATC club/day lookups and added a short shared cache for the assembled calendar
- Evidence:
  - `lib/classes-backend.ts`
  - `lib/coach-availability-matching.ts`
  - local timings moved from roughly `/classes` 3.09s and `/classes-by-date` 6.54s to `/classes` 1.96s and `/classes-by-date` 2.69s on the same Pi
- Expected payoff: better responsiveness without blind cache complexity

### PAY-2 Full payments migration into Ballbox host app
- Priority: P1
- Status: completed
- Depends on: OPS-1
- Scope shipped:
  - native MercadoPago webhook + QR order lifecycle is now owned in Ballbox routes/lib
  - bridge-oriented operational status copy removed from health/docs/admin summary
  - legacy approved-callback route reduced to transitional compatibility only; native path is now the documented operational flow
- Evidence:
  - `/notification/mercadopago`
  - `/api/integrations/payments/orders`
  - `app/api/integrations/payments/health/route.ts`
  - `app/api/integrations/payments/sessions/route.ts`
  - `docs/implemented-payments.md`
- Expected payoff: one-repo payments ownership, simpler operations, faster debugging

### PAY-3 TCN vending-machine adapter over native MercadoPago
- Priority: P1
- Status: ready
- Depends on: OPS-1, PAY-2
- Scope:
  - define the Ballbox machine-facing adapter for TCN payment init (`FunCode=8000`) over the existing MercadoPago order-create route
  - map TCN `MachineID`, `TradeNo`, `SlotNo`, `Price`, `NotityUrl`, and response `CodeUrl` to Ballbox-native payment fields
  - define the payment-success handshake back to TCN so approved payments can unlock dispense
  - support one shared machine payment flow with two payment-owner modes:
    - `BALLBOX` for club machines that Ballbox collects on
    - `TENANT` for customer-owned collection setups such as Adidas rental machines
  - keep `/admin/payments` positioned as an operator test/debug harness rather than the production vending UX
  - document the exact adapter contract and remaining TCN unknowns before implementation
- Notes:
  - TCN protocol evidence is documented in `docs/tcn-payments-integration-plan.md`
  - master rollout direction is documented in `docs/payments-machine-rollout-rfc.md`
  - technical implementation shape is documented in `docs/payments-machine-implementation-rfc.md`
  - do not assume extra scanner hardware for the buyer flow; the open question is adapter contract detail, not QR display feasibility
  - club settlement automation can be revisited after the machine-facing flow is stable; manual bookkeeping is the current default
- Expected payoff: closes the actual machine integration path without fragmenting Ballbox collection vs tenant-direct collection into separate technical stacks

## P2 Sequenced Refactors

### PAY-4 Mercado Pago native split for club revenue share
- Priority: P2
- Status: blocked
- Depends on: OPS-1, PAY-2, PAY-3
- Scope:
  - keep scheduled manual settlements as the current operating default for Ballbox-collected club machines
  - document Mercado Pago native split as the only future automation path under consideration for club payouts
  - if automation is ever chosen, define onboarding, credential storage, rotation, and support rules before implementation
  - capture the trigger conditions that justify leaving manual bookkeeping behind
- Notes:
  - Ballbox currently runs QR vending payments through the native Mercado Pago order/webhook flow, so split automation is a separate future decision
  - first-wave rollout uses mixed owner modes (`BALLBOX` + `TENANT`), and settlement work only applies to the `BALLBOX` side
  - keep this behind real-world payments validation first (`OPS-1`) and machine-facing TCN adapter definition (`PAY-3`)
- Expected payoff: a clear path from manual settlements to a future Mercado Pago split if the machine flow and business volume justify it

### ARCH-4 Domain folder architecture
- Priority: P2
- Status: blocked
- Depends on: ARCH-2, ARCH-3
- Scope:
  - move flat prefix-based modules into domain folders in `lib/` and `components/`
  - preserve behavior; focus on discoverability and ownership boundaries
- Expected payoff: major readability improvement for future work

### ARCH-5 Route IA normalization (`/classes*` + `/coaches*`)
- Priority: P2
- Status: blocked
- Depends on: DOC-1
- Scope:
  - align route grouping and naming with real auth/surface behavior
  - keep redirects/aliases explicit during transition
- Expected payoff: lower confusion in feature placement and routing maintenance

### ARCH-6 Naming conventions and metadata cleanup
- Priority: P2
- Status: blocked
- Depends on: ARCH-4
- Scope:


**Evaluating tasks for updates**

I need to choose task 8 tests and inspect the relevant components. It’s important to update the files first before I exit. I should also ensure that I edit the TASKS and STATE markers to show that these tasks are in progress. That way, everything is tracked correctly, and there’s no confusion later on. I’m just making sure everything flows smoothly!

edit

8. pending - add or adjust tests for changed semantics where useful, especially keyboard interaction for weekly availability grid and new live-region semantics.

8. in_progress - add or adjust tests for changed semantics where useful, especially keyboard interaction for weekly availability grid and new live-region semantics.


Successfully replaced 1 block(s) in /home/sebas/runtime/ralph-loops/ballbox-a11y-20260517-120638/TASKS.md.

    ...
  8 4. done - club-coaches-page-client: calendar grid action text/status cleanup and explicit helper copy.
  9 5. done - payments-admin-client: CRUD/session forms now use semantic form/fieldset structure, explicit labels, helper copy, and stronger status/live messaging.
 10 6. done - authenticated/public nav final keyboard/a11y polish audit: public/workspace navs now expose explicit nav labels, `aria-current` or pressed state, and screen-reader labels on menu/profile triggers.
 11 7. done - cross-flow pass: `/coaches`, `/classes/[offerId]`, and `/clubs/venues/[venueId]` now expose semantic live-region error/status messaging for auth submit, class request submit, and venue autosave/update flows.
-12 8. pending - add or adjust tests for changed semantics where useful, especially keyboard interaction for weekly availability grid and new live-region semantics.
+12 8. in_progress - add or adjust tests for changed semantics where useful, especially keyboard interaction for weekly availability grid and new live-region semantics.
 13 9. done - validation run: `pnpm exec eslint components/coach-settings-page-client.tsx components/weekly-availability-grid.tsx components/club-coaches-page-client.tsx` and `pnpm typecheck` passed.
 14 10. pending - write final summary and remaining backlog.


Current owner: agent-8
Current focus: iteration 8

Current owner: agent-8
Current focus: task 8 - accessibility test coverage for weekly availability and live-region semantics


Successfully replaced 1 block(s) in /home/sebas/runtime/ralph-loops/ballbox-a11y-20260517-120638/STATE.md.

    ...
  7 Rule: work only in /home/sebas/work/projects/ballbox.
  8 Rule: do not push or merge.
  9
 10 Current owner: agent-8
-11 Current focus: iteration 8
+11 Current focus: task 8 - accessibility test coverage for weekly availability and live-region semantics
 12 Last result: updated `components/coach-access-page-client.tsx`, `components/classes-request-form.tsx`, and `components/club-venue-page-client.tsx` so auth errors announce with `role="alert"`, class-request success/error messages announce semantically, and venue autosave now exposes a live status plus alert semantics for errors; synced `PLAN.md`, `docs/implemented-host-app.md`, and `docs/implemented-sports.md`. Validation: `pnpm exec eslint components/coach-access-page-client.tsx components/classes-request-form.tsx components/club-venue-page-client.tsx` and `pnpm typecheck` passed. Next suggested task: task 8, add or adjust tests around weekly-availability keyboard semantics and the new live-region feedback.


**Inspecting test files**

I'm getting ready to inspect the test files. This seems like an important step for ensuring everything is functioning correctly. I think I need to look for any potential issues or errors that might have shown up. I'll want to check for consistency and accuracy in the tests to build confidence in the overall project. My goal is to make sure everything is running smoothly before proceeding. Let's see what I can find!

bash

cd /home/sebas/work/projects/ballbox && rg -n "weekly-availability|classes-request-form|coach-access|venue" tests components | sed -n '1,240p'


tests/unit/sports/use-sports-admin-client-state.test.tsx:11:  venues: [{ id: "venue_1", name: "Court One", clubId: "club_1", clubName: "Club One" }],
tests/unit/sports/use-sports-admin-client-state.test.tsx:32:    expect(result.current.openMatchForm).toEqual({ venueId: "venue_1", title: "", startsAt: "" });
tests/unit/sports/use-sports-admin-client-state.test.tsx:33:    expect(result.current.classForm).toEqual({ venueId: "venue_1", title: "", startsAt: "" });
tests/unit/sports/use-sports-admin-client-state.test.tsx:75:    expect(result.current.message).toBe("El venue seleccionado no existe.");
components/network-admin-venue-card.tsx:5:import { NetworkAdminVenueHeader } from "@/components/network-admin-venue-header";
components/network-admin-venue-card.tsx:11:  venue: Venue;
components/network-admin-venue-card.tsx:17:  venueStatusOptions: VenueStatus[];
components/network-admin-venue-card.tsx:27:  venue,
components/network-admin-venue-card.tsx:33:  venueStatusOptions,
components/network-admin-venue-card.tsx:47:              venues: item.venues.map((candidate) => (candidate.id === venue.id ? { ...candidate, ...patch } : candidate)),
components/network-admin-venue-card.tsx:60:              venues: item.venues.map((candidate) =>
components/network-admin-venue-card.tsx:61:                candidate.id !== venue.id
components/network-admin-venue-card.tsx:77:      <NetworkAdminVenueHeader venue={venue} />
components/network-admin-venue-card.tsx:80:        <Input value={venue.name} onChange={(event) => updateVenue({ name: event.target.value })} disabled={busy} />
components/network-admin-venue-card.tsx:81:        <Input value={venue.slug} onChange={(event) => updateVenue({ slug: event.target.value })} disabled={busy} />
components/network-admin-venue-card.tsx:83:          value={venue.status}
components/network-admin-venue-card.tsx:88:          {venueStatusOptions.map((status) => (
components/network-admin-venue-card.tsx:100:              const response = await fetch(`/api/network/${clubId}/venues/${venue.id}`, {
components/network-admin-venue-card.tsx:103:                body: JSON.stringify({ name: venue.name, slug: venue.slug, status: venue.status }),
components/network-admin-venue-card.tsx:118:              const response = await fetch(`/api/network/${clubId}/venues/${venue.id}`, { method: "DELETE" });
components/network-admin-venue-card.tsx:128:        Screens: {venue.screens}
components/network-admin-venue-card.tsx:129:        {venue.screenIds.length > 0 ? ` · ${venue.screenIds.join(", ")}` : ""}
components/network-admin-venue-card.tsx:136:          venueId={venue.id}
components/network-admin-venue-card.tsx:145:        {venue.vendingMachines.map((machine) => (
components/network-admin-venue-card.tsx:170:                    const response = await fetch(`/api/network/venues/${venue.id}/vending-machines/${machine.id}`, {
components/network-admin-venue-card.tsx:188:                    const response = await fetch(`/api/network/venues/${venue.id}/vending-machines/${machine.id}`, {
components/network-admin-shell.tsx:11:  venueStatusOptions,
components/network-admin-shell.tsx:26:  venueForms: Record<string, VenueFormState>;
components/network-admin-shell.tsx:41:  venueForms,
components/network-admin-shell.tsx:65:        venueForms={venueForms}
components/network-admin-shell.tsx:71:        venueStatusOptions={venueStatusOptions}
components/coach-access-page-client.tsx:43:  const errorId = "coach-access-error";
tests/unit/sports/backend-events.test.ts:7:  venue: {
tests/unit/sports/backend-events.test.ts:46:  it("loads sports admin data with mapped venues, coaches, and events", async () => {
tests/unit/sports/backend-events.test.ts:48:    prisma.venue.findMany.mockResolvedValue([
tests/unit/sports/backend-events.test.ts:50:        id: "venue_001",
tests/unit/sports/backend-events.test.ts:51:        name: "Main venue",
tests/unit/sports/backend-events.test.ts:73:        venue: {
tests/unit/sports/backend-events.test.ts:74:          id: "venue_001",
tests/unit/sports/backend-events.test.ts:75:          name: "Main venue",
tests/unit/sports/backend-events.test.ts:88:        venue: {
tests/unit/sports/backend-events.test.ts:89:          id: "venue_001",
tests/unit/sports/backend-events.test.ts:90:          name: "Main venue",
tests/unit/sports/backend-events.test.ts:104:      venues: [
tests/unit/sports/backend-events.test.ts:106:          id: "venue_001",
tests/unit/sports/backend-events.test.ts:107:          name: "Main venue",
tests/unit/sports/backend-events.test.ts:123:          venueId: "venue_001",
tests/unit/sports/backend-events.test.ts:124:          venueName: "Main venue",
tests/unit/sports/backend-events.test.ts:134:          venueId: "venue_001",
tests/unit/sports/backend-events.test.ts:135:          venueName: "Main venue",
tests/unit/sports/backend-events.test.ts:146:    prisma.venue.findUnique.mockResolvedValue({
tests/unit/sports/backend-events.test.ts:147:      id: "venue_001",
tests/unit/sports/backend-events.test.ts:157:      venue: {
tests/unit/sports/backend-events.test.ts:158:        id: "venue_001",
tests/unit/sports/backend-events.test.ts:159:        name: "Main venue",
tests/unit/sports/backend-events.test.ts:169:      venueId: "venue_001",
tests/unit/sports/backend-events.test.ts:176:        venueId: "venue_001",
tests/unit/sports/backend-events.test.ts:181:        venue: {
tests/unit/sports/backend-events.test.ts:197:        venueId: "venue_001",
tests/unit/sports/backend-events.test.ts:198:        venueName: "Main venue",
components/network-admin-club-card.tsx:2:import { NetworkAdminCreateVenueForm } from "@/components/network-admin-create-venue-form";
components/network-admin-club-card.tsx:11:import { NetworkAdminVenueCard } from "@/components/network-admin-venue-card";
components/network-admin-club-card.tsx:19:  venueForm: VenueFormState;
components/network-admin-club-card.tsx:25:  venueStatusOptions: VenueStatus[];
components/network-admin-club-card.tsx:38:  venueForm,
components/network-admin-club-card.tsx:44:  venueStatusOptions,
components/network-admin-club-card.tsx:108:
Venues: {club.venues.length}

components/network-admin-club-card.tsx:110:            Machines: {club.venues.reduce((total, venue) => total + venue.machines, 0)} · Screens: {" "}
components/network-admin-club-card.tsx:111:            {club.venues.reduce((total, venue) => total + venue.screens, 0)}
components/network-admin-club-card.tsx:117:
Add venue

components/network-admin-club-card.tsx:121:          venueForm={venueForm}
components/network-admin-club-card.tsx:124:          statusOptions={venueStatusOptions}
components/network-admin-club-card.tsx:131:        {club.venues.length === 0 ? (
components/network-admin-club-card.tsx:132:          <div className={`${mutedPanelClassName} text-sm text-muted-foreground`}>No venues yet.

components/network-admin-club-card.tsx:134:          club.venues.map((venue) => (
components/network-admin-club-card.tsx:136:              key={venue.id}
components/network-admin-club-card.tsx:138:              venue={venue}
components/network-admin-club-card.tsx:141:              machineForm={resolveMachineForm(machineForms, venue.id, emptyMachineForm)}
components/network-admin-club-card.tsx:144:              venueStatusOptions={venueStatusOptions}
components/network-admin-section-header.tsx:12:
Clubs + venues + vending machines

components/network-admin-section-header.tsx:14:            Ballbox ya usa network core en Postgres. Delete safe: bloquea clubs, venues y máquinas cuando todavía tienen dependencias activas.
tests/unit/sports/sports-admin-client-config.test.ts:17:  venues: [
tests/unit/sports/sports-admin-client-config.test.ts:18:    { id: "venue_1", name: "Court One", clubId: "club_1", clubName: "Club One" },
tests/unit/sports/sports-admin-client-config.test.ts:19:    { id: "venue_2", name: "Court Two", clubId: "club_1", clubName: "Club One" },
tests/unit/sports/sports-admin-client-config.test.ts:33:    venueId: "venue_1",
tests/unit/sports/sports-admin-client-config.test.ts:34:    venueName: "Court One",
tests/unit/sports/sports-admin-client-config.test.ts:45:    expect(emptyEventForm).toEqual({ venueId: "", title: "", startsAt: "" });
tests/unit/sports/sports-admin-client-config.test.ts:48:  it("prefills event forms from the first venue", () => {
tests/unit/sports/sports-admin-client-config.test.ts:50:      venueId: "venue_1",
tests/unit/sports/sports-admin-client-config.test.ts:68:  it("updates event venue metadata from the selected venue", () => {
tests/unit/sports/sports-admin-client-config.test.ts:69:    expect(updateEventDraftVenue(events, "event_1", "venue_2", sportsData)).toEqual([
tests/unit/sports/sports-admin-client-config.test.ts:72:        venueId: "venue_2",
tests/unit/sports/sports-admin-client-config.test.ts:73:        venueName: "Court Two",
tests/unit/sports/sports-admin-client-config.test.ts:86:        venueId: "venue_1",
tests/unit/sports/sports-admin-client-config.test.ts:87:        venueName: "Court One",
components/classes-offers-page-client.tsx:80:                {offer.venue.clubName ?? "ATC no disponible"}
components/classes-offers-page-client.tsx:89:
{offer.venue.name}

tests/unit/network/use-network-admin-client-forms.test.tsx:17:    expect(result.current.venueForms).toEqual({});
tests/unit/network/use-network-admin-client-forms.test.tsx:21:  it("updates club, venue, and machine form state independently", () => {
tests/unit/network/use-network-admin-client-forms.test.tsx:26:      result.current.setVenueForms({ club_2: { name: "Venue Two", slug: "venue-two", status: "inactive" } });
tests/unit/network/use-network-admin-client-forms.test.tsx:27:      result.current.setMachineForms({ venue_2: { label: "Machine Two", active: false } });
tests/unit/network/use-network-admin-client-forms.test.tsx:31:    expect(result.current.venueForms).toEqual({
tests/unit/network/use-network-admin-client-forms.test.tsx:32:      club_2: { name: "Venue Two", slug: "venue-two", status: "inactive" },
tests/unit/network/use-network-admin-client-forms.test.tsx:35:      venue_2: { label: "Machine Two", active: false },
tests/unit/network/use-network-admin-client-forms.test.tsx:38:    expect(result.current.venueForms.club_2).not.toBe(emptyVenueForm);
tests/unit/network/use-network-admin-client-forms.test.tsx:39:    expect(result.current.machineForms.venue_2).not.toBe(emptyMachineForm);
tests/unit/network/network-admin-client-config.test.ts:12:    expect(resolveMachineForm({}, "venue_1")).toBe(emptyMachineForm);
tests/unit/network/network-admin-client-config.test.ts:16:    const venueFallback = { name: "", slug: "", status: "active" as const };
tests/unit/network/network-admin-client-config.test.ts:19:    expect(resolveVenueForm({}, "club_3", venueFallback)).toBe(venueFallback);
tests/unit/network/network-admin-client-config.test.ts:20:    expect(resolveMachineForm({}, "venue_3", machineFallback)).toBe(machineFallback);
tests/unit/network/network-admin-client-config.test.ts:24:    const venueForm = { name: "Venue Two", slug: "venue-two", status: "inactive" as const };
tests/unit/network/network-admin-client-config.test.ts:27:    expect(resolveVenueForm({ club_2: venueForm }, "club_2")).toBe(venueForm);
tests/unit/network/network-admin-client-config.test.ts:28:    expect(resolveMachineForm({ venue_2: machineForm }, "venue_2")).toBe(machineForm);
tests/unit/network/use-network-admin-client-state.test.tsx:14:    venues: [],
tests/unit/network/use-network-admin-client-state.test.tsx:24:    venues: [],
tests/unit/network/backend-mappers.test.ts:5:  it("maps persisted venue statuses to api values", () => {
tests/unit/network/backend-mappers.test.ts:10:  it("maps venue input statuses to persisted values", () => {
tests/unit/players/players-admin-client-config.test.ts:6:  { id: "club_1", atcSportclubId: "106", name: "Club One", locationName: null, venues: 1, machines: 1, screens: 1 },
tests/unit/players/players-admin-client-config.test.ts:7:  { id: "club_2", atcSportclubId: "107", name: "Club Two", locationName: null, venues: 1, machines: 1, screens: 1 },
components/coach-settings-page-client.tsx:12:} from "@/components/weekly-availability-grid";
components/coach-settings-page-client.tsx:43:  venue: CoachStudentBooking["venue"];
components/coach-settings-page-client.tsx:55:  venueId: string;
components/coach-settings-page-client.tsx:315:    venueId: panel.venues[0]?.id ?? "",
components/coach-settings-page-client.tsx:355:    venueId: "",
components/coach-settings-page-client.tsx:497:      const venueStillExists = studentsPanel.venues.some((venue) => venue.id === current.venueId);
components/coach-settings-page-client.tsx:500:        venueId: current.venueId && venueStillExists ? current.venueId : nextDefaults.venueId,
components/coach-settings-page-client.tsx:577:        booking.venue.id,
components/coach-settings-page-client.tsx:591:        venue: booking.venue,
components/coach-settings-page-client.tsx:665:          weekRevenue: weekBookings.reduce((total, booking) => total + (booking.coachPriceMinor ?? 0), 0),
components/coach-settings-page-client.tsx:948:          venueId: studentBookingDraft.venueId,
components/coach-settings-page-client.tsx:1123:    studentsPanel.venues.length > 0 &&
components/coach-settings-page-client.tsx:1127:    studentBookingDraft.venueId.length > 0 &&
components/coach-settings-page-client.tsx:1182:                    {context.mode === "venue"
components/coach-settings-page-client.tsx:1183:                      ? coach.venue
components/coach-settings-page-client.tsx:1184:                        ? `Sede ${coach.venue.name}`
components/coach-settings-page-client.tsx:1298:                                          {session.venue.name}
components/coach-settings-page-client.tsx:1374:                          {selectedCalendarSession.venue.clubName} · {selectedCalendarSession.venue.name}
components/coach-settings-page-client.tsx:1484:                        {clubItem.venueNames.length > 0
components/coach-settings-page-client.tsx:1485:                          ? clubItem.venueNames.join(" · ")
components/coach-settings-page-client.tsx:1512:
{formatMoney(clubItem.listedRevenue)}

components/coach-settings-page-client.tsx:1579:
{row.student.venueNames.join(" · ") || "Sin sede"}

components/coach-settings-page-client.tsx:1585:                      {formatMoney(row.weekRevenue)}
components/coach-settings-page-client.tsx:1601:                  {coach.venue ? `Trabajas desde la sede ${coach.venue.name}.` : "Todavia no te asignaron una sede dentro del club."}
components/coach-settings-page-client.tsx:1740:                          {clubItem.venues.map((venue) => (
components/coach-settings-page-client.tsx:1741:
components/coach-settings-page-client.tsx:1742:                              {venue.name}
components/coach-settings-page-client.tsx:1786:                    {context.mode === "venue"
components/coach-settings-page-client.tsx:2205:                          value={studentBookingDraft.venueId}
components/coach-settings-page-client.tsx:2206:                          onChange={(event) => setStudentBookingDraft((current) => ({ ...current, venueId: event.target.value }))}
components/coach-settings-page-client.tsx:2210:                          {studentsPanel?.venues.map((venue) => (
components/coach-settings-page-client.tsx:2211:                            <option key={venue.id} value={venue.id}>
components/coach-settings-page-client.tsx:2212:                              {venue.clubName} · {venue.name}
components/coach-settings-page-client.tsx:2401:                          {student.venueNames.join(" · ") || "Sin sedes"}
tests/unit/classes/backend.test.ts:53:        venue: {
tests/unit/classes/backend.test.ts:54:          id: "venue_001",
tests/unit/classes/backend.test.ts:55:          name: "Main venue",
tests/unit/classes/backend.test.ts:82:        venue: {
tests/unit/classes/backend.test.ts:111:        venue: {
tests/unit/classes/backend.test.ts:112:          id: "venue_001",
tests/unit/classes/backend.test.ts:113:          name: "Main venue",
tests/unit/classes/backend.test.ts:141:      venue: {
tests/unit/classes/backend.test.ts:200:      venue: {
tests/unit/classes/backend.test.ts:280:      venue: {
tests/unit/classes/backend.test.ts:309:      venue: {
components/tvs-admin-client.tsx:28:    venues: BallboxStoreTvAdminVenueOption[];
components/tvs-admin-client.tsx:36:  venueId: "",
components/tvs-admin-client.tsx:81:  VENUE_NOT_FOUND: "El venue seleccionado no existe.",
components/tvs-admin-client.tsx:113:    venueId: operations.venues[0]?.id ?? "",
components/tvs-admin-client.tsx:205:              <p className={`mt-1 text-sm ${secondaryTextClass}`}>Pantallas, venue, estado operativo y vínculo con TV device.

components/tvs-admin-client.tsx:211:              value={screenForm.venueId}
components/tvs-admin-client.tsx:212:              onChange={(event) => setScreenForm((current) => ({ ...current, venueId: event.target.value }))}
components/tvs-admin-client.tsx:216:              {adminData.venues.map((venue) => (
components/tvs-admin-client.tsx:217:                <option key={venue.id} value={venue.id}>
components/tvs-admin-client.tsx:218:                  {(venue.clubName ?? "ATC no disponible")} · {venue.venueName}
components/tvs-admin-client.tsx:251:              disabled={busy || !screenForm.venueId || screenForm.name.trim().length === 0}
components/tvs-admin-client.tsx:258:                      venueId: screenForm.venueId,
components/tvs-admin-client.tsx:272:                    venueId: adminData.venues[0]?.id ?? "",
components/tvs-admin-client.tsx:298:                    value={screen.venueId}
components/tvs-admin-client.tsx:300:                      const nextVenue = adminData.venues.find((venue) => venue.id === event.target.value);
components/tvs-admin-client.tsx:309:                                venueId: nextVenue.id,
components/tvs-admin-client.tsx:310:                                venueName: nextVenue.venueName,
components/tvs-admin-client.tsx:321:                    {adminData.venues.map((venue) => (
components/tvs-admin-client.tsx:322:                      <option key={venue.id} value={venue.id}>
components/tvs-admin-client.tsx:323:                        {(venue.clubName ?? "ATC no disponible")} · {venue.venueName}
components/tvs-admin-client.tsx:396:                            venueId: screen.venueId,
components/tvs-admin-client.tsx:430:                  {(screen.clubName ?? "ATC no disponible")} · {screen.venueName}
tests/e2e/support/cleanup-playwright-db.ts:31:  const [clubs, venues, players, screens, tvDevices, campaigns] = await Promise.all([
tests/e2e/support/cleanup-playwright-db.ts:43:    prisma.venue.findMany({
tests/e2e/support/cleanup-playwright-db.ts:80:  const venueIds = venues.map((venue) => venue.id);
tests/e2e/support/cleanup-playwright-db.ts:183:  if (venueIds.length > 0) {
tests/e2e/support/cleanup-playwright-db.ts:187:          { venueId: { in: venueIds } },
tests/e2e/support/cleanup-playwright-db.ts:193:    await prisma.venue.deleteMany({
tests/e2e/support/cleanup-playwright-db.ts:194:      where: { id: { in: venueIds } },
tests/e2e/support/test-fixtures.ts:5:export const E2E_VENUE_SLUG_PREFIX = "pw-e2e-venue-";
tests/e2e/admin-navigation-and-network.spec.ts:25:test("network admin supports club, venue, and vending machine CRUD", async ({ page }) => {
tests/e2e/admin-navigation-and-network.spec.ts:28:  const venueName = `${E2E_VENUE_NAME_PREFIX} ${suffix}`;
tests/e2e/admin-navigation-and-network.spec.ts:29:  const venueSlug = `${E2E_VENUE_SLUG_PREFIX}${suffix}`;
tests/e2e/admin-navigation-and-network.spec.ts:30:  const venueNameUpdated = `${venueName} Updated`;
tests/e2e/admin-navigation-and-network.spec.ts:56:  await clubArticle.getByPlaceholder("Venue name").fill(venueName);
tests/e2e/admin-navigation-and-network.spec.ts:57:  await clubArticle.getByPlaceholder("optional-slug").fill(venueSlug);
tests/e2e/admin-navigation-and-network.spec.ts:58:  await clubArticle.getByRole("button", { name: "Add venue" }).click();
tests/e2e/admin-navigation-and-network.spec.ts:62:  const venueNameInput = clubArticle.locator(`input[value="${venueName}"]`).first();
tests/e2e/admin-navigation-and-network.spec.ts:63:  await venueNameInput.scrollIntoViewIfNeeded();
tests/e2e/admin-navigation-and-network.spec.ts:64:  await expect(venueNameInput).toBeVisible();
tests/e2e/admin-navigation-and-network.spec.ts:66:  await venueNameInput.fill(venueNameUpdated);
tests/e2e/admin-navigation-and-network.spec.ts:69:  await expect(clubArticle.locator(`input[value="${venueNameUpdated}"]`).first()).toBeVisible();
tests/e2e/admin-navigation-and-network.spec.ts:94:  await expect(clubArticle.locator(`input[value="${venueNameUpdated}"]`)).toHaveCount(0);
components/network-admin-create-venue-form.tsx:10:  venueForm: VenueFormState;
components/network-admin-create-venue-form.tsx:21:  venueForm,
components/network-admin-create-venue-form.tsx:31:        value={venueForm.name}
components/network-admin-create-venue-form.tsx:32:        onChange={(event) => setVenueForms((current) => ({ ...current, [clubId]: { ...venueForm, name: event.target.value } }))}
components/network-admin-create-venue-form.tsx:37:        value={venueForm.slug}
components/network-admin-create-venue-form.tsx:38:        onChange={(event) => setVenueForms((current) => ({ ...current, [clubId]: { ...venueForm, slug: event.target.value } }))}
components/network-admin-create-venue-form.tsx:43:        value={venueForm.status}
components/network-admin-create-venue-form.tsx:45:          setVenueForms((current) => ({ ...current, [clubId]: { ...venueForm, status: event.target.value as VenueStatus } }))
components/network-admin-create-venue-form.tsx:58:        disabled={busy || venueForm.name.trim().length === 0}
components/network-admin-create-venue-form.tsx:61:            const response = await fetch(`/api/network/${clubId}/venues`, {
components/network-admin-create-venue-form.tsx:65:                name: venueForm.name,
components/network-admin-create-venue-form.tsx:66:                slug: venueForm.slug || undefined,
components/network-admin-create-venue-form.tsx:67:                status: venueForm.status,
components/network-admin-create-venue-form.tsx:76:        Add venue
components/network-admin-mutation-helpers.ts:9:  CLUB_HAS_VENUES: "No se puede borrar el club porque todavía tiene venues.",
components/network-admin-mutation-helpers.ts:12:  VENUE_NOT_FOUND: "El venue ya no existe.",
components/network-admin-mutation-helpers.ts:13:  VENUE_SLUG_CONFLICT: "Ya existe otro venue con ese slug en el club.",
components/network-admin-mutation-helpers.ts:14:  VENUE_HAS_SCREENS: "No se puede borrar el venue porque todavía tiene pantallas.",
components/network-admin-mutation-helpers.ts:15:  VENUE_HAS_VENDING_MACHINES: "No se puede borrar el venue porque todavía tiene máquinas.",
components/network-admin-mutation-helpers.ts:16:  VENUE_HAS_OPEN_MATCHES: "No se puede borrar el venue porque todavía tiene open matches vinculados.",
components/network-admin-mutation-helpers.ts:17:  VENUE_HAS_CLASSES: "No se puede borrar el venue porque todavía tiene clases vinculadas.",
components/network-admin-venue-header.tsx:3:type Venue = BallboxStoreClubDetail["venues"][number];
components/network-admin-venue-header.tsx:6:  venue: Venue;
components/network-admin-venue-header.tsx:9:export function NetworkAdminVenueHeader({ venue }: NetworkAdminVenueHeaderProps) {
components/network-admin-venue-header.tsx:14:
{venue.name}

components/network-admin-venue-header.tsx:17:        slug {venue.slug}
components/network-admin-venue-header.tsx:18:        {venue.screens} screens
components/network-admin-venue-header.tsx:19:        {venue.machines} machines
components/club-venue-page-client.tsx:12:} from "@/components/weekly-availability-grid";
components/club-venue-page-client.tsx:26:  venue: {
components/club-venue-page-client.tsx:118:function createDraft(venue: VenueDetail): VenueDraft {
components/club-venue-page-client.tsx:120:    name: venue.name,
components/club-venue-page-client.tsx:121:    status: venue.status,


"use client";

import { useEffect, useMemo, useState } from "react";

export type WeeklyAvailabilityRange = {
  dayOfWeek: number;
  startTime: string;
  endTime: string;
};

type WeeklyAvailabilityGridProps = {
  value: WeeklyAvailabilityRange[];
  onChange: (next: WeeklyAvailabilityRange[]) => void;
  blockedRanges?: WeeklyAvailabilityRange[];
  selectedLabel: string;
  openLabel: string;
  blockedLabel: string;
  instructionsId?: string;
};

const DAY_LABELS = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"];
const DAY_FULL_LABELS = ["domingo", "lunes", "martes", "miercoles", "jueves", "viernes", "sabado"];
const HALF_HOUR_SLOTS = Array.from({ length: 47 }, (_, index) => {
  const hours = Math.floor(index / 2);
  const minutes = index % 2 === 0 ? "00" : "30";
  return `${String(hours).padStart(2, "0")}:${minutes}`;
});

function timeToMinutes(value: string) {
  const [hours, minutes] = value.split(":").map((part) => Number(part));
  return hours * 60 + minutes;
}

function cellKey(dayOfWeek: number, startTime: string) {
  return `${dayOfWeek}|${startTime}`;
}

function expandRangesToCells(ranges: WeeklyAvailabilityRange[]) {
  const cells = new Set<string>();

  for (const range of ranges) {
    let minuteCursor = timeToMinutes(range.startTime);
    const endMinutes = timeToMinutes(range.endTime);

    while (minuteCursor < endMinutes) {
      const hour = Math.floor(minuteCursor / 60);
      const minute = minuteCursor % 60;
      cells.add(cellKey(range.dayOfWeek, `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`));
      minuteCursor += 30;
    }
  }

  return cells;
}

function compressCellsToRanges(cells: Set<string>) {
  const next: WeeklyAvailabilityRange[] = [];

  for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek += 1) {
    const daySlots = HALF_HOUR_SLOTS.filter((slot) => cells.has(cellKey(dayOfWeek, slot)));
    let index = 0;

    while (index < daySlots.length) {
      const startTime = daySlots[index];
      let endMinutes = timeToMinutes(startTime) + 30;
      let cursor = index + 1;

      while (cursor < daySlots.length && timeToMinutes(daySlots[cursor]) === endMinutes) {
        endMinutes += 30;
        cursor += 1;
      }

      next.push({
        dayOfWeek,
        startTime,
        endTime: `${String(Math.floor(endMinutes / 60)).padStart(2, "0")}:${String(endMinutes % 60).padStart(2, "0")}`,
      });
      index = cursor;
    }
  }

  return next;
}

export function clampWeeklyAvailabilityRanges(value: WeeklyAvailabilityRange[], allowedRanges: WeeklyAvailabilityRange[]) {
  const allowedCells = expandRangesToCells(allowedRanges);
  const nextCells = new Set<string>();

  for (const key of expandRangesToCells(value)) {
    if (allowedCells.has(key)) {
      nextCells.add(key);
    }
  }

  return compressCellsToRanges(nextCells);
}

function formatSlotLabel(value: string) {
  return value;
}

function getCellAriaLabel(dayOfWeek: number, slot: string, stateLabel: string) {
  return `${DAY_FULL_LABELS[dayOfWeek] ?? "dia"} ${slot}, ${stateLabel}`;
}

export function WeeklyAvailabilityGrid({
  value,
  onChange,
  blockedRanges = [],
  selectedLabel,
  openLabel,
  blockedLabel,
  instructionsId,
}: WeeklyAvailabilityGridProps) {
  const selectedCells = useMemo(() => expandRangesToCells(value), [value]);
  const blockedCells = useMemo(() => expandRangesToCells(blockedRanges), [blockedRanges]);
  const [dragMode, setDragMode] = useState<boolean | null>(null);

  useEffect(() => {
    function clearDragMode() {
      setDragMode(null);
    }

    window.addEventListener("mouseup", clearDragMode);
    return () => window.removeEventListener("mouseup", clearDragMode);
  }, []);

  function updateCell(dayOfWeek: number, slot: string, nextValue: boolean) {
    const nextCells = new Set(selectedCells);
    const key = cellKey(dayOfWeek, slot);

    if (nextValue) {
      nextCells.add(key);
    } else {
      nextCells.delete(key);
    }

    onChange(compressCellsToRanges(nextCells));
  }

  return (

          Arrastra para marcar bloques de 30 minutos. Tambien puedes usar Tab y Enter o Espacio sobre cada bloque.

          {DAY_LABELS.map((label) => (

              {label}

          ))}

          {HALF_HOUR_SLOTS.map((slot) => (

{formatSlotLabel(slot)}

              {DAY_LABELS.map((_label, dayOfWeek) => {
                const key = cellKey(dayOfWeek, slot);
                const isBlocked = blockedRanges.length > 0 && !blockedCells.has(key);
                const isSelected = selectedCells.has(key);

                return (
                  <button
                    key={key}
                    type="button"
                    aria-pressed={isSelected}
                    aria-disabled={isBlocked}
                    aria-label={getCellAriaLabel(dayOfWeek, slot, isBlocked ? blockedLabel : isSelected ? selectedLabel : openLabel)}
                    aria-describedby={instructionsId}
                    title={isBlocked ? blockedLabel : isSelected ? selectedLabel : openLabel}
                    className={`h-8 rounded-md border text-[10px] transition ${
                      isBlocked
                        ? "cursor-not-allowed border-red-500/25 bg-red-500/15 text-red-100/80"
                        : isSelected
                          ? "border-[#c4d600]/40 bg-[#c4d600]/20 text-white"
                          : "border-white/10 bg-black/25 text-white/45 hover:border-white/20 hover:text-white"
                    }`}
                    onClick={() => {
                      if (isBlocked) return;
                      updateCell(dayOfWeek, slot, !isSelected);
                    }}
                    onMouseDown={() => {
                      if (isBlocked) return;
                      const nextValue = !isSelected;
                      setDragMode(nextValue);
                      updateCell(dayOfWeek, slot, nextValue);
                    }}
                    onMouseEnter={() => {
                      if (isBlocked || dragMode === null) return;
                      if (dragMode !== isSelected) {
                        updateCell(dayOfWeek, slot, dragMode);
                      }
                    }}
                  >
                    {isBlocked ? blockedLabel : isSelected ? selectedLabel : openLabel}
                  </button>
                );
              })}

          ))}

  );
}


"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { formatBallboxDateTime } from "@/lib/ballbox-datetime";

type ClassAtcSlot = {
  start: string;
  durationMinutes: number;
  priceMinor: number | null;
  currency: string | null;
  sportclubId: string | null;
  courtId: string | null;
  courtName: string | null;
};

type ClassesRequestFormProps = {
  classOfferId: string;
  slots: ClassAtcSlot[];
  loadingSlots?: boolean;
  initialSelectedSlot?: ClassAtcSlot | null;
};

function formatMoney(value: number | null, currency: string | null) {
  if (value === null || !currency) return "Precio a confirmar";

  return new Intl.NumberFormat("es-AR", {
    style: "currency",
    currency,
    maximumFractionDigits: 0,
  }).format(value / 100);
}

function slotKey(slot: ClassAtcSlot) {
  return [
    slot.start,
    slot.durationMinutes,
    slot.priceMinor ?? "null",
    slot.currency ?? "null",
    slot.sportclubId ?? "null",
    slot.courtId ?? "null",
  ].join("|");
}

function resolveInitialSelection(slots: ClassAtcSlot[], initialSelectedSlot: ClassAtcSlot | null) {
  if (initialSelectedSlot) {
    const matchedSlot = slots.find((slot) => slotKey(slot) === slotKey(initialSelectedSlot));
    if (matchedSlot) {
      return {
        selectionMode: "slot" as const,
        selectedSlotKey: slotKey(matchedSlot),
      };
    }
  }

  return {
    selectionMode: slots.length === 0 ? ("flexible" as const) : null,
    selectedSlotKey: "",
  };
}

export function ClassesRequestForm({ classOfferId, slots, loadingSlots = false, initialSelectedSlot = null }: ClassesRequestFormProps) {
  const errorId = "classes-request-error";
  const successId = "classes-request-success";
  const matchedInitialSlot = initialSelectedSlot
    ? slots.find((slot) => slotKey(slot) === slotKey(initialSelectedSlot))
      ?? slots.find(
          (slot) =>
            slot.start === initialSelectedSlot.start
            && slot.durationMinutes === initialSelectedSlot.durationMinutes
            && (initialSelectedSlot.sportclubId ? slot.sportclubId === initialSelectedSlot.sportclubId : true)
        )
      ?? initialSelectedSlot
    : null;
  const displaySlots = matchedInitialSlot ? [matchedInitialSlot] : slots;
  const showFlexibleOption = !matchedInitialSlot;
  const initialSelection = resolveInitialSelection(displaySlots, matchedInitialSlot);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [selectionMode, setSelectionMode] = useState<"slot" | "flexible" | null>(initialSelection.selectionMode);
  const [selectedSlotKey, setSelectedSlotKey] = useState<string>(initialSelection.selectedSlotKey);
  const studentNameInputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (selectionMode !== "slot" || selectedSlotKey.length === 0) {
      return;
    }

    studentNameInputRef.current?.focus();
  }, [selectedSlotKey, selectionMode]);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    setPending(true);
    setError(null);
    setSuccess(null);

    if (!selectionMode) {
      setError("Elige un horario visible o marca cualquier horario / lugar.");
      setPending(false);
      return;
    }

    const selectedSlot = selectionMode === "slot" ? displaySlots.find((slot) => slotKey(slot) === selectedSlotKey) ?? null : null;
    if (selectionMode === "slot" && !selectedSlot) {
      setError("Elige un horario valido antes de enviar la solicitud.");
      setPending(false);
      return;
    }

    const formData = new FormData(form);
    const payload = {
      classOfferId,
      studentName: String(formData.get("studentName") ?? ""),
      studentEmail: String(formData.get("studentEmail") ?? ""),
      studentPhone: String(formData.get("studentPhone") ?? ""),
      message: String(formData.get("message") ?? ""),
      selectionMode,
      ...(selectedSlot
        ? {
            selectedSlotStart: selectedSlot.start,
            selectedSlotDurationMinutes: selectedSlot.durationMinutes,
            selectedSlotPriceMinor: selectedSlot.priceMinor,
            selectedSlotCurrency: selectedSlot.currency,
            selectedAtcSportclubId: selectedSlot.sportclubId,
            selectedAtcCourtId: selectedSlot.courtId,
          }
        : {}),
    };

    const response = await fetch("/api/classes/requests", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });

    const body = (await response.json().catch(() => null)) as { ok?: boolean; error?: string; item?: { id: string } } | null;

    if (!response.ok || !body || body.ok !== true) {
      setError(
        body?.error === "SLOT_NOT_AVAILABLE"
          ? "Ese horario ya no aparece disponible. Elige otro o usa cualquier horario / lugar."
          : "No pudimos guardar la solicitud. Revisa los datos e intenta de nuevo."
      );
      setPending(false);
      return;
    }

    form.reset();
    setSelectionMode(slots.length === 0 ? "flexible" : null);
    setSelectedSlotKey("");
    setSuccess(
      selectionMode === "slot"
        ? "Solicitud enviada con el horario elegido. Ballbox la guardo como lead local para seguimiento."
        : "Solicitud enviada con preferencia flexible. Ballbox la guardo como lead local para seguimiento."
    );
    setPending(false);
  }

  return (
    <form
      id="request-form"
      onSubmit={handleSubmit}
      data-local-submit="true"
      className="space-y-4 rounded-[1.75rem] border border-white/10 bg-[#101510]/95 p-6 shadow-[0_24px_60px_-35px_rgba(0,0,0,0.55)]"
    >

Solicitar

Elige horario y deja tus datos

          Elige uno de los horarios visibles o usa cualquier horario / lugar como fallback. Ballbox guarda la solicitud localmente; no hay booking ATC automatico en este MVP.

      <fieldset className="space-y-3 rounded-[1.5rem] border border-white/10 bg-black/20 p-4">
        <legend className="px-2 text-sm font-medium text-white">Horario preferido</legend>
        {loadingSlots ? (

Buscando horarios visibles de ATC...

        ) : null}
        {displaySlots.length > 0 ? (

            {displaySlots.map((slot) => {
              const key = slotKey(slot);
              const checked = selectionMode === "slot" && selectedSlotKey === key;

              return (

                  <input
                    type="radio"
                    name="slotSelection"
                    className="mt-1"
                    checked={checked}
                    onChange={() => {
                      setSelectionMode("slot");
                      setSelectedSlotKey(key);
                    }}
                  />

{formatBallboxDateTime(slot.start)}

                      {slot.durationMinutes} min{slot.courtName ? ` - ${slot.courtName}` : ""}

{formatMoney(slot.priceMinor, slot.currency)}

              );
            })}

        ) : !loadingSlots ? (

No hay horarios visibles ahora mismo. Puedes enviar la solicitud como cualquier horario / lugar.

        ) : null}

        {showFlexibleOption ? (

            <input
              type="radio"
              name="slotSelection"
              className="mt-1"
              checked={selectionMode === "flexible"}
              onChange={() => {
                setSelectionMode("flexible");
                setSelectedSlotKey("");
              }}
            />

Cualquier horario / lugar

Usa esta opcion si las alternativas visibles no te sirven. Luego aclara tus condiciones en el mensaje.

        ) : null}
      </fieldset>

          Nombre
          <input
            ref={studentNameInputRef}
            name="studentName"
            required
            aria-invalid={error ? true : undefined}
            aria-describedby={error ? errorId : success ? successId : undefined}
            className="h-11 w-full rounded-xl border border-white/15 bg-black/20 px-4 text-white outline-none focus:border-[#c4d600]/50"
          />

          Email
          <input
            name="studentEmail"
            type="email"
            required
            aria-invalid={error ? true : undefined}
            aria-describedby={error ? errorId : success ? successId : undefined}
            className="h-11 w-full rounded-xl border border-white/15 bg-black/20 px-4 text-white outline-none focus:border-[#c4d600]/50"
          />

        Telefono
        <input
          name="studentPhone"
          aria-invalid={error ? true : undefined}
          aria-describedby={error ? errorId : success ? successId : undefined}
          className="h-11 w-full rounded-xl border border-white/15 bg-black/20 px-4 text-white outline-none focus:border-[#c4d600]/50"
        />

        Mensaje
        <textarea
          name="message"
          rows={4}
          aria-invalid={error ? true : undefined}
          aria-describedby={error ? errorId : success ? successId : undefined}
          className="w-full rounded-xl border border-white/15 bg-black/20 px-4 py-3 text-white outline-none focus:border-[#c4d600]/50"
          placeholder="Objetivo, nivel y condiciones. Ejemplo: me sirven martes o jueves despues de las 19, o sedes Palermo/Belgrano."
        />

      {error ?
{error}
 : null}
      {success ?
{success}
 : null}

      <Button
        type="submit"
        loading={pending}
        disabled={pending}
        className="h-11 w-full rounded-xl text-sm font-medium disabled:cursor-not-allowed disabled:bg-[#7f9012] disabled:text-[#0b0e09]"
      >
        {pending ? "Enviando..." : "Solicitar clase"}
      </Button>
    </form>
  );
}