"use client";
import { calendarYearPickerVariants } from '@heroui/styles';
import { useDateFormatter } from '@react-aria/i18n';
import React__default from 'react';
import { Button } from 'react-aria-components';
import { getYearRange } from '../../utils/calendar.js';
import { composeTwRenderProps, composeSlotClassName } from '../../utils/compose.js';
import { IconChevronRight } from '../icons.js';
import { useYearPicker, useYearPickerState } from './year-picker-context.js';
import { jsx, Fragment } from 'react/jsx-runtime';

const CalendarYearPickerTriggerContext = /*#__PURE__*/React__default.createContext(null);
function useCalendarYearPickerTriggerContext() {
  const context = React__default.useContext(CalendarYearPickerTriggerContext);
  if (!context) {
    throw new Error("CalendarYearPicker trigger components must be used within <CalendarYearPicker.Trigger>.");
  }
  return context;
}
const CalendarYearPickerTrigger = ({
  children,
  className,
  onKeyDown,
  onPress,
  ...props
}) => {
  const {
    isYearPickerOpen,
    setIsYearPickerOpen
  } = useYearPicker();
  const state = useYearPickerState();
  const slots = React__default.useMemo(() => calendarYearPickerVariants(), []);

  // Format "Month Year" (e.g. "December 2025"), handling non-Gregorian calendars and eras
  const focusedDate = state.focusedDate;
  const monthYearFormatter = useDateFormatter({
    month: "long",
    year: "numeric",
    era: focusedDate.calendar.identifier === "gregory" && focusedDate.era === "BC" ? "short" : undefined,
    calendar: focusedDate.calendar.identifier,
    timeZone: state.timeZone
  });
  const monthYear = monthYearFormatter.format(focusedDate.toDate(state.timeZone));
  const handleToggle = React__default.useCallback(() => {
    setIsYearPickerOpen(!isYearPickerOpen);
  }, [isYearPickerOpen, setIsYearPickerOpen]);
  const handleKeyDown = e => {
    onKeyDown?.(e);
    if (e.defaultPrevented) {
      return;
    }
    if (e.key === "Escape" && isYearPickerOpen) {
      e.preventDefault();
      setIsYearPickerOpen(false);
    }
  };
  const values = React__default.useMemo(() => ({
    isOpen: isYearPickerOpen,
    monthYear,
    toggle: handleToggle
  }), [handleToggle, isYearPickerOpen, monthYear]);
  const contextValue = React__default.useMemo(() => ({
    ...values,
    slots
  }), [slots, values]);
  return /*#__PURE__*/jsx(CalendarYearPickerTriggerContext, {
    value: contextValue,
    children: /*#__PURE__*/jsx(Button, {
      "aria-expanded": isYearPickerOpen,
      "aria-label": `${monthYear}, year selector`,
      className: composeTwRenderProps(className, slots.trigger()),
      "data-open": isYearPickerOpen || undefined,
      "data-slot": "calendar-year-picker-trigger",
      slot: null,
      onKeyDown: handleKeyDown,
      onPress: event => {
        onPress?.(event);
        handleToggle();
      },
      ...props,
      children: typeof children === "function" ? children(values) : children
    })
  });
};
CalendarYearPickerTrigger.displayName = "HeroUI.CalendarYearPicker.Trigger";

/* -------------------------------------------------------------------------------------------------
 * CalendarYearPickerTriggerHeading
 * -----------------------------------------------------------------------------------------------*/
const CalendarYearPickerTriggerHeading = ({
  children,
  className,
  ...props
}) => {
  const {
    monthYear,
    slots,
    ...values
  } = useCalendarYearPickerTriggerContext();
  return /*#__PURE__*/jsx("span", {
    className: composeSlotClassName(slots.triggerHeading, className),
    "data-slot": "calendar-year-picker-trigger-heading",
    ...props,
    children: typeof children === "function" ? children({
      monthYear,
      ...values
    }) : children || monthYear
  });
};
CalendarYearPickerTriggerHeading.displayName = "HeroUI.CalendarYearPicker.TriggerHeading";

/* -------------------------------------------------------------------------------------------------
 * CalendarYearPickerTriggerIndicator
 * -----------------------------------------------------------------------------------------------*/
const CalendarYearPickerTriggerIndicator = ({
  children,
  className,
  ...props
}) => {
  const {
    monthYear,
    slots,
    ...values
  } = useCalendarYearPickerTriggerContext();
  return /*#__PURE__*/jsx("span", {
    "aria-hidden": "true",
    className: composeSlotClassName(slots.triggerIndicator, className),
    "data-slot": "calendar-year-picker-trigger-indicator",
    ...props,
    children: typeof children === "function" ? children({
      monthYear,
      ...values
    }) : children || /*#__PURE__*/jsx(IconChevronRight, {
      height: "1em",
      width: "1em"
    })
  });
};
CalendarYearPickerTriggerIndicator.displayName = "HeroUI.CalendarYearPicker.TriggerIndicator";

