/**
 * Enhanced Admin Controls JavaScript
 * Handles Elementor-style controls functionality
 */
(function($) {
    'use strict';

    // Initialize when document is ready
    $(document).ready(function() {
        initDimensionsControls();
        initColorPickers();
        initSelectControls();
        initNumberControls();
        initTextControls();
        initTooltips();
    });


    /**
     * Initialize dimensions controls
     */
    function initDimensionsControls() {
        $('.proddisp-control-dimensions').each(function() {
            const $container = $(this);
            const $inputs = $container.find('.proddisp-control-dimension input');
            const $linkButton = $container.find('.proddisp-link-dimensions');
            const $hiddenInput = $container.find('input[type="hidden"]');
            
            // Set initial linked state
            const isLinked = checkIfLinked($inputs);
            $linkButton.toggleClass('linked', isLinked);
            
            // Handle input changes
            $inputs.on('input change', function() {
                const $input = $(this);
                const fieldName = $input.data('field');
                
                if ($linkButton.hasClass('linked')) {
                    // Update all inputs with the same value
                    const value = $input.val();
                    $inputs.val(value);
                }
                
                updateHiddenInput($container);
            });
            
            // Handle link/unlink button
            $linkButton.on('click', function(e) {
                e.preventDefault();
                const $button = $(this);
                const wasLinked = $button.hasClass('linked');
                
                $button.toggleClass('linked');
                
                if (!wasLinked) {
                    // Just linked - sync all values to the first non-empty input
                    const firstValue = $inputs.filter(function() {
                        return $(this).val() !== '';
                    }).first().val() || '0';
                    
                    $inputs.val(firstValue);
                    updateHiddenInput($container);
                }
                
                // Add visual feedback
                $button.addClass('animate');
                setTimeout(() => $button.removeClass('animate'), 300);
            });
            
            // Initialize hidden input value
            updateHiddenInput($container);
        });
    }

    /**
     * Check if all dimension values are the same (linked state)
     */
    function checkIfLinked($inputs) {
        const values = $inputs.map(function() {
            return $(this).val() || '0';
        }).get();
        
        return values.every(val => val === values[0]);
    }

    /**
     * Update the hidden input with combined dimension values
     */
    function updateHiddenInput($container) {
        const $inputs = $container.find('.proddisp-control-dimension input');
        const $hiddenInput = $container.find('input[type="hidden"]');
        
        const values = {
            top: $inputs.filter('[data-setting="top"]').val() || '0',
            right: $inputs.filter('[data-setting="right"]').val() || '0',
            bottom: $inputs.filter('[data-setting="bottom"]').val() || '0',
            left: $inputs.filter('[data-setting="left"]').val() || '0'
        };
        
        // Create CSS-style value
        let cssValue;
        if (values.top === values.right && values.right === values.bottom && values.bottom === values.left) {
            // All same
            cssValue = values.top + 'px';
        } else if (values.top === values.bottom && values.right === values.left) {
            // Top/bottom same, left/right same
            cssValue = values.top + 'px ' + values.right + 'px';
        } else {
            // All different
            cssValue = values.top + 'px ' + values.right + 'px ' + values.bottom + 'px ' + values.left + 'px';
        }
        
        $hiddenInput.val(cssValue);
        
        // Trigger change event for any listeners
        $hiddenInput.trigger('change');
    }

    /**
     * Initialize enhanced color pickers
     */
    function initColorPickers() {
        if (typeof $.wp === 'undefined' || typeof $.wp.wpColorPicker === 'undefined') {
            // Fallback for basic color input
            $('.proddisp-color-picker').attr('type', 'color');
            return;
        }

        $('.proddisp-color-picker').each(function() {
            const $input = $(this);
            const hasAlpha = $input.hasClass('proddisp-color-picker-alpha');
            
            const options = {
                defaultColor: false,
                change: function(event, ui) {
                    const color = ui.color.toString();
                    $input.val(color).trigger('change');
                    updateColorPreview($input, color);
                },
                clear: function() {
                    $input.val('').trigger('change');
                    updateColorPreview($input, 'transparent');
                }
            };
            
            // Add alpha support if available
            if (hasAlpha && typeof $.wp.wpColorPicker.prototype.options.alpha !== 'undefined') {
                options.alpha = true;
                options.alphaEnabled = true;
            }
            
            $input.wpColorPicker(options);
            
            // Initialize color preview
            updateColorPreview($input, $input.val());
        });
        
        // Handle color preset clicks
        $(document).on('click', '.proddisp-color-preset', function(e) {
            e.preventDefault();
            const $preset = $(this);
            const $colorControl = $preset.closest('.proddisp-color-control');
            const $input = $colorControl.find('.proddisp-color-picker');
            
            if ($preset.hasClass('proddisp-color-clear')) {
                $input.val('').trigger('change');
                updateColorPreview($input, 'transparent');
            } else {
                const color = $preset.data('color');
                $input.val(color).trigger('change');
                updateColorPreview($input, color);
            }
            
            // Update WordPress color picker if initialized
            if ($input.wpColorPicker) {
                $input.wpColorPicker('color', $input.val());
            }
        });
        
        // Handle color preview clicks
        $(document).on('click', '.proddisp-color-preview', function() {
            const $preview = $(this);
            const $input = $preview.siblings('.proddisp-color-picker');
            $input.focus().click();
        });
    }
    
    /**
     * Update color preview
     */
    function updateColorPreview($input, color) {
        const $preview = $input.siblings('.proddisp-color-preview');
        if ($preview.length) {
            $preview.css('background-color', color || 'transparent');
        }
    }

    /**
     * Initialize enhanced select controls
     */
    function initSelectControls() {
        // Handle visual select options
        $(document).on('click', '.proddisp-select-option', function() {
            const $option = $(this);
            const $container = $option.closest('.proddisp-select-control');
            const $hiddenSelect = $container.find('select');
            const value = $option.data('value');
            
            // Update visual state
            $option.siblings().removeClass('active');
            $option.addClass('active');
            
            // Update hidden select
            $hiddenSelect.val(value).trigger('change');
        });
        
        // Initialize visual state based on hidden select value
        $('.proddisp-select-with-icons').each(function() {
            const $container = $(this);
            const $hiddenSelect = $container.find('select');
            const currentValue = $hiddenSelect.val();
            
            $container.find('.proddisp-select-option').each(function() {
                const $option = $(this);
                if ($option.data('value') === currentValue) {
                    $option.addClass('active');
                }
            });
        });
    }

    

    // Handle keyboard navigation for alignment controls
    $(document).on('keydown', '.proddisp-choices input[type="radio"]', function(e) {
        const $current = $(this);
        const $choices = $current.closest('.proddisp-choices').find('input[type="radio"]');
        const currentIndex = $choices.index($current);
        
        let newIndex = currentIndex;
        
        switch(e.which) {
            case 37: // Left arrow
                newIndex = currentIndex > 0 ? currentIndex - 1 : $choices.length - 1;
                break;
            case 39: // Right arrow
                newIndex = currentIndex < $choices.length - 1 ? currentIndex + 1 : 0;
                break;
            default:
                return;
        }
        
        e.preventDefault();
        $choices.eq(newIndex).prop('checked', true).focus().trigger('change');
    });

    // Export functions for external use
    window.ProdDispEnhancedControls = {
        initDimensionsControls: initDimensionsControls,
        initColorPickers: initColorPickers,
        initSelectControls: initSelectControls,
        initNumberControls: initNumberControls,
        initTextControls: initTextControls,
        updateHiddenInput: updateHiddenInput,
        updateColorPreview: updateColorPreview
    };

})(jQuery);