(function($) {
    'use strict';

    $(document).ready(function() {
        // Handle tab clicks
        $('.linkcentral-pagestyles .nav-tab-wrapper a').on('click', function(e) {
            e.preventDefault();
            var tabId = $(this).attr('href').substring(1);
            showActiveTab(tabId, true);
        });

        // Function to show the active tab
        function showActiveTab(tab, updateUrl = false) {
            $('.linkcentral-pagestyles .nav-tab-wrapper a').removeClass('nav-tab-active');
            $('.linkcentral-pagestyles .nav-tab-wrapper a[href="#' + tab + '"]').addClass('nav-tab-active');
            $('.linkcentral-pagestyles .linkcentral-tab-content').hide();
            $('.linkcentral-pagestyles #' + tab).show();
            $('.linkcentral-pagestyles #active_tab').val(tab);

            if (updateUrl) {
                // Update URL without causing page jump
                history.pushState(null, '', '#' + tab);
            }
        }

        // Check if there's a hash in the URL and set the active tab accordingly
        function checkHash() {
            var hash = window.location.hash.substring(1);
            if (hash && $('#' + hash).length) {
                showActiveTab(hash);
            } else {
                // Set initial active tab based on hidden input or default to 'linkcentral-general'
                var activeTab = $('.linkcentral-pagestyles #active_tab').val() || 'linkcentral-general';
                showActiveTab(activeTab);
            }
        }

        // Initial check
        checkHash();

        // Listen for popstate events (back/forward browser navigation)
        $(window).on('popstate', checkHash);

        // Handle clicks on links with hash
        $('a[href^="#"]').on('click', function(e) {
            var tabId = $(this).attr('href').substring(1);
            if (tabId && tabId !== '' && $('#' + tabId).length) {
                e.preventDefault();
                showActiveTab(tabId, true);
            }
        });

        // Function to toggle tracking settings based on Disable Reporting checkbox
        // This function disables checkboxes to prevent interaction and submission when Disable Reporting is checked
        function toggleTrackingSettings() {
            var disableReporting = $('#linkcentral_disable_reporting').is(':checked');
            var trackingFields = [
                '#linkcentral_track_user_agent',
                '#linkcentral_track_unique_visitors',
                '#linkcentral_excluded_ips',
                'input[name="linkcentral_excluded_roles[]"]',
                '#linkcentral_exclude_bots',
                '#linkcentral_enable_ga',
                '#linkcentral_ga_measurement_id',
                '#linkcentral_ga_api_secret'
            ];

            trackingFields.forEach(function(selector) {
                $(selector).prop('disabled', disableReporting);
            });

            var trackingRows = [
                '#linkcentral_track_user_agent',
                '#linkcentral_track_unique_visitors',
                '#linkcentral_excluded_ips',
                'input[name="linkcentral_excluded_roles[]"]',
                '#linkcentral_exclude_bots',
                '#linkcentral_enable_ga'
            ];

            trackingRows.forEach(function(selector) {
                $(selector).closest('tr, div').css('opacity', disableReporting ? 0.4 : 1);
            });
        }

        // Initial call to set the state based on the current checkbox value
        toggleTrackingSettings();

        // Event listener for changes in the Disable Reporting checkbox
        $('#linkcentral_disable_reporting').on('change', toggleTrackingSettings);

        // Function to update the prefix example text based on the selected or custom value
        function updatePrefixExample() {
            var selectedValue = $('#linkcentral_url_prefix_select').val();
            if (selectedValue === 'custom') {
                selectedValue = $('#linkcentral_url_prefix').val();
            }
            $('#prefix-example').text(selectedValue);
        }

        // Event listener for changes in the URL prefix select dropdown
        $('#linkcentral_url_prefix_select').on('change', updatePrefixExample);
        // Event listener for input changes in the custom URL prefix text field
        $('#linkcentral_url_prefix').on('input', updatePrefixExample);
        // Initial update of the prefix example text
        updatePrefixExample();
        
        // Show or hide the custom URL prefix input based on the selected value
        $('#linkcentral_url_prefix_select').on('change', function() {
            if ($(this).val() === 'custom') {
                $('#linkcentral_url_prefix').show().focus();
            } else {
                $('#linkcentral_url_prefix').hide().val($(this).val());
            }
        });

        // Initialize the visibility of the custom URL prefix input
        if ($('#linkcentral_url_prefix_select').val() === 'custom') {
            $('#linkcentral_url_prefix').show();
        }

        // Enable or disable the data expiry period select based on the checkbox state
        $('input[name="linkcentral_enable_data_expiry"]').on('change', function() {
            $('select[name="linkcentral_data_expiry_days"]').prop('disabled', !$(this).is(':checked'));
        });

        // Accordion functionality
        $('.linkcentral-accordion-header').click(function() {
            $(this).toggleClass('linkcentral-accordion-active');
            $(this).next('.linkcentral-accordion-content').slideToggle();
        });

        
        /* 
         * Toggle Rows
         */
        // Generic function to toggle configuration rows
        function toggleConfigRows(targetSelector, show) {
            var $rows = $(targetSelector);
            if (show) {
                $rows.css('display', 'table-row');
            } else {
                $rows.hide();
            }
        }

        // Function to handle visibility of configuration links and rows
        function handleConfigVisibility(triggerElement, showConfig) {
            var $triggerElement = $(triggerElement);
            var $configLink = $triggerElement.siblings('.linkcentral-configure-link');
            var targetSelector = $configLink.data('toggle-rows');
            
            if (showConfig) {
                $configLink.show();
            } else {
                $configLink.hide().removeClass('linkcentral-active');
                if (targetSelector) {
                    toggleConfigRows(targetSelector, false);
                }
            }
        }

        // Event listener for changes in select dropdowns that have configuration options
        $('select').each(function() {
            var $select = $(this);
            var $configLink = $select.siblings('.linkcentral-configure-link');

            if ($configLink.length) {
                $select.on('change', function() {
                    handleConfigVisibility(this, $(this).val() === $configLink.data('target'));
                });

                // Initial setup
                $select.trigger('change');
            }
        });

        // Event listener for checkboxes that have configuration options
        $('input[type="checkbox"]').each(function() {
            var $checkbox = $(this);
            var $configLink = $checkbox.siblings('.linkcentral-configure-link');

            if ($configLink.length) {
                $checkbox.on('change', function() {
                    handleConfigVisibility(this, $(this).is(':checked'));
                });

                // Initial setup
                $checkbox.trigger('change');
            }
        });

        // Toggle visibility of specified rows
        $('.linkcentral-configure-link').on('click', function(e) {
            e.preventDefault();
            var targetSelector = $(this).data('toggle-rows');

            $(this).toggleClass('linkcentral-active');
            toggleConfigRows(targetSelector, $(this).hasClass('linkcentral-active'));
        });


        /* 
         * Country Tracking
         */
        

        /* 
         * Capability Dependencies
         */
        // When create_edit links is checked, ensure view links is checked
        $('input[value="linkcentral_create_edit_links"]').on('change', function() {
            if ($(this).prop('checked')) {
                // Find the view links checkbox in the same row
                const $row = $(this).closest('.linkcentral-capability-role-item');
                const roleName = $row.find('.linkcentral-capability-role-name').text();
                
                // Find and check the view links checkbox for this role
                $('input[value="linkcentral_view_links"]').each(function() {
                    if ($(this).closest('.linkcentral-capability-role-item').find('.linkcentral-capability-role-name').text() === roleName) {
                        $(this).prop('checked', true);
                    }
                });
            }
        });

        // Prevent unchecking view links if create_edit is checked
        $('input[value="linkcentral_view_links"]').on('change', function() {
            if (!$(this).prop('checked')) {
                const $row = $(this).closest('.linkcentral-capability-role-item');
                const roleName = $row.find('.linkcentral-capability-role-name').text();
                
                // Check if create_edit links is enabled for this role
                let hasCreateEdit = false;
                $('input[value="linkcentral_create_edit_links"]').each(function() {
                    if ($(this).closest('.linkcentral-capability-role-item').find('.linkcentral-capability-role-name').text() === roleName) {
                        if ($(this).prop('checked')) {
                            hasCreateEdit = true;
                            return false; // break the loop
                        }
                    }
                });

                if (hasCreateEdit) {
                    $(this).prop('checked', true);
                    alert('You cannot disable View Links while Create & Edit Links is enabled. Please disable that capability first.');
                }
            }
        });

        // Handle UTM Templates table
        function handleUTMTemplatesTable() {
            const $table = $('#linkcentral_utm_templates_table table');
            if (!$table.length) return;

            // Function to add a new empty row
            function addEmptyRow() {
                const $tbody = $table.find('tbody');
                const $lastRow = $tbody.find('tr:last');
                const newIndex = $tbody.find('tr').length;
                
                const $newRow = $lastRow.clone();
                $newRow.find('input').each(function() {
                    const name = $(this).attr('name');
                    $(this)
                        .attr('name', name.replace(/\[\d+\]/, '[' + newIndex + ']'))
                        .val('')
                        .removeClass('has-content');
                });
                
                $tbody.append($newRow);
            }

            // Monitor input in the last row
            $table.on('input', 'tr:last-child input', function() {
                const $lastRow = $(this).closest('tr');
                const hasContent = $lastRow.find('input').toArray().some(input => input.value.trim() !== '');
                
                if (hasContent) {
                    addEmptyRow();
                }
            });
        }

        // Initialize UTM Templates table
        handleUTMTemplatesTable();
        
        // Initialize WordPress color pickers
        $('.wp-color-picker').wpColorPicker();
    });
})(jQuery);