         isFocused
        }));
      }
    }, {
      key: "renderMenu",
      value: function renderMenu() {
        var _this4 = this;
        var _this$getComponents7 = this.getComponents(), Group2 = _this$getComponents7.Group, GroupHeading2 = _this$getComponents7.GroupHeading, Menu2 = _this$getComponents7.Menu, MenuList2 = _this$getComponents7.MenuList, MenuPortal2 = _this$getComponents7.MenuPortal, LoadingMessage2 = _this$getComponents7.LoadingMessage, NoOptionsMessage2 = _this$getComponents7.NoOptionsMessage, Option2 = _this$getComponents7.Option;
        var commonProps = this.commonProps;
        var focusedOption = this.state.focusedOption;
        var _this$props12 = this.props, captureMenuScroll = _this$props12.captureMenuScroll, inputValue = _this$props12.inputValue, isLoading = _this$props12.isLoading, loadingMessage2 = _this$props12.loadingMessage, minMenuHeight = _this$props12.minMenuHeight, maxMenuHeight = _this$props12.maxMenuHeight, menuIsOpen = _this$props12.menuIsOpen, menuPlacement = _this$props12.menuPlacement, menuPosition = _this$props12.menuPosition, menuPortalTarget = _this$props12.menuPortalTarget, menuShouldBlockScroll = _this$props12.menuShouldBlockScroll, menuShouldScrollIntoView = _this$props12.menuShouldScrollIntoView, noOptionsMessage2 = _this$props12.noOptionsMessage, onMenuScrollToTop = _this$props12.onMenuScrollToTop, onMenuScrollToBottom = _this$props12.onMenuScrollToBottom;
        if (!menuIsOpen) return null;
        var render = function render2(props, id) {
          var type = props.type, data = props.data, isDisabled = props.isDisabled, isSelected = props.isSelected, label = props.label, value = props.value;
          var isFocused = focusedOption === data;
          var onHover = isDisabled ? void 0 : function() {
            return _this4.onOptionHover(data);
          };
          var onSelect = isDisabled ? void 0 : function() {
            return _this4.selectOption(data);
          };
          var optionId = "".concat(_this4.getElementId("option"), "-").concat(id);
          var innerProps = {
            id: optionId,
            onClick: onSelect,
            onMouseMove: onHover,
            onMouseOver: onHover,
            tabIndex: -1,
            role: "option",
            "aria-selected": _this4.state.isAppleDevice ? void 0 : isSelected
            // is not supported on Apple devices
          };
          return /* @__PURE__ */ React__namespace.createElement(Option2, _extends({}, commonProps, {
            innerProps,
            data,
            isDisabled,
            isSelected,
            key: optionId,
            label,
            type,
            value,
            isFocused,
            innerRef: isFocused ? _this4.getFocusedOptionRef : void 0
          }), _this4.formatOptionLabel(props.data, "menu"));
        };
        var menuUI;
        if (this.hasOptions()) {
          menuUI = this.getCategorizedOptions().map(function(item) {
            if (item.type === "group") {
              var _data = item.data, options2 = item.options, groupIndex = item.index;
              var groupId = "".concat(_this4.getElementId("group"), "-").concat(groupIndex);
              var headingId = "".concat(groupId, "-heading");
              return /* @__PURE__ */ React__namespace.createElement(Group2, _extends({}, commonProps, {
                key: groupId,
                data: _data,
                options: options2,
                Heading: GroupHeading2,
                headingProps: {
                  id: headingId,
                  data: item.data
                },
                label: _this4.formatGroupLabel(item.data)
              }), item.options.map(function(option) {
                return render(option, "".concat(groupIndex, "-").concat(option.index));
              }));
            } else if (item.type === "option") {
              return render(item, "".concat(item.index));
            }
          });
        } else if (isLoading) {
          var message = loadingMessage2({
            inputValue
          });
          if (message === null) return null;
          menuUI = /* @__PURE__ */ React__namespace.createElement(LoadingMessage2, commonProps, message);
        } else {
          var _message = noOptionsMessage2({
            inputValue
          });
          if (_message === null) return null;
          menuUI = /* @__PURE__ */ React__namespace.createElement(NoOptionsMessage2, commonProps, _message);
        }
        var menuPlacementProps = {
          minMenuHeight,
          maxMenuHeight,
          menuPlacement,
          menuPosition,
          menuShouldScrollIntoView
        };
        var menuElement = /* @__PURE__ */ React__namespace.createElement(MenuPlacer, _extends({}, commonProps, menuPlacementProps), function(_ref4) {
          var ref = _ref4.ref, _ref4$placerProps = _ref4.placerProps, placement = _ref4$placerProps.placement, maxHeight = _ref4$placerProps.maxHeight;
          return /* @__PURE__ */ React__namespace.createElement(Menu2, _extends({}, commonProps, menuPlacementProps, {
            innerRef: ref,
            innerProps: {
              onMouseDown: _this4.onMenuMouseDown,
              onMouseMove: _this4.onMenuMouseMove
            },
            isLoading,
            placement
          }), /* @__PURE__ */ React__namespace.createElement(ScrollManager, {
            captureEnabled: captureMenuScroll,
            onTopArrive: onMenuScrollToTop,
            onBottomArrive: onMenuScrollToBottom,
            lockEnabled: menuShouldBlockScroll
          }, function(scrollTargetRef) {
            return /* @__PURE__ */ React__namespace.createElement(MenuList2, _extends({}, commonProps, {
              innerRef: function innerRef(instance) {
                _this4.getMenuListRef(instance);
                scrollTargetRef(instance);
              },
              innerProps: {
                role: "listbox",
                "aria-multiselectable": commonProps.isMulti,
                id: _this4.getElementId("listbox")
              },
              isLoading,
              maxHeight,
              focusedOption
            }), menuUI);
          }));
        });
        return menuPortalTarget || menuPosition === "fixed" ? /* @__PURE__ */ React__namespace.createElement(MenuPortal2, _extends({}, commonProps, {
          appendTo: menuPortalTarget,
          controlElement: this.controlRef,
          menuPlacement,
          menuPosition
        }), menuElement) : menuElement;
      }
    }, {
      key: "renderFormField",
      value: function renderFormField() {
        var _this5 = this;
        var _this$props13 = this.props, delimiter2 = _this$props13.delimiter, isDisabled = _this$props13.isDisabled, isMulti = _this$props13.isMulti, name = _this$props13.name, required = _this$props13.required;
        var selectValue = this.state.selectValue;
        if (required && !this.hasValue() && !isDisabled) {
          return /* @__PURE__ */ React__namespace.createElement(RequiredInput$1, {
            name,
            onFocus: this.onValueInputFocus
          });
        }
        if (!name || isDisabled) return;
        if (isMulti) {
          if (delimiter2) {
            var value = selectValue.map(function(opt) {
              return _this5.getOptionValue(opt);
            }).join(delimiter2);
            return /* @__PURE__ */ React__namespace.createElement("input", {
              name,
              type: "hidden",
              value
            });
          } else {
            var input = selectValue.length > 0 ? selectValue.map(function(opt, i2) {
              return /* @__PURE__ */ React__namespace.createElement("input", {
                key: "i-".concat(i2),
                name,
                type: "hidden",
                value: _this5.getOptionValue(opt)
              });
            }) : /* @__PURE__ */ React__namespace.createElement("input", {
              name,
              type: "hidden",
              value: ""
            });
            return /* @__PURE__ */ React__namespace.createElement("div", null, input);
          }
        } else {
          var _value = selectValue[0] ? this.getOptionValue(selectValue[0]) : "";
          return /* @__PURE__ */ React__namespace.createElement("input", {
            name,
            type: "hidden",
            value: _value
          });
        }
      }
    }, {
      key: "renderLiveRegion",
      value: function renderLiveRegion() {
        var commonProps = this.commonProps;
        var _this$state6 = this.state, ariaSelection = _this$state6.ariaSelection, focusedOption = _this$state6.focusedOption, focusedValue = _this$state6.focusedValue, isFocused = _this$state6.isFocused, selectValue = _this$state6.selectValue;
        var focusableOptions = this.getFocusableOptions();
        return /* @__PURE__ */ React__namespace.createElement(LiveRegion$1, _extends({}, commonProps, {
          id: this.getElementId("live-region"),
          ariaSelection,
          focusedOption,
          focusedValue,
          isFocused,
          selectValue,
          focusableOptions,
          isAppleDevice: this.state.isAppleDevice
        }));
      }
    }, {
      key: "render",
      value: function render() {
        var _this$getComponents8 = this.getComponents(), Control2 = _this$getComponents8.Control, IndicatorsContainer2 = _this$getComponents8.IndicatorsContainer, SelectContainer2 = _this$getComponents8.SelectContainer, ValueContainer2 = _this$getComponents8.ValueContainer;
        var _this$props14 = this.props, className = _this$props14.className, id = _this$props14.id, isDisabled = _this$props14.isDisabled, menuIsOpen = _this$props14.menuIsOpen;
        var isFocused = this.state.isFocused;
        var commonProps = this.commonProps = this.getCommonProps();
        return /* @__PURE__ */ React__namespace.createElement(SelectContainer2, _extends({}, commonProps, {
          className,
          innerProps: {
            id,
            onKeyDown: this.onKeyDown
          },
          isDisabled,
          isFocused
        }), this.renderLiveRegion(), /* @__PURE__ */ React__namespace.createElement(Control2, _extends({}, commonProps, {
          innerRef: this.getControlRef,
          innerProps: {
            onMouseDown: this.onControlMouseDown,
            onTouchEnd: this.onControlTouchEnd
          },
          isDisabled,
          isFocused,
          menuIsOpen
        }), /* @__PURE__ */ React__namespace.createElement(ValueContainer2, _extends({}, commonProps, {
          isDisabled
        }), this.renderPlaceholderOrValue(), this.renderInput()), /* @__PURE__ */ React__namespace.createElement(IndicatorsContainer2, _extends({}, commonProps, {
          isDisabled
        }), this.renderClearIndicator(), this.renderLoadingIndicator(), this.renderIndicatorSeparator(), this.renderDropdownIndicator())), this.renderMenu(), this.renderFormField());
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(props, state) {
        var prevProps = state.prevProps, clearFocusValueOnUpdate = state.clearFocusValueOnUpdate, inputIsHiddenAfterUpdate = state.inputIsHiddenAfterUpdate, ariaSelection = state.ariaSelection, isFocused = state.isFocused, prevWasFocused = state.prevWasFocused, instancePrefix = state.instancePrefix;
        var options2 = props.options, value = props.value, menuIsOpen = props.menuIsOpen, inputValue = props.inputValue, isMulti = props.isMulti;
        var selectValue = cleanValue(value);
        var newMenuOptionsState = {};
        if (prevProps && (value !== prevProps.value || options2 !== prevProps.options || menuIsOpen !== prevProps.menuIsOpen || inputValue !== prevProps.inputValue)) {
          var focusableOptions = menuIsOpen ? buildFocusableOptions(props, selectValue) : [];
          var focusableOptionsWithIds = menuIsOpen ? buildFocusableOptionsWithIds(buildCategorizedOptions(props, selectValue), "".concat(instancePrefix, "-option")) : [];
          var focusedValue = clearFocusValueOnUpdate ? getNextFocusedValue(state, selectValue) : null;
          var focusedOption = getNextFocusedOption(state, focusableOptions);
          var focusedOptionId = getFocusedOptionId(focusableOptionsWithIds, focusedOption);
          newMenuOptionsState = {
            selectValue,
            focusedOption,
            focusedOptionId,
            focusableOptionsWithIds,
            focusedValue,
            clearFocusValueOnUpdate: false
          };
        }
        var newInputIsHiddenState = inputIsHiddenAfterUpdate != null && props !== prevProps ? {
          inputIsHidden: inputIsHiddenAfterUpdate,
          inputIsHiddenAfterUpdate: void 0
        } : {};
        var newAriaSelection = ariaSelection;
        var hasKeptFocus = isFocused && prevWasFocused;
        if (isFocused && !hasKeptFocus) {
          newAriaSelection = {
            value: valueTernary(isMulti, selectValue, selectValue[0] || null),
            options: selectValue,
            action: "initial-input-focus"
          };
          hasKeptFocus = !prevWasFocused;
        }
        if ((ariaSelection === null || ariaSelection === void 0 ? void 0 : ariaSelection.action) === "initial-input-focus") {
          newAriaSelection = null;
        }
        return _objectSpread2(_objectSpread2(_objectSpread2({}, newMenuOptionsState), newInputIsHiddenState), {}, {
          prevProps: props,
          ariaSelection: newAriaSelection,
          prevWasFocused: hasKeptFocus
        });
      }
    }]);
    return Select2;
  }(React.Component);
  Select$1.defaultProps = defaultProps;
  var StateManagedSelect = /* @__PURE__ */ React.forwardRef(function(props, ref) {
    var baseSelectProps = useStateManager(props);
    return /* @__PURE__ */ React__namespace.createElement(Select$1, _extends({
      ref
    }, baseSelectProps));
  });
  var StateManagedSelect$1 = StateManagedSelect;
  const CountryFlag = (props) => {
    const { countryId, style } = props;
    if (!countryId) return null;
    return /* @__PURE__ */ React.createElement(
      "img",
      {
        style: __spreadValues({ height: "16px", width: "23px" }, style || {}),
        src: `https://u.alicdn.com/mobile/g/common/flags/1.0.0/assets/${countryId.toLowerCase()}.png`
      }
    );
  };
  const getValue = (options2, value) => {
    if (!value) return null;
    const target = (options2 || []).reduce((buf, cur) => {
      return [...buf, ...cur.options || []];
    }, []).find((item) => item.value === value);
    return target || null;
  };
  const countryItemRender = (item) => {
    const { value, label, selectOption } = item;
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "crated-header-ship-to-country-item",
        onClick: (e2) => {
          e2.stopPropagation();
          selectOption({ label, value });
        }
      },
      /* @__PURE__ */ React.createElement(CountryFlag, { style: { marginInlineEnd: "8px", marginInlineStart: "2px" }, countryId: value }),
      label
    );
  };
  const Select = (props) => {
    const _a = props, { options: options2, value, onChange, onMenuOpen, onMenuClose } = _a, others = __objRest(_a, ["options", "value", "onChange", "onMenuOpen", "onMenuClose"]);
    const current = getValue(options2, value);
    return /* @__PURE__ */ React.createElement(
      StateManagedSelect$1,
      __spreadProps(__spreadValues({}, others), {
        options: options2,
        value: current,
        defaultValue: current,
        onChange: (target) => {
          onChange((target == null ? void 0 : target.value) || null);
        },
        onMenuOpen,
        onMenuClose,
        menuPosition: "fixed",
        components: {
          Option: (optionProps) => countryItemRender(optionProps),
          Control: (_b) => {
            var _c = _b, { children } = _c, controlProps = __objRest(_c, ["children"]);
            return /* @__PURE__ */ React.createElement(components.Control, __spreadValues({}, controlProps), value ? /* @__PURE__ */ React.createElement(CountryFlag, { style: { marginInlineStart: "14px" }, countryId: value }) : null, children);
          }
        }
      })
    );
  };
  const i18nBase = {
    Title: "Choose your location",
    Desc: "Delivery options and fees may vary based on your locations",
    SeeAll: "See all addresses",
    Add: "Add an address",
    Save: "Save",
    PopularCountry: "Popular countries/regions",
    AllCountries: "All countries/regions",
    ZipPlaceholder: "Enter city or zip",
    ShipToTitle: "Ship to: ",
    SignInTips: "Sign in to see your address"
  };
  const win = typeof window === "undefined" ? {} : window;
  const i18n = (win == null ? void 0 : win.i18n) || i18nBase;
  const i18nAllMap = {
    "ru_RU": {
      "Default": "Адрес доставки по умолчанию"
    },
    "it_IT": {
      "Default": "Indirizzo di spedizione predefinito"
    },
    "tr_TR": {
      "Default": "Varsayılan gönderim adresi"
    },
    "hi_IN": {
      "Default": "डिफ़ॉल्ट शिपिंग पता"
    },
    "th_TH": {
      "Default": "ที่อยู่จัดส่งเริ่มต้น"
    },
    "fr_FR": {
      "Default": "Adresse de livraison par défaut"
    },
    "ja_JP": {
      "Default": "デフォルトの配送先住所"
    },
    "in_ID": {
      "Default": "Alamat utama"
    },
    "de_DE": {
      "Default": "Standard-Versandadresse"
    },
    "ar_SA": {
      "Default": "عنوان الشحن الافتراضي"
    },
    "zh_TW": {
      "Default": "預設收件地址"
    },
    "es_ES": {
      "Default": "Dirección de envío predeterminada"
    },
    "nl_NL": {
      "Default": "Standaard verzendadres"
    },
    "bn_IN": {
      "Default": "##@@@ta.order.com.shippingAddressForm.tags.DEFAULT##trade-contract@@@##"
    },
    "iw_IL": {
      "Default": "כתובת ברירת מחדל למשלוח"
    },
    "vi_VN": {
      "Default": "Địa chỉ vận chuyển mặc định"
    },
    "ko_KR": {
      "Default": "기본 배송 주소"
    },
    "en_US": {
      "Default": "Default shipping address"
    },
    "zh_CN": {
      "Default": "默认收货地址"
    },
    "pt_PT": {
      "Default": "Endereço de Entrega Padrão"
    }
  };
  const lang = getLatestCookieData().language;
  const i18nMap = i18nAllMap[lang] || i18nAllMap.en_US;
  function log(key, params) {
    try {
      const { goldlog } = window;
      if (goldlog && goldlog.record) {
        const querys = Object.keys(params || {}).map((k2) => {
          return `${k2}=${params == null ? void 0 : params[k2]}`;
        });
        querys.push(`st_page_id=${window.dmtrack_pageid || ""}`);
        goldlog.record(key, "EXP", querys.join("&"));
      }
    } catch (e2) {
    }
  }
  function logSyncCookieError() {
    logError({
      api: "syncCookieShipTo",
      errorType: "JSONP"
    });
  }
  function logError(params) {
    log("/sc.sc_header_footer.error", params);
  }
  function logAdd() {
    log("/sc.sc_header_footer_ship_to.add");
  }
  function logAllAddress() {
    log("/sc.sc_header_footer_ship_to.all_address");
  }
  function logSelectItem(params) {
    log("/sc.sc_header_footer_ship_to.select", params);
  }
  function logSavetem(params) {
    log("/sc.sc_header_footer_ship_to.save", params);
  }
  function logLogin() {
    log("/sc.sc_header_footer_ship_to.login");
  }
  var fetchJsonp$1 = { exports: {} };
  (function(module2, exports$1) {
    (function(global2, factory) {
      {
        factory(exports$1, module2);
      }
    })(commonjsGlobal, function(exports$12, module3) {
      var defaultOptions = {
        timeout: 5e3,
        jsonpCallback: "callback"
      };
      function generateCallbackFunction() {
        return "jsonp_" + Date.now() + "_" + Math.ceil(Math.random() * 1e5);
      }
      function clearFunction(functionName) {
        try {
          delete window[functionName];
        } catch (e2) {
          window[functionName] = void 0;
        }
      }
      function removeScript(scriptId) {
        var script = document.getElementById(scriptId);
        if (script) {
          document.getElementsByTagName("head")[0].removeChild(script);
        }
      }
      function fetchJsonp2(_url) {
        var options2 = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1];
        var url = _url;
        var timeout = options2.timeout || defaultOptions.timeout;
        var jsonpCallback = options2.jsonpCallback || defaultOptions.jsonpCallback;
        var timeoutId = void 0;
        return new Promise(function(resolve, reject) {
          var callbackFunction = options2.jsonpCallbackFunction || generateCallbackFunction();
          var scriptId = jsonpCallback + "_" + callbackFunction;
          window[callbackFunction] = function(response) {
            resolve({
              ok: true,
              // keep consistent with fetch API
              json: function json() {
                return Promise.resolve(response);
              }
            });
            if (timeoutId) clearTimeout(timeoutId);
            removeScript(scriptId);
            clearFunction(callbackFunction);
          };
          url += url.indexOf("?") === -1 ? "?" : "&";
          var jsonpScript = document.createElement("script");
          jsonpScript.setAttribute("src", "" + url + jsonpCallback + "=" + callbackFunction);
          if (options2.charset) {
            jsonpScript.setAttribute("charset", options2.charset);
          }
          if (options2.nonce) {
            jsonpScript.setAttribute("nonce", options2.nonce);
          }
          if (options2.referrerPolicy) {
            jsonpScript.setAttribute("referrerPolicy", options2.referrerPolicy);
          }
          if (options2.crossorigin) {
            jsonpScript.setAttribute("crossorigin", "true");
          }
          jsonpScript.id = scriptId;
          document.getElementsByTagName("head")[0].appendChild(jsonpScript);
          timeoutId = setTimeout(function() {
            reject(new Error("JSONP request to " + _url + " timed out"));
            clearFunction(callbackFunction);
            removeScript(scriptId);
            window[callbackFunction] = function() {
              clearFunction(callbackFunction);
            };
          }, timeout);
          jsonpScript.onerror = function() {
            reject(new Error("JSONP request to " + _url + " failed"));
            clearFunction(callbackFunction);
            removeScript(scriptId);
            if (timeoutId) clearTimeout(timeoutId);
          };
        });
      }
      module3.exports = fetchJsonp2;
    });
  })(fetchJsonp$1, fetchJsonp$1.exports);
  var fetchJsonpExports = fetchJsonp$1.exports;
  const fetchJsonp = /* @__PURE__ */ getDefaultExportFromCjs(fetchJsonpExports);
  const Fetch_Domain = `//ug.alibaba.${getTopLevelDomain()}/`;
  function getTopLevelDomain() {
    var _a;
    const hostTemps = (_a = location == null ? void 0 : location.host) == null ? void 0 : _a.match(/(.*?).alibaba\.(.*?)$/);
    if (hostTemps && hostTemps.length >= 3) {
      return hostTemps[2];
    } else {
      return "com";
    }
  }
  const saveLocalData = (params) => {
    let fetchSaveUrl = `${Fetch_Domain}api/ship/write`;
    Object.keys(params).forEach((key) => {
      const value = params[key];
      if (value) {
        fetchSaveUrl += `${fetchSaveUrl.indexOf("?") > -1 ? "&" : "?"}${key}=${value}`;
      }
    });
    return fetchJsonp(fetchSaveUrl).then((res) => res.json()).then((res) => {
      if (res.data && res.code === 200) {
        location.reload();
      } else {
        logSyncCookieError();
      }
    }).catch(() => {
      logSyncCookieError();
    });
  };
  const queryList = () => __async(this, null, function* () {
    return fetchJsonp(`${Fetch_Domain}api/ship/queryShipToPanelAddressList?ctoken=${getCtoken()}`).then((res) => res.json()).then((res) => {
      if ((res == null ? void 0 : res.code) === 200 && res.data) {
        return res.data;
      } else {
        logError({
          api: "ajaxShipToList",
          errorType: "JSONP"
        });
      }
    }).catch(() => {
      logError({
        api: "ajaxShipToList",
        errorType: "JSONP"
      });
    });
  });
  const queryCountryCurrency = () => __async(this, null, function* () {
    return fetchJsonp(`${Fetch_Domain}api/ship/read`).then((res) => res.json()).then((res) => res.data);
  });
  function ShipTo({
    localData,
    onVisibleChange,
    i18n: propsI18N,
    onMenuStateChange
  }) {
    var _a;
    const i18n$1 = propsI18N || i18n;
    const popupRef = React.useRef(null);
    const [loading, setLoading] = React.useState(true);
    const [isLogin, setIsLogin] = React.useState(false);
    const [list, setList] = React.useState([]);
    const [selectAddressId, setSelectAddressId] = React.useState(-1);
    const [defaultAddress, setDefaultAddressId] = React.useState(-1);
    const [countryDataSource, setCountryDataSource] = React.useState([]);
    const [zip, setZip] = React.useState("");
    const [country, setCountry] = React.useState(null);
    const [isInvalid, setIsInvalid] = React.useState(false);
    const [addressInvalid, setAddressInvalid] = React.useState(false);
    const [countryInvalid, setCountryInvalid] = React.useState(false);
    const isValidList = Array.isArray(list) && list.length > 0;
    React.useEffect(() => {
      initLocalData();
      initAddressList();
    }, [localData]);
    const onSelectItem = (item) => {
      setSelectAddressId(item.appAddressId);
      setCountry(null);
      setZip("");
      logSelectItem({
        country: item.appCountry,
        zip: item.appZipCode
      });
      setAddressInvalid(false);
      setCountryInvalid(false);
    };
    const onSave = () => __async(this, null, function* () {
      if (!country && selectAddressId === -1) {
        setCountryInvalid(true);
        return;
      }
      if (isInvalid || addressInvalid) return;
      setLoading(true);
      let params = {
        localCountry: null
      };
      if (selectAddressId === -1) {
        params = {
          localCountry: country,
          localZipCode: zip
        };
      } else {
        const target = list.find((item) => item.appAddressId === selectAddressId);
        if (target) {
          params = {
            localCountry: target.appCountry,
            localZipCode: target.appZipCode,
            localAddressId: target.appAddressId
          };
        }
      }
      if (selectAddressId === -1 && !params.localCountry && !params.localZipCode) return;
      yield saveLocalData(params);
      setLoading(false);
      logSavetem(params);
      onVisibleChange == null ? void 0 : onVisibleChange(false);
    });
    const handleLogin = () => {
      var _a2, _b;
      const xman = (_a2 = window.loadXman) == null ? void 0 : _a2.call(window, {
        signInSuccess: () => {
        }
      });
      if (xman) {
        (_b = xman.show) == null ? void 0 : _b.call(xman);
      } else {
        window.open("https://login.alibaba.com?tracelog=purchase_cart");
      }
      logLogin();
    };
    const handleCountryChange = (nextCountry) => {
      setCountry(nextCountry);
      setSelectAddressId(-1);
      setAddressInvalid(false);
      setCountryInvalid(false);
    };
    const handleZipChange = (e2) => {
      setZip(e2.target.value);
      setSelectAddressId(-1);
      setAddressInvalid(false);
    };
    const formatCountryItem = function(item) {
      const { code, name } = item;
      return __spreadProps(__spreadValues({}, item), {
        label: name,
        value: code
      });
    };
    const initLocalData = () => __async(this, null, function* () {
      const {
        countryModule,
        currentlySelectedLocalCountry = DEFAULT_COUNTRY,
        currentlySelectedLocalAddressId,
        currentlySelectedLocalZipCode = ""
      } = localData || (yield queryCountryCurrency()) || {};
      handleSetCountryList(countryModule);
      if (!currentlySelectedLocalAddressId) {
        setCountry(currentlySelectedLocalCountry);
        setZip(currentlySelectedLocalZipCode);
      }
    });
    const initAddressList = () => __async(this, null, function* () {
      var _a2, _b;
      const loginRes = getIsLoggedIn();
      setIsLogin(loginRes);
      if (loginRes) {
        let addressList = [];
        if ((_a2 = window == null ? void 0 : window.headerShipToAddressData) == null ? void 0 : _a2.addressList) {
          addressList = (_b = window == null ? void 0 : window.headerShipToAddressData) == null ? void 0 : _b.addressList;
        } else {
          const listRes = yield queryList();
          window.headerShipToAddressData = listRes;
          addressList = (listRes == null ? void 0 : listRes.addressList) || [];
        }
        setList(addressList || []);
        addressList.forEach((item) => {
          if (item.selected) setSelectAddressId(item.appAddressId);
          if (item.isDefault) setDefaultAddressId(item.appAddressId);
        });
        preConnect("https://logistics.alibaba.com");
      }
      setLoading(false);
    });
    const handleSetCountryList = (countryModule) => {
      const countryList = [];
      const { popularCountryList, allCountryList } = countryModule || {};
      if (popularCountryList == null ? void 0 : popularCountryList.length) {
        countryList.push({
          label: i18n$1.PopularCountry,
          options: popularCountryList.map(
            formatCountryItem
          )
        });
      }
      if (allCountryList == null ? void 0 : allCountryList.length) {
        countryList.push({
          label: i18n$1.AllCountries,
          options: allCountryList.filter((allItem) => {
            return !(popularCountryList || []).some(
              (popularItem) => popularItem.code === allItem.code
            );
          }).map(formatCountryItem)
        });
      }
      setCountryDataSource(countryList);
    };
    return /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to" }, /* @__PURE__ */ React.createElement("b", { className: "crated-header-ship-to-title" }, i18n$1.Title), /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-desc" }, i18n$1.Desc), loading && isLogin ? /* @__PURE__ */ React.createElement(Loading, null) : null, !isLogin ? /* @__PURE__ */ React.createElement("a", { className: "crated-header-ship-to-sign-in", "data-role": "sign-in", onClick: handleLogin }, i18n$1.SignInTips) : /* @__PURE__ */ React.createElement(React.Fragment, null, (_a = list == null ? void 0 : list.slice(0, 3)) == null ? void 0 : _a.map((item) => {
      return /* @__PURE__ */ React.createElement("div", { className: "address-item-container", key: item.appAddressId }, /* @__PURE__ */ React.createElement(
        "div",
        {
          "data-id": `${item.appAddressId}`,
          className: `crated-header-ship-to-item ${item.appAddressId === selectAddressId ? "current" : ""}`,
          onClick: () => {
            onSelectItem(item);
          }
        },
        /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("b", null, item.contactName, " "), item.displayAddress)),
        item.appAddressId === defaultAddress ? /* @__PURE__ */ React.createElement("span", { className: "crated-header-ship-to-item-default" }, i18nMap.Default) : null,
        addressInvalid && item.appAddressId === selectAddressId && /* @__PURE__ */ React.createElement("span", { className: "ship-to-invalid-span", style: { marginTop: "12px" } }, /* @__PURE__ */ React.createElement("img", { src: "https://img.alicdn.com/imgextra/i3/O1CN01hhrXZV29AQ9C7DoXD_!!6000000008027-2-tps-32-32.png" }), i18n$1[`sctnh.header_shipto_address_invalid_${item.appCountry}`] || i18n$1["sctnh.header_shipto_address_invalid"] || 'Invalid ZIP code. Example of the correct format: "1000".Please type in a new zip code below.')
      ));
    }), isValidList && /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-action-container" }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: VALID_LIST_URL,
        target: "_blank",
        role: "see-all-address",
        className: "crated-header-ship-to-action",
        onClick: logAllAddress,
        rel: "noreferrer"
      },
      i18n$1.SeeAll
    ), /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-separator" }), /* @__PURE__ */ React.createElement(
      "a",
      {
        href: VALID_ADD_URL,
        target: "_blank",
        role: "add-address",
        className: "crated-header-ship-to-action",
        onClick: logAdd,
        rel: "noreferrer"
      },
      i18n$1.Add
    ))), !isValidList && isLogin ? /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-no-data-container", style: { marginTop: "12px" } }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: VALID_ADD_URL,
        target: "_blank",
        role: "add-address",
        className: "crated-header-ship-to-action-btn",
        onClick: logAdd,
        rel: "noreferrer"
      },
      i18n$1.Add
    )) : null, /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-dash-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-dash-line" }), /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-dash-line-text-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-dash-line-text" }, i18n$1["sctnh.header_shipto_or"] || "Or"))), /* @__PURE__ */ React.createElement(
      Select,
      {
        value: country,
        onChange: handleCountryChange,
        className: `ship-to-country ${countryInvalid ? "invalid-country" : ""}`,
        placeholder: i18n$1["sctnh.header_shipto_select_empty"] || "Enter keyword to search.",
        options: countryDataSource,
        onMenuOpen: () => {
          onMenuStateChange == null ? void 0 : onMenuStateChange(true);
        },
        onMenuClose: () => {
          setTimeout(() => {
            onMenuStateChange == null ? void 0 : onMenuStateChange(false);
          }, 100);
        }
      }
    ), countryInvalid && /* @__PURE__ */ React.createElement(
      "span",
      {
        className: "ship-to-invalid-span",
        style: { marginTop: "14px", display: "block", marginBottom: "-7px" }
      },
      i18n$1["sctnh.header_shipto_country_empty"] || "Please select a country"
    ), /* @__PURE__ */ React.createElement("div", { id: "ship-to-popup", ref: popupRef }), /* @__PURE__ */ React.createElement(
      Input$2,
      {
        value: zip,
        country,
        onChange: handleZipChange,
        isInvalid,
        setIsInvalid,
        className: "ship-to-zip",
        i18n: i18n$1
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "crated-header-ship-to-action-main" }, /* @__PURE__ */ React.createElement("button", { "data-role": "save", onClick: onSave }, i18n$1.Save)));
  }
  exports2.ShipTo = ShipTo;
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
});
Ә