(function($) {
    'use strict';

    console.log('[LolaCore MCP] Script loaded. jQuery:', typeof $);

    $(document).ready(function() {
        console.log('[LolaCore MCP] DOM ready. lolacore_ajax:', typeof lolacore_ajax);
        if (typeof lolacore_ajax === 'undefined') {
            console.error('[LolaCore MCP] lolacore_ajax is UNDEFINED — aborting.');
            return;
        }

        const i18n = lolacore_ajax.i18n || {};
        console.log('[LolaCore MCP] Generate button found:', $('#lc-mcp-generate-configs').length);

        // ===== Generate Configs (Status Tab) =====
        const $generateBtn = $('#lc-mcp-generate-configs');
        const $usernameInput = $('#lc-mcp-username');
        const $passwordInput = $('#lc-mcp-app-password');
        const $configsContainer = $('#lc-mcp-configs-container');

        $generateBtn.on('click', function(e) {
            e.preventDefault();

            const username = $usernameInput.val().trim();
            const password = $passwordInput.val().trim();

            if (!password) {
                showToast(i18n.password_required || 'Please enter an Application Password.', 'error');
                $passwordInput.focus();
                return;
            }

            // Build the Base64 credential string for Basic Auth
            const credentials = btoa(username + ':' + password);

            // Populate all templates by replacing {{CREDENTIALS}}
            $configsContainer.find('code[data-template]').each(function() {
                const $code = $(this);
                let template = $code.attr('data-template');
                template = template.replace(/\{\{CREDENTIALS\}\}/g, credentials);
                $code.text(template);
            });

            $configsContainer.slideDown(300);
        });

        // ===== Config Tabs (IDE Selector) =====
        $('.lc-mcp-config-tab-btn').on('click', function() {
            const $btn = $(this);
            const targetId = $btn.data('target');

            $('.lc-mcp-config-tab-btn').removeClass('is-active');
            $('.lc-mcp-config-pane').removeClass('is-active');

            $btn.addClass('is-active');
            $('#' + targetId).addClass('is-active');
        });

        // ===== Copy Buttons =====
        $('.lc-mcp-settings-wrap').on('click', '.lc-mcp-copy-btn', function() {
            const $btn = $(this);
            const targetId = $btn.data('target');
            const textToCopy = $('#' + targetId).text().trim();
            const originalText = $btn.text();

            if (!textToCopy) return;

            navigator.clipboard.writeText(textToCopy).then(function() {
                $btn.text(i18n.copied || 'Copied!');
                setTimeout(function() {
                    $btn.text(originalText);
                }, 2000);
            }).catch(function() {
                // Fallback for non-HTTPS environments
                const textarea = document.createElement('textarea');
                textarea.value = textToCopy;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand('copy');
                    $btn.text(i18n.copied || 'Copied!');
                    setTimeout(function() { $btn.text(originalText); }, 2000);
                } catch (err) {
                    showToast('Failed to copy. Please select and copy manually.', 'error');
                }
                document.body.removeChild(textarea);
            });
        });

        // ===== Toast Notification =====
        function showToast(message, type) {
            // Remove existing toast
            $('.lc-mcp-toast').remove();

            const bgColor = type === 'success' ? 'var(--lc-mint)' : 'var(--lc-salmon)';
            const $toast = $('<div class="lc-mcp-toast"></div>').text(message).css({
                position: 'fixed',
                bottom: '24px',
                right: '24px',
                background: bgColor,
                color: '#fff',
                padding: '12px 24px',
                borderRadius: 'var(--lc-radius-btn)',
                fontFamily: 'var(--lc-font-primary)',
                fontWeight: '600',
                fontSize: '0.9em',
                zIndex: 999999,
                boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
                opacity: 0,
                transform: 'translateY(8px)',
                transition: 'opacity 0.25s, transform 0.25s'
            });

            $('body').append($toast);

            // Trigger animation
            requestAnimationFrame(function() {
                $toast.css({ opacity: 1, transform: 'translateY(0)' });
            });

            setTimeout(function() {
                $toast.css({ opacity: 0, transform: 'translateY(8px)' });
                setTimeout(function() { $toast.remove(); }, 300);
            }, 3000);
        }
    });

})(jQuery);
