var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var stdin_exports = {};
__export(stdin_exports, {
  default: () => stdin_default
});
module.exports = __toCommonJS(stdin_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_popup = require("../popup");
var import_button = __toESM(require("../button"));
var import_toast = __toESM(require("../toast/index"));
var import_CalendarHeader = __toESM(require("./CalendarHeader"));
var import_CalendarMonth = __toESM(require("./CalendarMonth"));
var import_hooks = require("../hooks");
var import_get_rect = require("../hooks/get-rect");
var import_use_refs = __toESM(require("../hooks/use-refs"));
var import_utils = require("./utils");
var import_utils2 = require("../utils");
var import_raf = require("../utils/raf");
var import_ConfigProviderContext = __toESM(require("../config-provider/ConfigProviderContext"));
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : function(target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends.apply(this, arguments);
}
const Calendar = /* @__PURE__ */ (0, import_react.forwardRef)((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = (0, import_react.useContext)(import_ConfigProviderContext.default);
  const [bem] = createNamespace("calendar", prefixCls);
  const {
    type,
    title,
    showTitle,
    showSubtitle,
    firstDayOfWeek,
    minDate,
    maxDate,
    safeAreaInsetBottom,
    footer,
    showConfirm,
    className,
    style
  } = props;
  const limitDateRange = (date, minDate2 = props.minDate, maxDate2 = props.maxDate) => {
    if ((0, import_utils.compareDay)(date, minDate2) === -1) {
      return minDate2;
    }
    if ((0, import_utils.compareDay)(date, maxDate2) === 1) {
      return maxDate2;
    }
    return date;
  };
  const getInitialDate = (defaultDate = props.defaultDate) => {
    if (defaultDate === null) {
      return defaultDate;
    }
    const now = (0, import_utils.getToday)();
    if (type === "range") {
      if (!Array.isArray(defaultDate)) {
        defaultDate = [];
      }
      const start = limitDateRange(defaultDate[0] || now, minDate, (0, import_utils.getPrevDay)(maxDate));
      const end = limitDateRange(defaultDate[1] || now, (0, import_utils.getNextDay)(minDate));
      return [start, end];
    }
    if (type === "multiple") {
      if (Array.isArray(defaultDate)) {
        return defaultDate.map((date) => limitDateRange(date));
      }
      return [limitDateRange(now)];
    }
    if (!defaultDate || Array.isArray(defaultDate)) {
      defaultDate = now;
    }
    return limitDateRange(defaultDate);
  };
  const bodyRef = (0, import_react.useRef)(null);
  const bodyHeightRef = (0, import_react.useRef)(0);
  const [subtitle, setSubtitle] = (0, import_react.useState)("");
  const [currentDate, setCurrentDate] = (0, import_react.useState)(getInitialDate());
  const [monthRefs, setMonthRefs] = (0, import_use_refs.default)();
  const dayOffset = (0, import_react.useMemo)(() => firstDayOfWeek ? +firstDayOfWeek % 7 : 0, [firstDayOfWeek]);
  const monthsList = (0, import_react.useMemo)(() => {
    const months = [];
    const cursor = new Date(minDate);
    cursor.setDate(1);
    do {
      months.push(new Date(cursor));
      cursor.setMonth(cursor.getMonth() + 1);
    } while ((0, import_utils.compareMonth)(cursor, maxDate) !== 1);
    return months;
  }, [minDate, maxDate]);
  const buttonDisabled = (0, import_react.useMemo)(() => {
    if (currentDate) {
      if (props.type === "range") {
        return !currentDate[0] || !currentDate[1];
      }
      if (props.type === "multiple") {
        return !currentDate.length;
      }
    }
    return !currentDate;
  }, [props.type, currentDate]);
  const onScroll = () => {
    var _a;
    if (!bodyRef.current)
      return;
    const top = (0, import_utils2.getScrollTop)(bodyRef.current);
    const bottom = top + bodyHeightRef.current;
    const heights = monthsList.map((_, index) => monthRefs[index].getHeight());
    const heightSum = heights.reduce((a, b) => a + b, 0);
    if (bottom > heightSum && top > 0) {
      return;
    }
    let height = 0;
    let currentMonth;
    const visibleRange = [-1, -1];
    for (let i = 0; i < monthsList.length; i++) {
      const month = monthRefs[i];
      const visible = height <= bottom && height + heights[i] >= top;
      if (visible) {
        visibleRange[1] = i;
        if (!currentMonth) {
          currentMonth = month;
          visibleRange[0] = i;
        }
        if (!monthRefs[i].showed) {
          monthRefs[i].showed = true;
          (_a = props.onMonthShow) == null ? void 0 : _a.call(props, {
            date: month.date,
            title: month.getTitle()
          });
        }
      }
      height += heights[i];
    }
    monthsList.forEach((_, index) => {
      const visible = index >= visibleRange[0] - 1 && index <= visibleRange[1] + 1;
      monthRefs[index].setVisible(visible);
    });
    if (currentMonth) {
      setSubtitle(currentMonth.getTitle());
    }
  };
  const scrollToDate = (targetDate) => {
    (0, import_raf.raf)(() => {
      monthsList.some((month, index) => {
        if ((0, import_utils.compareMonth)(month, targetDate) === 0) {
          if (bodyRef.current) {
            monthRefs[index].scrollToDate(bodyRef.current, targetDate);
          }
          return true;
        }
        return false;
      });
      onScroll();
    });
  };
  const scrollToCurrentDate = (date) => {
    if (props.poppable && !props.show) {
      return;
    }
    const currentDate2 = date || getInitialDate();
    if (currentDate2) {
      const targetDate = props.type === "single" ? currentDate2 : currentDate2[0];
      scrollToDate(targetDate);
    } else {
      (0, import_raf.raf)(onScroll);
    }
  };
  const init = () => {
    if (props.poppable && !props.show) {
      return;
    }
    (0, import_raf.raf)(() => {
      bodyHeightRef.current = Math.floor((0, import_get_rect.getRect)(bodyRef.current).height);
      scrollToCurrentDate();
    });
  };
  const reset = (date = getInitialDate()) => {
    setCurrentDate(date);
    scrollToCurrentDate(date);
  };
  const onConfirm = (date) => {
    var _a;
    (_a = props.onConfirm) == null ? void 0 : _a.call(props, (0, import_utils.cloneDates)(date || currentDate));
  };
  const checkRange = (date) => {
    var _a;
    const {
      maxRange,
      rangePrompt,
      showRangePrompt
    } = props;
    if (maxRange && (0, import_utils.calcDateNum)(date) > maxRange) {
      if (showRangePrompt) {
        (0, import_toast.default)(rangePrompt || (0, import_utils.t)("rangePrompt", maxRange));
      }
      (_a = props.onOverRange) == null ? void 0 : _a.call(props);
      return false;
    }
    return true;
  };
  const select = (date, complete) => {
    const toSetCurrentDate = (date2) => {
      var _a;
      setCurrentDate(date2);
      (_a = props.onSelect) == null ? void 0 : _a.call(props, (0, import_utils.cloneDates)(date2));
    };
    if (complete && props.type === "range") {
      const valid = checkRange(date);
      if (!valid) {
        toSetCurrentDate([date[0], (0, import_utils.getDayByOffset)(date[0], +props.maxRange - 1)]);
        return;
      }
    }
    toSetCurrentDate(date);
    if (complete && !props.showConfirm) {
      onConfirm(date);
    }
  };
  const onClickDay = (item) => {
    var _a;
    if (props.readonly || !item.date) {
      return;
    }
    const {
      date
    } = item;
    const {
      type: type2
    } = props;
    if (type2 === "range") {
      if (!currentDate) {
        select([date]);
        return;
      }
      const [startDay, endDay] = currentDate;
      if (startDay && !endDay) {
        const compareToStart = (0, import_utils.compareDay)(date, startDay);
        if (compareToStart === 1) {
          select([startDay, date], true);
        } else if (compareToStart === -1) {
          select([date]);
        } else if (props.allowSameDay) {
          select([date, date], true);
        }
      } else {
        select([date]);
      }
    } else if (type2 === "multiple") {
      if (!currentDate) {
        select([date]);
        return;
      }
      const dates = currentDate;
      const selectedIndex = dates.findIndex((dateItem) => (0, import_utils.compareDay)(dateItem, date) === 0);
      if (selectedIndex !== -1) {
        const [unselectedDate] = dates.splice(selectedIndex, 1);
        (_a = props.onUnselect) == null ? void 0 : _a.call(props, (0, import_utils.cloneDate)(unselectedDate));
        setCurrentDate([...dates]);
      } else if (props.maxRange && dates.length >= props.maxRange) {
        (0, import_toast.default)(props.rangePrompt || (0, import_utils.t)("rangePrompt", props.maxRange));
      } else {
        select([...dates, date]);
      }
    } else {
      select(date, true);
    }
  };
  const renderMonth = (date, index) => {
    const showMonthTitle = index !== 0 || !props.showSubtitle;
    return /* @__PURE__ */ import_react.default.createElement(import_CalendarMonth.default, _extends({
      key: index,
      ref: setMonthRefs(index),
      date,
      currentDate,
      showMonthTitle,
      firstDayOfWeek: dayOffset
    }, (0, import_utils2.pick)(props, ["type", "color", "minDate", "maxDate", "showMark", "formatter", "rowHeight", "lazyRender", "showSubtitle", "allowSameDay"]), {
      onClick: onClickDay
    }));
  };
  const renderFooter = () => {
    const disabled = buttonDisabled;
    const text = disabled ? props.confirmDisabledText : props.confirmText;
    return /* @__PURE__ */ import_react.default.createElement("div", {
      className: (0, import_classnames.default)(bem("footer"), {
        "rc-safe-area-bottom": safeAreaInsetBottom
      })
    }, footer || (showConfirm ? /* @__PURE__ */ import_react.default.createElement(import_button.default, {
      round: true,
      block: true,
      type: "danger",
      color: props.color,
      className: (0, import_classnames.default)(bem("confirm")),
      disabled: buttonDisabled,
      nativeType: "button",
      onClick: () => onConfirm()
    }, text || "\u786E\u8BA4") : null));
  };
  const renderCalendar = () => /* @__PURE__ */ import_react.default.createElement("div", {
    className: (0, import_classnames.default)(bem(), className),
    style
  }, /* @__PURE__ */ import_react.default.createElement(import_CalendarHeader.default, {
    title,
    subtitle: props.subtitle || subtitle,
    showTitle,
    showSubtitle,
    firstDayOfWeek,
    onClickSubtitle: (event) => {
      var _a;
      (_a = props.onClickSubtitle) == null ? void 0 : _a.call(props, event);
    }
  }), /* @__PURE__ */ import_react.default.createElement("div", {
    ref: bodyRef,
    className: (0, import_classnames.default)(bem("body")),
    onScroll
  }, monthsList.map(renderMonth)), renderFooter());
  (0, import_react.useEffect)(() => {
    init();
  }, [props.show]);
  (0, import_hooks.useUpdateEffect)(() => {
    reset(getInitialDate());
  }, [props.type, props.minDate, props.maxDate]);
  (0, import_hooks.useUpdateEffect)(() => {
    setCurrentDate(props.defaultDate);
    scrollToCurrentDate();
  }, [props.defaultDate]);
  (0, import_react.useImperativeHandle)(ref, () => ({
    reset,
    scrollToDate
  }));
  return props.poppable ? /* @__PURE__ */ import_react.default.createElement(import_popup.Popup, {
    visible: props.show,
    className: (0, import_classnames.default)(bem("popup")),
    round: props.round,
    position: props.position,
    closeable: props.showTitle || props.showSubtitle,
    teleport: props.teleport,
    closeOnClickOverlay: props.closeOnClickOverlay,
    closeOnPopstate: props.closeOnPopstate,
    onClose: () => {
      var _a;
      return (_a = props.onClose) == null ? void 0 : _a.call(props);
    }
  }, renderCalendar()) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, renderCalendar());
});
Calendar.defaultProps = {
  type: "single",
  title: "\u65E5\u671F\u9009\u62E9",
  color: "#ee0a24",
  rowHeight: 64,
  poppable: true,
  lazyRender: true,
  showMark: true,
  showTitle: true,
  showSubtitle: true,
  showConfirm: true,
  showRangePrompt: true,
  readonly: false,
  firstDayOfWeek: 0,
  footer: null,
  minDate: (0, import_utils.getToday)(),
  maxDate: (() => {
    const now = (0, import_utils.getToday)();
    return new Date(now.getFullYear(), now.getMonth() + 6, now.getDate());
  })(),
  show: false,
  position: "bottom",
  round: true,
  closeOnPopstate: true,
  closeOnClickOverlay: true,
  safeAreaInsetBottom: true,
  maxRange: null,
  allowSameDay: false
};
var stdin_default = Calendar;
