/**
 * Email Template Customizer — admin JS.
 *
 * Handles tab switching between email types, AJAX save, debounced
 * live preview via iframe, and WordPress color picker integration.
 */
(function ($) {
    'use strict';

    var debounceTimer = null;
    var DEBOUNCE_MS   = 600;

    // ---------------------------------------------------------------
    // Initialise
    // ---------------------------------------------------------------

    $(function () {
        initColorPickersInPanel($('.strp-email-customizer__panel--active'));
        bindTabs();
        bindSave();
        bindPreviewUpdates();
        triggerPreview(); // Load initial preview.
    });

    // ---------------------------------------------------------------
    // Color pickers
    // ---------------------------------------------------------------

    /**
     * Initialize color pickers only when their parent panel is visible.
     * Avoids wpColorPicker issues with hidden elements.
     *
     * @param {jQuery} panel The panel element to initialize pickers in.
     */
    function initColorPickersInPanel(panel) {
        var $pickers = $(panel).find('.strp-email-customizer__color-picker').not('.wp-color-picker');
        if ($pickers.length) {
            $pickers.wpColorPicker({
                change: function () {
                    schedulePreview();
                },
                clear: function () {
                    schedulePreview();
                }
            });
        }
    }

    // ---------------------------------------------------------------
    // Tab switching
    // ---------------------------------------------------------------

    function bindTabs() {
        $(document).on('click', '.strp-email-customizer__tab', function () {
            var type = $(this).data('type');

            // Activate tab.
            $('.strp-email-customizer__tab').removeClass('strp-email-customizer__tab--active');
            $(this).addClass('strp-email-customizer__tab--active');

            // Show matching panel.
            $('.strp-email-customizer__panel').removeClass('strp-email-customizer__panel--active');
            var $panel = $('.strp-email-customizer__panel[data-type="' + type + '"]');
            $panel.addClass('strp-email-customizer__panel--active');

            // Initialize color pickers in the newly visible panel.
            initColorPickersInPanel($panel);

            // Refresh preview for active panel.
            triggerPreview();
        });
    }

    // ---------------------------------------------------------------
    // Save template
    // ---------------------------------------------------------------

    function bindSave() {
        $(document).on('click', '.strp-email-customizer__save', function () {
            var $btn   = $(this);
            var type   = $btn.data('type');
            var $panel = $('.strp-email-customizer__panel[data-type="' + type + '"]');
            var $notice = $panel.find('.strp-email-customizer__notice');

            var data = {
                action:     'strp_sub_save_email_template',
                email_type: type,
                enabled:    $panel.find('input[name="enabled"]').is(':checked') ? '1' : '',
                subject:    $panel.find('input[name="subject"]').val(),
                header:     $panel.find('input[name="header"]').val(),
                body:       $panel.find('textarea[name="body"]').val(),
                footer:     $panel.find('input[name="footer"]').val(),
                brand_color: getColorValue($panel)
            };

            // Include the per-type nonce field.
            var nonceField = $panel.find('input[name="strp_sub_email_nonce_' + type + '"]');
            if (nonceField.length) {
                data['strp_sub_email_nonce_' + type] = nonceField.val();
            }

            $btn.prop('disabled', true).text(strp_sub_email_customizer_params.i18n_saving);

            $.post(strp_sub_email_customizer_params.ajax_url, data, function (response) {
                $btn.prop('disabled', false).text($btn.data('original-text') || 'Save Template');

                if (response.success) {
                    showNotice($notice, strp_sub_email_customizer_params.i18n_saved, 'success');
                } else {
                    showNotice($notice, response.data && response.data.message ? response.data.message : strp_sub_email_customizer_params.i18n_error, 'error');
                }
            }).fail(function () {
                $btn.prop('disabled', false).text($btn.data('original-text') || 'Save Template');
                showNotice($notice, strp_sub_email_customizer_params.i18n_error, 'error');
            });
        });

        // Store original button text.
        $('.strp-email-customizer__save').each(function () {
            $(this).data('original-text', $(this).text().trim());
        });
    }

    // ---------------------------------------------------------------
    // Live preview (debounced)
    // ---------------------------------------------------------------

    function bindPreviewUpdates() {
        $(document).on(
            'input change',
            '.strp-email-customizer__panel--active input, .strp-email-customizer__panel--active textarea',
            function () {
                schedulePreview();
            }
        );
    }

    function schedulePreview() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(triggerPreview, DEBOUNCE_MS);
    }

    function triggerPreview() {
        var $panel = $('.strp-email-customizer__panel--active');
        if (!$panel.length) {
            return;
        }

        var data = {
            action:     'strp_sub_preview_email_template',
            _wpnonce:   strp_sub_email_customizer_params.nonce,
            email_type: $panel.find('input[name="email_type"]').val(),
            subject:    $panel.find('input[name="subject"]').val(),
            header:     $panel.find('input[name="header"]').val(),
            body:       $panel.find('textarea[name="body"]').val(),
            footer:     $panel.find('input[name="footer"]').val(),
            brand_color: getColorValue($panel)
        };

        $.post(strp_sub_email_customizer_params.ajax_url, data, function (response) {
            if (response.success && response.data && response.data.html) {
                var iframe = document.getElementById('strp-email-preview-iframe');
                if (iframe) {
                    var doc = iframe.contentDocument || iframe.contentWindow.document;
                    doc.open();
                    doc.write(response.data.html);
                    doc.close();
                }
            }
        }).fail(function () {
            var iframe = document.getElementById('strp-email-preview-iframe');
            if (iframe) {
                var doc = iframe.contentDocument || iframe.contentWindow.document;
                doc.open();
                doc.write('<p style="padding:20px;color:#666;">Preview could not be loaded. Please try again.</p>');
                doc.close();
            }
        });
    }

    // ---------------------------------------------------------------
    // Helpers
    // ---------------------------------------------------------------

    function getColorValue($panel) {
        var $picker = $panel.find('.strp-email-customizer__color-picker');
        return $picker.length ? $picker.wpColorPicker('color') : '#8444F9';
    }

    function showNotice($el, message, type) {
        $el
            .text(message)
            .removeClass('strp-email-customizer__notice--success strp-email-customizer__notice--error')
            .addClass('strp-email-customizer__notice--' + type)
            .fadeIn(200);

        setTimeout(function () {
            $el.fadeOut(400);
        }, 3000);
    }

})(jQuery);
