/**
 * Guard Dog Customizer JavaScript
 *
 * Handles all customizer interactivity including live preview,
 * color picker, media library, and AJAX operations.
 *
 * @package GuardDog
 * @since 1.8.45
 */

(function($) {
    'use strict';

    /**
     * Customizer Controller
     */
    const GuardDogCustomizer = {
        // State
        customizerId: null,
        previewFrame: null,
        previewDebounce: null,
        hasUnsavedChanges: false,
        mediaFrames: {},

        /**
         * Initialize the customizer
         */
        init: function() {
            this.customizerId = $('.guard-dog-customizer').data('customizer-id');

            if (!this.customizerId) {
                return;
            }

            this.previewFrame = $('#customizer-preview-iframe');

            // Initialize components
            this.initColorPickers();
            this.initImageControls();
            this.initCharacterCounts();
            this.initPreview();
            this.initDeviceSwitcher();
            this.initSectionToggles();
            this.initTemplateTypeSelector();

            // Bind events
            this.bindControlChanges();
            this.bindActions();
            this.bindBeforeUnload();

            // Initial preview load
            this.updatePreview();
        },

        /**
         * Initialize WordPress color pickers
         */
        initColorPickers: function() {
            $('.guard-dog-color-picker').each(function() {
                const $input = $(this);
                const defaultColor = $input.data('default-color');

                $input.wpColorPicker({
                    defaultColor: defaultColor,
                    change: function(event, ui) {
                        const color = ui.color.toString();
                        $input.val(color).trigger('change');
                    },
                    clear: function() {
                        $input.val(defaultColor).trigger('change');
                    }
                });
            });
        },

        /**
         * Initialize image upload controls
         */
        initImageControls: function() {
            const self = this;

            // Upload button click
            $(document).on('click', '.upload-image-button', function(e) {
                e.preventDefault();

                const $button = $(this);
                const $control = $button.closest('.guard-dog-image-control');
                const $input = $control.find('.image-value');
                const $preview = $control.find('.image-preview-wrapper');
                const controlId = $input.attr('id');
                const storageType = $input.data('storage-type') || 'url';

                // Create media frame if it doesn't exist
                if (!self.mediaFrames[controlId]) {
                    self.mediaFrames[controlId] = wp.media({
                        title: guardDogCustomizer.strings.selectImage || 'Select Image',
                        button: {
                            text: guardDogCustomizer.strings.useImage || 'Use This Image'
                        },
                        multiple: false,
                        library: {
                            type: 'image'
                        }
                    });

                    // Handle selection
                    self.mediaFrames[controlId].on('select', function() {
                        const attachment = self.mediaFrames[controlId]
                            .state()
                            .get('selection')
                            .first()
                            .toJSON();

                        // Store value based on storage type
                        const value = storageType === 'id' ? attachment.id : attachment.url;
                        $input.val(value).trigger('change');

                        // Update preview
                        self.updateImagePreview($control, attachment.url);
                    });
                }

                // Open media frame
                self.mediaFrames[controlId].open();
            });

            // Remove button click
            $(document).on('click', '.remove-image-button', function(e) {
                e.preventDefault();

                const $button = $(this);
                const $control = $button.closest('.guard-dog-image-control');
                const $input = $control.find('.image-value');

                $input.val('').trigger('change');
                self.clearImagePreview($control);
            });
        },

        /**
         * Update image preview
         */
        updateImagePreview: function($control, imageUrl) {
            const $wrapper = $control.find('.image-preview-wrapper');

            $wrapper.html(
                '<img src="' + imageUrl + '" alt="Preview" class="image-preview">'
            );

            // Show remove button
            const $buttons = $control.find('.image-control-buttons');
            if ($buttons.find('.remove-image-button').length === 0) {
                $buttons.append(
                    '<button type="button" class="button remove-image-button">' +
                    '<span class="dashicons dashicons-no-alt"></span> ' +
                    (guardDogCustomizer.strings.remove || 'Remove') +
                    '</button>'
                );
            }
        },

        /**
         * Clear image preview
         */
        clearImagePreview: function($control) {
            const $wrapper = $control.find('.image-preview-wrapper');

            $wrapper.html(
                '<div class="image-preview-placeholder">' +
                '<span class="dashicons dashicons-format-image"></span>' +
                '<p>' + (guardDogCustomizer.strings.noImage || 'No image selected') + '</p>' +
                '</div>'
            );

            // Remove the remove button
            $control.find('.remove-image-button').remove();
        },

        /**
         * Initialize character counters for textareas
         */
        initCharacterCounts: function() {
            $('.customizer-control textarea').each(function() {
                const $textarea = $(this);
                const $control = $textarea.closest('.customizer-control');
                let $counter = $control.find('.char-count');

                // Create counter if it doesn't exist
                if ($counter.length === 0 && $textarea.attr('maxlength')) {
                    const maxLength = $textarea.attr('maxlength');
                    $counter = $('<p class="char-count"><span class="current-count">0</span> / <span class="max-count">' + maxLength + '</span> characters</p>');
                    $control.find('.description').after($counter);
                }

                if ($counter.length > 0) {
                    // Update counter
                    const updateCounter = function() {
                        const current = $textarea.val().length;
                        const max = $textarea.attr('maxlength');
                        $counter.find('.current-count').text(current);

                        if (max && current > max) {
                            $counter.addClass('over-limit');
                        } else {
                            $counter.removeClass('over-limit');
                        }
                    };

                    // Bind events
                    $textarea.on('input keyup', updateCounter);

                    // Initial update
                    updateCounter();
                }
            });
        },

        /**
         * Initialize live preview
         */
        initPreview: function() {
            // Trigger preview update on iframe load
            this.previewFrame.on('load', function() {
                $('.customizer-preview-frame').removeClass('loading');
            });
        },

        /**
         * Initialize device switcher
         */
        initDeviceSwitcher: function() {
            $('.preview-device').on('click', function(e) {
                e.preventDefault();

                const $button = $(this);
                const device = $button.data('device');

                // Update active state
                $('.preview-device').removeClass('active');
                $button.addClass('active');

                // Update preview frame
                $('.customizer-preview-frame').attr('data-device', device);
            });
        },

        /**
         * Initialize section toggle functionality
         */
        initSectionToggles: function() {
            $('.customizer-section-title').on('click', function() {
                $(this).closest('.customizer-section').toggleClass('collapsed');
            });
        },

        /**
         * Initialize template type selector (for email template customizer)
         */
        initTemplateTypeSelector: function() {
            $('#template-type-select').on('change', function() {
                var templateType = $(this).val();
                var currentUrl = new URL(window.location.href);
                currentUrl.searchParams.set('template_type', templateType);
                window.location.href = currentUrl.toString();
            });
        },

        /**
         * Bind control change events
         */
        bindControlChanges: function() {
            const self = this;

            // Text inputs
            $('.customizer-control input[type="text"]').on('input', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Textareas
            $('.customizer-control textarea').on('input', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Number inputs
            $('.customizer-control input[type="number"]').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Checkboxes
            $('.customizer-control input[type="checkbox"]').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Radio buttons
            $('.customizer-control input[type="radio"]').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Select dropdowns
            $('.customizer-control select').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Color pickers (handled in wpColorPicker callback)
            $('.customizer-control input.guard-dog-color-picker').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });

            // Image uploads (handled in image control callbacks)
            $('.customizer-control input.image-value').on('change', function() {
                self.markUnsaved();
                self.schedulePreviewUpdate();
            });
        },

        /**
         * Bind action button events
         */
        bindActions: function() {
            const self = this;

            // Save button
            $('.customizer-save').on('click', function(e) {
                e.preventDefault();
                self.saveSettings();
            });

            // Reset button
            $('.customizer-reset').on('click', function(e) {
                e.preventDefault();

                if (confirm(guardDogCustomizer.strings.resetConfirm)) {
                    self.resetSettings();
                }
            });

            // Export button
            $('.customizer-export').on('click', function(e) {
                e.preventDefault();
                self.exportToTheme();
            });

            // Send test email button
            $('.send-test-email').on('click', function(e) {
                e.preventDefault();
                self.sendTestEmail();
            });
        },

        /**
         * Bind beforeunload event to warn about unsaved changes
         */
        bindBeforeUnload: function() {
            const self = this;

            $(window).on('beforeunload', function() {
                if (self.hasUnsavedChanges) {
                    return guardDogCustomizer.strings.unsavedWarning || 'You have unsaved changes. Are you sure you want to leave?';
                }
            });
        },

        /**
         * Mark form as having unsaved changes
         */
        markUnsaved: function() {
            this.hasUnsavedChanges = true;
        },

        /**
         * Mark form as saved
         */
        markSaved: function() {
            this.hasUnsavedChanges = false;
        },

        /**
         * Get all current control values
         */
        getSettings: function() {
            const settings = {};

            $('.customizer-control').each(function() {
                const $control = $(this);
                const controlId = $control.data('control-id');
                const controlType = $control.data('control-type');

                let value = null;

                switch (controlType) {
                    case 'text':
                    case 'textarea':
                    case 'number':
                        value = $control.find('input, textarea').val();
                        break;

                    case 'color':
                        value = $control.find('.guard-dog-color-picker').val();
                        break;

                    case 'image':
                        value = $control.find('.image-value').val();
                        break;

                    case 'checkbox':
                        value = $control.find('input[type="checkbox"]').is(':checked');
                        break;

                    case 'radio':
                        value = $control.find('input[type="radio"]:checked').val();
                        break;

                    case 'select':
                        value = $control.find('select').val();
                        break;
                }

                if (controlId && value !== null) {
                    settings[controlId] = value;
                }
            });

            return settings;
        },

        /**
         * Schedule preview update (debounced)
         */
        schedulePreviewUpdate: function() {
            const self = this;

            // Clear existing timeout
            if (this.previewDebounce) {
                clearTimeout(this.previewDebounce);
            }

            // Schedule new update
            this.previewDebounce = setTimeout(function() {
                self.updatePreview();
            }, 500); // 500ms debounce
        },

        /**
         * Update preview via AJAX
         */
        updatePreview: function() {
            const self = this;
            const settings = this.getSettings();

            // Get template type from selector if it exists (for email template customizer)
            const templateType = $('#template-type-select').length ? $('#template-type-select').val() : null;

            // Show loading state
            $('.customizer-preview-frame').addClass('loading');

            const ajaxData = {
                action: 'guard_dog_customizer_preview_' + this.customizerId,
                nonce: guardDogCustomizer.nonces.preview,
                settings: settings
            };

            // Include template type if available
            if (templateType) {
                ajaxData.template_type = templateType;
            }

            $.ajax({
                url: guardDogCustomizer.ajaxUrl,
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    if (response.success && response.data.html) {
                        // Write HTML to iframe
                        const iframe = self.previewFrame[0];
                        const doc = iframe.contentDocument || iframe.contentWindow.document;

                        doc.open();
                        doc.write(response.data.html);
                        doc.close();
                    } else {
                        self.showNotice('error', response.data.message || 'Failed to load preview');
                        $('.customizer-preview-frame').removeClass('loading');
                    }
                },
                error: function() {
                    self.showNotice('error', 'Failed to load preview. Please try again.');
                    $('.customizer-preview-frame').removeClass('loading');
                }
            });
        },

        /**
         * Save settings via AJAX
         */
        saveSettings: function() {
            const self = this;
            const settings = this.getSettings();
            const $button = $('.customizer-save');

            // Show loading state
            $button.addClass('loading').prop('disabled', true);
            $button.find('.dashicons').removeClass('dashicons-yes').addClass('dashicons-update');

            $.ajax({
                url: guardDogCustomizer.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_customizer_save_' + this.customizerId,
                    nonce: guardDogCustomizer.nonces.save,
                    settings: settings
                },
                success: function(response) {
                    if (response.success) {
                        self.markSaved();
                        self.showNotice('success', response.data.message || guardDogCustomizer.strings.saved);
                    } else {
                        self.showNotice('error', response.data.message || guardDogCustomizer.strings.saveFailed);
                    }
                },
                error: function() {
                    self.showNotice('error', guardDogCustomizer.strings.saveFailed);
                },
                complete: function() {
                    $button.removeClass('loading').prop('disabled', false);
                    $button.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-yes');
                }
            });
        },

        /**
         * Reset settings to defaults
         */
        resetSettings: function() {
            const self = this;
            const $button = $('.customizer-reset');

            // Show loading state
            $button.addClass('loading').prop('disabled', true);

            $.ajax({
                url: guardDogCustomizer.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_customizer_reset_' + this.customizerId,
                    nonce: guardDogCustomizer.nonces.reset
                },
                success: function(response) {
                    if (response.success) {
                        self.markSaved();
                        self.showNotice('success', response.data.message || guardDogCustomizer.strings.resetComplete);

                        // Reload page to reflect reset values
                        setTimeout(function() {
                            window.location.reload();
                        }, 1000);
                    } else {
                        self.showNotice('error', response.data.message || 'Failed to reset settings');
                    }
                },
                error: function() {
                    self.showNotice('error', 'Failed to reset settings. Please try again.');
                },
                complete: function() {
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },

        /**
         * Export settings to theme file
         */
        exportToTheme: function() {
            const self = this;
            const $button = $('.customizer-export');

            // Show loading state
            $button.addClass('loading').prop('disabled', true);

            $.ajax({
                url: guardDogCustomizer.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_customizer_export_' + this.customizerId,
                    nonce: guardDogCustomizer.nonces.export
                },
                success: function(response) {
                    if (response.success) {
                        self.showNotice('success', response.data.message || guardDogCustomizer.strings.exportSuccess);

                        // Update status indicator if theme file was created
                        if (response.data.file_path) {
                            $('.customizer-status').removeClass('database-settings').addClass('theme-override');
                            $('.status-indicator')
                                .removeClass('database-settings')
                                .addClass('theme-override')
                                .html('<span class="dashicons dashicons-admin-appearance"></span> Using theme file override');
                        }
                    } else {
                        self.showNotice('error', response.data.message || guardDogCustomizer.strings.exportFailed);
                    }
                },
                error: function() {
                    self.showNotice('error', guardDogCustomizer.strings.exportFailed);
                },
                complete: function() {
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },

        /**
         * Send test email
         */
        sendTestEmail: function() {
            const self = this;
            const settings = this.getSettings();

            // Get template type from selector if it exists (for email template customizer)
            const templateType = $('#template-type-select').length ? $('#template-type-select').val() : null;

            const $button = $('.send-test-email');

            // Show loading state
            $button.addClass('loading').prop('disabled', true);
            const originalText = $button.html();
            $button.html('<span class="dashicons dashicons-update"></span> ' + (guardDogCustomizer.strings.sending || 'Sending...'));

            const ajaxData = {
                action: 'guard_dog_send_test_email',
                nonce: guardDogCustomizer.nonces.preview,
                settings: settings
            };

            // Include template type if available
            if (templateType) {
                ajaxData.template_type = templateType;
            }

            $.ajax({
                url: guardDogCustomizer.ajaxUrl,
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    if (response.success) {
                        self.showNotice('success', response.data.message || 'Test email sent successfully!');
                    } else {
                        self.showNotice('error', response.data.message || 'Failed to send test email');
                    }
                },
                error: function() {
                    self.showNotice('error', 'Failed to send test email. Please try again.');
                },
                complete: function() {
                    $button.removeClass('loading').prop('disabled', false);
                    $button.html(originalText);
                }
            });
        },

        /**
         * Show notification message
         */
        showNotice: function(type, message) {
            // Remove existing notices
            $('.customizer-notice').remove();

            // Icon based on type
            let icon = '';
            switch (type) {
                case 'success':
                    icon = '<span class="dashicons dashicons-yes-alt"></span>';
                    break;
                case 'error':
                    icon = '<span class="dashicons dashicons-warning"></span>';
                    break;
                case 'info':
                    icon = '<span class="dashicons dashicons-info"></span>';
                    break;
                case 'warning':
                    icon = '<span class="dashicons dashicons-flag"></span>';
                    break;
            }

            // Create notice
            const $notice = $('<div class="customizer-notice ' + type + '"><p>' + icon + ' ' + message + '</p></div>');

            // Insert notice
            $('.guard-dog-customizer > h1').after($notice);

            // Auto-remove after 5 seconds
            setTimeout(function() {
                $notice.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);

            // Scroll to notice
            $('html, body').animate({
                scrollTop: $notice.offset().top - 32
            }, 300);
        }
    };

    /**
     * Initialize on document ready
     */
    $(document).ready(function() {
        GuardDogCustomizer.init();
    });

})(jQuery);
