/**
 * 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() {
        // Small delay to ensure all sections are loaded
        setTimeout(function() {
            initSidebarNavigation();
            initExistingFunctionality();
        }, 100);
    });

    // Also try on window load as backup
    $(window).on('load', function() {
        setTimeout(function() {
            if (!$('.newssync-sidebar nav a.active').length) {
                console.log('NewsSync: No active section found on window load, reinitializing...');
                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');

        console.log('NewsSync: Initializing sidebar navigation');
        console.log('NewsSync: Found sidebar links:', $sidebarLinks.length);
        console.log('NewsSync: Found sections:', $sections.length);
        console.log('NewsSync: Section IDs:', $sections.map(function() { return $(this).data('section'); }).get());
        console.log('NewsSync: Link data-sections:', $sidebarLinks.map(function() { return $(this).data('section'); }).get());

        if ($sidebarLinks.length === 0 || $sections.length === 0) {
            // New UI not active yet, skip
            console.warn('NewsSync: Sidebar or sections not found, skipping initialization');
            return;
        }

        /**
         * Activate a section
         */
        function activateSection(sectionId) {
            console.log('NewsSync: activateSection called with', sectionId);
            // Verify section exists before activating
            const $targetSection = $sections.filter(`[data-section="${sectionId}"]`);
            console.log('NewsSync: Found sections for', sectionId, ':', $targetSection.length, 'sections');
            console.log('NewsSync: All available sections:', $sections.map(function() { return $(this).data('section'); }).get());
            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/hide sections
            $sections.removeClass('active').hide();
            $targetSection.addClass('active').fadeIn(200);

            // 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}`);
            }
        }

        // Handle sidebar clicks
        $sidebarLinks.on('click', function(e) {
            const href = $(this).attr('href');
            const dataSection = $(this).data('section');
            console.log('NewsSync: Sidebar link clicked');
            console.log('NewsSync: - href:', href);
            console.log('NewsSync: - data-section:', dataSection);
            console.log('NewsSync: - element:', this);

            // Only prevent default for section links (with data-section)
            if (dataSection) {
                e.preventDefault();
                console.log('NewsSync: Activating section from click:', dataSection);
                activateSection(dataSection);
            } else {
                console.log('NewsSync: No data-section attribute, allowing default behavior');
            }
            // Otherwise let normal links work (Tools, Documentation)
        });

        // 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)
        // Prefer localized `newssyncServerData.forceSection` if available, then fallback to legacy window flag
        if (!initialSection) {
            if (typeof newssyncServerData !== 'undefined' && newssyncServerData.forceSection) {
                initialSection = newssyncServerData.forceSection;
                console.log('NewsSync: Forced section from localized data:', initialSection);
            } else if (window.newssyncForceSection) {
                initialSection = window.newssyncForceSection;
                console.log('NewsSync: Forced section from window.newssyncForceSection:', initialSection);
            }
            console.log('NewsSync: Available sections:', $sections.map(function() { return $(this).data('section'); }).get());
        }

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

        // 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
            }
        }

        console.log('NewsSync: Final initial section:', initialSection);

        const validSections = ['hub', 'feeds', 'settings', 'tools', 'documentation'];
        if (validSections.indexOf(initialSection) !== -1) {
            console.log('NewsSync: Activating section:', initialSection);
            activateSection(initialSection);
        } else {
            console.log('NewsSync: Invalid section, activating hub');
            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);
