/**
 * Tiriri - Frontend Disclosure & Script Detection
 */
(function () {
    'use strict';

    // Bail if config not available
    if (typeof tiririConfig === 'undefined') {
        return;
    }

    var config = tiririConfig;
    var COOKIE_NAME = 'tiriri_dismissed';

    /**
     * Check if disclosure was already dismissed
     */
    function isDismissed() {
        return document.cookie.indexOf(COOKIE_NAME + '=1') !== -1;
    }

    /**
     * Set dismiss cookie
     */
    function setDismissed() {
        var hours = config.cookieDuration || 24;
        var date = new Date();
        date.setTime(date.getTime() + hours * 60 * 60 * 1000);
        var secure = location.protocol === 'https:' ? '; Secure' : '';
        document.cookie =
            COOKIE_NAME + '=1; expires=' + date.toUTCString() + '; path=/; SameSite=Lax' + secure;
    }

    /**
     * Show the disclosure banner
     */
    function showDisclosure() {
        var el = document.getElementById('tiriri-disclosure');
        if (!el || isDismissed()) {
            return;
        }

        el.style.display = 'block';

        // Dismiss button
        var dismissBtn = el.querySelector('.tiriri-disclosure__dismiss');
        if (dismissBtn) {
            dismissBtn.addEventListener('click', function () {
                el.style.display = 'none';
                setDismissed();
            });
        }

        // Dismiss with Escape key
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && el.style.display !== 'none') {
                el.style.display = 'none';
                setDismissed();
            }
        });
    }

    /**
     * Detect third-party AI chatbot scripts on the page
     */
    function detectThirdPartyScripts() {
        if (!config.scriptPatterns || !config.scriptPatterns.length) {
            return [];
        }

        var detected = [];
        var scripts = document.querySelectorAll('script[src]');
        var iframes = document.querySelectorAll('iframe[src]');

        // Check script tags
        for (var i = 0; i < scripts.length; i++) {
            var src = scripts[i].src || '';
            for (var j = 0; j < config.scriptPatterns.length; j++) {
                var pattern = config.scriptPatterns[j];
                if (src.indexOf(pattern.pattern) !== -1) {
                    detected.push(pattern);
                }
            }
        }

        // Check iframes (some chatbots embed via iframe)
        for (var k = 0; k < iframes.length; k++) {
            var iframeSrc = iframes[k].src || '';
            for (var l = 0; l < config.scriptPatterns.length; l++) {
                var iframePattern = config.scriptPatterns[l];
                if (iframeSrc.indexOf(iframePattern.pattern) !== -1) {
                    detected.push(iframePattern);
                }
            }
        }

        // Also check inline scripts for known patterns
        // Skip our own config script to avoid false positives
        var inlineScripts = document.querySelectorAll('script:not([src])');
        for (var m = 0; m < inlineScripts.length; m++) {
            var content = inlineScripts[m].textContent || '';
            if (content.indexOf('tiririConfig') !== -1) {
                continue;
            }
            for (var n = 0; n < config.scriptPatterns.length; n++) {
                var inlinePattern = config.scriptPatterns[n];
                if (content.indexOf(inlinePattern.pattern) !== -1) {
                    detected.push(inlinePattern);
                }
            }
        }

        // Deduplicate
        var seen = {};
        var unique = [];
        for (var o = 0; o < detected.length; o++) {
            if (!seen[detected[o].pattern]) {
                seen[detected[o].pattern] = true;
                unique.push(detected[o]);
            }
        }

        return unique;
    }

    /**
     * Main initialization
     */
    function init() {
        if (!config.enabled) {
            return;
        }

        // Check if chatbot was already detected server-side
        var el = document.getElementById('tiriri-disclosure');
        var serverDetected = el && el.getAttribute('data-chatbot-detected') === 'true';

        // Run client-side script detection
        var clientDetected = detectThirdPartyScripts();
        var hasChatbot = clientDetected.some(function (d) {
            return d.category === 'chatbot';
        });

        // Show disclosure if any chatbot detected
        if (serverDetected || hasChatbot) {
            showDisclosure();
        }

        // Store detection results in sessionStorage for potential admin reporting
        if (clientDetected.length > 0) {
            try {
                sessionStorage.setItem(
                    'tiriri_detected_scripts',
                    JSON.stringify(clientDetected)
                );
            } catch (e) {
                // sessionStorage not available, ignore
            }
        }
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
