(function() {
    'use strict';

    // Check config exists
    if (typeof wpscConfig === 'undefined') return;

    // Hide on mobile if configured
    if (!wpscConfig.showOnMobile && window.innerWidth <= 768) return;

    var widget = document.getElementById('wpsc-chat-widget');
    var toggleBtn = document.getElementById('wpsc-toggle-btn');
    var chatWindow = document.getElementById('wpsc-chat-window');
    var closeBtn = document.getElementById('wpsc-close-btn');
    var messagesDiv = document.getElementById('wpsc-messages');
    var input = document.getElementById('wpsc-input');
    var sendBtn = document.getElementById('wpsc-send-btn');
    var iconChat = document.getElementById('wpsc-icon-chat');
    var iconClose = document.getElementById('wpsc-icon-close');

    var isOpen = false;
    var sessionId = getSessionId();

    // Set primary color CSS variable
    widget.style.setProperty('--wpsc-primary', wpscConfig.primaryColor);

    // Show widget
    widget.style.display = 'block';

    // Toggle chat
    toggleBtn.addEventListener('click', function() {
        isOpen = !isOpen;
        chatWindow.style.display = isOpen ? 'flex' : 'none';
        iconChat.style.display = isOpen ? 'none' : 'block';
        iconClose.style.display = isOpen ? 'block' : 'none';

        if (isOpen) {
            toggleBtn.classList.add('wpsc-open');
        } else {
            toggleBtn.classList.remove('wpsc-open');
        }

        if (isOpen && messagesDiv.children.length === 0) {
            addBotMessage(wpscConfig.welcome);
        }

        if (isOpen) {
            setTimeout(function() { input.focus(); }, 100);
        }
    });

    // Close button
    closeBtn.addEventListener('click', function() {
        isOpen = false;
        chatWindow.style.display = 'none';
        iconChat.style.display = 'block';
        iconClose.style.display = 'none';
        toggleBtn.classList.remove('wpsc-open');
    });

    // Send message
    sendBtn.addEventListener('click', sendMessage);
    input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') sendMessage();
    });

    function sendMessage() {
        var message = input.value.trim();
        if (!message) return;

        // Add user message
        addUserMessage(message);
        input.value = '';

        // Show typing indicator
        showTyping();

        // Call API
        fetch(wpscConfig.restUrl + 'chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': wpscConfig.nonce
            },
            body: JSON.stringify({
                message: message,
                session_id: sessionId,
                page_url: window.location.href
            })
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            hideTyping();
            if (data.message) {
                addBotMessage(data.message, data.sources || {});
            }
        })
        .catch(function() {
            hideTyping();
            addBotMessage('Sorry, something went wrong. Please try again.');
        });
    }

    function addUserMessage(text) {
        var div = document.createElement('div');
        div.className = 'wpsc-msg wpsc-msg-user';
        div.textContent = text;
        messagesDiv.appendChild(div);
        scrollToBottom();
    }

    function addBotMessage(text, sources) {
        var div = document.createElement('div');
        div.className = 'wpsc-msg wpsc-msg-bot';
        div.textContent = text;

        // Add sources if available
        if (sources && Object.keys(sources).length > 0) {
            var sourcesDiv = document.createElement('div');
            sourcesDiv.className = 'wpsc-msg-sources';
            sourcesDiv.innerHTML = '<strong>Learn more:</strong> ';

            var links = [];
            for (var url in sources) {
                links.push('<a href="' + escapeHtml(url) + '" target="_blank">' + escapeHtml(sources[url]) + '</a>');
            }
            sourcesDiv.innerHTML += links.slice(0, 3).join(', ');
            div.appendChild(sourcesDiv);
        }

        messagesDiv.appendChild(div);
        scrollToBottom();
    }

    function showTyping() {
        var div = document.createElement('div');
        div.className = 'wpsc-typing';
        div.id = 'wpsc-typing-indicator';
        div.innerHTML = '<span></span><span></span><span></span>';
        messagesDiv.appendChild(div);
        scrollToBottom();
    }

    function hideTyping() {
        var typing = document.getElementById('wpsc-typing-indicator');
        if (typing) typing.remove();
    }

    function scrollToBottom() {
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    function getSessionId() {
        var key = 'wpsc_session_id';
        var id = sessionStorage.getItem(key);
        if (!id) {
            id = 'wpsc_' + Date.now() + '_' + Math.random().toString(36).substring(2, 10);
            sessionStorage.setItem(key, id);
        }
        return id;
    }

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

})();
