/**
 * Nova Customizer Help Tooltips (Scoped)
 * 
 * Contextual help tooltips for specific Customizer panels.
 * 
 * Rules:
 * - Only applies to allowed panels (Header, Front Page, Blog, Layout...).
 * - Shows (?) icon for optional help text.
 * - Keeps "NOTE:" descriptions visible.
 * - Skips empty descriptions.
 */

(function ($) {
    'use strict';

    var novaTooltips = {
        // IDs of PANELS where tooltips are allowed
        allowedPanels: [
            'blog_over_header_panel',
            'blog_over_frontpage_panel',
            'Blog_Over_panel',
            'blog_over_layout_panel',
            'blog_over_theme_panel',
            'blog_over_footer_panel',
            // 'Theme Options' might be a generic name for one of these, or a missed ID.
            // Adding likely candidates if they exist:
            'blog_over_theme_options',
            'theme_options'
        ],

        // IDs of SECTIONS allowed (if controls are directly in a section not in a panel)
        allowedSections: [
            // Add section IDs here if needed
        ],

        tooltipClass: 'blog-over-help-tooltip',
        iconClass: 'blog-over-help-icon',
        activeClass: 'blog-over-tooltip-active',

        noteKeywords: [
            'NOTE:', 'Note:', 'note:',
            'IMPORTANT:', 'Important:',
            'WARNING:', 'Warning:',
            'REQUIRED:', 'Required:'
        ],

        init: function () {
            var self = this;

            if (typeof wp === 'undefined' || typeof wp.customize === 'undefined') {
                return;
            }



            // Process immediately and observe
            self.processControls();
            self.setupObserver();

            // Bind to ready as backup
            wp.customize.bind('ready', function () {
                self.processControls();
                self.setupObserver();
            });

            self.bindEvents();
        },

        bindEvents: function () {
            var self = this;

            // Click Interaction
            $(document).on('click', '.' + self.iconClass, function (e) {
                e.preventDefault();
                e.stopPropagation();
                var $icon = $(this);
                var tooltipId = $icon.attr('aria-describedby');
                var $tooltip = $('#' + tooltipId);
                self.toggleTooltip($icon, $tooltip);
            });

            // Hover Interaction
            $(document).on('mouseenter', '.' + self.iconClass, function () {
                var $icon = $(this);
                var tooltipId = $icon.attr('aria-describedby');
                var $tooltip = $('#' + tooltipId);
                self.showTooltip($icon, $tooltip);
            });

            $(document).on('mouseleave', '.' + self.iconClass, function () {
                var $icon = $(this);
                var tooltipId = $icon.attr('aria-describedby');
                var $tooltip = $('#' + tooltipId);
                setTimeout(function () {
                    if (!$tooltip.is(':hover')) {
                        self.hideTooltip($icon, $tooltip);
                    }
                }, 100);
            });

            // Close on outside click/ESC
            $(document).on('click', function (e) {
                if (!$(e.target).closest('.' + self.iconClass + ', .' + self.tooltipClass).length) {
                    self.hideAllTooltips();
                }
            });
            $(document).on('keydown', function (e) {
                if (e.key === 'Escape') {
                    self.hideAllTooltips();
                }
            });
        },

        setupObserver: function () {
            var self = this;
            var targetNode = document.getElementById('customize-controls');
            if (!targetNode) return;

            var observer = new MutationObserver(function (mutations) {
                var shouldProcess = false;
                for (var mutation of mutations) {
                    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                        shouldProcess = true;
                        break;
                    }
                }
                if (shouldProcess) {
                    if (self._debounceTimer) clearTimeout(self._debounceTimer);
                    // Process almost immediately to prevent UI lag
                    self._debounceTimer = setTimeout(function () {
                        self.processControls();
                    }, 10);
                }
            });
            observer.observe(targetNode, { childList: true, subtree: true });
        },

        // Check if a control is in an allowed Panel/Section
        isScoped: function (controlId) {
            var self = this;

            // Get control object from Customizer API
            var control = wp.customize.control(controlId);
            if (!control) return false; // Not a registered control

            var sectionId = control.section();
            if (!sectionId) return false;

            // Check if Section is strictly allowed
            if (self.allowedSections.indexOf(sectionId) !== -1) return true;

            // Check Panel
            var section = wp.customize.section(sectionId);
            if (section && section.panel()) {
                var panelId = section.panel();
                if (self.allowedPanels.indexOf(panelId) !== -1) {
                    return true;
                }
            }

            return false;
        },

        isNoteDescription: function (text) {
            var self = this;
            for (var i = 0; i < self.noteKeywords.length; i++) {
                if (text.indexOf(self.noteKeywords[i]) !== -1) return true;
            }
            return false;
        },

        processControls: function () {
            var self = this;

            $('.customize-control:not(.blog-over-tooltip-processed)').each(function () {
                var $control = $(this);

                // Get Control ID (remove 'customize-control-' prefix)
                var domId = $control.attr('id') || '';
                var controlId = domId.replace('customize-control-', '');

                // SCOPE CHECK: Only proceed if this control is in a whitelisted panel
                if (!self.isScoped(controlId)) {
                    // Mark as processed so we don't check again, but don't add tooltip
                    // Actually, let's NOT mark as processed in case it moves? 
                    // No, controls rarely move panels dynamically. Safe to mark.
                    $control.addClass('blog-over-tooltip-processed blog-over-out-of-scope');
                    return;
                }

                // Description & Label finding
                var $description = $control.find('.description.customize-control-description');
                var $label = $control.find('.customize-control-title');
                if ($label.length === 0) $label = $control.find('.customize-control-title-label');

                if ($description.length === 0 || $label.length === 0) return;

                var descriptionText = $description.text().trim();
                if (!descriptionText || descriptionText === '') return;

                // Note Check
                if (self.isNoteDescription(descriptionText)) {
                    $control.addClass('blog-over-tooltip-processed blog-over-has-note');
                    return;
                }

                // Add Tooltip
                self.addHelpIcon($control, $label, $description);
                $control.addClass('blog-over-tooltip-processed');
            });
        },

        addHelpIcon: function ($control, $label, $description) {
            var self = this;
            var uniqueId = 'blog-over-tooltip-' + Math.floor(Math.random() * 1000000);

            var $icon = $('<button>', {
                type: 'button',
                class: self.iconClass,
                'aria-label': 'Show help',
                'aria-describedby': uniqueId,
                html: '<span class="blog-over-help-icon-inner">?</span>'
            });

            var $tooltip = $('<div>', {
                id: uniqueId,
                class: self.tooltipClass,
                role: 'tooltip',
                'aria-hidden': 'true',
                html: $description.html()
            });

            $description.addClass('blog-over-description-hidden');
            $label.append($icon);
            $('body').append($tooltip);
        },

        showTooltip: function ($icon, $tooltip) {
            var self = this;
            self.hideAllTooltips();
            self.positionTooltip($icon, $tooltip);
            $tooltip.addClass(self.activeClass).attr('aria-hidden', 'false');
            $icon.addClass(self.activeClass).attr('aria-expanded', 'true');
        },

        hideTooltip: function ($icon, $tooltip) {
            var self = this;
            $tooltip.removeClass(self.activeClass).attr('aria-hidden', 'true');
            $icon.removeClass(self.activeClass).attr('aria-expanded', 'false');
        },

        hideAllTooltips: function () {
            var self = this;
            $('.' + self.tooltipClass).removeClass(self.activeClass).attr('aria-hidden', 'true');
            $('.' + self.iconClass).removeClass(self.activeClass).attr('aria-expanded', 'false');
        },

        toggleTooltip: function ($icon, $tooltip) {
            var self = this;
            if ($tooltip.hasClass(self.activeClass)) {
                self.hideTooltip($icon, $tooltip);
            } else {
                self.showTooltip($icon, $tooltip);
            }
        },

        positionTooltip: function ($icon, $tooltip) {
            var iconOffset = $icon.offset();
            $tooltip.css({
                top: iconOffset.top + $icon.outerHeight() + 10,
                left: iconOffset.left - 20,
                position: 'fixed',
                zIndex: 9999999
            });
        }
    };

    $(document).ready(function () {
        novaTooltips.init();
    });

})(jQuery);
