<script nonce="<?php echo $block->getNonce(); ?>">

    var countryMap = {
        'ALB': 'AL',
        'ARG': 'AR',
        'AUT': 'AT',
        'AUS': 'AU',
        'BEL': 'BE',
        'BGR': 'BG',
        'BOL': 'BL',
        'BRA': 'BR',
        'CAN': 'CA',
        'CHE': 'CH',
        'CHL': 'CL',
        'CHN': 'CN',
        'COL': 'CO',
        'DEU': 'DE',
        'DNK': 'DK',
        'ECU': 'EC',
        'EST': 'EE',
        'ESP': 'ES',
        'FIN': 'FI',
        'FRA': 'FR',
        'GRC': 'GR',
        'GUY': 'GY',
        'HRV': 'HR',
        'IND': 'IN',
        'ISL': 'IS',
        'ITA': 'IT',
        'LTU': 'LT',
        'LVA': 'LV',
        'MEX': 'MX',
        'PER': 'PE',
        'POL': 'PL',
        'PRT': 'PT',
        'PRY': 'PY',
        'ROU': 'RO',
        'SWE': 'SE',
        'SUR': 'SR',
        'URY': 'UY',
        'USA': 'US',
        'VEN': 'VE'
    };

    var regions = <?= /* @noEscape */ $this->helper(\Magento\Directory\Helper\Data::class)->getRegionJson() ?>;

    const selectRegionCountries = Object.entries(regions).filter(function (region) {
        return region[0] !== 'config'
    }).map(function (region) {
        return region[0]
    })
    var regionMap = function (result) {
        if (typeof countryMap[result.CountryISO] === 'undefined') {
            return null;
        }

        var mappedCountry = countryMap[result.CountryISO];
        var val = '';
        for (var regionIndex in regions[mappedCountry]) {
            if (regions[mappedCountry][regionIndex].code === result.TraditionalCounty) {
                val = regionIndex;
                break;
            }
            if (['CN', 'BG', 'IT', 'FR', 'DE', 'GR', 'AU'].indexOf(mappedCountry) > 0 && regions[mappedCountry][regionIndex].name.match(result.TraditionalCounty)) {
                val = regionIndex;
            }
        }

        return val;

    };

    var afdOptions = {
        platformVersion: 'mag010900',
        typeahead: {
            maxItems: '<?php echo $block->getConfig('afd_typeahead/quantity/maxItems');?>',
            pushUp: true,
            afterHideTypeahead: '<?php echo $block->getConfig('afd_typeahead/fields/afterHideTypeahead');?>' === '1',
            searchAgain: '<?php echo $block->getConfig('afd_typeahead/fields/enableSearchAgainButton');?>' === '1',
            afterClearTypeahead: '<?php echo $block->getConfig('afd_typeahead/fields/afterClearTypeahead');?>' === '1',
            beforeHideResults: '<?php echo $block->getConfig('afd_typeahead/fields/beforeHideResults');?>' === '1',
            fewResultsManualInput: '<?php echo $block->getConfig('afd_typeahead/quantity/enableFewItemsText');?>' === '1',
            fewResultsManualInputText: '<?php echo $block->escapeHtml($block->getConfig('afd_typeahead/quantity/fewItemsText'));?>',
            notEmptyShowResults: true,
            parentClass: 'field',
            fieldSets: ['fieldset.street', 'fieldset [data-index="street"], .admin__field.field-street'],
            hideEmpties: '<?php echo $block->getConfig('afd_typeahead/fields/hideEmpties');?>' === '1',
            manualInputButton: '<?php echo $block->getConfig('afd_typeahead/fields/enableManualEntryButton');?>' === '1',
            containers: ['#order-billing_address', '#order-shipping_address', '.customer_form_areas_address_address_customer_address_update_modal', '.form-address-edit'],
            matchPositions: '<?php echo $block->getConfig('afd_typeahead/fields/highlightMatches');?>' === '1',
            postcodeFirst: '<?php echo $block->getConfig('afd_typeahead/fields/postcodeFirst');?>' === '1',
            listEnv: '<?php echo $block->getConfig('afd_typeahead/fields/postcodeFirst');?>' !== '1',
            showForCountries: '<?php echo $block->getConfig('afd_typeahead/countries/typeaheadCountries');?>'.split(','),
            containerOnlyContainsControl: false,
            regionMap: regionMap,
            afterRetrieveHideResultsList: true,
            requiredSelector: '.required-entry, ._required',
            extraPCESearchParams: {
                <?php
                // Create search params as a JavaScript object with key-value pairs
                $customParams = $block->getSerializedConfig('afd_typeahead/advanced/customPCEParams');
                $outputLines = [];

                if (is_array($customParams)) {
                    foreach ($customParams as $param) {
                        if (isset($param['param_name']) && isset($param['param_value']) && $param['param_name'] !== '') {
                            // Format as JavaScript object property
                            $outputLines[] = "'{$param['param_name']}': '{$param['param_value']}'";
                        }
                    }
                }

                echo implode(",\n                ", $outputLines);
                ?>
            },
            extraPCERetrieveParams: {
                <?php
                // Create retrieve params as a JavaScript object with key-value pairs
                $outputLines = [];

                // Add crown dependencies parameter if enabled
                if ($block->getConfig('afd_typeahead/fields/crownDependencies') == '1') {
                    $outputLines[] = "'crownCountry': '1'";
                }

                // Add custom parameters from admin configuration
                $customParams = $block->getSerializedConfig('afd_typeahead/advanced/customPCEParams');

                if (is_array($customParams)) {
                    foreach ($customParams as $param) {
                        if (isset($param['param_name']) && isset($param['param_value']) && $param['param_name'] !== '') {
                            // Format as JavaScript object property
                            $outputLines[] = "'{$param['param_name']}': '{$param['param_value']}'";
                        }
                    }
                }

                echo implode(",\n                ", $outputLines);
                ?>
            },
            w3wMode: <?php echo $block->getConfig('afd_typeahead/what3words/mode');?>,
            w3wNear: '<?php echo $block->getConfig('afd_typeahead/what3words/near');?>' === '1',
            w3wNearTemplate: '<?php echo $block->getConfig('afd_typeahead/what3words/nearTemplate');?>',
            w3wFocusMode: '<?php echo $block->getConfig('afd_typeahead/what3words/focusMode');?>' === '0' ? false : '<?php echo $block->getConfig('afd_typeahead/what3words/focusMode');?>',
            w3wDistance: '<?php echo $block->getConfig('afd_typeahead/what3words/distance');?>' === '1',
            w3wDistanceUnit: '<?php echo $block->getConfig('afd_typeahead/what3words/distanceUnit');?>',
            w3wDistanceTemplate: '<?php echo $block->getConfig('afd_typeahead/what3words/distanceTemplate');?>'
        },
        country: {
            customCountryControl: '[name="country_id"], .form-address-edit #country, #order-billing_address_country_id, #order-shipping_address_country_id'
        },
        phone: {
            defaultDialingCode: '<?php echo $block->getConfig('afd_phone/fields/dialingCode');?>',
            defaultCountry: '<?php echo $block->getConfig('general/country/default') ?: 'GB'; ?>',
            loadingSpinner: '.control',
            countryControl: '[name="country_id"]'
        },
        email: {
            loadingSpinner: '.field',
            task: '<?php echo $block->getConfig('afd_email/fields/emailTask');?>',
            invalidEmailMessage: '<?php echo $block->getConfig('afd_email/fields/msg');?>'
        },
        reverseGeocode: {
            containers: ['.form-shipping-address', '.billing-address-form', '.form-address-edit'],
            hideOnDesktop: '<?php echo $block->getConfig('afd_typeahead/reverseGeocode/mobileOnly');?>' === '1',
        }
    };

    <?php if($block->getConfig('afd_general/account/method') == "id"){; ?>
    afdOptions.pceUrl = '<?php echo $block->getConfig('afd_general/account/idPceUrl'); ?>';
    afdOptions.id = '<?php echo $block->getConfig('afd_general/account/id'); ?>';
    afdOptions.token = '<?php echo $block->getConfig('afd_general/account/token'); ?>';
    <?php } else { ?>
    afdOptions.pceUrl = '<?php echo $block->getConfig('afd_general/account/serialPceUrl'); ?>';
    afdOptions.serial = '<?php echo $block->getConfig('afd_general/account/serial'); ?>';
    afdOptions.password = '<?php echo $block->getConfig('afd_general/account/password'); ?>';
    <?php } ?>
    var hideStateCountries = '<?php echo $block->getConfig('afd_typeahead/fields/hideRegion');?>'.split(',');
    // custom options that are needed in some parts of the application where templates cannot access back end config
    afdOptions.magentoOptions = {
        typeahead: {
            adminEditCustomerEnabled: <?php echo $block->getConfig('afd_typeahead/forms/adminCustomer'); ?> === 1,
            adminCreateOrderEnabled: <?php echo $block->getConfig('afd_typeahead/forms/adminOrder'); ?> === 1,
            useAdvancedCountryControl: <?php echo $block->getConfig('afd_typeahead/countries/useAdvancedCountryControl'); ?> === 1,
            usePreferredCountries: <?php echo $block->getConfig('afd_typeahead/countries/usePreferredCountries'); ?> === 1,
            preferredCountriesCount: <?php echo (int)$block->getConfig('afd_typeahead/countries/preferredCountriesCount') ?: 5; ?>,
            defaultCountry: '<?php echo $block->getConfig('general/country/default') ?: 'GB'; ?>',
            crownCountries: <?php echo $block->getConfig('afd_typeahead/fields/crownDependencies'); ?> === 1,
            zipPlusFour: <?php echo $block->getConfig('afd_typeahead/fields/zipPlusFour'); ?> === 1,
            afdCounty: '<?php echo $block->getConfig('afd_typeahead/fields/afdCounty'); ?>',
            combineFirstLine: <?php echo $block->getConfig('afd_typeahead/fields/combineFirstLine'); ?> === 1,
            customCountryDefaultID: '<?php echo $block->getConfig('afd_general/account/id'); ?>',
            customCountryDefaultToken: '<?php echo $block->getConfig('afd_general/account/token'); ?>',
            customCountryCredentials: <?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentials'); ?> === 1,
            customCountryCredentialsUK: <?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUK'); ?> === 1,
            customCountryCredentialsUS: <?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUS'); ?> === 1,
            customCountryCredentialsIE: <?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsIE'); ?> === 1,
            customCountryCredentialsUKID: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUKID'); ?>',
            customCountryCredentialsUKToken: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUKToken'); ?>',
            customCountryCredentialsUSID: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUSID'); ?>',
            customCountryCredentialsUSToken: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsUSToken'); ?>',
            customCountryCredentialsIEID: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsIEID'); ?>',
            customCountryCredentialsIEToken: '<?php echo $block->getConfig('afd_typeahead/advanced/customCountryCredentialsIEToken'); ?>',
            regionFieldRemoved: <?php echo $block->getConfig('afd_typeahead/fields/regionFieldRemoved'); ?> === 1
        },
        email: {
            emailEnabled: <?php echo $block->getConfig('afd_email/enable/enable'); ?> === 1,
            accountChangeEmailEnabled: <?php echo $block->getConfig('afd_email/forms/account'); ?> === 1,
            loggedOutCheckoutEnabled: <?php echo $block->getConfig('afd_email/forms/checkout'); ?> === 1,
            adminEditCustomerEnabled:  <?php echo $block->getConfig('afd_email/forms/adminCustomer'); ?> ===1
        },
        phone: {
            phoneEnabled: <?php echo $block->getConfig('afd_phone/enable/enable'); ?> === 1,
            loggedOutCheckoutEnabled: <?php echo $block->getConfig('afd_phone/forms/checkout'); ?> === 1,
            invalidMessage: '<?php echo $block->getConfig("afd_phone/fields/msg"); ?>',
            adminEditCustomerEnabled: <?php echo $block->getConfig('afd_phone/forms/adminCustomer'); ?> === 1,
            adminCreateOrderEnabled:  <?php echo $block->getConfig('afd_phone/forms/adminOrder'); ?> === 1
        },
        version: '<?php echo $block->getMageVersion() ?>'
    }

    //logic for which region field should be shown after results populate
    function showHideRegion(e, $element, $container, result) {

        const $region_id = $container.find('#region_id, [name="region_id"], #order-billing_address_region_id, #order-shipping_address_region_id');
        const $region = $container.find('#region, [name="region"], #order-billing_address_region, #order-shipping_address_region');
        const country = $container.find(afdOptions.country.customCountryControl).val() || jQuery(afdOptions.country.customCountryControl).last().val()
        const requireRegionCountries = '<?php print_r($block->getConfig('general/region/state_required')); ?>'.split(',');
        const regionHiddenIfOptional = '<?php echo $block->getConfig('general/region/display_all') ?>' !== '1';
        // Magento gives the option to hide non required region fields
        if (requireRegionCountries.indexOf(country) < 0 && regionHiddenIfOptional) {
            $region_id.closest('.' + afdOptions.typeahead.parentClass).hide();
            $region.closest('.' + afdOptions.typeahead.parentClass).hide();
        } else {
            // if the correct field is region_id
            if (selectRegionCountries.indexOf(country) > 0) {
                $region.closest('.' + afdOptions.typeahead.parentClass).hide();
                $region_id.closest('.' + afdOptions.typeahead.parentClass).show();
                $region_id.change()
                $region.hide();
            } else {
                $region_id.closest('.' + afdOptions.typeahead.parentClass).hide();
                $region.closest('.' + afdOptions.typeahead.parentClass).show();
                $region_id.hide();
            }
        }

    }

