<script>
    (function () {
        if (window.__addressFieldEnhancerInitialized) {
            return;
        }
        window.__addressFieldEnhancerInitialized = true;

        const eastAfricaCountries = [
            'Burundi', 'Comoros', 'Djibouti', 'DR Congo', 'Eritrea', 'Ethiopia', 'Kenya', 'Madagascar',
            'Malawi', 'Mauritius', 'Mozambique', 'Rwanda', 'Seychelles', 'Somalia', 'South Sudan',
            'Tanzania', 'Uganda', 'Zambia', 'Zimbabwe'
        ];

        const africaCountries = [
            'Algeria', 'Angola', 'Benin', 'Botswana', 'Burkina Faso', 'Cameroon', 'Cape Verde',
            'Central African Republic', 'Chad', 'Congo', "Cote d'Ivoire", 'Egypt', 'Equatorial Guinea',
            'Eswatini', 'Gabon', 'Gambia', 'Ghana', 'Guinea', 'Guinea-Bissau', 'Liberia', 'Libya',
            'Mali', 'Mauritania', 'Morocco', 'Namibia', 'Niger', 'Nigeria', 'Sao Tome and Principe',
            'Senegal', 'Sierra Leone', 'South Africa', 'Sudan', 'Togo', 'Tunisia'
        ];

        const worldCountries = [
            'Afghanistan', 'Albania', 'Andorra', 'Antigua and Barbuda', 'Argentina', 'Armenia',
            'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados',
            'Belarus', 'Belgium', 'Belize', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Brazil',
            'Brunei', 'Bulgaria', 'Cambodia', 'Canada', 'Chile', 'China', 'Colombia', 'Costa Rica',
            'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Dominica', 'Dominican Republic',
            'Ecuador', 'El Salvador', 'Estonia', 'Fiji', 'Finland', 'France', 'Georgia', 'Germany',
            'Greece', 'Grenada', 'Guatemala', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland',
            'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan',
            'Jordan', 'Kazakhstan', 'Kiribati', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon',
            'Lesotho', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Malaysia', 'Maldives', 'Malta',
            'Marshall Islands', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro',
            'Myanmar', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua', 'North Korea',
            'North Macedonia', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea',
            'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia',
            'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa',
            'San Marino', 'Saudi Arabia', 'Serbia', 'Singapore', 'Slovakia', 'Slovenia',
            'Solomon Islands', 'South Korea', 'Spain', 'Sri Lanka', 'Suriname', 'Sweden',
            'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Thailand', 'Timor-Leste', 'Tonga',
            'Trinidad and Tobago', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Ukraine',
            'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan',
            'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen'
        ];

        const kenyaCounties = [
            'Baringo', 'Bomet', 'Bungoma', 'Busia', 'Elgeyo-Marakwet', 'Embu', 'Garissa', 'Homa Bay',
            'Isiolo', 'Kajiado', 'Kakamega', 'Kericho', 'Kiambu', 'Kilifi', 'Kirinyaga', 'Kisii',
            'Kisumu', 'Kitui', 'Kwale', 'Laikipia', 'Lamu', 'Machakos', 'Makueni', 'Mandera', 'Marsabit',
            'Meru', 'Migori', 'Mombasa', 'Muranga', 'Nairobi', 'Nakuru', 'Nandi', 'Narok', 'Nyamira',
            'Nyandarua', 'Nyeri', 'Samburu', 'Siaya', 'Taita-Taveta', 'Tana River', 'Tharaka-Nithi',
            'Trans Nzoia', 'Turkana', 'Uasin Gishu', 'Vihiga', 'Wajir', 'West Pokot'
        ];

        const stateOptionsByCountry = {
            Kenya: kenyaCounties,
            Uganda: ['Central', 'Eastern', 'Northern', 'Western', 'Karamoja'],
            Tanzania: ['Arusha', 'Dar es Salaam', 'Dodoma', 'Geita', 'Iringa', 'Kagera', 'Katavi', 'Kigoma', 'Kilimanjaro', 'Lindi', 'Mara', 'Mbeya', 'Morogoro', 'Mtwara', 'Mwanza', 'Njombe', 'Pemba North', 'Pemba South', 'Pwani', 'Rukwa', 'Ruvuma', 'Shinyanga', 'Simiyu', 'Singida', 'Songwe', 'Tabora', 'Tanga', 'Zanzibar North', 'Zanzibar South', 'Zanzibar West'],
            Rwanda: ['Kigali', 'Eastern Province', 'Northern Province', 'Southern Province', 'Western Province'],
            Burundi: ['Bubanza', 'Bujumbura Mairie', 'Bujumbura Rural', 'Bururi', 'Cankuzo', 'Cibitoke', 'Gitega', 'Karuzi', 'Kayanza', 'Kirundo', 'Makamba', 'Muramvya', 'Muyinga', 'Mwaro', 'Ngozi', 'Rumonge', 'Rutana', 'Ruyigi'],
            Ethiopia: ['Addis Ababa', 'Afar', 'Amhara', 'Benishangul-Gumuz', 'Dire Dawa', 'Gambela', 'Harari', 'Oromia', 'Sidama', 'Somali', 'South Ethiopia', 'South West Ethiopia Peoples', 'Tigray'],
            'South Sudan': ['Central Equatoria', 'Eastern Equatoria', 'Jonglei', 'Lakes', 'Northern Bahr el Ghazal', 'Unity', 'Upper Nile', 'Warrap', 'Western Bahr el Ghazal', 'Western Equatoria'],
            Somalia: ['Awdal', 'Bakool', 'Banadir', 'Bari', 'Bay', 'Galguduud', 'Gedo', 'Hiran', 'Lower Juba', 'Lower Shabelle', 'Middle Juba', 'Middle Shabelle', 'Mudug', 'Nugal', 'Sanaag', 'Sool', 'Togdheer', 'Woqooyi Galbeed'],
            'DR Congo': ['Bas-Uele', 'Equateur', 'Haut-Katanga', 'Haut-Lomami', 'Haut-Uele', 'Ituri', 'Kasai', 'Kasai-Central', 'Kasai-Oriental', 'Kinshasa', 'Kongo Central', 'Kwango', 'Kwilu', 'Lomami', 'Lualaba', 'Mai-Ndombe', 'Maniema', 'Mongala', 'Nord-Ubangi', 'North Kivu', 'Sankuru', 'South Kivu', 'Sud-Ubangi', 'Tanganyika', 'Tshopo', 'Tshuapa'],
            Nigeria: ['North Central', 'North East', 'North West', 'South East', 'South South', 'South West'],
            'South Africa': ['Eastern Cape', 'Free State', 'Gauteng', 'KwaZulu-Natal', 'Limpopo', 'Mpumalanga', 'North West', 'Northern Cape', 'Western Cape'],
            India: ['Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttar Pradesh', 'Uttarakhand', 'West Bengal', 'Delhi', 'Jammu and Kashmir', 'Ladakh'],
            'United States': ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'],
            Canada: ['Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador', 'Nova Scotia', 'Ontario', 'Prince Edward Island', 'Quebec', 'Saskatchewan', 'Northwest Territories', 'Nunavut', 'Yukon'],
            Australia: ['Australian Capital Territory', 'New South Wales', 'Northern Territory', 'Queensland', 'South Australia', 'Tasmania', 'Victoria', 'Western Australia'],
            'United Kingdom': ['England', 'Northern Ireland', 'Scotland', 'Wales'],
            Germany: ['Baden-Wurttemberg', 'Bavaria', 'Berlin', 'Brandenburg', 'Bremen', 'Hamburg', 'Hesse', 'Lower Saxony', 'Mecklenburg-Vorpommern', 'North Rhine-Westphalia', 'Rhineland-Palatinate', 'Saarland', 'Saxony', 'Saxony-Anhalt', 'Schleswig-Holstein', 'Thuringia'],
            France: ['Auvergne-Rhone-Alpes', 'Bourgogne-Franche-Comte', 'Brittany', 'Centre-Val de Loire', 'Corsica', 'Grand Est', 'Hauts-de-France', 'Ile-de-France', 'Normandy', 'Nouvelle-Aquitaine', 'Occitanie', 'Pays de la Loire', 'Provence-Alpes-Cote d\'Azur'],
            'United Arab Emirates': ['Abu Dhabi', 'Ajman', 'Dubai', 'Fujairah', 'Ras Al Khaimah', 'Sharjah', 'Umm Al Quwain']
        };

        const defaultStateByCountry = { Kenya: 'Nairobi' };

        function getField(name, scope) {
            return (scope || document).querySelector('[name="' + name + '"]');
        }

        function findFieldContainer(field) {
            if (!field) {
                return null;
            }
            return field.closest('.col-md-12, .col-md-6, .col-md-4, .col-sm-12, .col-sm-6, .col-sm-4, .form-group');
        }

        function updateLabel(field, text) {
            if (!field) {
                return;
            }
            const id = field.id || '';
            let label = null;
            if (id) {
                label = document.querySelector('label[for="' + id + '"]');
            }
            if (!label) {
                const wrapper = field.closest('.form-group, .col-md-12, .col-md-6, .col-md-4, .col-sm-12, .col-sm-6, .col-sm-4');
                if (wrapper) {
                    label = wrapper.querySelector('label');
                }
            }
            if (label) {
                label.textContent = text;
            }
        }

        function buildCountrySelect(field, selectedValue) {
            const select = document.createElement('select');
            select.name = field.name;
            select.id = field.id || field.name;
            select.className = field.className || 'form-control';
            select.setAttribute('data-address-country', '1');

            const groups = [
                { label: 'East Africa', items: eastAfricaCountries },
                { label: 'Rest of Africa', items: africaCountries },
                { label: 'Rest of World', items: worldCountries }
            ];

            groups.forEach(function (group) {
                const optGroup = document.createElement('optgroup');
                optGroup.label = group.label;
                group.items.forEach(function (country) {
                    const option = document.createElement('option');
                    option.value = country;
                    option.textContent = country;
                    optGroup.appendChild(option);
                });
                select.appendChild(optGroup);
            });

            const finalValue = selectedValue || field.value || 'Kenya';
            if ([].some.call(select.options, function (opt) { return opt.value === finalValue; })) {
                select.value = finalValue;
            } else {
                select.value = 'Kenya';
            }

            return select;
        }

        function buildStateSelect(field, values, selectedValue) {
            const select = document.createElement('select');
            select.name = field.name;
            select.id = field.id || field.name;
            select.className = field.className || 'form-control';
            select.setAttribute('data-address-state', '1');

            const placeholder = document.createElement('option');
            placeholder.value = '';
            placeholder.textContent = 'Select County/State';
            select.appendChild(placeholder);

            values.forEach(function (entry) {
                const option = document.createElement('option');
                option.value = entry;
                option.textContent = entry;
                select.appendChild(option);
            });

            if (selectedValue && values.indexOf(selectedValue) !== -1) {
                select.value = selectedValue;
            } else {
                select.value = '';
            }

            return select;
        }

        function ensureCountryField(prefix, scope) {
            const field = getField(prefix + '_country', scope);
            if (!field) {
                return null;
            }

            updateLabel(field, 'Country');

            if (field.tagName === 'SELECT' && field.dataset.addressCountry === '1') {
                if (!field.value) {
                    field.value = 'Kenya';
                }
                return field;
            }

            const replacement = buildCountrySelect(field, field.value || 'Kenya');
            field.parentNode.replaceChild(replacement, field);
            return replacement;
        }

        function ensureStateField(prefix, scope) {
            const countryField = getField(prefix + '_country', scope);
            const stateField = getField(prefix + '_state', scope);
            if (!countryField || !stateField) {
                return;
            }

            updateLabel(stateField, 'County/State');

            const selectedCountry = countryField.value || 'Kenya';
            const options = stateOptionsByCountry[selectedCountry] || null;
            const currentValue = stateField.value || defaultStateByCountry[selectedCountry] || '';

            if (options && options.length) {
                const replacement = buildStateSelect(stateField, options, currentValue);
                stateField.parentNode.replaceChild(replacement, stateField);
                return;
            }

            if (stateField.tagName === 'SELECT' && stateField.dataset.addressState === '1') {
                const input = document.createElement('input');
                input.type = 'text';
                input.name = stateField.name;
                input.id = stateField.id || stateField.name;
                input.className = stateField.className || 'form-control';
                input.placeholder = 'Enter County/State';
                input.value = currentValue;
                stateField.parentNode.replaceChild(input, stateField);
            } else {
                stateField.placeholder = 'Enter County/State';
                if (!stateField.value && defaultStateByCountry[selectedCountry]) {
                    stateField.value = defaultStateByCountry[selectedCountry];
                }
            }
        }

        function ensureZipLabel(prefix, scope) {
            const zipField = getField(prefix + '_zip', scope);
            if (!zipField) {
                return;
            }
            updateLabel(zipField, 'Postal/Zip Code');
            if (!zipField.placeholder || /zip code/i.test(zipField.placeholder)) {
                zipField.placeholder = 'Enter Postal/Zip Code';
            }
        }

        function reorderFields(prefix, scope) {
            const cityField = getField(prefix + '_city', scope);
            const countryField = getField(prefix + '_country', scope);
            if (!cityField || !countryField) {
                return;
            }

            const cityContainer = findFieldContainer(cityField);
            const countryContainer = findFieldContainer(countryField);
            if (!cityContainer || !countryContainer || cityContainer.parentNode !== countryContainer.parentNode) {
                return;
            }

            if (countryContainer.nextElementSibling !== cityContainer) {
                cityContainer.parentNode.insertBefore(countryContainer, cityContainer);
            }
        }

        function wireCountryChange(prefix, scope) {
            const countryField = getField(prefix + '_country', scope);
            if (!countryField || countryField.dataset.countryWatcher === '1') {
                return;
            }
            countryField.dataset.countryWatcher = '1';
            countryField.addEventListener('change', function () {
                ensureStateField(prefix, scope);
                reorderFields(prefix, scope);
            });
        }

        function enhancePrefix(prefix, scope) {
            const countryField = ensureCountryField(prefix, scope);
            if (!countryField) {
                return;
            }
            ensureStateField(prefix, scope);
            ensureZipLabel(prefix, scope);
            reorderFields(prefix, scope);
            wireCountryChange(prefix, scope);
        }

        function initAddressEnhancer(scope) {
            enhancePrefix('billing', scope || document);
            enhancePrefix('shipping', scope || document);
        }

        document.addEventListener('DOMContentLoaded', function () {
            initAddressEnhancer(document);
            const observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    mutation.addedNodes.forEach(function (node) {
                        if (node.nodeType === 1) {
                            initAddressEnhancer(node);
                        }
                    });
                });
            });
            observer.observe(document.body, { childList: true, subtree: true });
        });
    })();
</script>

<?php /**PATH D:\FromHardDisk\Davies\CleverSys\The Systems\erp.cleversys.co.ke\resources\views/partials/admin/address-enhancer-script.blade.php ENDPATH**/ ?>