(function() {
var lastURL = '';
var conditions = [];
var defaultButtonKey = "4c2c0004-5817-41c7-9107-3e2dcb06eb07";
var defaultButtonVersion = 1772758655;
var hasCountryConditions = false;
var autoTranslate = false;

async function fetchVisitorCountry() {
    try {
        var response = await fetch('https://app.boei.help/geo/country');
        var data = await response.json();
        return data.country || null;
    } catch (e) {
        return null;
    }
}

async function evaluateConditions() {
    var pageUrl = location.hostname + location.pathname;
    var urlQuery = location.search;
    var visitorCountry = null;

    // Only fetch country if we have country-based conditions
    if (hasCountryConditions) {
        visitorCountry = await fetchVisitorCountry();
        console.log('Boei: Detected visitor country:', visitorCountry || 'unknown');
    }

    for (var i = 0; i < conditions.length; i++) {
        var c = conditions[i];
        if (isConditionValid(c, pageUrl, urlQuery, visitorCountry)) {
            // Return object: matched=true, button_key (null = hide), version
            return { matched: true, button_key: c.button_key, version: c.button_version || 0 };
        }
    }
    return { matched: false, button_key: null, version: 0 };
}

function isConditionValid(c, pageUrl, urlQuery, visitorCountry) {
    var combined = (pageUrl + urlQuery).toLowerCase();
    var value = (c.value || '').toLowerCase();

    switch (c.type) {
        case 'pageContains':
            return combined.indexOf(value) !== -1;
        case 'pageNotContains':
            return combined.indexOf(value) === -1;
        case 'pageIs':
            var path = getPath(pageUrl);
            return path === c.value || (path + urlQuery) === c.value;
        case 'pageNotIs':
            var path = getPath(pageUrl);
            return path !== c.value && (path + urlQuery) !== c.value;
        case 'visitorIsMobile':
            return /android|iphone|ipad|ipod|mobile|webos|blackberry|iemobile|opera mini/i.test(navigator.userAgent);
        case 'visitorIsNotMobile':
            return !/android|iphone|ipad|ipod|mobile|webos|blackberry|iemobile|opera mini/i.test(navigator.userAgent);
        case 'visitorCountryIs':
            return visitorCountry && visitorCountry.toUpperCase() === c.value.toUpperCase();
        case 'visitorCountryIsNot':
            return visitorCountry && visitorCountry.toUpperCase() !== c.value.toUpperCase();
        default:
            return false;
    }
}

function getPath(url) {
    try {
        return new URL('https://' + url).pathname;
    } catch (e) {
        return url;
    }
}

async function loadScript() {
    lastURL = location.href;

    var old = document.querySelector('script[data-id="boei-script"]');
    if (old) old.remove();

    var btn = document.querySelector('#boei_button');
    if (btn && window.boeiEmbed) {
        boeiEmbed.hideBoeiButton();
        btn.remove();
    }

    // Evaluate conditions to get button key, or use default
    var result = await evaluateConditions();
    var buttonKey;
    var buttonVersion;

    if (result.matched) {
        // Condition matched - use its button_key (null = hide widget)
        if (result.button_key === null) {
            return; // Hide widget on this page
        }
        buttonKey = result.button_key;
        buttonVersion = result.version;
    } else {
        // No condition matched - use default
        buttonKey = defaultButtonKey;
        buttonVersion = defaultButtonVersion;
    }

    if (!buttonKey) {
        console.log('Boei: No button configured');
        return;
    }

    var isMobile = /android|iphone|ipad|ipod|mobile|webos|blackberry|iemobile|opera mini/i.test(navigator.userAgent);
    var url = 'https://app.boei.help/embed/b/' + buttonKey + '?spa=0&iframe=0&plk=0&v=' + buttonVersion + '&d=' + (isMobile ? 'm' : 'd');

    var locale = document.getElementById('widget_set_locale');
    if (locale && locale.value) {
        url += '&locale=' + encodeURIComponent(locale.value);
    } else if (autoTranslate) {
        url += '&locale=' + (navigator.language || 'en').substring(0, 2);
    }

    var s = document.createElement('script');
    s.id = 'boei-script';
    s.dataset.id = 'boei-script';
    s.src = url;
    s.async = true;
    document.head.appendChild(s);
}

loadScript();
})();