// @vitest-environment jsdom

import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WeeklyAvailabilityGrid, type WeeklyAvailabilityRange } from "@/components/weekly-availability-grid";

function renderGrid(value: WeeklyAvailabilityRange[] = [], blockedRanges?: WeeklyAvailabilityRange[]) {
  const onChange = vi.fn();

  render(
    <WeeklyAvailabilityGrid
      value={value}
      onChange={onChange}
      blockedRanges={blockedRanges}
      selectedLabel="Horario para coaches"
      openLabel="Horario abierto"
      blockedLabel="La sede esta cerrada"
      instructionsId="weekly-grid-help"
    />
  );

  return { onChange };
}

describe("WeeklyAvailabilityGrid", () => {
  afterEach(() => {
    cleanup();
  });

  it("exposes focusable button semantics for keyboard users and toggles an open slot", () => {
    const { onChange } = renderGrid();
    const button = screen.getByRole("button", { name: "lunes 09:00, Horario abierto" });

    button.focus();
    fireEvent.click(button);

    expect(document.activeElement).toBe(button);
    expect(onChange).toHaveBeenCalledWith([
      {
        dayOfWeek: 1,
        startTime: "09:00",
        endTime: "09:30",
      },
    ]);
    expect(button.getAttribute("aria-describedby")).toBe("weekly-grid-help");
    expect(button.getAttribute("aria-pressed")).toBe("false");
  });

  it("marks closed slots as aria-disabled and ignores pointer interaction", () => {
    const { onChange } = renderGrid([], [
      {
        dayOfWeek: 1,
        startTime: "09:00",
        endTime: "10:00",
      },
    ]);

    const blockedButton = screen.getByRole("button", { name: "lunes 08:30, La sede esta cerrada" });
    expect(blockedButton.getAttribute("aria-disabled")).toBe("true");

    fireEvent.click(blockedButton);
    expect(onChange).not.toHaveBeenCalled();
  });
});
