/**
 * NewsSync Admin UI - JavaScript
 * Sidebar navigation, section switching, interactions
 *
 * @package NewsSync
 * @version 1.0.0
 */

(function($) {
    'use strict';

    // Wait for DOM ready and window load
    $(document).ready(function() {
        // Auto-dismiss success notices after 5 seconds
        autoDismissNotices();

        // Small delay to ensure all sections are loaded
        setTimeout(function() {
            initSidebarNavigation();
            initExistingFunctionality();
        }, 100);
    });

    /**
     * Auto-dismiss success/info notices after a few seconds
     */
    function autoDismissNotices() {
        const $notices = $('.notice.is-dismissible');
        if ($notices.length > 0) {
            $notices.each(function() {
                const $notice = $(this);
                setTimeout(function() {
                    $notice.fadeOut(400, function() {
                        $(this).remove();
                    });
                }, 5000); // 5 seconds
            });
        }
    }

    // Also try on window load as backup
    $(window).on('load', function() {
        setTimeout(function() {
            if (!$('.newssync-sidebar nav a.active').length) {
                // debug removed: reinitializing fallback
                initSidebarNavigation();
            }
        }, 200);
    });

    /**
     * Initialize sidebar navigation (section switching)
     */
    function initSidebarNavigation() {
        const $sidebarLinks = $('.newssync-sidebar nav a, .newssync-sidebar nav button');
        const $sections = $('.newssync-content-section');
        const $pageTitle = $('.newssync-content-header-title h1');
        const $pageSubtitle = $('.newssync-content-header-subtitle');
        const $headerIcon = $('.newssync-content-header-icon .dashicons');

        // Removed verbose debug logs for production

        if ($sidebarLinks.length === 0 || $sections.length === 0) {
            // New UI not active yet, skip
            return;
        }

        /**
         * Activate a section
         */
        function activateSection(sectionId) {
          try {
            // Verify section exists before activating
            const $targetSection = $sections.filter('[data-section="' + sectionId + '"]');
            if ($targetSection.length === 0) {
                console.warn('NewsSync: section not found:', sectionId);
                return false;
            }

            // Update sidebar active state
            $sidebarLinks.removeClass('active');
            $sidebarLinks.filter('[data-section="' + sectionId + '"]').addClass('active');

            // Show target FIRST, then hide others (safe order)
            $targetSection.addClass('active').css('display', 'block');
            $sections.not($targetSection).removeClass('active').css('display', 'none');

            // Special handling for Feeds section (ensure content loads)
            if (sectionId === 'feeds') {
                setTimeout(function() {
                    $targetSection.find('input, select, textarea').first().trigger('focus').blur();
                }, 250);
            }

            // Update page title and subtitle
            const activeLink = $sidebarLinks.filter('[data-section="' + sectionId + '"]');
            if (activeLink.length && $pageTitle.length) {
                const linkText = activeLink.text().trim();
                $pageTitle.text(linkText);

                // Update subtitle based on section
                const subtitles = {
                    'hub': 'Dashboard and quick stats',
                    'feeds': 'Manage your RSS feeds',
                    'settings': 'Configure plugin settings',
                    'tools': 'Database status and optimization tools',
                    'documentation': 'Learn how to use all shortcode parameters'
                };
                if ($pageSubtitle.length && subtitles[sectionId]) {
                    $pageSubtitle.text(subtitles[sectionId]);
                }

                // Update icon based on section
                const icons = {
                    'hub': 'dashicons-admin-home',
                    'feeds': 'dashicons-rss',
                    'settings': 'dashicons-admin-generic',
                    'tools': 'dashicons-admin-tools',
                    'documentation': 'dashicons-book'
                };
                if ($headerIcon.length && icons[sectionId]) {
                    $headerIcon.removeClass('dashicons-admin-home dashicons-rss dashicons-admin-generic')
                               .addClass(icons[sectionId]);
                }
            }

            // Update URL hash
            if (history.replaceState) {
                history.replaceState(null, null, '#' + sectionId);
            }

            // Auto-dismiss any notices that appear when section is activated
            setTimeout(function() { autoDismissNotices(); }, 250);
          } catch (jsErr) {
            // Fallback: ensure at least the target section stays visible
            console.error('NewsSync activateSection error:', jsErr);
            try {
                $sections.filter('[data-section="' + sectionId + '"]').css('display', 'block');
            } catch(e2) {}
          }
        }

        // Handle sidebar clicks
        $sidebarLinks.on('click', function(e) {
            const href = $(this).attr('href');
            const dataSection = $(this).data('section');

            // Only prevent default for section links (with data-section)
            if (dataSection) {
                e.preventDefault();
                activateSection(dataSection);
            }
        });

        // Handle wizard step links
        $(document).on('click', '.newssync-step-link', function(e) {
            const href = $(this).attr('href');
            if (href && href.startsWith('#')) {
                e.preventDefault();
                const sectionId = href.replace('#', '');
                activateSection(sectionId);
            }
        });

        // Initialize from hash or detect from URL parameters or window flag
        let initialSection = window.location.hash.replace('#', '');

        // PRIORITY 1: Check if server-side forced a specific section (submenu pages)
        if (!initialSection) {
            if (typeof newssyncServerData !== 'undefined' && newssyncServerData.forceSection) {
                initialSection = newssyncServerData.forceSection;
            } else if (window.newssyncForceSection) {
                initialSection = window.newssyncForceSection;
            }
        }

        // PRIORITY 2: Check if server-side set a flag for which tab to activate (legacy)
        if (!initialSection && window.newssyncActivateTab) {
            initialSection = window.newssyncActivateTab;
        }

        // PRIORITY 3: If no hash and no flag, check URL parameters to determine section
        if (!initialSection) {
            const urlParams = new URLSearchParams(window.location.search);
            const page = urlParams.get('page');

            // Map page slugs to sections
            if (page === 'rss-newssync-settings') {
                initialSection = 'settings';
            } else if (page === 'rss-newssync-tools') {
                initialSection = 'tools';
            } else if (page === 'rss-newssync-docs') {
                initialSection = 'documentation';
            } else if (page === 'rss-newssync') {
                // Always default to hub for main page unless hash specifies otherwise
                initialSection = 'hub';
            } else {
                initialSection = 'hub'; // Default
            }
        }

        // Support subtab anchors like #settings-pro or #settings-default
        var initialSubtab = null;
        if ( initialSection && initialSection.indexOf('settings-') === 0 ) {
            initialSubtab = initialSection.replace('settings-','');
            initialSection = 'settings';
        }

        const validSections = ['hub', 'feeds', 'settings', 'tools', 'documentation'];
        if ( validSections.indexOf(initialSection) !== -1 ) {
            activateSection(initialSection);
            if ( initialSection === 'settings' && initialSubtab ) {
                // Attempt to activate inner subtab after a short delay so DOM exists
                setTimeout(function(){
                    var $btn = $('.ns-tab-button[data-tab="' + initialSubtab + '"]');
                    if ( $btn.length ) {
                        $btn.trigger('click');
                    }
                }, 150);
            }
        } else {
            activateSection('hub');
        }
    }

    /**
     * Preserve existing functionality (drag&drop, AJAX, etc.)
     * This ensures old code continues to work with new UI
     */
    function initExistingFunctionality() {
        // Existing drag & drop for feeds is already initialized
        // in admin-feeds.js, so we don't interfere here.

        // Existing Force Import AJAX is also already setup in admin-auto-import.js,
        // so we just ensure compatibility.

        // If there are any conflicts, we can add bridges here.
    }

})(jQuery);
