
(function($) {
    'use strict';

    $(document).ready(function() {
        initTabs();
        initTrackingSettingsToggle();
        initUrlPrefixControls();
        initDataExpiryToggle();
        initAccordion();
        initConfigToggleRows();
        
        initCapabilityDependencies();
        initUTMTemplatesTable();
        initColorPickers();
        initInlineScopeDropdowns();
        initDomainScopeToggles();
    });

    // Function to show the active tab
    // Initialize main settings tabs, hash routing, and URL updates
    function initTabs() {
        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);
            }
        }

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

        checkHash();

        $(window).on('popstate', checkHash);

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

    // Enable/disable tracking-related controls when "Disable Reporting" is toggled
    function initTrackingSettingsToggle() {
        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);
            });
        }

        toggleTrackingSettings();
        $('#linkcentral_disable_reporting').on('change', toggleTrackingSettings);
    }

    // Sync URL prefix select/custom input and live example text
    function initUrlPrefixControls() {
        function updatePrefixExample() {
            var selectedValue = $('#linkcentral_url_prefix_select').val();
            if (selectedValue === 'custom') {
                selectedValue = $('#linkcentral_url_prefix').val();
            }
            $('#prefix-example').text(selectedValue);
        }

        $('#linkcentral_url_prefix_select').on('change', updatePrefixExample);
        $('#linkcentral_url_prefix').on('input', updatePrefixExample);
        updatePrefixExample();

        $('#linkcentral_url_prefix_select').on('change', function() {
            if ($(this).val() === 'custom') {
                $('#linkcentral_url_prefix').show().focus();
            } else {
                $('#linkcentral_url_prefix').hide().val($(this).val());
            }
        });

        if ($('#linkcentral_url_prefix_select').val() === 'custom') {
            $('#linkcentral_url_prefix').show();
        }
    }

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

    // Simple accordion behavior for collapsible sections
    function initAccordion() {
        $('.linkcentral-accordion-header').click(function() {
            $(this).toggleClass('linkcentral-accordion-active');
            $(this).next('.linkcentral-accordion-content').slideToggle();
        });
    }

    // Show/hide extra config rows via "Configure" links for select/checkbox options
    function initConfigToggleRows() {
        function toggleConfigRows(targetSelector, show) {
            var $rows = $(targetSelector);
            if (show) {
                $rows.css('display', 'table-row');
            } else {
                $rows.hide();
            }
        }

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

        $('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'));
                });

                $select.trigger('change');
            }
        });

        $('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'));
                });

                    $checkbox.trigger('change');
            }
        });

        $('.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'));
        });
    }

    // Enforce capability dependency: cannot have create/edit without view
    function initCapabilityDependencies() {
        $('input[value="linkcentral_create_edit_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();

                $('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);
                    }
                });
            }
        });

        $('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();

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

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

    // Manage dynamic UTM templates table (auto-add blank row when last row has content)
    function initUTMTemplatesTable() {
        const $table = $('#linkcentral_utm_templates_table table');
        if (!$table.length) return;

        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('td:first').text(newIndex + 1);
            $newRow.find('input').each(function() {
                const name = $(this).attr('name');
                $(this)
                    .attr('name', name.replace(/\[\d+\]/, '[' + newIndex + ']'))
                    .val('')
                    .removeClass('has-content');
            });

            $tbody.append($newRow);
        }

        $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 WordPress color pickers
    function initColorPickers() {
        $('.wp-color-picker').wpColorPicker();
    }

    // Custom inline dropdown component used inside labels
    function initInlineScopeDropdowns() {
        var $doc = $(document);
        var optionLabels = {};
        $('.linkcentral-inline-dropdown').each(function() {
            var $dd = $(this);
            var $trigger = $dd.find('.linkcentral-inline-dropdown-trigger');
            var $label = $dd.find('.linkcentral-inline-dropdown-label');
            var $hidden = $dd.find('input[type="hidden"]');
            var $panel = $dd.find('.linkcentral-inline-dropdown-panel');
            var $options = $dd.find('.linkcentral-inline-dropdown-option');

            if (!$options.length) return;

            optionLabels[$dd.attr('data-input-name')] = {};
            $options.each(function() {
                var val = $(this).data('value');
                optionLabels[$dd.attr('data-input-name')][val] = $(this).text();
            });

            function setSelected(value) {
                var labels = optionLabels[$dd.attr('data-input-name')];
                if (labels && labels[value]) {
                    $label.text(labels[value]);
                    $hidden.val(value);
                    $hidden.trigger('change');
                }
                $options.attr('aria-selected', 'false');
                $options.filter('[data-value="' + value + '"]').attr('aria-selected', 'true');
            }

            setSelected($hidden.val() || 'all');

            function close() {
                $dd.removeClass('open');
                $trigger.attr('aria-expanded', 'false');
                $panel.attr('hidden', true);
            }

            function open() {
                $('.linkcentral-inline-dropdown.open').not($dd[0]).each(function() {
                    $(this).removeClass('open');
                    $(this).find('.linkcentral-inline-dropdown-trigger').attr('aria-expanded', 'false');
                    $(this).find('.linkcentral-inline-dropdown-panel').attr('hidden', true);
                });
                $dd.addClass('open');
                $trigger.attr('aria-expanded', 'true');
                $panel.attr('hidden', false);
            }

            $trigger.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                if ($dd.hasClass('open')) {
                    close();
                } else {
                    open();
                }
            });

            $options.on('click', function(e) {
                e.preventDefault();
                var val = $(this).data('value');
                setSelected(val);
                close();
            });

            $options.on('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    $(this).trigger('click');
                }
            });
        });

        $doc.on('click', function(e) {
            if (!$(e.target).closest('.linkcentral-inline-dropdown').length) {
                $('.linkcentral-inline-dropdown').removeClass('open');
                $('.linkcentral-inline-dropdown-trigger').attr('aria-expanded', 'false');
                $('.linkcentral-inline-dropdown-panel').attr('hidden', true);
            }
        });
    }

    function initDomainScopeToggles() {
        var mappings = [
            {
                inputName: 'linkcentral_global_nofollow_scope',
                containerSelector: '#linkcentral_nofollow_external_domains_container'
            },
            {
                inputName: 'linkcentral_global_sponsored_scope',
                containerSelector: '#linkcentral_sponsored_external_domains_container'
            },
            {
                inputName: 'linkcentral_global_new_tab_scope',
                containerSelector: '#linkcentral_new_tab_external_domains_container'
            }
        ];

        mappings.forEach(function(mapping) {
            var $scopeInput = $('input[name="' + mapping.inputName + '"]');
            var $container = $(mapping.containerSelector);
            if (!$scopeInput.length || !$container.length) return;

            function toggleVisibility() {
                var show = $scopeInput.val() === 'external_domains';
                $container.toggleClass('is-hidden', !show);
            }

            toggleVisibility();
            $scopeInput.on('change', toggleVisibility);
        });
    }

})(jQuery);