/* -------------------------------------------------------------------------------------------------
 * CalendarYearPickerGrid
 *
 * Renders a 3-column grid of year buttons. Hidden via CSS opacity when closed,
 * visible when data-open="true".  tabIndex is toggled so only the active view
 * receives keyboard focus.
 * -----------------------------------------------------------------------------------------------*/

const CalendarYearPickerGridContext = /*#__PURE__*/React__default.createContext(null);
function useCalendarYearPickerGridContext() {
  const context = React__default.useContext(CalendarYearPickerGridContext);
  if (!context) {
    throw new Error("CalendarYearPicker components must be used within <CalendarYearPicker.Grid>.");
  }
  return context;
}
const CalendarYearPickerGrid = ({
  children,
  className,
  onKeyDown,
  ...props
}) => {
  const {
    calendarGridSlot,
    calendarRef,
    isYearPickerOpen,
    setIsYearPickerOpen
  } = useYearPicker();
  const state = useYearPickerState();
  const gridRef = React__default.useRef(null);
  const slots = React__default.useMemo(() => calendarYearPickerVariants(), []);
  const focusedDate = state.focusedDate;
  const yearFormatter = useDateFormatter({
    year: "numeric",
    era: focusedDate.calendar.identifier === "gregory" && focusedDate.era === "BC" ? "short" : undefined,
    calendar: focusedDate.calendar.identifier,
    timeZone: state.timeZone
  });
  const focusedYear = state.focusedDate.year;

  // Build calendar-aware year list using DateValue arithmetic
  const yearDates = React__default.useMemo(() => getYearRange(state.minValue, state.maxValue), [state.minValue, state.maxValue]);
  const years = React__default.useMemo(() => yearDates.map(d => d.year), [yearDates]);
  const yearDateMap = React__default.useMemo(() => new Map(yearDates.map(d => [d.year, d])), [yearDates]);
  const formatYear = React__default.useCallback(year => {
    const dateValue = yearDateMap.get(year);
    if (!dateValue) return String(year);
    return yearFormatter.format(dateValue.toDate(state.timeZone));
  }, [yearDateMap, yearFormatter, state.timeZone]);
  const [activeYear, setActiveYear] = React__default.useState(focusedYear);

  // Position the year grid to overlay the day grid
  React__default.useEffect(() => {
    const yearGrid = gridRef.current;
    if (!yearGrid) return;
    const calendar = calendarRef.current;
    const calendarGrid = calendar?.querySelector(`[data-slot='${calendarGridSlot}']`);
    if (calendarGrid) {
      yearGrid.style.top = `${calendarGrid.offsetTop}px`;
      yearGrid.style.height = `${calendarGrid.offsetHeight}px`;
    }
  }, [calendarGridSlot, calendarRef, state.focusedDate]);
  const focusYearCell = React__default.useCallback(year => {
    const yearGrid = gridRef.current;
    if (!yearGrid) return;
    const yearCell = yearGrid.querySelector(`[data-year='${year}']`);
    if (yearCell) {
      yearCell.focus();
    }
  }, []);

  // Keep keyboard navigation anchored to the currently selected year when opening.
  React__default.useEffect(() => {
    if (!isYearPickerOpen || years.length === 0) return;
    const [firstYear] = years;
    if (firstYear == null) return;
    const nextActiveYear = years.includes(focusedYear) ? focusedYear : firstYear;
    setActiveYear(nextActiveYear);

    // Focus after DOM updates so tab navigation lands directly on a year cell.
    const rafId = requestAnimationFrame(() => {
      focusYearCell(nextActiveYear);
    });
    return () => {
      cancelAnimationFrame(rafId);
    };
  }, [isYearPickerOpen, focusedYear, years, focusYearCell]);
  React__default.useEffect(() => {
    if (!isYearPickerOpen || years.length === 0) return;
    const [firstYear] = years;
    if (firstYear == null) return;
    if (!years.includes(activeYear)) {
      setActiveYear(firstYear);
    }
  }, [activeYear, isYearPickerOpen, years]);
  const handleYearSelect = React__default.useCallback(year => {
    const newDate = state.focusedDate.set({
      year
    });
    state.setFocusedDate(newDate);
    setIsYearPickerOpen(false);
  }, [setIsYearPickerOpen, state]);
  const handleKeyDown = e => {
    onKeyDown?.(e);
    if (e.defaultPrevented) {
      return;
    }
    if (e.key === "Escape" && isYearPickerOpen) {
      e.preventDefault();
      setIsYearPickerOpen(false);
      return;
    }
    if (!isYearPickerOpen || years.length === 0) {
      return;
    }
    const currentIndex = years.indexOf(activeYear);
    if (currentIndex === -1) {
      return;
    }
    let nextIndex = currentIndex;
    switch (e.key) {
      case "ArrowRight":
        nextIndex = Math.min(currentIndex + 1, years.length - 1);
        break;
      case "ArrowLeft":
        nextIndex = Math.max(currentIndex - 1, 0);
        break;
      case "ArrowDown":
        nextIndex = Math.min(currentIndex + 3, years.length - 1);
        break;
      case "ArrowUp":
        nextIndex = Math.max(currentIndex - 3, 0);
        break;
      case "Home":
        nextIndex = 0;
        break;
      case "End":
        nextIndex = years.length - 1;
        break;
      default:
        return;
    }
    if (nextIndex !== currentIndex) {
      const nextYear = years[nextIndex];
      if (nextYear == null) return;
      e.preventDefault();
      setActiveYear(nextYear);
      focusYearCell(nextYear);
    }
  };
  const contextValue = React__default.useMemo(() => ({
    focusedYear,
    isYearPickerOpen,
    activeYear,
    selectYear: handleYearSelect,
    setActiveYear,
    slots,
    years,
    formatYear
  }), [activeYear, focusedYear, formatYear, handleYearSelect, isYearPickerOpen, slots, years]);
  return /*#__PURE__*/jsx(CalendarYearPickerGridContext, {
    value: contextValue,
    children: /*#__PURE__*/jsx("div", {
      ref: gridRef,
      "aria-hidden": !isYearPickerOpen,
      "aria-label": "Year selector",
      className: composeSlotClassName(slots.yearGrid, className),
      "data-open": isYearPickerOpen || undefined,
      "data-slot": "calendar-year-picker-grid",
      role: "listbox",
      tabIndex: -1,
      onKeyDown: handleKeyDown,
      ...props,
      children: children
    })
  });
};
CalendarYearPickerGrid.displayName = "HeroUI.CalendarYearPicker.Grid";

