;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "c00ad18b-64ec-420e-9f77-feb3be53174a", e._sentryDebugIdIdentifier = "sentry-dbid-c00ad18b-64ec-420e-9f77-feb3be53174a");
  } catch (e) {
  }
}
;
import { jsx, jsxs } from "preact/jsx-runtime";
import { useState, useEffect } from "preact/hooks";
import { useQuery } from "@tanstack/preact-query";
import { b as useApiContext, k as httpGet, a7 as noop, u as useTranslation, aa as useI18nContext, v as useExperimentsContext, p as useAnalyticsContext, a0 as CountryCodes, z as Typography, a3 as createLogger } from "./StoreProvider-CqQrndhS.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { L as List } from "./List-BAzyC6sw.js";
import { S as Spacer } from "./Spacer-BK3jDget.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { S as StackLayout } from "./unincorporated-partnership-MeN1dp53.js";
import { I as InputText } from "./InputText-DRSK56ma.js";
import { M as MaskedInput, m as makeMask, n as numericInputs, a as nonInputs } from "./MaskedInput-DgjlsFWR.js";
import { J as JP_ADDRESS_REQUIRED_FIELDS } from "./jpAddressSchema-DEOyz9Yo.js";
import { h as addressValidationRulesV4, j as addressValidationRules } from "./Address-DMDTO9vd.js";
import { u as useDebouncedCallback } from "./debouncedInputEvent-Cv2S512Y.js";
import { c as convertFullToHalf } from "./TextArea-DR0WD0kF.js";
import { t as toFullWidth } from "./mapJpAddressSchemaToAddressLocalizations-C9oJGksz.js";
const retrieveFromPostcodeJp = async (legalEntityId, baseUrl, postalCode) => httpGet({
  baseUrl,
  path: `legalEntities/${legalEntityId}/addresses/jp/${postalCode}`
});
const useRetrieveFromPostcodeJp = (postalCode, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["retrieveAddress", postalCode],
    queryFn: () => retrieveFromPostcodeJp(rootLegalEntityId.value, baseUrl.value, postalCode),
    retry: false,
    ...options
  });
};
const jpField = "adyen-kyc-jp-field";
const styles = {
  jpField
};
const ReadonlyTextField = ({ name, label, value }) => /* @__PURE__ */ jsx(Field, { name, label, className: styles.jpField, children: (innerProps) => /* @__PURE__ */ jsx(InputText, { ...innerProps, name, type: "text", value, onInput: noop, readonly: true }) });
const logger = createLogger();
const JpAddress = ({
  addressType,
  data: dataProp,
  handleFieldChange,
  errors: propErrors,
  valid: propValid,
  fieldValidationErrors: propFieldValidationErrors,
  onChange
}) => {
  const { t } = useTranslation("common");
  const { i18n } = useI18nContext();
  const { isExperimentEnabled } = useExperimentsContext();
  const userEvents = useAnalyticsContext();
  const form = useForm({
    schema: JP_ADDRESS_REQUIRED_FIELDS,
    defaultData: dataProp,
    rules: isExperimentEnabled("StrictNameAndAddressValidationV4") ? addressValidationRulesV4(CountryCodes.Japan, i18n) : addressValidationRules(CountryCodes.Japan),
    fieldProblems: propFieldValidationErrors
  });
  let {
    handleChangeFor,
    data: formData,
    errors: formErrors,
    valid: formValid,
    fieldProblems: formFieldProblems
  } = form;
  const { isValid: formIsValid } = form;
  if (handleFieldChange) {
    handleChangeFor = handleFieldChange;
    formData = dataProp ?? {};
    formErrors = propErrors;
    formValid = propValid;
    formFieldProblems = propFieldValidationErrors;
  }
  const [postcodeToSearch, setPostcodeToSearch] = useState(formData.postalCode ?? "");
  const debouncedSetPostcodeToSearch = useDebouncedCallback(setPostcodeToSearch, 1e3);
  const retrieveFromPostcodeQuery = useRetrieveFromPostcodeJp(postcodeToSearch, {
    enabled: postcodeToSearch !== ""
  });
  useEffect(() => {
    if (retrieveFromPostcodeQuery.error) {
      logger.error(retrieveFromPostcodeQuery.error.message);
      handleChangeFor("jaHaniStateOrProvince")(void 0);
      handleChangeFor("jaHaniCity")(void 0);
      handleChangeFor("jaKanaStateOrProvince")(void 0);
      handleChangeFor("jaKanaCity")(void 0);
      handleChangeFor("stateOrProvince")(void 0);
      handleChangeFor("city")(void 0);
      return;
    }
    if (!retrieveFromPostcodeQuery.data) return;
    userEvents.addPageEvent("Success", {
      actionType: "select",
      actionLevel: "field",
      returnType: "backend",
      returnValue: "retrieveAddress"
    });
    const scriptResults = retrieveFromPostcodeQuery.data.multilocale;
    if (!scriptResults) return;
    const jaHani = scriptResults.find((script) => script.locale === "ja-Hani");
    const jaKana = scriptResults.find((script) => script.locale === "ja-Kana");
    const en = scriptResults.find((script) => script.locale === "en");
    if (jaHani) {
      handleChangeFor("jaHaniStateOrProvince")(jaHani.stateOrProvince);
      handleChangeFor("jaHaniCity")(jaHani.city);
    }
    if (jaKana) {
      handleChangeFor("jaKanaStateOrProvince")(jaKana.stateOrProvince);
      handleChangeFor("jaKanaCity")(jaKana.city);
    }
    if (en) {
      handleChangeFor("stateOrProvince")(en.stateOrProvince);
      handleChangeFor("city")(en.city);
    }
  }, [retrieveFromPostcodeQuery.data, retrieveFromPostcodeQuery.error, userEvents]);
  useEffect(() => {
    onChange?.({
      schema: JP_ADDRESS_REQUIRED_FIELDS,
      data: {
        ...formData,
        country: CountryCodes.Japan
      },
      errors: formErrors,
      valid: formValid,
      fieldProblems: formFieldProblems,
      isValid: formIsValid
    });
  }, [formData, formErrors, formFieldProblems, formIsValid, formValid]);
  const handleOtherAddressInformationFullWidth = {
    input: (e) => {
      handleChangeFor("otherAddressInformationFullWidth", "input")(e);
      handleChangeFor(
        "otherAddressInformation",
        "input"
      )({
        ...e,
        target: {
          ...e.target,
          value: convertFullToHalf(e.target.value)
        }
      });
    },
    blur: (e) => {
      handleChangeFor("otherAddressInformationFullWidth", "blur")(e);
      handleChangeFor(
        "otherAddressInformation",
        "blur"
      )({
        ...e,
        target: {
          ...e.target,
          value: convertFullToHalf(e.target.value)
        }
      });
    }
  };
  return /* @__PURE__ */ jsxs("fieldset", { children: [
    /* @__PURE__ */ jsx(Typography, { el: "legend", variant: "title", children: t(($) => $[addressType]) }),
    /* @__PURE__ */ jsx(
      MaskedInput,
      {
        name: "postalCode",
        type: "text",
        label: t(($) => $.postalCode),
        value: formData.postalCode ?? "",
        isValid: formValid.postalCode,
        errorMessage: formErrors.postalCode?.errorMessage ?? formErrors.postalCode?.hasError,
        onInput: (value) => {
          handleChangeFor("postalCode", "input")(value);
          debouncedSetPostcodeToSearch(value);
        },
        onBlur: handleChangeFor("postalCode", "blur"),
        mask: makeMask(...numericInputs(3), ...nonInputs(" - "), ...numericInputs(4)),
        formatGuidance: t(($) => $.enterNDigitsForExample, {
          numDigits: "7",
          example: "530-0001"
        })
      }
    ),
    /* @__PURE__ */ jsxs(StackLayout, { gap: "medium", children: [
      /* @__PURE__ */ jsx(List, { dividers: false, variant: "grouped-primary", children: /* @__PURE__ */ jsxs("fieldset", { children: [
        /* @__PURE__ */ jsx(Typography, { el: "legend", variant: "body-strongest", children: t(($) => $.kanjiAddress) }),
        /* @__PURE__ */ jsxs(StackLayout, { horizontal: true, children: [
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "jaHaniStateOrProvince",
              label: t(($) => $.prefecture),
              value: formData.jaHaniStateOrProvince
            }
          ),
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "jaHaniCity",
              label: t(($) => $.districtTownAreaCityWard),
              value: formData.jaHaniCity
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(StackLayout, { horizontal: true, children: [
          /* @__PURE__ */ jsx(
            Field,
            {
              className: styles.jpField,
              name: "otherAddressInformationFullWidth",
              label: t(($) => $.chomeAndBanchi),
              isValid: formValid.otherAddressInformation,
              errorMessage: formErrors.otherAddressInformation?.errorMessage ?? formErrors.otherAddressInformation?.hasError,
              children: (childProps) => /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  value: formData.otherAddressInformationFullWidth ?? toFullWidth(formData.otherAddressInformation ?? ""),
                  onInput: handleOtherAddressInformationFullWidth.input,
                  onBlur: handleOtherAddressInformationFullWidth.blur,
                  transformInput: (value) => toFullWidth(value),
                  transformMode: "blur"
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(Spacer, {})
        ] }),
        /* @__PURE__ */ jsx(
          Field,
          {
            className: styles.jpField,
            name: "jaHaniAddress",
            label: t(($) => $.buildingNameFloorRoomNumberEtc),
            isValid: formValid.jaHaniAddress,
            errorMessage: formErrors.jaHaniAddress?.errorMessage ?? formErrors.jaHaniAddress?.hasError,
            children: (childProps) => /* @__PURE__ */ jsx(
              InputText,
              {
                ...childProps,
                onInput: handleChangeFor("jaHaniAddress", "input"),
                value: formData.jaHaniAddress,
                transformInput: (value) => toFullWidth(value),
                transformMode: "blur"
              }
            )
          }
        )
      ] }) }),
      /* @__PURE__ */ jsx(List, { dividers: false, variant: "grouped-primary", children: /* @__PURE__ */ jsxs("fieldset", { children: [
        /* @__PURE__ */ jsx(Typography, { el: "legend", variant: "body-strongest", children: t(($) => $.katakanaAddress) }),
        /* @__PURE__ */ jsxs(StackLayout, { horizontal: true, children: [
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "jaKanaStateOrProvince",
              label: t(($) => $.prefecture),
              value: formData.jaKanaStateOrProvince
            }
          ),
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "jaKanaCity",
              label: t(($) => $.districtTownAreaCityWard),
              value: formData.jaKanaCity
            }
          )
        ] })
      ] }) }),
      /* @__PURE__ */ jsx(List, { dividers: false, variant: "grouped-primary", children: /* @__PURE__ */ jsxs("fieldset", { children: [
        /* @__PURE__ */ jsx(Typography, { el: "legend", variant: "body-strongest", children: t(($) => $.romajiAddress) }),
        /* @__PURE__ */ jsxs(StackLayout, { horizontal: true, children: [
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "stateOrProvince",
              label: t(($) => $.prefecture),
              value: formData.stateOrProvince
            }
          ),
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "city",
              label: t(($) => $.districtTownAreaCityWard),
              value: formData.city
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(StackLayout, { horizontal: true, children: [
          /* @__PURE__ */ jsx(
            ReadonlyTextField,
            {
              name: "otherAddressInformation",
              label: t(($) => $.chomeAndBanchi),
              value: formData.otherAddressInformation
            }
          ),
          /* @__PURE__ */ jsx(Spacer, {})
        ] }),
        /* @__PURE__ */ jsx(
          Field,
          {
            className: styles.jpField,
            name: "address",
            label: t(($) => $.buildingNameFloorRoomNumberEtc),
            isValid: formValid.address,
            errorMessage: formErrors.address?.errorMessage ?? formErrors.address?.hasError,
            children: (childProps) => /* @__PURE__ */ jsx(
              InputText,
              {
                ...childProps,
                onInput: handleChangeFor("address", "input"),
                onBlur: handleChangeFor("address", "blur"),
                value: formData.address,
                transformInput: (value) => convertFullToHalf(value),
                transformMode: "blur"
              }
            )
          }
        )
      ] }) })
    ] })
  ] });
};
export {
  JpAddress
};