</script>

<style>
    .afd-error {
        display: none;
    }


    .control.loading {
        position: relative
    }

    .field .control:before {
        border-color: rgba(0, 0, 0, 0.35);
    }

    .field .control.loading:before, .field .control.loading:after {
        transition: all 0s linear, opacity 0.2s ease;
        position: absolute;
        z-index: 3;
        content: "";
        top: 50%;
        right: 0.55em;
        margin-top: -0.675rem;
        width: 1.35rem;
        height: 1.35rem;
        box-sizing: border-box;
        border-radius: 500rem;
        border-style: solid;
        border-width: 0.1em;
    }

    .field .control._with-tooltip:before, .field .control._with-tooltip:after {
        right: 3.3em;
    }

    #shipping #customer-email-fieldset .control:before, #shipping #customer-email-fieldset .control:after {
        top: 25%;
    }

    .field .control:after {
        animation: button-spin 0.6s linear;
        animation-iteration-count: infinite;
        border-color: #fff transparent transparent;
        box-shadow: 0 0 0 1px transparent;
    }

    .afd-error {
        display: none;
        color: #e02b27;
        font-size: 1.2rem;
        margin-top: 7px;

    }

    .afd-invalid + .afd-error {
        display: block;
    }

    input.afd-invalid {
        border-color: #ed8380;
    }

    .afd-loading > :before, .afd-loading > :after {
        top: 32px;
        right: 48px;
    }

</style>
