/**
 * Unit tests for CalendarGrid: 42 cells, data-date, today class, month title in header.
 * Ported from webapp/js/calendar.test.js renderCalendar.
 */

import { describe, it, expect, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { CalendarGrid } from "./CalendarGrid";
import { CalendarHeader } from "./CalendarHeader";
import { resetAppStore } from "@/test/test-utils";

describe("CalendarGrid", () => {
  beforeEach(() => {
    resetAppStore();
  });

  it("renders 42 cells (6 weeks)", () => {
    const currentMonth = new Date(2025, 0, 1); // January 2025
    render(
      <CalendarGrid
        currentMonth={currentMonth}
        duties={[]}
        calendarEvents={[]}
        onDayClick={() => {}}
      />
    );
    const cells = screen.getAllByRole("button", { name: /;/ });
    expect(cells.length).toBe(42);
  });

  it("sets data-date on each cell to YYYY-MM-DD", () => {
    const currentMonth = new Date(2025, 0, 1);
    render(
      <CalendarGrid
        currentMonth={currentMonth}
        duties={[]}
        calendarEvents={[]}
        onDayClick={() => {}}
      />
    );
    const grid = screen.getByRole("grid", { name: "Calendar" });
    const buttons = grid.querySelectorAll('button[data-date]');
    expect(buttons.length).toBe(42);
    buttons.forEach((el) => {
      const date = el.getAttribute("data-date");
      expect(date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
    });
  });

  it("adds today styling to cell matching today", () => {
    const today = new Date();
    const currentMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    render(
      <CalendarGrid
        currentMonth={currentMonth}
        duties={[]}
        calendarEvents={[]}
        onDayClick={() => {}}
      />
    );
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, "0");
    const day = String(today.getDate()).padStart(2, "0");
    const todayKey = `${year}-${month}-${day}`;
    const todayCell = document.querySelector(`button[data-date="${todayKey}"]`);
    expect(todayCell).toBeTruthy();
    expect(todayCell?.className).toMatch(/today|bg-today/);
  });
});

describe("CalendarHeader", () => {
  beforeEach(() => {
    resetAppStore();
  });

  it("sets month title from lang and given year/month", () => {
    render(
      <CalendarHeader
        month={new Date(2025, 1, 1)}
        onPrevMonth={() => {}}
        onNextMonth={() => {}}
      />
    );
    const heading = screen.getByRole("heading", { level: 1 });
    expect(heading).toHaveTextContent("February");
    expect(heading).toHaveTextContent("2025");
  });
});