/* -------------------------------------------------------------------------------------------------
 * CalendarYearPickerGridBody
 * -----------------------------------------------------------------------------------------------*/
const CalendarYearPickerGridBody = ({
  children
}) => {
  const {
    focusedYear,
    formatYear,
    isYearPickerOpen,
    selectYear,
    years
  } = useCalendarYearPickerGridContext();
  const currentYear = new Date().getFullYear();
  return /*#__PURE__*/jsx(Fragment, {
    children: years.map(year => {
      const isSelected = year === focusedYear;
      const formattedYear = formatYear(year);
      const values = {
        formattedYear,
        isCurrentYear: year === currentYear,
        isOpen: isYearPickerOpen,
        isSelected,
        selectYear: () => selectYear(year),
        year
      };
      return /*#__PURE__*/jsx(React__default.Fragment, {
        children: typeof children === "function" ? children(values) : /*#__PURE__*/jsx(CalendarYearPickerCell, {
          year: year
        })
      }, year);
    })
  });
};
CalendarYearPickerGridBody.displayName = "HeroUI.CalendarYearPicker.GridBody";

/* -------------------------------------------------------------------------------------------------
 * CalendarYearPickerCell
 * -----------------------------------------------------------------------------------------------*/
const CalendarYearPickerCell = ({
  children,
  className,
  excludeFromTabOrder,
  onFocus,
  onPress,
  year,
  ...props
}) => {
  const {
    activeYear,
    focusedYear,
    formatYear,
    isYearPickerOpen,
    selectYear,
    setActiveYear,
    slots
  } = useCalendarYearPickerGridContext();
  const isSelected = year === focusedYear;
  const isActive = year === activeYear;
  const formattedYear = formatYear(year);
  const values = {
    formattedYear,
    isCurrentYear: year === new Date().getFullYear(),
    isOpen: isYearPickerOpen,
    isSelected,
    selectYear: () => selectYear(year),
    year
  };
  return /*#__PURE__*/jsx(Button, {
    "aria-label": formattedYear,
    "aria-selected": isSelected,
    className: composeTwRenderProps(className, slots.yearCell()),
    "data-selected": isSelected || undefined,
    "data-slot": "calendar-year-picker-year-cell",
    "data-year": year,
    excludeFromTabOrder: excludeFromTabOrder ?? !(isYearPickerOpen && isActive),
    slot: null,
    onFocus: event => {
      onFocus?.(event);
      setActiveYear(year);
    },
    onPress: event => {
      onPress?.(event);
      selectYear(year);
    },
    ...props,
    children: typeof children === "function" ? children(values) : children || formattedYear
  });
};
CalendarYearPickerCell.displayName = "HeroUI.CalendarYearPicker.Cell";

export { CalendarYearPickerCell, CalendarYearPickerGrid, CalendarYearPickerGridBody, CalendarYearPickerTrigger, CalendarYearPickerTriggerHeading, CalendarYearPickerTriggerIndicator };
