/**
 * Event Monster Layout Builder JavaScript
 * Handles drag-and-drop functionality and layout management
 */

(function($) {
    'use strict';
    
    let layoutData = {
        sections: []
    };
    
    // Initialize layout builder
    function initLayoutBuilder() {
        console.log('Layout builder initialization started');

        // Check if already initialized
        if ($('.em-layout-builder-wrapper').data('initialized')) {
            console.log('Layout builder already initialized');
            return;
        }

        // Mark as initialized
        $('.em-layout-builder-wrapper').data('initialized', true);

        // Mode switching - STARTER VERSION: Only preset mode allowed
        $('.em-mode-buttons button').on('click', function() {
            const mode = $(this).data('mode');

            // STARTER VERSION: Block custom mode
            if (mode === 'custom') {
                alert('Custom Layout Builder is a Pro feature. Upgrade to Pro for drag-and-drop custom layouts with unlimited components!');
                return;
            }

            $('.em-mode-buttons button').removeClass('button-primary');
            $(this).addClass('button-primary');

            if (mode === 'preset') {
                $('.em-preset-layouts').show();
                $('.em-custom-builder').hide();

                // Set to selected preset or default
                const selectedPreset = $('.em-preset-option.selected').data('layout') || 'default';
                $('#layout-preference').val(selectedPreset);

                // Clear custom layout data
                $('#custom-layout-data').val('');

                console.log('Switched to preset mode, layout preference:', selectedPreset);
            }
            // Custom mode disabled in Starter version
        });

        // Preset layout selection
        $('.em-preset-option').on('click', function() {
            $('.em-preset-option').removeClass('selected');
            $(this).addClass('selected');
            const selectedLayout = $(this).data('layout');
            $('#layout-preference').val(selectedLayout);

            // Debug: Confirm preset selection
            console.log('Preset selected:', selectedLayout);
            console.log('Layout preference field updated to:', $('#layout-preference').val());

            // Clear custom layout data when preset is selected
            $('#custom-layout-data').val('');
        });

        // Initialize the correct mode based on current settings
        // STARTER VERSION: Force preset mode
        let currentLayout = $('#layout-preference').val();
        console.log('Initializing layout builder with current layout:', currentLayout);

        // Force preset mode in Starter version
        if (currentLayout === 'custom') {
            currentLayout = 'default';
            $('#layout-preference').val('default');
        }

        $('#preset-mode').click();
        // Select the current preset
        $('.em-preset-option[data-layout="' + currentLayout + '"]').addClass('selected');
        console.log('Selected preset option for:', currentLayout);

        // Start building button
        $('#start-building').on('click', function() {
            addSection('single');
        });
        
        // Add section button
        $('#add-section').on('click', function() {
            showSectionTypeModal();
        });
        
        // Clear layout
        $('#clear-layout').on('click', function() {
            if (confirm('Are you sure you want to clear the entire layout?')) {
                clearLayout();
            }
        });
        
        // Save layout
        $('#save-layout').on('click', function() {
            saveLayout();
        });

        // Reset layout
        $('#reset-layout').on('click', function() {
            if (confirm('Are you sure you want to reset to default layout?')) {
                resetLayout();
            }
        });
        
        // Initialize drag and drop
        initDragAndDrop();
        
        // Load existing custom layout if available
        loadExistingLayout();
    }
    
    // Initialize drag and drop functionality
    function initDragAndDrop() {
        
        // Make components draggable
        $('.em-component-item').draggable({
            helper: 'clone',
            revert: 'invalid',
            zIndex: 1000,
            start: function(event, ui) {
                ui.helper.addClass('em-dragging');
            }
        });
        
        // Make canvas droppable
        $('#layout-canvas').droppable({
            accept: '.em-component-item, .em-section-component',
            drop: function(event, ui) {
                const componentKey = ui.draggable.data('component');
                if (componentKey && layoutData.sections.length === 0) {
                    // First component - create a section
                    addSection('single', [componentKey]);
                }
            }
        });
    }
    
    // Add a new section
    function addSection(type, components = []) {
        const sectionId = 'section-' + Date.now();
        const section = {
            id: sectionId,
            type: type,
            components: components
        };
        
        layoutData.sections.push(section);
        renderSection(section);
        updateCanvasVisibility();
    }
    
    // Render a section in the canvas
    function renderSection(section) {
        const sectionHtml = `
            <div class="em-layout-section" data-section-id="${section.id}" data-section-type="${section.type}">
                <div class="em-section-header">
                    <div class="em-section-info">
                        <span class="em-section-type">${getSectionTypeName(section.type)}</span>
                        <span class="em-section-count">${section.components.length} components</span>
                    </div>
                    <div class="em-section-actions">
                        <button type="button" class="em-section-settings" title="Section Settings">
                            <span class="dashicons dashicons-admin-generic"></span>
                        </button>
                        <button type="button" class="em-section-delete" title="Delete Section">
                            <span class="dashicons dashicons-trash"></span>
                        </button>
                    </div>
                </div>
                <div class="em-section-content em-section-${section.type}">
                    ${renderSectionComponents(section)}
                </div>
            </div>
        `;
        
        $('#layout-canvas').append(sectionHtml);
        
        // Make section sortable
        makeSectionSortable(section.id);
        
        // Bind section events
        bindSectionEvents(section.id);
    }
    
    // Render components within a section
    function renderSectionComponents(section) {
        if (section.components.length === 0) {
            return `
                <div class="em-section-placeholder">
                    <span class="dashicons dashicons-plus-alt"></span>
                    <p>Drop components here</p>
                </div>
            `;
        }
        
        let html = '';
        section.components.forEach(componentKey => {
            const component = getComponentData(componentKey);
            if (component) {
                html += `
                    <div class="em-section-component" data-component="${componentKey}">
                        <div class="em-component-preview">
                            <span class="dashicons ${component.icon}"></span>
                            <div class="em-component-details">
                                <strong>${component.name}</strong>
                                <small>${component.description}</small>
                            </div>
                            <button type="button" class="em-component-remove" title="Remove Component">
                                <span class="dashicons dashicons-no-alt"></span>
                            </button>
                        </div>
                    </div>
                `;
            }
        });
        
        return html;
    }
    
    // Make section components sortable
    function makeSectionSortable(sectionId) {
        $(`[data-section-id="${sectionId}"] .em-section-content`).sortable({
            items: '.em-section-component',
            placeholder: 'em-component-placeholder',
            update: function(event, ui) {
                updateSectionComponents(sectionId);
            }
        }).droppable({
            accept: '.em-component-item',
            drop: function(event, ui) {
                const componentKey = ui.draggable.data('component');
                if (componentKey) {
                    addComponentToSection(sectionId, componentKey);
                }
            }
        });
    }
    
    // Add component to section
    function addComponentToSection(sectionId, componentKey) {
        const section = layoutData.sections.find(s => s.id === sectionId);
        if (section && !section.components.includes(componentKey)) {
            section.components.push(componentKey);
            refreshSection(sectionId);
        }
    }
    
    // Remove component from section
    function removeComponentFromSection(sectionId, componentKey) {
        const section = layoutData.sections.find(s => s.id === sectionId);
        if (section) {
            section.components = section.components.filter(c => c !== componentKey);
            refreshSection(sectionId);
        }
    }
    
    // Update section components order
    function updateSectionComponents(sectionId) {
        const section = layoutData.sections.find(s => s.id === sectionId);
        if (section) {
            const components = [];
            $(`[data-section-id="${sectionId}"] .em-section-component`).each(function() {
                components.push($(this).data('component'));
            });
            section.components = components;
        }
    }
    
    // Refresh section display
    function refreshSection(sectionId) {
        const section = layoutData.sections.find(s => s.id === sectionId);
        if (section) {
            const $section = $(`[data-section-id="${sectionId}"]`);
            $section.find('.em-section-content').html(renderSectionComponents(section));
            $section.find('.em-section-count').text(section.components.length + ' components');
            makeSectionSortable(sectionId);
            bindComponentEvents(sectionId);
        }
    }
    
    // Bind section events
    function bindSectionEvents(sectionId) {
        const $section = $(`[data-section-id="${sectionId}"]`);
        
        // Section settings
        $section.find('.em-section-settings').on('click', function() {
            showSectionSettings(sectionId);
        });
        
        // Delete section
        $section.find('.em-section-delete').on('click', function() {
            if (confirm('Are you sure you want to delete this section?')) {
                deleteSection(sectionId);
            }
        });
        
        bindComponentEvents(sectionId);
    }
    
    // Bind component events
    function bindComponentEvents(sectionId) {
        const $section = $(`[data-section-id="${sectionId}"]`);
        
        // Remove component
        $section.find('.em-component-remove').on('click', function() {
            const componentKey = $(this).closest('.em-section-component').data('component');
            removeComponentFromSection(sectionId, componentKey);
        });
    }
    
    // Delete section
    function deleteSection(sectionId) {
        layoutData.sections = layoutData.sections.filter(s => s.id !== sectionId);
        $(`[data-section-id="${sectionId}"]`).remove();
        updateCanvasVisibility();
    }
    
    // Show section type selection modal
    function showSectionTypeModal() {
        const modal = `
            <div class="em-modal-overlay">
                <div class="em-modal">
                    <div class="em-modal-header">
                        <h3>Choose Section Type</h3>
                        <button type="button" class="em-modal-close">&times;</button>
                    </div>
                    <div class="em-modal-content">
                        <div class="em-section-types">
                            <div class="em-section-type-option" data-type="single">
                                <h4>Single Column</h4>
                                <p>Full-width components</p>
                            </div>
                            <div class="em-section-type-option" data-type="two_column_equal">
                                <h4>Two Columns (Equal)</h4>
                                <p>1:1 ratio columns</p>
                            </div>
                            <div class="em-section-type-option" data-type="two_column_wide">
                                <h4>Two Columns (Wide)</h4>
                                <p>2:1 ratio columns</p>
                            </div>
                            <div class="em-section-type-option" data-type="three_column">
                                <h4>Three Columns</h4>
                                <p>1:1:1 ratio columns</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modal);
        
        // Bind modal events
        $('.em-modal-close, .em-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                $('.em-modal-overlay').remove();
            }
        });
        
        $('.em-section-type-option').on('click', function() {
            const type = $(this).data('type');
            addSection(type);
            $('.em-modal-overlay').remove();
        });
    }
    
    // Utility functions
    function getSectionTypeName(type) {
        const names = {
            'single': 'Single Column',
            'two_column_equal': 'Two Columns (1:1)',
            'two_column_wide': 'Two Columns (2:1)',
            'three_column': 'Three Columns',
            'four_column': 'Four Columns'
        };
        return names[type] || type;
    }
    
    function getComponentData(componentKey) {
        // This would normally come from the PHP data
        const components = window.emComponents || {};
        const componentData = components[componentKey];

        if (!componentData) {
            console.warn('Component data not found for:', componentKey);
            // Return default data
            return {
                name: componentKey.charAt(0).toUpperCase() + componentKey.slice(1),
                description: 'Component description',
                icon: 'dashicons-admin-generic'
            };
        }

        return componentData;
    }
    
    function updateCanvasVisibility() {
        if (layoutData.sections.length === 0) {
            $('.em-canvas-placeholder').show();
        } else {
            $('.em-canvas-placeholder').hide();
        }
    }
    
    function clearLayout() {
        layoutData.sections = [];
        $('#layout-canvas').empty().append(`
            <div class="em-canvas-placeholder">
                <span class="dashicons dashicons-layout"></span>
                <p>Drag components here to build your layout</p>
                <button type="button" class="button button-primary" id="start-building">Start Building</button>
            </div>
        `);
        $('#start-building').on('click', function() {
            addSection('single');
        });
    }
    
    function saveLayout() {
        // Only save custom layout if we're in custom mode
        if ($('#custom-mode').hasClass('button-primary')) {
            const layoutConfig = convertToLayoutConfig();
            const layoutJson = JSON.stringify(layoutConfig);

            console.log('Saving custom layout config:', layoutConfig);
            console.log('Layout JSON:', layoutJson);

            $('#custom-layout-data').val(layoutJson);
            $('#layout-preference').val('custom');

            // Debug: Check if fields exist and have values
            console.log('Layout preference field value:', $('#layout-preference').val());
            console.log('Custom layout field value:', $('#custom-layout-data').val());

            // Show success message
            showNotice('Layout configuration updated! Save the post to apply changes.', 'info');
        } else {
            // In preset mode, don't override the preset selection
            console.log('In preset mode, not saving custom layout');
            console.log('Current layout preference:', $('#layout-preference').val());

            // Show message for preset mode
            showNotice('Preset layout selected! Save the post to apply changes.', 'info');
        }
    }
    
    function convertToLayoutConfig() {
        const config = {};
        
        layoutData.sections.forEach(section => {
            if (!config[section.type]) {
                config[section.type] = [];
            }
            
            if (['single', 'single_full', 'single_end'].includes(section.type)) {
                config[section.type] = config[section.type].concat(section.components);
            } else {
                config[section.type].push(section.components);
            }
        });
        
        return config;
    }
    
    function loadExistingLayout() {
        const existingData = $('#custom-layout-data').val();
        console.log('Loading existing layout data:', existingData);

        if (existingData && existingData.trim() !== '') {
            try {
                const config = JSON.parse(existingData);
                console.log('Parsed layout config:', config);
                loadLayoutFromConfig(config);
            } catch (e) {
                console.error('Error loading existing layout:', e);
                console.log('Invalid JSON data:', existingData);
            }
        } else {
            console.log('No existing layout data found');
        }
    }
    
    function loadLayoutFromConfig(config) {
        clearLayout();

        if (!config || typeof config !== 'object') {
            console.log('No valid layout config to load');
            return;
        }

        Object.keys(config).forEach(sectionType => {
            const sectionData = config[sectionType];

            if (!sectionData) {
                return;
            }

            if (['single', 'single_full', 'single_end'].includes(sectionType)) {
                if (Array.isArray(sectionData) && sectionData.length > 0) {
                    addSection(sectionType, sectionData);
                }
            } else {
                if (Array.isArray(sectionData)) {
                    sectionData.forEach(components => {
                        if (Array.isArray(components) && components.length > 0) {
                            addSection(sectionType, components);
                        }
                    });
                }
            }
        });
    }
    
    function resetLayout() {
        $('#layout-preference').val('default');
        $('#custom-layout-data').val('');
        clearLayout();
        showNotice('Layout reset to default', 'info');
    }
    
    function showNotice(message, type = 'info') {
        const notice = `<div class="notice notice-${type} is-dismissible"><p>${message}</p></div>`;
        $('.em-layout-builder-wrapper').prepend(notice);
        setTimeout(() => {
            $('.notice').fadeOut();
        }, 3000);
    }
    
    // Expose initialization function globally
    window.initLayoutBuilder = initLayoutBuilder;

    // Initialize when document is ready
    $(document).ready(function() {
        if ($('.em-layout-builder-wrapper').length) {
            initLayoutBuilder();
        }
    });

})(jQuery);
