/**
 * ChatBudgie Admin module.
 * Handles admin settings page interactions, color picker, and media uploader.
 */
(function($) {
    'use strict';

    $(function() {
        var colorRadios = $('input[name="chatbudgie_primary_color"]');
        var avatarRadios = $('input[name="chatbudgie_avatar_choice"]');
        var secondaryColorInput = $('#chatbudgie_secondary_color');
        var rebuildButton = $('#chatbudgie-rebuild-index');
        var changeIconButton = $('#chatbudgie-change-icon');
        var iconPreview = $('#chatbudgie-icon-preview');
        var customIconInput = $('#chatbudgie_custom_icon');
        var messageField = $('#chatbudgie_welcome_message');
        var messageCount = $('#chatbudgie-message-count');
        var saveButtons = $('.settings-form button[type="submit"]');
        
        // Initial values for change detection
        var initialValues = {
            primaryColor: $('input[name="chatbudgie_primary_color"]:checked').val(),
            avatarChoice: $('input[name="chatbudgie_avatar_choice"]:checked').val(),
            welcomeMessage: messageField.val()
        };

        /**
         * Check if any appearance settings have changed
         */
        function checkChanges() {
            var currentValues = {
                primaryColor: $('input[name="chatbudgie_primary_color"]:checked').val(),
                avatarChoice: $('input[name="chatbudgie_avatar_choice"]:checked').val(),
                welcomeMessage: messageField.val()
            };
            
            var changed = (currentValues.primaryColor !== initialValues.primaryColor ||
                           currentValues.avatarChoice !== initialValues.avatarChoice ||
                           currentValues.welcomeMessage !== initialValues.welcomeMessage);
            
            saveButtons.prop('disabled', !changed);
        }

        // WordPress Color Picker integration
        var $picker = $('#chatbudgie-custom-color-picker');
        
        /**
         * Lighten/Darken a color for secondary color generation
         */
        function adjustBrightness(col, amt) {
            var usePound = false;
            if (col[0] == "#") {
                col = col.slice(1);
                usePound = true;
            }
            var num = parseInt(col,16);
            var r = (num >> 16) + amt;
            if (r > 255) r = 255;
            else if  (r < 0) r = 0;
            var b = ((num >> 8) & 0x00FF) + amt;
            if (b > 255) b = 255;
            else if  (b < 0) b = 0;
            var g = (num & 0x0000FF) + amt;
            if (g > 255) g = 255;
            else if (g < 0) g = 0;
            return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16).padStart(6, '0');
        }

        /**
         * Generate a soft version of a color for secondary usage
         */
        function getSecondaryColor(hex) {
            return adjustBrightness(hex, 180);
        }

        if ($picker.length && $.isFunction($.fn.wpColorPicker)) {
            $picker.wpColorPicker({
                change: function(event, ui) {
                    var color = ui.color.toString();
                    updateCustomColorUI(color);
                }
            });
        }
        
        function updateCustomColorUI(color) {
            var customChoice = $('.color-choice--picker');
            var customRadio = customChoice.find('input[type="radio"]');
            var secondaryColor = getSecondaryColor(color);
            
            if (customRadio.length) {
                customRadio.val(color);
                customRadio.attr('data-secondary', secondaryColor);
                customRadio.prop('checked', true);
            }
            
            // Update hidden secondary input
            if (secondaryColorInput.length) {
                secondaryColorInput.val(secondaryColor);
            }
            
            syncColorState();
        }

        function syncColorState() {
            var $activeRadio = $('input[name="chatbudgie_primary_color"]:checked');
            
            // Clear all active classes
            $('.color-choice').removeClass('is-active');
            
            if ($activeRadio.length) {
                var choice = $activeRadio.closest('.color-choice');
                if (choice.length) {
                    choice.addClass('is-active');
                }

                var primary = $activeRadio.val();
                var secondary = $activeRadio.attr('data-secondary') || '';

                // Update hidden secondary input
                if (secondaryColorInput.length) {
                    secondaryColorInput.val(secondary);
                }
                
                // Update the row icon swatch
                var swatchIcon = $('.setting-row__icon--swatch');
                if (swatchIcon.length) {
                    swatchIcon.get(0).style.setProperty('--swatch-color', primary);
                }
            }
            checkChanges();
        }

        function syncAvatarState() {
            avatarRadios.each(function() {
                var radio = $(this);
                var choice = radio.closest('.avatar-choice');
                var isChecked = radio.prop('checked');
                
                if (choice.length) {
                    choice.toggleClass('is-active', isChecked);
                }
                
                if (isChecked && customIconInput.length) {
                    var avatarUrl = radio.val();
                    customIconInput.val(avatarUrl);
                    if (iconPreview.length) {
                        iconPreview.attr('src', avatarUrl);
                    }
                }
            });
            checkChanges();
        }

        function syncMessageCount() {
            if (messageField.length && messageCount.length) {
                messageCount.text(messageField.val().length);
            }
            checkChanges();
        }

        colorRadios.on('change', function() {
            syncColorState();
        });

        avatarRadios.on('change', syncAvatarState);

        if (messageField.length) {
            messageField.on('input', syncMessageCount);
        }

        if (rebuildButton.length) {
            rebuildButton.on('click', function(e) {
                if (!confirm(chatbudgie_admin_params.confirm_rebuild)) {
                    e.preventDefault();
                }
            });
        }

        if (changeIconButton.length) {
            var mediaUploader;
            changeIconButton.on('click', function(e) {
                e.preventDefault();
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }
                mediaUploader = wp.media({
                    title: chatbudgie_admin_params.choose_icon,
                    button: { text: chatbudgie_admin_params.select_icon },
                    multiple: false
                });
                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    if (customIconInput.length) customIconInput.val(attachment.url);
                    if (iconPreview.length) iconPreview.attr('src', attachment.url);
                    
                    // Update custom choice
                    var customChoice = $('.custom-choice');
                    var customRadio = customChoice.find('input');
                    var customImg = customChoice.find('img');
                    
                    if (customRadio.length) {
                        customRadio.val(attachment.url);
                        customRadio.prop('checked', true);
                    }
                    if (customImg.length) {
                        customImg.attr('src', attachment.url);
                    }
                    customChoice.css('display', 'inline-flex');
                    
                    syncAvatarState();
                });
                mediaUploader.open();
            });
        }

        // Initial sync
        syncColorState();
        syncAvatarState();
        syncMessageCount();
        
        // Reset initial values after initial sync to avoid false change detection on load
        initialValues = {
            primaryColor: $('input[name="chatbudgie_primary_color"]:checked').val(),
            avatarChoice: $('input[name="chatbudgie_avatar_choice"]:checked').val(),
            welcomeMessage: messageField.val()
        };
        checkChanges();
    });

})(jQuery);
