/**
 * Popup Settings Enhancement Script
 * Handles dynamic tab visibility based on popup type
 */

jQuery(document).ready(function($) {
    'use strict';

    // Initialize popup settings enhancement
    var PopupSettingsEnhancer = {

        init: function() {
            this.bindEvents();
            this.initializeTabVisibility();
        },

        bindEvents: function() {
            // Listen for popup type changes (if applicable)
            $(document).on('change', 'input[name="popup_type"], select[name="popup_type"]', this.handlePopupTypeChange.bind(this));

            // Handle tab switching
            $(document).on('click', '.v_tabs_list li', this.handleTabSwitch.bind(this));

            // Handle main tab switching
            $(document).on('click', '.tabs_list li', this.handleMainTabSwitch.bind(this));
        },

        handlePopupTypeChange: function(e) {
            var popupType = $(e.target).val();
            this.updateTabVisibility(popupType);
        },

        handleTabSwitch: function(e) {
            e.preventDefault();
            var $clickedTab = $(e.currentTarget);
            var tabId = $clickedTab.data('id');
            var $tabContainer = $clickedTab.closest('.vertical_tabs');

            // Remove active class from all tabs and content
            $tabContainer.find('.v_tabs_list li').removeClass('active');
            $tabContainer.find('.v_tab_content').removeClass('active');

            // Add active class to clicked tab and corresponding content
            $clickedTab.addClass('active');
            $tabContainer.find('#' + tabId + '.v_tab_content').addClass('active');
        },

        handleMainTabSwitch: function(e) {
            e.preventDefault();
            var $clickedTab = $(e.currentTarget);
            var tabId = $clickedTab.data('id');

            // Remove active class from all main tabs and content
            $('.tabs_list li').removeClass('active');
            $('.tab_content').removeClass('active');

            // Add active class to clicked tab and corresponding content
            $clickedTab.addClass('active');
            $('#' + tabId + '.tab_content').addClass('active');
        },

        updateTabVisibility: function(popupType) {
            var self = this;

            // Handle general tabs visibility
            var $generalTabs = $('.tabs_content #general .v_tabs_list li');

            $generalTabs.each(function() {
                var $tab = $(this);
                var tabId = $tab.data('id');
                var $tabContent = $('#' + tabId + '.v_tab_content');

                // Show/hide based on popup type
                if (tabId === 'pdf' && popupType !== 'pdf') {
                    $tab.hide();
                    $tabContent.hide();
                } else if (tabId === 'video' && popupType !== 'video') {
                    $tab.hide();
                    $tabContent.hide();
                } else if (tabId === 'image_gallery' && popupType !== 'image_gallery') {
                    $tab.hide();
                    $tabContent.hide();
                } else if (tabId === 'pdf' && popupType === 'pdf') {
                    $tab.show();
                    $tabContent.show();
                } else if (tabId === 'video' && popupType === 'video') {
                    $tab.show();
                    $tabContent.show();
                } else if (tabId === 'feedback_appearance' && popupType !== 'feedback') {
                    $tab.hide();
                    $tabContent.hide();
                } else if (tabId === 'feedback_appearance' && popupType === 'feedback') {
                    $tab.show();
                    $tabContent.show();
                } else if (tabId === 'image_gallery' && popupType === 'image_gallery') {
                    $tab.show();
                    $tabContent.show();
                } else {
                    // Show core tabs and other extension tabs
                    $tab.show();
                    $tabContent.show();
                }
            });

            // Ensure at least one tab is active
            this.ensureActiveTab();
        },

        ensureActiveTab: function() {
            var $generalTabs = $('.tabs_content #general .v_tabs_list');
            var $visibleTabs = $generalTabs.find('li:visible');
            var $activeTabs = $generalTabs.find('li.active:visible');

            // If no visible tabs are active, activate the first visible tab
            if ($activeTabs.length === 0 && $visibleTabs.length > 0) {
                var $firstTab = $visibleTabs.first();
                var tabId = $firstTab.data('id');

                // Remove all active classes
                $generalTabs.find('li').removeClass('active');
                $('.tabs_content #general .v_tab_content').removeClass('active');

                // Activate first visible tab
                $firstTab.addClass('active');
                $('#' + tabId + '.v_tab_content').addClass('active');
            }
        },

        initializeTabVisibility: function() {
            // Get current popup type from form data or URL
            var popupType = this.getCurrentPopupType();

            if (popupType) {
                this.updateTabVisibility(popupType);
            }

            // Ensure condition tabs are properly initialized
            this.initializeConditionTabs();
        },

        getCurrentPopupType: function() {
            // Try to get popup type from various sources
            var popupType = '';

            // From form inputs
            var $popupTypeInput = $('input[name="popup_type"]:checked, select[name="popup_type"]');
            if ($popupTypeInput.length) {
                popupType = $popupTypeInput.val();
            }

            // From URL parameters
            if (!popupType) {
                var urlParams = new URLSearchParams(window.location.search);
                popupType = urlParams.get('type') || '';
            }

            // From hidden inputs
            if (!popupType) {
                var $hiddenType = $('input[name="popup_temp_type"]');
                if ($hiddenType.length) {
                    popupType = $hiddenType.val().replace('popup_', '');
                }
            }

            return popupType;
        },

        initializeConditionTabs: function() {
            // Ensure Custom Targeting is available when extension is active
            var $conditionTabs = $('#condition .v_tabs_list');
            var $targetingTab = $conditionTabs.find('li[data-id="targeting"]');

            // If Custom Targeting extension is loaded, ensure it's properly initialized
            if ($targetingTab.length && typeof window.customTargetingInit === 'function') {
                window.customTargetingInit();
            }
        }
    };

    // Initialize the enhancer
    PopupSettingsEnhancer.init();

    // Make available globally for other scripts
    window.PopupSettingsEnhancer = PopupSettingsEnhancer;

    // Add CSS for smooth transitions
    $('<style>')
        .prop('type', 'text/css')
        .html(`
            .v_tabs_list li {
                transition: opacity 0.3s ease;
            }
            .v_tabs_list li:not(:visible) {
                opacity: 0;
            }
            .v_tab_content {
                transition: opacity 0.3s ease;
            }
            .v_tab_content.active {
                opacity: 1;
            }
            .v_tab_content:not(.active) {
                opacity: 0;
                pointer-events: none;
                display: none !important;
            }
        `)
        .appendTo('head');
});