import React from "react";

const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

export function Calendar({ month, year, selected, onSelect, className = "" }) {
  const now = new Date();
  const [cursor, setCursor] = React.useState({ m: month !== undefined ? month : now.getMonth(), y: year !== undefined ? year : now.getFullYear() });
  const first = new Date(cursor.y, cursor.m, 1);
  const offset = (first.getDay() + 6) % 7;
  const days = new Date(cursor.y, cursor.m + 1, 0).getDate();
  const shift = (n) => {
    let m = cursor.m + n, y = cursor.y;
    if (m < 0) { m = 11; y -= 1; }
    if (m > 11) { m = 0; y += 1; }
    setCursor({ m, y });
  };
  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(<span key={"e" + i} />);
  for (let d = 1; d <= days; d++) {
    const isToday = d === now.getDate() && cursor.m === now.getMonth() && cursor.y === now.getFullYear();
    cells.push(
      <button type="button" key={d} className="o-calendar__day" data-slot="calendar-day" data-today={isToday ? "" : undefined}
        data-selected={selected === d ? "" : undefined} onClick={() => onSelect && onSelect(new Date(cursor.y, cursor.m, d))}>{d}</button>
    );
  }
  return (
    <div className={["o-calendar", className].filter(Boolean).join(" ")} data-slot="calendar">
      <div className="o-calendar__header">
        <button type="button" className="o-btn o-btn--ghost o-btn--icon-sm" aria-label="Previous month" onClick={() => shift(-1)}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
        </button>
        <span className="o-calendar__title">{MONTHS[cursor.m]} {cursor.y}</span>
        <button type="button" className="o-btn o-btn--ghost o-btn--icon-sm" aria-label="Next month" onClick={() => shift(1)}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
        </button>
      </div>
      <div className="o-calendar__grid">
        {WEEKDAYS.map((w) => <span className="o-calendar__weekday" key={w}>{w}</span>)}
        {cells}
      </div>
    </div>
  );
}
