var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { h } from '@stencil/core';
import { MapToComponentField, MapToComponentMethod, VegaSlimmer } from 'vega-slimmer/core';
import { DomNodeSubjectObserverFactory } from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaChange } from '../../../../helpers/event-manager/event-id/vega-event-id';
import { VegaInternalIconManager } from '../../../../helpers/icon/internal-icon-manager';
import { getCountryCallingCode } from '../../../../polyfill/libphonenumber';
import { COUNTRIES } from '../../assets/countries';
import remoteInvocationRegistry from '../../../../helpers/remote-invocation/remote-invocation-registry';
import { VegaDropdownRenderItemInternalOverridden, VegaInputSelectRenderPrefixIconInternalOverridden, } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import domNodeSubjectFactory from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { FeatureFlag } from '../../../../helpers/feature-control/feature-flag-controller';
export class CountrySelectRenderer extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.valueUpdatedByCountryCodeChange = false;
    /**
     * The `openSelectDropdown` function is an arrow function that is defined within the
     * `CountrySelectRenderer` class. It is responsible for triggering the `doOpen` method on the
     * `inputSelectRef` element, which is a reference to the HTMLVegaInputSelectElement.
     */
    this.openSelectDropdown = () => {
      void this.inputSelectRef.doOpen();
    };
    /**
     * This `renderDropdownItem` function is responsible for rendering a dropdown item for a specific country in
     * the `VegaInputPhoneNumberCountryCodeRenderer` component.
     */
    this.renderDropdownItem = (item, fixHeight) => {
      return (h("vega-dropdown-item", { height: fixHeight, label: item.label, itemKey: item.key, key: item.key },
        h("vega-flex", { alignItems: "center", gap: "size-12" },
          h("vega-flag-icon", { country: item.key }),
          h("vega-font", { variant: "font-field-value", color: "text-primary" }, COUNTRIES[item.key]),
          h("vega-font", { variant: "font-field-value", color: "text-primary" }, `(${item.label})`))));
    };
    /**
     * The `private customCountriesFilter` function is a custom filter function used to filter out
     * countries based on the `countries` property of the `CountrySelectController` class.
     *
     * @param {VegaCountryType} countryType - the country to be filtered
     * @returns {boolean} the boolean return value
     */
    this.customCountriesFilter = (countryType) => {
      return this.allowedCountryCodes.includes(countryType.countryCode);
    };
  }
  /**
   * The function `watchCountryCode` emits an event with the calling code, country code, and name of the
   * selected country.
   *
   * @param {VegaCountryCode} newCountryCode - The `newCountryCode` parameter in the `watchCountryCode` function is
   * of type `VegaCountryCode`. It is used to specify the country for which the function will perform
   * some actions, such as emitting an event with information about the country like calling code, name,
   * and the country code itself.
   */
  watchCountryCode(newCountryCode) {
    this.countryChangeEventEmitter.emit({
      callingCode: getCountryCallingCode(newCountryCode),
      countryCode: newCountryCode,
      name: CountrySelectRenderer.allCountries[newCountryCode],
    });
  }
  /**
   * set valueUpdatedByCountryCodeChange
   *
   * @param {boolean} valueUpdatedByCountryCodeChange state of valueUpdatedByCountryCodeChange
   */
  setValueUpdatedByCountryCodeChange(valueUpdatedByCountryCodeChange) {
    this.valueUpdatedByCountryCodeChange = valueUpdatedByCountryCodeChange;
  }
  /**
   * get valueUpdatedByCountryCodeChange
   */
  getValueUpdatedByCountryCodeChange() {
    return this.valueUpdatedByCountryCodeChange;
  }
  /**
   * The `render()` method in the `VegaInputPhoneNumberCountryCodeRenderer` class is responsible for
   * rendering the JSX structure of the component. Here's a breakdown of what it is doing:
   */
  render() {
    const countries = this.getCountrySelectOptions();
    return (h("vega-box", null,
      h("vega-input-select", { source: countries.map((country) => ({
          id: country.countryCode,
          displayName: `+${country.callingCode}`,
        })), vegaDropdownProps: {
          isScreenPosition: FeatureFlag.isEnabled('VEGA_INPUT_PHONE_NUMBER.ENABLE_CALCULATION_POSITION_BY_SCREEN'),
          matchTargetWidth: false,
          size: this.estimateMaxWidthOfCountries(countries),
        }, size: this.size, prefixIcon: VegaInternalIconManager.getIconKey(this.countryCode), disabled: this.disabled, placeholder: "", ref: (inputSelect) => {
          this.inputSelectRef = inputSelect;
          DomNodeSubjectObserverFactory.addUniqueObserverToNode(inputSelect, VegaChange, 
          /*
           * The below method is e2e-test covered in
           * @see{module:vega-input-phone-number-country-select-change}
           */
          /* istanbul ignore next */
          (e) => {
            this.handleCountrySelectChange(e.detail);
          });
          remoteInvocationRegistry.register(domNodeSubjectFactory.getSubject(this.host, VegaDropdownRenderItemInternalOverridden), this.renderDropdownItem.bind(this));
          remoteInvocationRegistry.register(domNodeSubjectFactory.getSubject(this.host, VegaInputSelectRenderPrefixIconInternalOverridden), this.renderDropdownPrefixIconWithFlagIcon.bind(this));
        }, value: this.countryCode })));
  }
  renderDropdownPrefixIconWithFlagIcon(prefixIcon) {
    return h("vega-flag-icon", { country: prefixIcon.split(' ')[1] });
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-input-phone-number-country-select-change}
   */
  /* istanbul ignore next */
  /**
   *The `handleCountrySelectChange` method in the `CountrySelectRenderer` class is a private function
   *that is responsible for handling the change event when a country is selected in the input select
   *element of the component. Here's a breakdown of what it is doing:
   */
  handleCountrySelectChange(countryCode) {
    this.valueUpdatedByCountryCodeChange = true;
    this.countrySelectController.setCountryCode(countryCode);
    if (this.valueController.shouldSetEmptyValue(this.phoneNumberInputValue)) {
      this.valueController.setValue('');
    }
    else {
      this.valueController.setValue(`+${getCountryCallingCode(countryCode)}` + this.phoneNumberInputValue.replace(/\D/g, ''));
    }
    this.valueUpdatedByCountryCodeChange = false;
  }
  /**
   * The function `getCountrySelectOptions` returns an array of country options based on custom and
   * search filters.
   *
   * @returns {VegaCountryType[]} An array of `VegaCountryType` objects that have passed through the `customCountriesFilter` and
   * `countrySearchFilter` filters.
   */
  getCountrySelectOptions() {
    return this.constructCountryArray(CountrySelectRenderer.allCountries).filter(this.customCountriesFilter);
  }
  /**
   * The function constructCountryArray takes a list of country names and returns an array of country
   * objects with calling codes, country codes, and names.
   *
   * @param {VegaCountryNameType} countries - The `countries` parameter is of type
   * `VegaCountryNameType`, which is an object containing country names with their corresponding country
   * codes.
   * @returns {VegaCountryType[]} An array of objects of type `VegaCountryType` is being returned. Each object in the array
   * contains the properties `callingCode`, `countryCode`, and `name`. The values for these properties
   * are obtained by mapping over the keys of the `countryNames` object and calling the
   * `getCountryCallingCode` function with the country code as an argument.
   */
  constructCountryArray(countries) {
    return Object.keys(countries).map((country) => ({
      callingCode: getCountryCallingCode(country),
      countryCode: country,
      name: countries[country],
    }));
  }
  estimateMaxWidthOfCountries(countries) {
    const maxLength = Math.max(...countries.map((country) => country.name.length));
    // 162 is extra element width in dropdown-item, includes checked icon, country icon, country calling code,
    //   and gap of item, padding of item.
    return maxLength * 8.5 + 162;
  }
}
CountrySelectRenderer.allCountries = COUNTRIES;
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "size", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "disabled", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "countryCode", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "allowedCountryCodes", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "countrySelectController", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "countryChangeEventEmitter", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "valueController", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "phoneNumberInputValue", void 0);
__decorate([
  MapToComponentField()
], CountrySelectRenderer.prototype, "value", void 0);
__decorate([
  MapToComponentMethod('watchCountryCode')
], CountrySelectRenderer.prototype, "watchCountryCode", null);
