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_utils = require("../utils");
var import_hooks = require("../hooks");
var import_icon = __toESM(require("../icon"));
var import_tabs = __toESM(require("../tabs"));
var import_ConfigProviderContext = __toESM(require("../config-provider/ConfigProviderContext"));
var import_use_mounted_ref = __toESM(require("../hooks/use-mounted-ref"));
const INITIAL_STATE = {
  tabs: [],
  activeTab: 0
};
const Cascader = (props) => {
  const {
    prefixCls,
    createNamespace
  } = (0, import_react.useContext)(import_ConfigProviderContext.default);
  const [bem] = createNamespace("cascader", prefixCls);
  const [internalValue, setInternalValue] = (0, import_react.useState)(void 0);
  const [state, updateState] = (0, import_hooks.useSetState)(INITIAL_STATE);
  const mountedRef = (0, import_use_mounted_ref.default)();
  const {
    text: textKey,
    value: valueKey,
    children: childrenKey
  } = (0, import_utils.extend)({
    text: "text",
    value: "value",
    children: "children"
  }, props.fieldNames);
  const getSelectedOptionsByValue = (options, value) => {
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      if (option[valueKey] === value) {
        return [option];
      }
      if (option[childrenKey]) {
        const selectedOptions = getSelectedOptionsByValue(option[childrenKey], value);
        if (selectedOptions) {
          return [option, ...selectedOptions];
        }
      }
    }
    return void 0;
  };
  const updateTabs = () => {
    if (internalValue || internalValue === 0) {
      const selectedOptions = getSelectedOptionsByValue(props.options, internalValue);
      if (selectedOptions) {
        let optionsCursor = props.options;
        const tabs = selectedOptions.map((option) => {
          const tab = {
            options: optionsCursor,
            selectedOption: option
          };
          const next = optionsCursor.find((item) => item[valueKey] === option[valueKey]);
          if (next) {
            optionsCursor = next[childrenKey];
          }
          return tab;
        });
        if (optionsCursor) {
          tabs.push({
            options: optionsCursor,
            selectedOption: null
          });
        }
        updateState({
          tabs
        });
        setTimeout(() => {
          if (mountedRef.current) {
            updateState({
              activeTab: tabs.length - 1
            });
          }
        }, 0);
        return;
      }
    }
    updateState({
      tabs: [{
        options: props.options,
        selectedOption: null
      }]
    });
  };
  const onSelect = (option, tabIndex) => {
    var _a, _b;
    if (option.disabled) {
      return;
    }
    let tabs = JSON.parse(JSON.stringify(state.tabs));
    tabs[tabIndex].selectedOption = option;
    if (tabs.length > tabIndex + 1) {
      tabs = tabs.slice(0, tabIndex + 1);
    }
    if (option[childrenKey]) {
      const nextTab = {
        options: option[childrenKey],
        selectedOption: null
      };
      if (tabs[tabIndex + 1]) {
        tabs[tabIndex + 1] = nextTab;
      } else {
        tabs.push(nextTab);
      }
      updateState({
        tabs,
        activeTab: state.activeTab + 1
      });
    }
    const selectedOptions = tabs.map((tab) => tab.selectedOption).filter(Boolean);
    const eventParams = {
      value: option[valueKey],
      tabIndex,
      selectedOptions
    };
    setInternalValue(option[valueKey]);
    (_a = props.onChange) == null ? void 0 : _a.call(props, eventParams);
    if (!option[childrenKey]) {
      (_b = props.onFinish) == null ? void 0 : _b.call(props, eventParams);
    }
  };
  const onClose = () => {
    var _a;
    return (_a = props.onClose) == null ? void 0 : _a.call(props);
  };
  const onClickTab = ({
    name,
    title
  }) => {
    var _a;
    updateState({
      activeTab: +name
    });
    (_a = props.onClickTab) == null ? void 0 : _a.call(props, +name, title);
  };
  const getStateFromValue = (value) => {
    if (!value || !value.length)
      return INITIAL_STATE;
    try {
      const initialState = {
        activeTab: value.length - 1,
        tabs: []
      };
      value.reduce((options, v) => {
        const selectedOption = options.find((tabs) => tabs[valueKey] === v);
        if (!selectedOption) {
          throw Error("Cascader: unable to match options correctly, Please check value or defaultValue props.");
        }
        initialState.tabs.push({
          options,
          selectedOption
        });
        return selectedOption[childrenKey];
      }, props.options);
      return initialState;
    } catch (error) {
      console.error(error);
      return INITIAL_STATE;
    }
  };
  const renderCloseIcon = () => {
    if (!props.closeable)
      return null;
    if (typeof props.closeIcon === "string") {
      return /* @__PURE__ */ import_react.default.createElement(import_icon.default, {
        name: props.closeIcon,
        className: (0, import_classnames.default)(bem("close-icon")),
        onClick: onClose
      });
    }
    if (/* @__PURE__ */ (0, import_react.isValidElement)(props.closeIcon)) {
      return props.closeIcon;
    }
    return null;
  };
  const renderHeader = () => /* @__PURE__ */ import_react.default.createElement("div", {
    className: (0, import_classnames.default)(bem("header"))
  }, /* @__PURE__ */ import_react.default.createElement("h2", {
    className: (0, import_classnames.default)(bem("title"))
  }, props.title), renderCloseIcon());
  const renderOption = (option, selectedOption, tabIndex) => {
    const selected = selectedOption && option[valueKey] === selectedOption[valueKey];
    const color = option.color || (selected ? props.activeColor : void 0);
    const Text = props.optionRender ? props.optionRender({
      option,
      selected
    }) : /* @__PURE__ */ import_react.default.createElement("span", null, option[textKey]);
    return /* @__PURE__ */ import_react.default.createElement("li", {
      key: option[valueKey],
      className: (0, import_classnames.default)(bem("option", {
        selected,
        disabled: option.disabled
      }), option.className),
      style: {
        color
      },
      onClick: () => onSelect(option, tabIndex)
    }, Text, selected ? /* @__PURE__ */ import_react.default.createElement(import_icon.default, {
      name: "success",
      className: (0, import_classnames.default)(bem("selected-icon"))
    }) : null);
  };
  const renderOptions = (options, selectedOption, tabIndex) => /* @__PURE__ */ import_react.default.createElement("ul", {
    key: tabIndex,
    className: (0, import_classnames.default)(bem("options"))
  }, options.map((option) => renderOption(option, selectedOption, tabIndex)));
  const renderTab = (tab, tabIndex) => {
    const {
      options,
      selectedOption
    } = tab;
    const title = selectedOption ? selectedOption[textKey] : props.placeholder || "\u8BF7\u9009\u62E9";
    return /* @__PURE__ */ import_react.default.createElement(import_tabs.default.TabPane, {
      key: tabIndex,
      title,
      titleClass: (0, import_classnames.default)(bem("tab", {
        unselected: !selectedOption
      }))
    }, renderOptions(options, selectedOption, tabIndex));
  };
  const renderTabs = () => /* @__PURE__ */ import_react.default.createElement(import_tabs.default, {
    animated: true,
    active: state.activeTab,
    className: (0, import_classnames.default)(bem("tabs")),
    color: props.activeColor,
    swipeThreshold: 0,
    swipeable: props.swipeable,
    onClickTab
  }, state.tabs.map(renderTab));
  (0, import_react.useEffect)(() => {
    updateTabs();
  }, [JSON.stringify(props.options)]);
  (0, import_react.useEffect)(() => {
    var _a;
    const value = (_a = props.value) != null ? _a : props.defaultValue;
    if (!value || Array.isArray(value) && !value.length)
      return;
    const initialState = getStateFromValue(value);
    updateState(initialState);
  }, []);
  (0, import_hooks.useUpdateEffect)(() => {
    const initialState = getStateFromValue(props.value);
    updateState(initialState);
  }, [props.value]);
  (0, import_hooks.useUpdateEffect)(() => {
    if (internalValue || internalValue === 0) {
      const values = state.tabs.map((tab) => {
        var _a;
        return (_a = tab.selectedOption) == null ? void 0 : _a[valueKey];
      });
      if (values.includes(internalValue)) {
        return;
      }
    }
    updateTabs();
  }, [internalValue]);
  return /* @__PURE__ */ import_react.default.createElement("div", {
    className: (0, import_classnames.default)(bem())
  }, renderHeader(), state.tabs.length ? renderTabs() : null);
};
Cascader.defaultProps = {
  closeable: true,
  swipeable: true,
  options: [],
  closeIcon: "cross"
};
var stdin_default = Cascader;
