import type { JSX } from "solid-js";
import { For } from "solid-js";
import { useCalendarContext } from "./calendar-context";
import { CalendarCell } from "./calendar-cell";
import type { CalendarGridBodyProps } from "./calendar.props";

/** Splits a flat array of dates into rows of 7 (one per week). */
function chunkWeeks(days: Date[]): Date[][] {
  const weeks: Date[][] = [];
  for (let i = 0; i < days.length; i += 7) {
    weeks.push(days.slice(i, i + 7));
  }
  return weeks;
}

/** Formats a Date as YYYY-MM-DD for use as an ISO date key. */
function toISO(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

/** Renders the tbody of the calendar grid, one tr per week and one CalendarCell per day. */
export function CalendarGridBody(props: CalendarGridBodyProps): JSX.Element {
  const ctx = useCalendarContext();

  const weeks = () => chunkWeeks(ctx.getDaysInMonth());

  return (
    <tbody data-scope="calendar" data-part="grid-body" {...props}>
      <For each={weeks()}>
        {(week) => (
          <tr>
            <For each={week}>
              {(day) => (
                <CalendarCell date={toISO(day)}>
                  {day.getDate()}
                </CalendarCell>
              )}
            </For>
          </tr>
        )}
      </For>
    </tbody>
  );
}
