/**
 * Admin Settings: Interactive Features
 * 
 * Handles dynamic show/hide of settings fields and security warnings
 * based on checkbox states - matches original admin.php functionality.
 */

(function($) {
    'use strict';

    /**
     * Initialize tab navigation with session persistence
     */
    function initTabNavigation() {
        var radios = document.querySelectorAll('.thespl-tab-radio');
        
        function saveActiveTab() {
            var id = '';
            radios.forEach(function(r) {
                if (r.checked) {
                    id = r.id;
                }
            });
            if (id) {
                try {
                    sessionStorage.setItem('thespl-active-tab', id);
                } catch (e) {}
            }
        }
        
        // Event Listener für Tab-Wechsel
        radios.forEach(function(radio) {
            radio.addEventListener('change', saveActiveTab);
        });
        
        // Gespeicherten Tab wiederherstellen
        var saved = '';
        try {
            saved = sessionStorage.getItem('thespl-active-tab') || '';
        } catch (e) {}
        if (saved) {
            var savedRadio = document.getElementById(saved);
            if (savedRadio) {
                savedRadio.checked = true;
            }
        }
    }

    function initSettingsInteractivity() {
        // Audio Config fields are handled by embedded scripts in render functions
        // Security Section Toggles - only handle security-related fields here

        // Security Section Toggles
        var secToggle = document.querySelector('input[name="thespl_player_settings[streaming_security_enabled]"]');
        var secLifeInput = document.querySelector('input[name="thespl_player_settings[streaming_token_lifetime]"]');
        var secLifeWrapper = secLifeInput ? secLifeInput.closest('tr') : null;

        var rlToggle = document.querySelector('input[name="thespl_player_settings[streaming_rate_limit_enabled]"]');
        var rlRpmInput = document.querySelector('input[name="thespl_player_settings[streaming_rate_limit_rpm]"]');
        var rlBurstInput = document.querySelector('input[name="thespl_player_settings[streaming_rate_limit_burst]"]');
        var rlRpmWrapper = rlRpmInput ? rlRpmInput.closest('tr') : null;
        var rlBurstWrapper = rlBurstInput ? rlBurstInput.closest('tr') : null;

        var htToggle = document.querySelector('input[name="thespl_player_settings[streaming_htaccess_enabled]"]');

        var showVerifToggle = document.querySelector('input[name="thespl_player_settings[show_security_verification]"]');
        var showVerifWrapper = showVerifToggle ? showVerifToggle.closest('tr') : null;

        function toggleSecurityFields() {
            if(secLifeWrapper){ secLifeWrapper.style.display = (secToggle && secToggle.checked) ? "" : "none"; }
            var rlOn = (rlToggle && rlToggle.checked);
            if(rlRpmWrapper){ rlRpmWrapper.style.display = rlOn ? "" : "none"; }
            if(rlBurstWrapper){ rlBurstWrapper.style.display = rlOn ? "" : "none"; }

            var anySec = (secToggle && secToggle.checked) || (rlToggle && rlToggle.checked) || (htToggle && htToggle.checked);
            if(showVerifWrapper){ showVerifWrapper.style.display = anySec ? "" : "none"; }

            var warnToken    = document.querySelector('.thespl-security-warn-token');
            var warnHtaccess = document.querySelector('.thespl-security-warn-htaccess');
            var warnRl       = document.querySelector('.thespl-security-warn-rl');

            if(warnToken){ warnToken.style.display = (secToggle && secToggle.checked) ? "none" : "block"; }
            if(warnHtaccess){ warnHtaccess.style.display = (htToggle && htToggle.checked) ? "none" : "block"; }
            if(warnRl){
                var rlOn = (rlToggle && rlToggle.checked && !rlToggle.disabled);
                warnRl.style.display = rlOn ? "none" : "block";
            }
        }

        // Add event listeners
        if (secToggle) {
            secToggle.addEventListener('change', toggleSecurityFields);
        }
        if (rlToggle) {
            rlToggle.addEventListener('change', toggleSecurityFields);
        }
        if (htToggle) {
            htToggle.addEventListener('change', toggleSecurityFields);
        }
        if (showVerifToggle) {
            showVerifToggle.addEventListener('change', toggleSecurityFields);
        }

        toggleSecurityFields(); // Initial state

        var uploadSubdirInput = document.getElementById('upload-subdir');
        if (uploadSubdirInput) {
            var uploadSubdirNotice = null;

            function findInvalidSubdirChars(value) {
                var invalid = [];
                var val = (value || '').toString();
                if (!val) {
                    return invalid;
                }
                var allowed = /[a-zA-Z0-9_\-\/]/;
                for (var i = 0; i < val.length; i++) {
                    var ch = val.charAt(i);
                    if (!allowed.test(ch)) {
                        if (invalid.indexOf(ch) === -1) {
                            invalid.push(ch);
                        }
                    }
                }
                if (val.indexOf('..') !== -1 && invalid.indexOf('.') === -1) {
                    invalid.push('.');
                }
                return invalid;
            }

            function ensureUploadSubdirNotice() {
                if (!uploadSubdirNotice) {
                    uploadSubdirNotice = document.createElement('div');
                    uploadSubdirNotice.className = 'thespl-admin-subdir-invalid';
                    var parent = uploadSubdirInput.parentNode;
                    if (parent) {
                        var next = uploadSubdirInput.nextSibling;
                        parent.insertBefore(uploadSubdirNotice, next);
                    }
                }
                return uploadSubdirNotice;
            }

            function clearUploadSubdirNotice() {
                if (uploadSubdirNotice && uploadSubdirNotice.parentNode) {
                    uploadSubdirNotice.parentNode.removeChild(uploadSubdirNotice);
                }
                uploadSubdirNotice = null;
                uploadSubdirInput.classList.remove('thespl-admin-input-invalid');
            }

            function updateUploadSubdirState() {
                var raw = uploadSubdirInput.value || '';
                var invalidChars = findInvalidSubdirChars(raw);
                if (!raw || invalidChars.length === 0) {
                    clearUploadSubdirNotice();
                    return;
                }

                uploadSubdirInput.classList.add('thespl-admin-input-invalid');
                var notice = ensureUploadSubdirNotice();
                notice.textContent = 'Invalid characters: ' + invalidChars.join(' ');
            }

            uploadSubdirInput.addEventListener('input', updateUploadSubdirState);
            updateUploadSubdirState();

            var settingsForm = uploadSubdirInput.form;
            if (settingsForm) {
                settingsForm.addEventListener('submit', function(event) {
                    var value = uploadSubdirInput.value || '';
                    var invalidChars = findInvalidSubdirChars(value);
                    if (value && invalidChars.length > 0) {
                        updateUploadSubdirState();
                        uploadSubdirInput.focus();
                        event.preventDefault();
                    }
                });
            }
        }
    }

    function initStreamingSliders() {
        var chunkSlider = document.querySelector('input[name="thespl_player_settings[streaming_chunk_level]"]');
        var chunkValue = document.getElementById('thespl-chunk-level-val');
        var prebufferSlider = document.querySelector('input[name="thespl_player_settings[streaming_prebuffer_sec]"]');
        var prebufferValue = document.getElementById('thespl-prebuffer-val');
        var autoCheckbox = document.querySelector('input[name="thespl_player_settings[streaming_auto_detect_network]"]');
        var chunkWrapper = document.getElementById('thespl-chunk-wrapper');
        var prebufferWrapper = document.getElementById('thespl-prebuffer-wrapper');
        var chunkRow = chunkWrapper && chunkWrapper.closest ? chunkWrapper.closest('tr') : null;
        var prebufferRow = prebufferWrapper && prebufferWrapper.closest ? prebufferWrapper.closest('tr') : null;
        var chunkLabels = ['128 KiB', '256 KiB', '512 KiB', '768 KiB', '1 MiB', '1.5 MiB', '2 MiB', '3 MiB', '4 MiB', '6 MiB'];

        function updateChunkLevel() {
            if (!chunkSlider || !chunkValue) {
                return;
            }
            var i = parseInt(chunkSlider.value, 10) || 0;
            if (i < 0) {
                i = 0;
            }
            if (i > 9) {
                i = 9;
            }
            if (chunkLabels[i]) {
                chunkValue.textContent = chunkLabels[i];
            }
        }

        function updatePrebuffer() {
            if (!prebufferSlider || !prebufferValue) {
                return;
            }
            var v = parseInt(prebufferSlider.value, 10) || 0;
            if (v < 0) {
                v = 0;
            }
            if (v > 30) {
                v = 30;
            }
            prebufferValue.textContent = v + ' s';
        }

        function updateAutoDetect() {
            if (!autoCheckbox) {
                return;
            }
            var on = !!autoCheckbox.checked;
            if (chunkWrapper) {
                if (on) {
                    chunkWrapper.classList.add('thespl-admin-hidden');
                } else {
                    chunkWrapper.classList.remove('thespl-admin-hidden');
                }
            }
            if (prebufferWrapper) {
                if (on) {
                    prebufferWrapper.classList.add('thespl-admin-hidden');
                } else {
                    prebufferWrapper.classList.remove('thespl-admin-hidden');
                }
            }
            if (chunkRow) {
                if (on) {
                    chunkRow.classList.add('thespl-admin-hidden');
                } else {
                    chunkRow.classList.remove('thespl-admin-hidden');
                }
            }
            if (prebufferRow) {
                if (on) {
                    prebufferRow.classList.add('thespl-admin-hidden');
                } else {
                    prebufferRow.classList.remove('thespl-admin-hidden');
                }
            }
            var chunkInput = document.querySelector('input[name="thespl_player_settings[streaming_chunk_level]"]');
            var prebufferInput = document.querySelector('input[name="thespl_player_settings[streaming_prebuffer_sec]"]');
            if (chunkInput) {
                chunkInput.disabled = on;
            }
            if (prebufferInput) {
                prebufferInput.disabled = on;
            }
        }

        if (chunkSlider && chunkValue) {
            chunkSlider.addEventListener('input', updateChunkLevel);
            chunkSlider.addEventListener('change', updateChunkLevel);
            updateChunkLevel();
        }
        if (prebufferSlider && prebufferValue) {
            prebufferSlider.addEventListener('input', updatePrebuffer);
            prebufferSlider.addEventListener('change', updatePrebuffer);
            updatePrebuffer();
        }
        if (autoCheckbox) {
            autoCheckbox.addEventListener('change', updateAutoDetect);
            updateAutoDetect();
        }
    }

    $(document).ready(function() {
        initTabNavigation();
        initSettingsInteractivity();
        initStreamingSliders();
    });

})(jQuery);
