(function($) {
    'use strict';

    var shadowPresets = {
        none:   'none',
        light:  '0 2px 4px',
        medium: '0 3px 12px',
        heavy:  '0 6px 20px'
    };

    function initColorPickers() {
        $('.bs-color-picker').each(function() {
            if (!$(this).hasClass('wp-color-picker')) {
                $(this).wpColorPicker({
                    change: function() { markDirty(); },
                    clear:  function() { markDirty(); }
                });
            }
        });

        $('.bs-color-picker-alpha').each(function() {
            if (!$(this).hasClass('wp-color-picker')) {
                $(this).wpColorPicker({
                    change: function() { markDirty(); },
                    clear:  function() { markDirty(); }
                });
            }
        });
    }

    function initShadowPreviews() {
        $('.bs-shadow-select').each(function() {
            updateShadowPreview($(this));
        });
    }

    function updateShadowPreview($select) {
        var preset = $select.val();
        var fieldKey = $select.closest('tr').find('.bs-shadow-preview-box').data('shadow-field');
        var $previewBox = $select.closest('tr').find('.bs-shadow-preview-box');

        var colorFieldKey = fieldKey + '_color';
        var $colorInput = $('[name="styles[' + colorFieldKey + ']"]');
        var color = 'rgba(0,0,0,0.16)';
        if ($colorInput.length) {
            color = $colorInput.val() || 'rgba(0,0,0,0.16)';
        }

        if (preset === 'none') {
            $previewBox.css('box-shadow', 'none');
        } else {
            $previewBox.css('box-shadow', shadowPresets[preset] + ' ' + color);
        }
    }

    function initFontPreviews() {
        $('.bs-font-select').each(function() {
            updateFontPreview($(this));
        });
    }

    function updateFontPreview($select) {
        var font = $select.val();
        $select.closest('td').find('.bs-font-preview').css('font-family', font);
    }

    var isDirty = false;
    function markDirty() {
        isDirty = true;
    }

    function showStatus(message, isError) {
        var $status = $('.bs-save-status');
        $status.text(message)
               .toggleClass('error', !!isError)
               .addClass('visible');

        setTimeout(function() {
            $status.removeClass('visible');
        }, 3000);
    }

    function collectFormData() {
        var data = {};
        $('#bs-style-form').find('input, select').each(function() {
            var name = $(this).attr('name');
            if (name && name.indexOf('styles[') === 0) {
                var key = name.replace('styles[', '').replace(']', '');
                data[key] = $(this).val();
            }
        });
        return data;
    }

    function applyDefaults(defaults, targetSection) {
        $.each(defaults, function(key, val) {
            var $field = $('[name="styles[' + key + ']"]');
            if (!$field.length) return;

            if (targetSection) {
                if (!$field.closest('[data-panel="' + targetSection + '"]').length) {
                    return;
                }
            }

            if ($field.hasClass('bs-color-picker') || $field.hasClass('bs-color-picker-alpha')) {
                $field.val(val);
                if ($field.closest('.wp-picker-container').length) {
                    $field.wpColorPicker('color', val);
                }
            } else {
                $field.val(val);
            }
        });

        initShadowPreviews();
        initFontPreviews();
    }

    $(document).ready(function() {

        initColorPickers();
        initShadowPreviews();
        initFontPreviews();

        // Tab navigation
        $('.bs-style-tab').on('click', function(e) {
            e.preventDefault();
            var tab = $(this).data('tab');

            $('.bs-style-tab').removeClass('active');
            $(this).addClass('active');

            $('.bs-style-panel').removeClass('active');
            $('[data-panel="' + tab + '"]').addClass('active');
        });

        // Font select change
        $(document).on('change', '.bs-font-select', function() {
            updateFontPreview($(this));
            markDirty();
        });

        // Shadow select change
        $(document).on('change', '.bs-shadow-select', function() {
            updateShadowPreview($(this));
            markDirty();
        });

        // Generic input change
        $(document).on('change input', '.bs-style-table input, .bs-style-table select', function() {
            markDirty();
        });

        // Save
        $('#bs-style-form').on('submit', function(e) {
            e.preventDefault();

            var $btn = $('#bs-save-styles');
            $btn.prop('disabled', true).text('Saving...');

            $.ajax({
                url: bsStyleSettings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'bidspirit_save_styles',
                    nonce: bsStyleSettings.nonce,
                    styles: collectFormData()
                },
                success: function(response) {
                    if (response.success) {
                        isDirty = false;
                        showStatus('Styles saved successfully!');
                    } else {
                        showStatus('Error saving styles.', true);
                    }
                },
                error: function() {
                    showStatus('Server error. Please try again.', true);
                },
                complete: function() {
                    $btn.prop('disabled', false).html('Save All Styles');
                }
            });
        });

        // Reset All
        $('#bs-reset-all').on('click', function() {
            if (!confirm('Reset ALL style settings to defaults? This cannot be undone.')) return;

            var $btn = $(this);
            $btn.prop('disabled', true);

            $.ajax({
                url: bsStyleSettings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'bidspirit_reset_styles',
                    nonce: bsStyleSettings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        applyDefaults(response.data.defaults);
                        isDirty = false;
                        showStatus('All styles reset to defaults.');
                    }
                },
                error: function() {
                    showStatus('Error resetting styles.', true);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        // Reset Section
        $(document).on('click', '.bs-reset-section', function() {
            var section = $(this).data('section');
            if (!confirm('Reset this section to defaults?')) return;

            var $btn = $(this);
            $btn.prop('disabled', true);

            $.ajax({
                url: bsStyleSettings.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'bidspirit_reset_section',
                    nonce: bsStyleSettings.nonce,
                    section: section
                },
                success: function(response) {
                    if (response.success) {
                        applyDefaults(response.data.defaults, section);
                        showStatus('Section reset to defaults.');
                    }
                },
                error: function() {
                    showStatus('Error resetting section.', true);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        // Warn on leave with unsaved changes
        $(window).on('beforeunload', function() {
            if (isDirty) {
                return 'You have unsaved style changes.';
            }
        });
    });

})(jQuery);
