/**
 * Sifency Metabox Controls Script
 *
 * - Color Picker Initialization
 * - Range Sliders
 * - Media & File Uploaders
 * - Repeater Fields (Add, Remove, Sort)
 * - Field Dependencies (Show/Hide logic)
 * - Tabbed Interface
 *
 * @refactored Vanilla JS (ES6+)
 */

document.addEventListener('DOMContentLoaded', () => {

    const SifencyMetabox = {

        init() {
            this.initColorPicker();
            this.initSliders();
            this.initSortable();
            this.checkDependencies();
            this.bindEvents();
        },

        /**
         * Initialize WP Color Picker (Requires jQuery)
         */
        initColorPicker(context = document) {
            if (window.jQuery && window.jQuery.fn.wpColorPicker) {
                window.jQuery(context).find('.sifency-color-picker').wpColorPicker();
            }
        },

        /**
         * Initialize jQuery UI Sortable for Repeater Fields
         */
        initSortable(context = document) {
            if (window.jQuery && window.jQuery.fn.sortable) {
                window.jQuery(context).find('.sifency-repeater-items').sortable({
                    handle: '.sifency-repeater-handle',
                    placeholder: 'repeater-placeholder',
                    forcePlaceholderSize: true
                });
            }
        },

        /**
         * Initialize Sliders Value Display
         */
        initSliders(context = document) {
            context.querySelectorAll('.sifency-slider-input').forEach(slider => {
                const parent = slider.parentElement;
                const valueDisplay = parent.querySelector('.sifency-slider-value');
                if (valueDisplay) {
                    valueDisplay.textContent = slider.value;
                }
            });
        },

        /**
         * Check Dependency Logic for Show/Hide Fields
         */
        checkDependencies() {
            document.querySelectorAll('[data-dependency-controller]').forEach(dependent => {
                const controllerId = dependent.dataset.dependencyController;
                const operator = dependent.dataset.dependencyOperator;
                const requiredVal = String(dependent.dataset.dependencyValue);

                const controllers = document.querySelectorAll(`[name="${controllerId}"]`);
                if (controllers.length === 0) return;

                let controllerVal = '';
                const firstCtrl = controllers[0];

                if (firstCtrl.type === 'radio') {
                    const checked = Array.from(controllers).find(r => r.checked);
                    controllerVal = checked ? checked.value : '';
                } else if (firstCtrl.type === 'checkbox') {
                    controllerVal = firstCtrl.checked ? firstCtrl.value : '';
                } else {
                    controllerVal = firstCtrl.value;
                }

                const conditionMet = (operator === '==') ? (controllerVal === requiredVal) : (controllerVal !== requiredVal);

                // Show / Hide element (Vanilla JS equivalent of slideDown/slideUp)
                dependent.style.display = conditionMet ? '' : 'none';
            });
        },

        /**
         * Main Event Delegation
         */
        bindEvents() {

            // --- Input & Change Events ---
            document.body.addEventListener('input', (e) => {
                // Slider Logic
                if (e.target.matches('.sifency-slider-input')) {
                    const valueDisplay = e.target.parentElement.querySelector('.sifency-slider-value');
                    if (valueDisplay) {
                        valueDisplay.textContent = e.target.value;
                    }
                }
            });

            document.body.addEventListener('change', (e) => {
                // Trigger Dependency Check if input inside metabox changes
                if (e.target.closest('.sifency-metabox-wrapper')) {
                    this.checkDependencies();
                }
            });

            // --- Click Events ---
            document.body.addEventListener('click', (e) => {

                const mediaUploadBtn = e.target.closest('.sifency-media-upload');
                if (mediaUploadBtn) {
                    e.preventDefault();
                    this.handleMediaUpload(mediaUploadBtn);
                }

                const mediaRemoveBtn = e.target.closest('.sifency-media-remove');
                if (mediaRemoveBtn) {
                    e.preventDefault();
                    const parent = mediaRemoveBtn.parentElement;
                    parent.querySelector('.sifency-media-input').value = '';
                    parent.querySelector('.sifency-media-preview').innerHTML = '';
                }

                const fileUploadBtn = e.target.closest('.sifency-upload-add');
                if (fileUploadBtn) {
                    e.preventDefault();
                    this.handleFileUpload(fileUploadBtn);
                }

                const fileRemoveBtn = e.target.closest('.sifency-upload-remove');
                if (fileRemoveBtn) {
                    e.preventDefault();
                    const parent = fileRemoveBtn.parentElement;
                    parent.querySelector('.sifency-upload-input').value = '';
                    const filenameDisplay = parent.querySelector('.sifency-upload-filename');
                    filenameDisplay.textContent = '';
                    filenameDisplay.style.display = 'none';
                    fileRemoveBtn.style.display = 'none';
                }

                const repeaterAddBtn = e.target.closest('.sifency-repeater-add');
                if (repeaterAddBtn) {
                    e.preventDefault();
                    this.handleAddRepeater(repeaterAddBtn);
                }

                const repeaterRemoveBtn = e.target.closest('.sifency-repeater-remove');
                if (repeaterRemoveBtn) {
                    e.preventDefault();
                    repeaterRemoveBtn.closest('.sifency-repeater-row').remove();
                }

                const tabNavBtn = e.target.closest('.sifency-tab-nav-item');
                if (tabNavBtn) {
                    e.preventDefault();
                    this.handleTabNavigation(tabNavBtn);
                }
            });
        },

        /**
         * Handle WordPress Media Frame for Images
         */
        handleMediaUpload(button) {
            const parent = button.parentElement;
            const input = parent.querySelector('.sifency-media-input');
            const preview = parent.querySelector('.sifency-media-preview');

            const frame = wp.media({
                title: 'Select or Upload Media',
                button: { text: 'Use this media' },
                multiple: false
            });

            frame.on('select', () => {
                const attachment = frame.state().get('selection').first().toJSON();
                input.value = attachment.id;

                const previewUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
                preview.innerHTML = `<img src="${previewUrl}" style="max-width:150px; height:auto;" />`;
            });

            frame.open();
        },

        /**
         * Handle WordPress Media Frame for Generic Files
         */
        handleFileUpload(button) {
            const parent = button.parentElement;
            const input = parent.querySelector('.sifency-upload-input');
            const filenameDisplay = parent.querySelector('.sifency-upload-filename');
            const removeBtn = parent.querySelector('.sifency-upload-remove');

            const frame = wp.media({
                title: 'Select or Upload File',
                button: { text: 'Use this file' },
                multiple: false
            });

            frame.on('select', () => {
                const attachment = frame.state().get('selection').first().toJSON();
                input.value = attachment.id;

                filenameDisplay.textContent = attachment.filename;
                filenameDisplay.style.display = ''; // Show element
                removeBtn.style.display = ''; // Show remove button
            });

            frame.open();
        },

        /**
         * Add New Repeater Row
         */
        handleAddRepeater(button) {
            // Find the container before the button
            const container = button.previousElementSibling;
            if (!container || !container.classList.contains('sifency-repeater-items')) return;

            const templateId = container.dataset.templateId;
            const templateEl = document.getElementById(templateId);
            if (!templateEl) return;

            const newIndex = container.querySelectorAll('.sifency-repeater-row').length;
            const newHtml = templateEl.innerHTML.replace(/__i__/g, newIndex);

            // Append HTML
            container.insertAdjacentHTML('beforeend', newHtml);

            // Re-initialize scripts for new DOM elements
            setTimeout(() => {
                this.initSliders(container);
                this.initColorPicker(container);
            }, 100);
        },

        /**
         * Tabbed Interface Logic
         */
        handleTabNavigation(navItem) {
            const section = navItem.dataset.section;
            const tabsContainer = navItem.closest('.sifency-tabs');
            if (!tabsContainer) return;

            // Remove active class from all nav items
            tabsContainer.querySelectorAll('.sifency-tab-nav-item').forEach(nav => {
                nav.classList.remove('active');
            });
            navItem.classList.add('active');

            // Hide all panels
            const panelsContainer = tabsContainer.querySelector('.sifency-tabs-panels');
            panelsContainer.querySelectorAll('.sifency-tab-panel').forEach(panel => {
                panel.style.display = 'none';
                panel.classList.remove('active');
            });

            // Show target panel
            const targetPanel = panelsContainer.querySelector(`.sifency-tab-panel[data-section="${section}"]`);
            if (targetPanel) {
                targetPanel.style.display = '';
                targetPanel.classList.add('active');

                // Re-init inputs that might have rendering issues when hidden
                this.initSliders(targetPanel);
                this.initColorPicker(targetPanel);
                this.checkDependencies();
            }
        }
    };

    // Initialize logic
    SifencyMetabox.init();

});