jQuery(document).ready(function($) {
    console.log('Folderra Smart Folder: New Folder page loaded.');

    // =========================
    // LOADING & UI HELPERS
    // =========================

    // Function to show loading animation
    function showLoading(message) {
        if (typeof message === 'undefined') {
            message = 'Loading...';
        }
        $('.loading-overlay').remove();
        var loadingHTML =
            '<div class="loading-overlay">' +
                '<div class="loading-content">' +
                    '<div class="loading-spinner"></div>' +
                    '<p style="margin-top: 15px; font-size: 16px; color: #333;">' + message + '</p>' +
                '</div>' +
            '</div>';
        $('body').append(loadingHTML);
    }

    // Function to hide loading
    function hideLoading() {
        $('.loading-overlay').fadeOut(300, function() {
            $(this).remove();
        });
    }

    // Function to disable a button during loading
    function disableButton(button, showSpinner) {
        var $button = $(button);
        if (typeof showSpinner === 'undefined') {
            showSpinner = true;
        }
        $button.prop('disabled', true);
        if (showSpinner) {
            $button.addClass('button-loading');
        }
    }

    // Function to enable a button
    function enableButton(button) {
        var $button = $(button);
        $button.prop('disabled', false);
        $button.removeClass('button-loading');
    }

    // =========================
    // GENERIC POPUP
    // =========================

    // Function to open centered popup
    function openCenteredPopup(content) {
        $('.popup-overlay').remove();
        var $popupOverlay  = $('<div class="popup-overlay"></div>');
        var $popupContent  = $('<div class="popup-content"></div>').html(content);
        $popupOverlay.append($popupContent);
        $('body').append($popupOverlay);

        // Center popup
        $popupContent.css({
            'position': 'fixed',
            'top': '50%',
            'left': '50%',
            'transform': 'translate(-50%, -50%)',
            'backgroundColor': '#fff',
            'padding': '20px',
            'boxShadow': '0 0 10px rgba(0, 0, 0, 0.5)',
            'zIndex': 1001,
            'minWidth': '400px',
            'borderRadius': '8px'
        });

        // Show overlay
        $popupOverlay.css({
            'position': 'fixed',
            'top': 0,
            'left': 0,
            'width': '100%',
            'height': '100%',
            'background': 'rgba(0,0,0,0.7)',
            'zIndex': 1000,
            'display': 'none'
        }).fadeIn();

        // Close popup by clicking outside content
        $popupOverlay.on('click', function(event) {
            if ($(event.target).is('.popup-overlay')) {
                $popupOverlay.fadeOut(function() {
                    $(this).remove();
                });
            }
        });

        return $popupOverlay;
    }

    // =========================
    // FREE TEMPLATE SELECTION & CREATION
    // =========================

    function initFreeTemplateSelection() {
        console.log('Initializing FREE template selection.');
        // Remove previous handlers
        $('.template-card').off('click');

        // Handle clicks on FREE template cards
        $('.template-card').on('click', function() {
            var $card        = $(this);
            var templateSlug = $card.data('template');
            var templateName = $card.find('h4').text().trim();
            console.log('Selected FREE template:', templateSlug, templateName);
            openFolderNamePopup(templateSlug, templateName);
        });
    }

    // Function to open folder name popup for FREE templates
    function openFolderNamePopup(templateSlug, templateName) {
        var popupContent =
            '<div style="text-align: center;">' +
                '<h3 style="margin: 0 0 10px 0;">Create "' + templateName + '" Folder</h3>' +
                '<p style="margin: 0 0 20px 0; color: #666; font-size: 14px;">' +
                    'Choose a name for your new folder' +
                '</p>' +
                '<input type="text" id="folder-name-input" placeholder="e.g., My Blog Posts" ' +
                       'style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">' +
                '<div style="display: flex; gap: 10px; justify-content: center; margin-top: 5px;">' +
                    '<button id="confirm-create-folder-btn" class="button button-primary" data-template="' + templateSlug + '">Create Folder</button>' +
                    '<button id="cancel-create-folder-btn" class="button">Cancel</button>' +
                '</div>' +
            '</div>';

        var popup = openCenteredPopup(popupContent);
        $('#folder-name-input').focus();

        // Confirm button
        $('#confirm-create-folder-btn').on('click', function() {
            var folderName   = $('#folder-name-input').val().trim();
            var templateSlug = $(this).data('template');
            if (!folderName) {
                alert('Please enter a folder name.');
                $('#folder-name-input').focus();
                return;
            }
            createFolderFromTemplate(folderName, templateSlug, $(this));
        });

        // Cancel button
        $('#cancel-create-folder-btn').on('click', function() {
            popup.fadeOut(function() { $(this).remove(); });
        });

        // Enter key handler
        $('#folder-name-input').on('keypress', function(e) {
            if (e.which === 13) {
                $('#confirm-create-folder-btn').click();
            }
        });
    }

    // AJAX: Create Folder (for FREE templates only)
    function createFolderFromTemplate(folderName, templateSlug, $button) {
        console.log('Creating folder:', folderName, 'Template:', templateSlug);
        disableButton($button);
        showLoading('Creating folder...');

        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_create_folder_from_template',
                folder_name: folderName,
                template_slug: templateSlug,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                console.log('Create folder response:', response);
                hideLoading();
                enableButton($button);

                if (response && response.success) {
                    $('.popup-overlay').fadeOut(function() { $(this).remove(); });
                    
                    var confirmationMessage =
                        '<div style="text-align: center; padding: 20px;">' +
                            '<div style="font-size: 48px; margin-bottom: 15px;">✅</div>' +
                            '<h3 style="margin: 0 0 10px 0; color: #333;">Folder Created!</h3>' +
                            '<p style="margin: 0 0 20px 0; color: #666;">' +
                                '"' + folderName + '" has been created successfully.' +
                            '</p>' +
                            '<p style="margin: 0; color: #999; font-size: 12px;">' +
                                'Redirecting to folder details...' +
                            '</p>' +
                        '</div>';

                    var confirmationPopup = openCenteredPopup(confirmationMessage);
                    setTimeout(function() {
                        confirmationPopup.fadeOut(function() { $(this).remove(); });
                        if (response.data && response.data.redirect_url) {
                            window.location.href = response.data.redirect_url;
                        }
                    }, 1500);
                } else {
                    var errorMsg = (response && response.data && response.data.message) ? response.data.message : 'An error occurred. Please try again.';
                    alert('Error: ' + errorMsg);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                hideLoading();
                enableButton($button);
                alert('Could not create folder. Please check your connection and try again.');
            }
        });
    }

    // =========================
    // PRO TEMPLATES MODAL
    // =========================

    // Function to open PRO template modal
    function openProTemplateModal(templateSlug) {
        console.log('Opening PRO template modal for:', templateSlug);
        
        // Get template data from PHP
        var template = fold82smProTemplates[templateSlug];
        if (!template) {
            console.error('PRO template data not found for:', templateSlug);
            return;
        }
        
        // Populate modal content
        $('#fold82sm-pro-modal-icon').text(template.icon);
        $('#fold82sm-pro-modal-title').text(template.name);
        $('#fold82sm-pro-modal-description').text(template.description);
        
        // Build features list
        var featuresHtml = '';
        if (template.features && template.features.length) {
            for (var i = 0; i < template.features.length; i++) {
                featuresHtml += '<li style="margin-bottom: 6px;">' + template.features[i] + '</li>';
            }
        }
        $('#fold82sm-pro-modal-features').html(featuresHtml);
        
        // Update modal link with UTM parameters
        var proLink = 'https://wpsmartfolder.com/pro?utm_source=plugin&utm_medium=modal&utm_campaign=' + 
                      encodeURIComponent(templateSlug) + '_template&utm_content=' + encodeURIComponent(template.name);
        $('#fold82sm-pro-modal-link').attr('href', proLink);
        
        // Show modal
        $('#fold82sm-pro-modal').fadeIn(300);
    }

    // Function to initialize PRO template interactions
    function initProTemplates() {
        console.log('Initializing PRO template showcase.');

        // Handle clicks on the entire PRO template card
        $('.pro-template-card').not('.coming-soon').on('click', function(e) {
            // Don't trigger if clicking the "Learn More" button
            if ($(e.target).is('button') || $(e.target).closest('button').length) {
                return;
            }
            var templateSlug = $(this).data('pro-template');
            openProTemplateModal(templateSlug);
        });
        
        // Handle clicks on the "Learn More" buttons inside PRO cards
        $('.pro-learn-more-btn').on('click', function(e) {
            e.stopPropagation();
            var card = $(this).closest('.pro-template-card');
            var templateSlug = card.data('pro-template');
            openProTemplateModal(templateSlug);
        });
        
        // Close modal handlers (X button and Close button)
        $('#fold82sm-pro-modal-close, #fold82sm-pro-modal-close-btn').on('click', function() {
            $('#fold82sm-pro-modal').fadeOut(200);
        });
        
        // Close modal when clicking on the dark background overlay
        $(window).on('click', function(e) {
            if ($(e.target).is('#fold82sm-pro-modal')) {
                $('#fold82sm-pro-modal').fadeOut(200);
            }
        });
    }

    // =========================
    // PAGE INITIALIZATION
    // =========================

    // Initialize everything when the page is ready
    console.log('Initializing Folderra New Folder page...');
    
    // 1. Set up FREE template creation
    initFreeTemplateSelection();
    
    // 2. Set up PRO template information modals
    initProTemplates();
    
    console.log('Folderra initialization complete.');
});