import { forwardRef } from "react";

/**
 * Calendar - custom datepicker grid
 *
 * Prefer <input type="date"> for simple use cases.
 *
 * month:  string - display label, e.g. "May 2026"
 * onPrev: function - previous-month button click handler
 * onNext: function - next-month button click handler
 *
 * Compose with <CalendarWeek> and <CalendarDay> as children.
 */
export const Calendar = forwardRef(function Calendar(
  { month, onPrev, onNext, className = "", children, ...props },
  ref
) {
  return (
    <div ref={ref} className={["prs-cal", className].filter(Boolean).join(" ")} {...props}>
      <div className="prs-cal-header">
        <button type="button" className="prs-cal-prev" aria-label="Previous month" onClick={onPrev}>
          <ChevronLeftIcon />
        </button>
        <button type="button" className="prs-cal-next" aria-label="Next month" onClick={onNext}>
          <ChevronRightIcon />
        </button>
        <span className="prs-cal-my">{month}</span>
      </div>
      <div className="prs-cal-days">{children}</div>
    </div>
  );
});

/**
 * CalendarWeek
 *
 * days: string[] - day labels (default: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"])
 */
export const CalendarWeek = forwardRef(function CalendarWeek(
  { days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], ...props },
  ref
) {
  return (
    <div ref={ref} className="prs-cal-week" {...props}>
      {days.map((d) => <span key={d}>{d}</span>)}
    </div>
  );
});

/**
 * CalendarDay
 *
 * today:     boolean - marks as today; sets aria-current="date"
 * selected:  boolean - marks as selected
 * disabled:  boolean - out-of-month or unavailable day
 * ariaLabel: string - e.g. "May 12, 2026"
 */
export const CalendarDay = forwardRef(function CalendarDay(
  { today = false, selected = false, disabled = false, ariaLabel, className = "", children, ...props },
  ref
) {
  const classes = [
    "prs-cal-day",
    today && "prs-cal-day_today",
    selected && "prs-cal-day_selected",
    disabled && "prs-cal-day_disabled",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <button
      ref={ref}
      type="button"
      className={classes}
      aria-label={ariaLabel}
      aria-current={today ? "date" : undefined}
      disabled={disabled}
      {...props}
    >
      {children}
    </button>
  );
});

const ChevronLeftIcon = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
  </svg>
);

const ChevronRightIcon = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
  </svg>
);
