/**
 * Core Initialization Module
 * Handles: DOM caching, initial setup, tab management
 */
(function($) {
    'use strict';

    window.SchemafyCore = {
        // DOM cache
        $tabs: null,
        $tabContents: null,
        $refreshStats: null,

        /**
         * Initialize the core module
         */
        init: function() {
            this.cacheDom();
            this.bindCoreEvents();
            this.initTabs();
        },

        /**
         * Cache DOM elements for performance
         */
        cacheDom: function() {
            this.$tabs = $('.schemafy-tab-btn-v2');
            this.$tabContents = $('.schemafy-tab-content-v2');
            this.$refreshStats = $('#schemafy-refresh-stats');
        },

        /**
         * Bind core events
         */
        bindCoreEvents: function() {
            this.$tabs.on('click', (e) => this.switchTab(e));
            this.$refreshStats.on('click', () => {
                if (window.SchemafyDashboard) {
                    window.SchemafyDashboard.refreshStats();
                }
            });

            // Sidebar Toggle
            $(document).on('click', '#schemafy-toggle-sidebar', () => this.toggleSidebar());

            // Browser back/forward navigation
            $(window).on('popstate', (e) => this.handlePopState(e));

            // bfcache fix: if the page is restored from the browser's back-forward
            // cache (e.g. after visiting the Freemius pricing page and pressing Back),
            // the nonce embedded in schemafy_ajax will be stale and all AJAX calls will
            // fail.  Force a fresh load so WordPress issues a new nonce.
            window.addEventListener('pageshow', function(event) {
                if (event.persisted) {
                    window.location.reload();
                }
            });
        },

        /**
         * Initialize tabs
         */
        initTabs: function() {
            // Ensure URL detail view is hidden
            $('#schemafy-url-detail-view').hide();

            // Check if there's a tab parameter in the URL
            const urlParams = new URLSearchParams(window.location.search);
            const requestedTab = urlParams.get('tab');
            let activeTab = 'dashboard';

            if (requestedTab) {
                const $requestedTabBtn = $(`.schemafy-tab-btn-v2[data-tab="${requestedTab}"]`);

                if ($requestedTabBtn.length > 0) {
                    activeTab = requestedTab;

                    // Update buttons
                    this.$tabs.removeClass('active');
                    $requestedTabBtn.addClass('active');

                    // Hide all tabs and show only the requested one
                    this.$tabContents.removeClass('active').hide();
                    $(`#schemafy-tab-${requestedTab}`).addClass('active').show();

                    this.updatePageTitle(requestedTab);

                    // Load data for the active tab
                    this.loadTabData(requestedTab);
                } else {
                    // Invalid tab — fall back to dashboard
                    this.activateDefaultTab();
                }
            } else {
                // No tab param — activate dashboard
                this.activateDefaultTab();
            }

            // Store initial state for browser back/forward
            if (window.history && window.history.replaceState) {
                window.history.replaceState({ schemafyTab: activeTab }, '');
            }

            // Auto-open edit modal if edit_schema_id is in URL (e.g., from metabox Edit link)
            const editId = urlParams.get('edit_schema_id');
            if (editId) {
                // Wait for the bulk tab to finish loading data, then open the edit modal
                setTimeout(function() {
                    if (window.SchemafyOperations && typeof window.SchemafyOperations.editSchema === 'function') {
                        window.SchemafyOperations.editSchema(parseInt(editId, 10));
                    }
                }, 800);
            }

            // Auto-load schema directly in the chosen editor when coming from the Gutenberg sidebar.
            // The sidebar sends ?tab=builder&edit_id=X or ?tab=manual&edit_id=X.
            // We bypass the mode-selection modal because the user already chose Smart Builder or Manual JSON.
            const gutenbergEditId = urlParams.get('edit_id');
            if (gutenbergEditId && (requestedTab === 'builder' || requestedTab === 'manual')) {
                const targetMode = requestedTab === 'builder' ? 'smart-builder' : 'manual-json';
                setTimeout(function() {
                    if (!window.SchemafyOperations) return;
                    $.ajax({
                        url: schemafy_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'schemafy_get_schema',
                            id: parseInt(gutenbergEditId, 10),
                            nonce: schemafy_ajax.nonce
                        },
                        success: function(response) {
                            if (response && response.success && response.data) {
                                if (targetMode === 'smart-builder' &&
                                    typeof window.SchemafyOperations.loadSchemaInSmartBuilder === 'function') {
                                    window.SchemafyOperations.loadSchemaInSmartBuilder(response.data);
                                } else if (targetMode === 'manual-json' &&
                                    typeof window.SchemafyOperations.loadSchemaInManualEditor === 'function') {
                                    window.SchemafyOperations.loadSchemaInManualEditor(response.data);
                                }
                            }
                        }
                    });
                }, 500);
            }
        },

        /**
         * Activate the default tab (dashboard)
         */
        activateDefaultTab: function() {
            this.$tabs.removeClass('active').first().addClass('active');
            this.$tabContents.removeClass('active').hide();
            this.$tabContents.first().addClass('active').show();
            this.updatePageTitle('dashboard');
        },

        /**
         * Switch between tabs
         * @param {Event} e - Click event
         * @param {boolean} skipPushState - If true, don't push to browser history (used by popstate handler)
         */
        switchTab: function(e, skipPushState) {
            const $btn = $(e.currentTarget || e);

            const tab = $btn.data('tab');

            // Get the currently active tab before switching
            const $currentActiveBtn = this.$tabs.filter('.active');
            const previousTab = $currentActiveBtn.data('tab');

            // Don't switch if already on this tab
            if (previousTab === tab) {
                return;
            }

            // Reset previous tab's state when leaving
            if (previousTab && previousTab !== tab) {
                this.resetTabState(previousTab);
            }

            // Close URL detail view if open
            $('#schemafy-url-detail-view').hide();

            // Update buttons
            this.$tabs.removeClass('active');
            $btn.addClass('active');

            // Update contents
            this.$tabContents.removeClass('active').hide();
            $(`#schemafy-tab-${tab}`).addClass('active').show();

            // Update page title in topbar
            this.updatePageTitle(tab);

            // Update browser URL so WP menu stays in sync on reload
            if (!skipPushState && window.history && window.history.pushState) {
                const newUrl = tab === 'dashboard'
                    ? 'admin.php?page=schemafy-custom-schema'
                    : 'admin.php?page=schemafy-custom-schema&tab=' + tab;
                window.history.pushState({ schemafyTab: tab }, '', newUrl);

                // Update WordPress admin menu highlighting
                this.updateWPMenuHighlight(tab);
            }

            // Close mobile sidebar after selection
            if (window.innerWidth <= 782) {
                $('.schemafy-sidebar').removeClass('mobile-open');
            }

            // Load tab-specific content
            this.loadTabData(tab);
        },

        /**
         * Load data for a specific tab
         * Called by both initTabs (page load) and switchTab (click)
         * @param {string} tab - The tab slug to load data for
         */
        loadTabData: function(tab) {
            switch(tab) {
                case 'dashboard':
                    if (window.SchemafyDashboard) {
                        window.SchemafyDashboard.loadDashboard();
                    }
                    break;
                case 'bulk':
                    if (window.SchemafyBulk) {
                        window.SchemafyBulk.loadBulkSchemas();
                    }
                    break;
                case 'manual':
                    if (window.SchemafyEditor) {
                        window.SchemafyEditor.loadSiteUrls();
                        window.SchemafyEditor.updateLineNumbers();
                        window.SchemafyEditor.updateEditorStats();
                    }
                    break;
            }
        },

        /**
         * Handle browser back/forward navigation
         */
        handlePopState: function(e) {
            const state = e.originalEvent.state;
            let tab = 'dashboard';

            if (state && state.schemafyTab) {
                tab = state.schemafyTab;
            } else {
                // Read from URL as fallback
                const urlParams = new URLSearchParams(window.location.search);
                tab = urlParams.get('tab') || 'dashboard';
            }

            const $targetBtn = $(`.schemafy-tab-btn-v2[data-tab="${tab}"]`);
            if ($targetBtn.length > 0) {
                this.switchTab({ currentTarget: $targetBtn[0] }, true);
                this.updateWPMenuHighlight(tab);
            }
        },

        /**
         * Update WordPress admin menu highlighting to match current tab
         * @param {string} tab - The active tab slug
         */
        updateWPMenuHighlight: function(tab) {
            const $wpSubmenu = $('#adminmenu .wp-submenu a[href*="schemafy-custom-schema"]');
            if ($wpSubmenu.length === 0) return;

            // Remove current highlight from all submenu items
            $wpSubmenu.closest('li').removeClass('current');
            $wpSubmenu.removeClass('current');

            // Find and highlight the matching submenu item
            const targetUrl = tab === 'dashboard'
                ? 'admin.php?page=schemafy-custom-schema'
                : 'admin.php?page=schemafy-custom-schema&tab=' + tab;

            $wpSubmenu.each(function() {
                const href = $(this).attr('href');
                // Use exact match to avoid highlighting all items when on the dashboard
                // (every plugin URL contains "schemafy-custom-schema" as a substring)
                if (href === targetUrl) {
                    $(this).addClass('current').closest('li').addClass('current');
                }
            });
        },

        /**
         * Reset tab state when leaving a tab
         * @param {string} tabName - Name of the tab being left
         */
        resetTabState: function(tabName) {
            switch(tabName) {
                case 'manual':
                    // Reset Manual JSON editor when leaving
                    if (window.SchemafyOperations && typeof window.SchemafyOperations.resetManualEditor === 'function') {
                        window.SchemafyOperations.resetManualEditor();
                    }
                    break;
                case 'builder':
                    // Reset Smart Builder when leaving
                    if (window.SchemafyOperations && typeof window.SchemafyOperations.resetSmartBuilder === 'function') {
                        window.SchemafyOperations.resetSmartBuilder();
                    }
                    break;
            }

            // Generic seam so optional modules can tear their own tab down
            // without core needing to know they exist.
            $(document).trigger('schemafy:tab-left', [tabName]);
        },

        /**
         * Update page title in topbar based on active tab
         */
        updatePageTitle: function(tabName) {
            const titles = {
                'dashboard': 'Dashboard',
                'builder': 'Smart Builder',
                'manual': 'Manual JSON',
                'ai-paste': 'AI Generator',
                'auto-generator': 'AutoGenerator',
                'bulk': 'Rich Snippets',
                'sitemap': 'Sitemap',
                'metadata': 'Meta Tags',
            };

            const title = titles[tabName] || 'Dashboard';
            $('#schemafy-current-page-title').text(title);
        },

        /**
         * Toggle Sidebar visibility
         */
        toggleSidebar: function() {
            const $sidebar = $('.schemafy-sidebar');
            const $mainContent = $('.schemafy-main-content');

            if (window.innerWidth <= 782) {
                $sidebar.toggleClass('mobile-open');
            } else {
                $sidebar.toggleClass('collapsed');

                if ($sidebar.hasClass('collapsed')) {
                    $mainContent.css('margin-right', '60px');
                } else {
                    $mainContent.css('margin-right', '240px');
                }
            }
        },

        /**
         * Toggle Tools Panel visibility
         */
        toggleToolsPanel: function() {
            const $panel = $('#schemafy-tools-panel');
            const $btn = $('#schemafy-toggle-tools');
            const $arrow = $btn.find('.dashicons-arrow-down-alt2, .dashicons-arrow-up-alt2');

            if ($panel.is(':visible')) {
                $panel.slideUp(200);
                $arrow.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
            } else {
                $panel.slideDown(200);
                $arrow.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
            }
        },

        /**
         * Toggle Extended Filters visibility
         */
        toggleExtendedFilters: function() {
            const $filters = $('#schemafy-extended-filters');
            const $btn = $('#schemafy-toggle-more-filters');

            if ($filters.is(':visible')) {
                $filters.slideUp(200);
                $btn.css('background', 'white');
            } else {
                $filters.slideDown(200);
                $btn.css('background', 'var(--schemafy-gray-100)');
            }
        }
    };

})(jQuery);
