/**
 * Schema Template Editor
 * Manages the Schema Generator modal on the "Edit Schema Template" admin page
 * and in inline mode directly on the Schema Templates list page.
 */
jQuery(document).ready(function ($) {
    'use strict';

    if (typeof seoFuryTemplateEditor === 'undefined') {
        return;
    }

    var config    = seoFuryTemplateEditor;
    var isSaving  = false;
    var isInline  = (config.mode === 'inline');

    // Last schema data snapshot received from the Schema Editor modal save event.
    var lastSavedSchema = null;

    // Track whether the template was saved (to decide whether to delete on cancel).
    var templateSavedToServer = false;

    // ------------------------------------------------------------------ //
    // Shared DOM refs
    // ------------------------------------------------------------------ //
    var $schemaItemsInput = $('#seo_fury_schema_items');
    var $pageNameInput    = $('#sf-template-name-input');
    var $modalNameInput   = $('#sf-tpl-name-modal-input');

    // ------------------------------------------------------------------ //
    // Initialise schemaItems hidden input from PHP-supplied data
    // (standalone mode only — inline mode starts empty and loads via AJAX).
    // ------------------------------------------------------------------ //
    if (!isInline && $schemaItemsInput.length && config.schemaItems) {
        $schemaItemsInput.val(config.schemaItems);
    }

    // ------------------------------------------------------------------ //
    // Sync template name between the page/hidden input and the modal input.
    // ------------------------------------------------------------------ //
    if ($modalNameInput.length) {
        $modalNameInput.val($pageNameInput.val());
    }

    $pageNameInput.on('input', function () {
        $modalNameInput.val($(this).val());
    });

    $modalNameInput.on('input', function () {
        $pageNameInput.val($(this).val());
    });

    // ------------------------------------------------------------------ //
    // Open the Schema Generator modal.
    // ------------------------------------------------------------------ //
    function openGenerator() {
        $modalNameInput.val($pageNameInput.val());
        $(document).trigger('seo-fury:open-schema-generator', ['templates']);
    }

    $('#sf-open-schema-generator').on('click', function () {
        openGenerator();
    });

    // ------------------------------------------------------------------ //
    // STANDALONE MODE: auto-open the generator on page load.
    // ------------------------------------------------------------------ //
    if (!isInline) {
        setTimeout(openGenerator, 300);
    }

    // ------------------------------------------------------------------ //
    // INLINE MODE: open modal when Edit or Add New is clicked.
    // ------------------------------------------------------------------ //
    if (isInline) {
        $(document).on('click', '#seo-tpl-add-new-btn, .seo-tpl-add-new-btn', function () {
            openForEdit(0);
        });

        $(document).on('click', '.seo-tpl-edit-btn', function () {
            var id = parseInt($(this).data('id'), 10) || 0;
            openForEdit(id);
        });
    }

    /**
     * Load template data via AJAX then open the generator modal.
     * Pass id=0 to create a new draft template.
     */
    function openForEdit(templateId) {
        // Reset state for this edit session
        lastSavedSchema       = null;
        templateSavedToServer = false;

        $.post(config.ajaxUrl, {
            action:      'seo_fury_prepare_template_editor',
            nonce:       config.nonce,
            template_id: templateId
        }, function (res) {
            if (!res.success) {
                alert(res.data && res.data.message ? res.data.message : (typeof config.i18n !== 'undefined' && config.i18n.errorLoadingTemplate ? config.i18n.errorLoadingTemplate : 'Error loading template.'));
                return;
            }

            var d = res.data;

            // Update runtime config so save/cancel use the correct template id
            config.templateId        = d.templateId;
            config.schemaItemId      = d.schemaItemId;
            config.initialSchemaType = d.initialSchemaType;
            config._isNew            = d.isNew;

            // Push schema items into post-meta.js
            $(document).trigger('seo-fury:reset-schema-items', [d.schemaItems, d.schemaItemId]);

            // Set name inputs
            $pageNameInput.val(d.templateName);
            $modalNameInput.val(d.templateName);

            openGenerator();
        }).fail(function () {
            alert(typeof config.i18n !== 'undefined' && config.i18n.networkError ? config.i18n.networkError : 'Network error. Please try again.');
        });
    }

    // ------------------------------------------------------------------ //
    // Capture schema data when Schema Editor sub-modal saves.
    // ------------------------------------------------------------------ //
    $(document).on('seo-fury:schema-editor-saved', function (e, savedId, savedData) {
        lastSavedSchema = savedData;
    });

    var _prevSchemaItemsVal = $schemaItemsInput.val();
    $(document).on('seo-fury:schema-modal-tab-click seo-fury:schema-applied', function () {
        _prevSchemaItemsVal = $schemaItemsInput.val();
    });

    // ------------------------------------------------------------------ //
    // Cancel handler.
    // ------------------------------------------------------------------ //
    var redirecting = false;

    function handleCancel() {
        if (isInline) {
            // In inline mode just close the modal; delete draft if unsaved new template
            if (config._isNew && !templateSavedToServer && config.templateId) {
                $.post(config.ajaxUrl, {
                    action:      'seo_fury_delete_schema_template',
                    nonce:       config.nonce,
                    template_id: config.templateId
                });
            }
            closeModal();
            return;
        }

        // Standalone: redirect back to list
        if (redirecting) return;
        redirecting = true;

        var isNew = !templateSavedToServer && config.initialSchemaType === 'none';
        if (isNew && config.templateId) {
            $.post(config.ajaxUrl, {
                action:      'seo_fury_delete_schema_template',
                nonce:       config.nonce,
                template_id: config.templateId
            }).always(function () {
                window.location.href = config.listUrl;
            });
        } else {
            window.location.href = config.listUrl;
        }
    }

    function closeModal() {
        $('#seo-fury-schema-modal').hide();
        $('body').removeClass('modal-open').css('overflow', '');
    }

    // Outer generator modal: Cancel button
    $(document).on('click', '.sf-tpl-cancel-btn', handleCancel);

    // Schema Editor sub-modal: Cancel button and X button
    $(document).on('click', '.schema-editor-cancel, .schema-editor-modal-close', handleCancel);

    // ------------------------------------------------------------------ //
    // Save Template button (inside generator modal footer).
    // ------------------------------------------------------------------ //
    $(document).on('click', '.sf-tpl-save-btn', function () {
        $pageNameInput.val($modalNameInput.val());
        saveTemplateToServer(/* closeModal */ true);
    });

    // ------------------------------------------------------------------ //
    // Resolve the schema item to save.
    // ------------------------------------------------------------------ //
    function resolveSchemaToSave() {
        if (lastSavedSchema) {
            return lastSavedSchema;
        }

        var items = [];
        try {
            items = JSON.parse($schemaItemsInput.val() || '[]');
        } catch (e) {}

        var candidate = items.find(function (i) { return i.type && i.type !== 'none'; });
        return candidate || items[0] || null;
    }

    // ------------------------------------------------------------------ //
    // Core save function.
    // ------------------------------------------------------------------ //
    function saveTemplateToServer(doClose) {
        if (isSaving) return;

        var templateName = $pageNameInput.val().trim() || $modalNameInput.val().trim();
        if (!templateName) {
            showNotice('error', config.i18n.enterTemplateName || 'Please enter a template name before saving.');
            $modalNameInput.addClass('sf-input-error').focus();
            setTimeout(function () { $modalNameInput.removeClass('sf-input-error'); }, 2500);
            return;
        }
        $pageNameInput.val(templateName);
        $modalNameInput.val(templateName);

        var item = resolveSchemaToSave();
        if (!item || !item.type || item.type === 'none') {
            showNotice('error', config.i18n.noSchemaSelected || 'Please select a schema type and edit it before saving.');
            return;
        }

        var dataStr = '{}';
        if (item.mode === 'generator' && item.data) {
            try { dataStr = JSON.stringify(item.data); } catch (e) {}
        }

        var builderStr = '';
        if (item.builder_data) {
            try { builderStr = JSON.stringify(item.builder_data); } catch (e) {}
        }

        isSaving = true;
        showNotice('info', config.i18n.saving || 'Saving...');

        $.post(config.ajaxUrl, {
            action:       'seo_fury_save_schema_template',
            nonce:        config.nonce,
            template_id:  config.templateId,
            name:         templateName,
            mode:         item.mode  || 'custom',
            type:         item.type  || 'none',
            data:         dataStr,
            custom:       item.custom || '',
            builder_data: builderStr
        }, function (response) {
            isSaving = false;
            if (response.success) {
                templateSavedToServer = true;

                if (isInline) {
                    // Close modal and refresh the template list
                    if (doClose) {
                        closeModal();
                        $(document).trigger('seo-fury:template-list-refresh');
                    }
                } else {
                    // Standalone: update heading and redirect
                    $('h1.wp-heading-inline').text(
                        (config.i18n.editTitle || 'Edit Schema Template:') + ' ' + templateName
                    );
                    showNotice('success', config.i18n.saved || 'Template saved successfully!');
                    if (doClose) {
                        setTimeout(function () {
                            window.location.href = config.listUrl;
                        }, 1200);
                    }
                }
            } else {
                var msg = (response.data && response.data.message)
                    ? response.data.message
                    : (config.i18n.saveError || 'Failed to save template.');
                showNotice('error', msg);
            }
        }).fail(function () {
            isSaving = false;
            showNotice('error', config.i18n.saveError || 'Failed to save template.');
        });
    }

    // ------------------------------------------------------------------ //
    // Show an admin notice.
    // ------------------------------------------------------------------ //
    function showNotice(type, message) {
        var $notices = $('#sf-template-editor-notices');
        $notices.empty();
        var $n = $('<div class="notice notice-' + escAttr(type) + ' is-dismissible"><p>' +
            $('<span>').text(message).html() +
            '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>');
        $notices.append($n);
        $n.find('.notice-dismiss').on('click', function () { $n.fadeOut(200, function () { $n.remove(); }); });
        if (type === 'success' || type === 'info') {
            setTimeout(function () { $n.fadeOut(400, function () { $n.remove(); }); }, 4000);
        }
        $('html, body').animate({ scrollTop: 0 }, 200);
    }

    function escAttr(str) {
        return String(str).replace(/[&<>"']/g, function (c) {
            return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
        });
    }
});
