(function($) {
    'use strict';

    var SeoFurySettingsPreview = {

        shortcodeMap: {},
        debounceTimer: null,
        debounceDelay: 250,

        init: function() {
            this.shortcodeMap = {
                '%sitename%':         seoFuryPreview.siteName || 'Site Name',
                '%sitedesc%':         seoFuryPreview.siteDesc || 'Site description',
                '%sep%':              seoFuryPreview.separator || '-',
                '%separator%':        seoFuryPreview.separator || '-',
                '%title%':            seoFuryPreview.exampleTitle || 'Example Post Title',
                '%excerpt%':          seoFuryPreview.exampleExcerpt || 'This is an example excerpt...',
                '%date%':             seoFuryPreview.currentDate || '2025-01-01',
                '%name%':             seoFuryPreview.authorName || 'Author',
                '%currentyear%':      new Date().getFullYear().toString(),
                '%category%':         seoFuryPreview.exampleCategory || 'Category',
                '%tag%':              seoFuryPreview.exampleTag || 'Tag',
                '%term_title%':       seoFuryPreview.exampleTerm || 'Term',
                '%term_description%': seoFuryPreview.exampleTermDesc || 'Term description...',
                '%searchquery%':      seoFuryPreview.exampleSearch || 'example search',
                '%page%':             '1',
                '%pagetotal%':        '10',
                '%pagenumber%':       '1'
            };

            this.bindEvents();
            this.updateAllPreviews();
            this.loadSchemaTemplates();
            this.bindBulkActions();
        },

        bindEvents: function() {
            var self = this;

            // Listen to input on all text fields within preview containers' associated inputs
            $(document).on('input', '.seo-meta-template-field input[type="text"]', function() {
                self.debouncedUpdate($(this));
            });

            // When the separator dropdown changes, update the map and refresh all previews
            $(document).on('change', '#title-separator-select', function() {
                var newSep = $(this).val();
                self.shortcodeMap['%sep%'] = newSep;
                self.shortcodeMap['%separator%'] = newSep;
                self.updateAllPreviews();
            });

            // When shortcode is inserted via dropdown, trigger an update
            $(document).on('click', '.seo-admin-shortcode-item', function() {
                var wrapper = $(this).closest('.seo-admin-input-with-dropdown');
                var input = wrapper.find('input[type="text"]').first();
                if (input.length) {
                    setTimeout(function() {
                        self.debouncedUpdate(input);
                    }, 50);
                }
            });
        },

        debouncedUpdate: function($input) {
            var self = this;
            if (self.debounceTimer) {
                clearTimeout(self.debounceTimer);
            }
            self.debounceTimer = setTimeout(function() {
                // Find the closest preview container related to this input
                var $container = $input.closest('.seo-meta-template-row').next('.seo-fury-settings-preview');
                if ($container.length) {
                    self.updatePreview($container);
                } else {
                    // If not found as next sibling, the input might be inside a template row
                    // that has a preview container following it. Search in parent.
                    var $parent = $input.closest('.seo-meta-panel, .seo-meta-titles-panels');
                    if ($parent.length) {
                        $parent.find('.seo-fury-settings-preview').each(function() {
                            self.updatePreview($(this));
                        });
                    }
                }
            }, self.debounceDelay);
        },

        parseShortcodes: function(template) {
            if (!template) {
                return '';
            }
            var result = template;
            for (var key in this.shortcodeMap) {
                if (this.shortcodeMap.hasOwnProperty(key)) {
                    // Use a global replace via split/join to handle multiple occurrences
                    result = result.split(key).join(this.shortcodeMap[key]);
                }
            }
            return result;
        },

        truncate: function(text, maxLen) {
            if (!text) {
                return '';
            }
            if (text.length > maxLen) {
                return text.substring(0, maxLen) + '...';
            }
            return text;
        },

        updatePreview: function($container) {
            var titleInputName = $container.data('title-input');
            var descInputName = $container.data('desc-input');

            var $titleInput = $('input[name="' + titleInputName + '"]');
            var $descInput = $('input[name="' + descInputName + '"]');

            var titleTemplate = $titleInput.length ? $titleInput.val() : '';
            var descTemplate = $descInput.length ? $descInput.val() : '';

            var parsedTitle = this.parseShortcodes(titleTemplate);
            var parsedDesc = this.parseShortcodes(descTemplate);

            // Google SERP preview
            var serpTitle = this.truncate(parsedTitle, 60);
            var serpDesc = this.truncate(parsedDesc, 160);

            $container.find('.serp-title').text(serpTitle || (typeof seoFuryPreview !== 'undefined' && seoFuryPreview.i18n && seoFuryPreview.i18n.titlePlaceholder ? seoFuryPreview.i18n.titlePlaceholder : 'Page Title'));
            $container.find('.serp-description').text(serpDesc || (typeof seoFuryPreview !== 'undefined' && seoFuryPreview.i18n && seoFuryPreview.i18n.noDescriptionSet ? seoFuryPreview.i18n.noDescriptionSet : 'No description set. Search engines will generate a snippet from your page content.'));

            // Character counts
            var titleLen = parsedTitle.length;
            var descLen = parsedDesc.length;

            var $titleCount = $container.find('.serp-title-count');
            var $descCount = $container.find('.serp-desc-count');

            if ($titleCount.length) {
                $titleCount.text(titleLen + '/60');
                if (titleLen > 60) {
                    $titleCount.addClass('over-limit');
                } else {
                    $titleCount.removeClass('over-limit');
                }
            }

            if ($descCount.length) {
                $descCount.text(descLen + '/160');
                if (descLen > 160) {
                    $descCount.addClass('over-limit');
                } else {
                    $descCount.removeClass('over-limit');
                }
            }

            // Social preview
            var socialTitle = this.truncate(parsedTitle, 70);
            var socialDesc = this.truncate(parsedDesc, 200);

            $container.find('.social-preview-title').text(socialTitle || (typeof seoFuryPreview !== 'undefined' && seoFuryPreview.i18n && seoFuryPreview.i18n.titlePlaceholder ? seoFuryPreview.i18n.titlePlaceholder : 'Page Title'));
            $container.find('.social-preview-desc').text(socialDesc || (typeof seoFuryPreview !== 'undefined' && seoFuryPreview.i18n && seoFuryPreview.i18n.noDescriptionAvailable ? seoFuryPreview.i18n.noDescriptionAvailable : 'No description available.'));
        },

        updateAllPreviews: function() {
            var self = this;
            $('.seo-fury-settings-preview').each(function() {
                self.updatePreview($(this));
            });
        },

        /**
         * Load saved Schema templates into all post-type template selects.
         */
        loadSchemaTemplates: function() {
            if (!seoFuryPreview.schemaTemplatesNonce || !$('.seo-fury-pt-template-select').length) {
                return;
            }
            var self = this;
            $.ajax({
                url: seoFuryPreview.ajax_url,
                method: 'POST',
                data: {
                    action: 'seo_fury_get_schema_templates',
                    nonce: seoFuryPreview.schemaTemplatesNonce
                },
                success: function(response) {
                    if (!response.success) return;
                    var templates = response.data.templates || [];
                    $('.seo-fury-pt-template-select').each(function() {
                        var $sel = $(this);
                        var firstOpt = $sel.find('option:first').clone();
                        $sel.empty().append(firstOpt);
                        if (!templates.length) {
                            $sel.append($('<option>').val('').text(seoFuryPreview.i18n.noTemplates).prop('disabled', true));
                            return;
                        }
                        $.each(templates, function(i, tpl) {
                            var label = tpl.name + (tpl.type && tpl.type !== 'none' ? ' (' + tpl.type + ')' : '');
                            $sel.append($('<option>').val(tpl.id).text(label));
                        });
                    });
                }
            });
        },

        /**
         * Bind bulk-action buttons: delete schema / apply template.
         */
        bindBulkActions: function() {
            var self = this;
            var i18n = seoFuryPreview.i18n;

            // Delete Schema from all posts of this post type
            $(document).on('click', '.seo-fury-delete-pt-schema', function() {
                var $btn = $(this);
                var pt    = $btn.data('pt');
                var label = $btn.data('label');
                var msg   = i18n.confirmDeleteSchema.replace('%s', label);

                if (!window.confirm(msg)) return;

                $btn.prop('disabled', true).find('.dashicons').after(' ').end()
                    .contents().last().replaceWith(' ' + i18n.deleting);

                $.ajax({
                    url: seoFuryPreview.ajax_url,
                    method: 'POST',
                    data: {
                        action: 'seo_fury_delete_post_type_schema',
                        nonce: seoFuryPreview.nonce,
                        post_type: pt
                    },
                    success: function(response) {
                        var text = response.success
                            ? response.data.message
                            : (response.data && response.data.message ? response.data.message : i18n.error);
                        self.showNotice($btn, text, response.success ? 'success' : 'error');
                    },
                    error: function() {
                        self.showNotice($btn, i18n.error, 'error');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html(
                            '<span class="dashicons dashicons-trash" style="font-size:16px;width:16px;height:16px;margin-top:3px;vertical-align:middle;"></span> ' +
                            i18n.deleteSchemaBtn
                        );
                    }
                });
            });

            // Apply saved Schema template to all posts of this post type
            $(document).on('click', '.seo-fury-apply-pt-template', function() {
                var $btn        = $(this);
                var pt          = $btn.data('pt');
                var label       = $btn.data('label');
                var $sel        = $('.seo-fury-pt-template-select[data-pt="' + pt + '"]');
                var templateId  = $sel.val();
                var templateName = $sel.find('option:selected').text();

                if (!templateId) {
                    window.alert(i18n.selectTemplate);
                    return;
                }

                var msg = i18n.confirmApplyTemplate.replace('%s', templateName);
                if (!window.confirm(msg)) return;

                $btn.prop('disabled', true).text(i18n.applying);

                $.ajax({
                    url: seoFuryPreview.ajax_url,
                    method: 'POST',
                    data: {
                        action: 'seo_fury_apply_template_to_post_type',
                        nonce: seoFuryPreview.nonce,
                        post_type: pt,
                        template_id: templateId
                    },
                    success: function(response) {
                        var text = response.success
                            ? response.data.message
                            : (response.data && response.data.message ? response.data.message : i18n.error);
                        self.showNotice($btn, text, response.success ? 'success' : 'error');
                    },
                    error: function() {
                        self.showNotice($btn, i18n.error, 'error');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text(i18n.applyTemplateBtn);
                    }
                });
            });
        },

        /**
         * Show an inline notice near $refEl.
         */
        showNotice: function($refEl, message, type) {
            var cls = type === 'success' ? '#00a32a' : '#b32d2e';
            var $notice = $('<div>')
                .css({
                    'margin-top': '8px',
                    'padding': '6px 10px',
                    'border-left': '4px solid ' + cls,
                    'background': '#fff',
                    'border-radius': '2px',
                    'font-size': '13px',
                    'color': '#1d2327'
                })
                .text(message);

            var $container = $refEl.closest('.seo-meta-section');
            $container.find('.seo-fury-bulk-notice').remove();
            $notice.addClass('seo-fury-bulk-notice');
            $container.append($notice);

            setTimeout(function() {
                $notice.fadeOut(400, function() { $(this).remove(); });
            }, 5000);
        }
    };

    $(document).ready(function() {
        if (typeof seoFuryPreview !== 'undefined') {
            SeoFurySettingsPreview.init();
        }
    });

})(jQuery);
