@if (config('zt.ip_lookup.browser_detection_enabled', true) && ($currencyInfo['source'] ?? null) !== 'manual' && empty($currencyInfo['locked']))
    <script>
        (function () {
            const lookupUrl = @json(config('zt.ip_lookup.browser_url'));
            const postUrl = @json(route('currency.browser-country'));
            const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            const currentCountry = @json($currencyInfo['country'] ?? null);
            const currentCurrency = @json($cart->currency ?? config('zt.currency.fallback'));
            const localCountry = @json(config('zt.currency.local_country_code'));
            const localCurrency = @json(config('zt.currency.local_currency'));
            const defaultCurrency = @json(config('zt.currency.default'));

            if (!lookupUrl || !postUrl || !csrf) {
                return;
            }

            function normalizeCountry(data) {
                if (!data || typeof data !== 'object') {
                    return null;
                }

                const value = data.country_code || data.countryCode || data.country;
                if (!value || typeof value !== 'string') {
                    return null;
                }

                const country = value.trim().toUpperCase();
                return /^[A-Z]{2}$/.test(country) ? country : null;
            }

            fetch(lookupUrl, {cache: 'no-store'})
                .then(response => response.ok ? response.json() : null)
                .then(data => {
                    const country = normalizeCountry(data);
                    if (!country || country === currentCountry) {
                        return;
                    }

                    const nextCurrency = country === localCountry ? localCurrency : defaultCurrency;
                    if (nextCurrency === currentCurrency && country === currentCountry) {
                        return;
                    }

                    return fetch(postUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': csrf,
                        },
                        body: JSON.stringify({country}),
                    }).then(response => {
                        if (response.ok) {
                            window.location.reload();
                        }
                    });
                })
                .catch(() => {});
        })();
    </script>
@endif
