/**
 * Shois Chat Button — GDPR Consent Banner
 *
 * Frontend consent banner that must be accepted before
 * link tracking / analytics events fire.
 *
 * @package ShoisChatButton
 */
(function () {
    'use strict';

    var CONSENT_KEY = 'shcb_consent_given';

    /**
     * Check if consent was already given.
     *
     * @return {boolean} True if consent exists.
     */
    function hasConsent() {
        try {
            return localStorage.getItem(CONSENT_KEY) === '1';
        } catch (e) {
            return false;
        }
    }

    /**
     * Store consent.
     */
    function giveConsent() {
        try {
            localStorage.setItem(CONSENT_KEY, '1');
        } catch (e) {
            /* Storage unavailable */
        }
    }

    /**
     * Initialize GDPR banner if needed.
     */
    function init() {
        if (typeof window.shcb_config === 'undefined') {
            return;
        }

        var config = window.shcb_config;

        // Only show if GDPR consent is enabled in settings.
        if (!config.gdpr || !config.gdpr.enabled) {
            return;
        }

        // Already consented.
        if (hasConsent()) {
            window.shcb_consent_granted = true;
            return;
        }

        window.shcb_consent_granted = false;

        // Create banner.
        var banner = document.createElement('div');
        banner.className = 'shcb-gdpr-banner';
        banner.setAttribute('role', 'dialog');
        banner.setAttribute('aria-label', 'Cookie consent');

        var message = config.gdpr.message || 'We use cookies to improve your chat experience.';
        var btnText = config.gdpr.button_text || 'Accept';

        var messageEl = document.createElement('p');
        messageEl.className = 'shcb-gdpr-message';
        messageEl.textContent = message;

        var acceptBtn = document.createElement('button');
        acceptBtn.className = 'shcb-gdpr-accept';
        acceptBtn.type = 'button';
        acceptBtn.textContent = btnText;

        acceptBtn.addEventListener('click', function () {
            giveConsent();
            window.shcb_consent_granted = true;
            banner.classList.add('shcb-gdpr-hidden');
            setTimeout(function () {
                if (banner.parentNode) {
                    banner.parentNode.removeChild(banner);
                }
            }, 300);
        });

        banner.appendChild(messageEl);
        banner.appendChild(acceptBtn);

        // Attach to widget container.
        var widget = document.getElementById('shcb-widget');
        if (widget) {
            widget.appendChild(banner);
        } else {
            document.body.appendChild(banner);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
