/**
 * Divine Form Integration JavaScript
 */

(function($) {
    'use strict';

    const Integration = {

        currentFormId: null,
        currentConfig: null,
        formFields: [],
        templatePlaceholders: [],

        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            $('#divine-add-integration-btn').on('click', () => this.openModal());

            $(document).on('click', '.divine-edit-integration', (e) => {
                const formId = $(e.currentTarget).data('form-id');
                this.editIntegration(formId);
            });

            $(document).on('click', '.divine-delete-integration', (e) => {
                const formId = $(e.currentTarget).data('form-id');
                this.deleteIntegration(formId);
            });

            $('#divine-select-form').on('change', () => this.onFormSelected());
            $('#divine-template-id').on('change', () => this.onTemplateSelected());
            $('#divine-save-integration-btn').on('click', () => this.saveIntegration());
            $('#divine-test-mapping-btn').on('click', () => this.testMapping());

            $('#divine-cancel-integration-btn, .divine-modal-close').on('click', () => this.closeModal());
            $('.divine-modal-overlay').on('click', () => this.closeModal());
            $('.divine-modal-content').on('click', (e) => e.stopPropagation());
        },

        openModal: function() {
            this.resetForm();
            $('#divine-integration-modal').fadeIn(200);
        },

        closeModal: function() {
            $('.divine-modal').fadeOut(200);
        },

        resetForm: function() {
            this.currentFormId = null;
            this.currentConfig = null;
            this.formFields = [];
            this.templatePlaceholders = [];

            $('#divine-integration-form')[0].reset();
            $('#divine-form-id').val('');
            $('#divine-select-form').prop('disabled', false);
            $('.divine-config-section').hide();
            $('.divine-mapping-section').hide();
        },

        editIntegration: function(formId) {
            this.currentFormId = formId;

            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_get_integration_config',
                    nonce: divineIntegration.nonce,
                    form_id: formId
                },
                success: (response) => {
                    if (response.success && response.data.config) {
                        this.currentConfig = response.data.config;
                        this.openModal();
                        this.populateForm();
                    }
                }
            });
        },

        populateForm: function() {
            if (!this.currentConfig) {
                return;
            }

            $('#divine-form-id').val(this.currentFormId);
            $('#divine-select-form').val(this.currentFormId).prop('disabled', true);
            $('#divine-enabled').prop('checked', this.currentConfig.enabled);
            $('#divine-template-id').val(this.currentConfig.template_id);
            $('#divine-send-email').prop('checked', this.currentConfig.send_email);

            this.loadFormFields(this.currentFormId, () => {
                $('#divine-email-field').val(this.currentConfig.email_field);

                this.loadTemplatePlaceholders(this.currentConfig.template_id, () => {
                    this.renderFieldMapping(this.currentConfig.field_mapping);
                });
            });

            $('.divine-config-section').show();
            $('.divine-mapping-section').show();
        },

        deleteIntegration: function(formId) {
            if (!confirm(divineIntegration.strings.confirm_delete)) {
                return;
            }

            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_delete_form_integration',
                    nonce: divineIntegration.nonce,
                    form_id: formId
                },
                success: (response) => {
                    if (response.success) {
                        $('tr[data-form-id="' + formId + '"]').fadeOut(300, function() {
                            $(this).remove();
                        });
                        this.showNotice(response.data.message, 'success');
                    } else {
                        this.showNotice(response.data.message, 'error');
                    }
                }
            });
        },

        onFormSelected: function() {
            const formId = $('#divine-select-form').val();

            if (!formId) {
                $('.divine-config-section').hide();
                $('.divine-mapping-section').hide();
                return;
            }

            this.currentFormId = formId;
            $('#divine-form-id').val(formId);

            this.loadFormFields(formId, () => {
                $('.divine-config-section').slideDown();
            });
        },

        onTemplateSelected: function() {
            const templateId = $('#divine-template-id').val();

            if (!templateId) {
                $('.divine-mapping-section').hide();
                return;
            }

            this.loadTemplatePlaceholders(templateId, () => {
                $('.divine-mapping-section').slideDown();
            });
        },

        loadFormFields: function(formId, callback) {
            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_get_form_fields',
                    nonce: divineIntegration.nonce,
                    form_id: formId
                },
                success: (response) => {
                    if (response.success) {
                        this.formFields = response.data.fields;
                        this.populateEmailFieldDropdown();
                        if (callback) {
                            callback();
                        }
                    }
                }
            });
        },

        loadTemplatePlaceholders: function(templateId, callback) {
            $('#divine-field-mapping-container').html('<div class="divine-mapping-loading"><span class="spinner is-active"></span> Loading...</div>');

            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_get_template_placeholders',
                    nonce: divineIntegration.nonce,
                    template_id: templateId
                },
                success: (response) => {
                    if (response.success) {
                        this.templatePlaceholders = response.data.placeholders;
                        this.renderFieldMapping();
                        if (callback) {
                            callback();
                        }
                    }
                }
            });
        },

        populateEmailFieldDropdown: function() {
            const $select = $('#divine-email-field');
            $select.html('<option value="">-- Select Email Field --</option>');

            this.formFields.forEach((field) => {
                $select.append(
                    $('<option></option>')
                        .val(field.id)
                        .text(field.label + ' (' + field.id + ')')
                );
            });
        },

        renderFieldMapping: function(existingMapping = {}) {
            const $container = $('#divine-field-mapping-container');

            if (this.templatePlaceholders.length === 0) {
                $container.html('<div class="divine-mapping-empty">No placeholders found in selected template.</div>');
                return;
            }

            let html = '<table class="divine-mapping-table">';
            html += '<thead><tr>';
            html += '<th>Template Placeholder</th>';
            html += '<th>Form Field</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            this.templatePlaceholders.forEach((placeholder) => {
                const selectedField = existingMapping[placeholder] || '';

                html += '<tr>';
                html += '<td><code class="divine-placeholder-label">{{' + this.escapeHtml(placeholder) + '}}</code></td>';
                html += '<td><select name="field_mapping[' + this.escapeHtml(placeholder) + ']" class="divine-mapping-select">';
                html += '<option value="">-- Not Mapped --</option>';

                this.formFields.forEach((field) => {
                    const selected = selectedField === field.id ? ' selected' : '';
                    html += '<option value="' + this.escapeHtml(field.id) + '"' + selected + '>';
                    html += this.escapeHtml(field.label) + ' (' + this.escapeHtml(field.id) + ')';
                    html += '</option>';
                });

                html += '</select></td>';
                html += '</tr>';
            });

            html += '</tbody></table>';

            const unmappedFields = this.formFields.filter((field) => !Object.values(existingMapping).includes(field.id));

            if (unmappedFields.length > 0) {
                html += '<div class="divine-unmapped-fields">';
                html += '<h4>Available Unmapped Form Fields:</h4>';
                html += '<ul>';
                unmappedFields.forEach((field) => {
                    html += '<li>' + this.escapeHtml(field.label) + ' (' + this.escapeHtml(field.id) + ')</li>';
                });
                html += '</ul>';
                html += '</div>';
            }

            $container.html(html);
        },

        saveIntegration: function() {
            const $btn = $('#divine-save-integration-btn');
            const formId = $('#divine-form-id').val() || $('#divine-select-form').val();
            const enabled = $('#divine-enabled').is(':checked');
            const templateId = $('#divine-template-id').val();
            const sendEmail = $('#divine-send-email').is(':checked');
            const emailField = $('#divine-email-field').val();

            if (!formId) {
                alert('Please select a form.');
                return;
            }

            if (!templateId) {
                alert('Please select a template.');
                return;
            }

            if (!emailField) {
                alert('Please select an email field.');
                return;
            }

            const fieldMapping = {};
            $('.divine-mapping-select').each(function() {
                const $select = $(this);
                const placeholder = $select.attr('name').match(/\[([^\]]+)\]/)[1];
                const fieldId = $select.val();

                if (fieldId) {
                    fieldMapping[placeholder] = fieldId;
                }
            });

            $btn.addClass('loading').prop('disabled', true);

            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_save_form_integration',
                    nonce: divineIntegration.nonce,
                    form_id: formId,
                    enabled: enabled,
                    template_id: templateId,
                    send_email: sendEmail,
                    email_field: emailField,
                    field_mapping: fieldMapping
                },
                success: (response) => {
                    $btn.removeClass('loading').prop('disabled', false);

                    if (response.success) {
                        this.showNotice(response.data.message, 'success');
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        this.showNotice(response.data.message, 'error');
                    }
                },
                error: () => {
                    $btn.removeClass('loading').prop('disabled', false);
                    this.showNotice('Error saving integration', 'error');
                }
            });
        },

        testMapping: function() {
            const templateId = $('#divine-template-id').val();

            if (!templateId) {
                alert('Please select a template first.');
                return;
            }

            const fieldMapping = {};
            $('.divine-mapping-select').each(function() {
                const $select = $(this);
                const placeholder = $select.attr('name').match(/\[([^\]]+)\]/)[1];
                const fieldId = $select.val();

                if (fieldId) {
                    fieldMapping[placeholder] = fieldId;
                }
            });

            const $btn = $('#divine-test-mapping-btn');
            $btn.addClass('loading').prop('disabled', true);

            $.ajax({
                url: divineIntegration.ajax_url,
                type: 'POST',
                data: {
                    action: 'divine_test_form_mapping',
                    nonce: divineIntegration.nonce,
                    template_id: templateId,
                    field_mapping: fieldMapping
                },
                success: (response) => {
                    $btn.removeClass('loading').prop('disabled', false);

                    if (response.success) {
                        $('#divine-test-preview-content').html(response.data.preview);
                        $('#divine-test-preview-modal').fadeIn(200);
                    } else {
                        this.showNotice(response.data.message, 'error');
                    }
                },
                error: () => {
                    $btn.removeClass('loading').prop('disabled', false);
                    this.showNotice('Error testing mapping', 'error');
                }
            });
        },

        showNotice: function(message, type) {
            const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
            const $notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');

            $('.divine-integration-settings h1').after($notice);

            setTimeout(() => {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);
        },

        escapeHtml: function(text) {
            const safeText = String(text);
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                '\'': '&#039;'
            };
            return safeText.replace(/[&<>"']/g, (character) => map[character]);
        }
    };

    $(document).ready(() => {
        if ($('.divine-integration-settings').length) {
            Integration.init();
        }
    });

})(jQuery);
