/**
 * Smart Convert – Currency & Unit Conversion - Templates Manager
 *
 * SCP Templates AJAX Handler
 * * This script handles all asynchronous interactions for the SCP Template management interface.
 * It utilizes jQuery for DOM manipulation and AJAX requests to the WordPress backend.
 * * Key features:
 * - Asynchronous creation, updating, and deletion of templates.
 * - Dynamic swapping of view/edit modes without page reloads (for updates).
 * - UI feedback management (flash messages, button states, loading indicators).
 *
 * @package           smart-convert-currency-unit-conversion
 * @author            Petr Novák
 * @copyright         2025 Petr Novák
 * @license           GPL-2.0-or-later
 * @licenseURI        https://www.gnu.org/licenses/gpl-2.0.html
 */
 
jQuery(document).ready(function($) {
    
    /**
     * ------------------------------------------------------------------------
     * Event Handler: Submit Template Form (Create & Update)
     * ------------------------------------------------------------------------
     * Intercepts the form submission to process data via AJAX instead of a standard POST.
     * Uses event delegation on 'document' to ensure it works for forms dynamically 
     * injected into the DOM (e.g., when switching to edit mode).
     */
    $(document).on('submit', '.smart-convert-currency-unit-conversion-template-form-ajax', function(e) {
        // Prevent standard HTML form submission to stop page reload
        e.preventDefault();
        
        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        var $card = $form.closest('.smart-convert-currency-unit-conversion-template-card');
        
        // UX: Disable the submit button and update text to indicate processing state
        // to prevent double-submission.
        $submitBtn.prop('disabled', true).text(SmartConvertCurrencyUnitConversionTemplatesAjax.saving);
        
        // Perform the AJAX request
        $.ajax({
            url: SmartConvertCurrencyUnitConversionTemplatesAjax.ajaxUrl, // WordPress AJAX endpoint localized via wp_localize_script
            type: 'POST',
            // Serialize form inputs and append the specific action hook required by wp_ajax_*
            data: $form.serialize() + '&action=smart_convert_currency_unit_conversion_ajax_save_template',
            success: function(response) {
                if (response.success) {
                    // Feedback: Display success notice to the user
                    showFlashMessage(response.data.message, 'success');
                    
                    // Logic branch: Edit vs. Create
                    if ($form.data('editing')) {
                        // In Edit mode: Replace the form directly with the rendered HTML 
                        // of the updated template card returned by the server.
                        $card.replaceWith(response.data.html);
                    } else {
                        // In Create mode: Full reload is preferred here to ensure the 
                        // new template appears in the correct order/location in the grid.
                        location.reload();
                    }
                } else {
                    // Handle logical errors returned by server (e.g., validation failure)
                    showFlashMessage(response.data.message, 'error');
                    // Reset button state so user can try again
                    $submitBtn.prop('disabled', false).text(SmartConvertCurrencyUnitConversionTemplatesAjax.save);
                }
            },
            error: function() {
                // Handle HTTP/Network errors
                showFlashMessage(SmartConvertCurrencyUnitConversionTemplatesAjax.errorGeneric, 'error');
                $submitBtn.prop('disabled', false).text(SmartConvertCurrencyUnitConversionTemplatesAjax.save);
            }
        });
    });
    
    /**
     * ------------------------------------------------------------------------
     * Event Handler: Delete Template
     * ------------------------------------------------------------------------
     * Handles the removal of a specific template. Includes a native confirmation
     * dialog before proceeding with the destructive action.
     */
    $(document).on('click', '.smart-convert-currency-unit-conversion-delete-template-ajax', function(e) {
        e.preventDefault();
        
        // Security/UX: Confirm intent before deletion
        if (!confirm(SmartConvertCurrencyUnitConversionTemplatesAjax.confirmDelete)) {
            return;
        }
        
        var $btn = $(this);
        var $card = $btn.closest('.smart-convert-currency-unit-conversion-template-card');
        // Extract ID and Nonce from data attributes for security verification
        var templateId = $btn.data('template-id');
        var nonce = $btn.data('nonce');
        
        // Prevent multiple clicks while processing
        $btn.prop('disabled', true);
        
        $.ajax({
            url: SmartConvertCurrencyUnitConversionTemplatesAjax.ajaxUrl,
            type: 'POST',
            data: {
                action: 'smart_convert_currency_unit_conversion_ajax_delete_template',
                template_id: templateId,
                _wpnonce: nonce // Verify request authenticity
            },
            success: function(response) {
                if (response.success) {
                    showFlashMessage(response.data.message, 'success');
                    // UI: Fade out the card visually, then remove from DOM for a smooth transition
                    $card.fadeOut(300, function() { $(this).remove(); });
                } else {
                    showFlashMessage(response.data.message, 'error');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                showFlashMessage(SmartConvertCurrencyUnitConversionTemplatesAjax.errorGeneric, 'error');
                $btn.prop('disabled', false);
            }
        });
    });
    
    /**
     * ------------------------------------------------------------------------
     * Event Handler: Initialize Edit Mode
     * ------------------------------------------------------------------------
     * Fetches the edit form for a specific template and replaces the 
     * static display card with that form.
     */
    $(document).on('click', '.smart-convert-currency-unit-conversion-edit-template-ajax', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var $card = $btn.closest('.smart-convert-currency-unit-conversion-template-card');
        var templateId = $btn.data('template-id');
        var nonce = $btn.data('nonce');
        
        // UX: Indicate loading state on the button
        $btn.prop('disabled', true).text(SmartConvertCurrencyUnitConversionTemplatesAjax.loading);
        
        $.ajax({
            url: SmartConvertCurrencyUnitConversionTemplatesAjax.ajaxUrl,
            type: 'POST',
            data: {
                action: 'smart_convert_currency_unit_conversion_ajax_get_edit_form', // Request the HTML form markup
                template_id: templateId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    // Replace the display card with the form HTML returned by server
                    $card.replaceWith(response.data.html);
                } else {
                    showFlashMessage(response.data.message, 'error');
                    $btn.prop('disabled', false).text(SmartConvertCurrencyUnitConversionTemplatesAjax.edit);
                }
            },
            error: function() {
                showFlashMessage(SmartConvertCurrencyUnitConversionTemplatesAjax.errorGeneric, 'error');
                $btn.prop('disabled', false).text(SmartConvertCurrencyUnitConversionTemplatesAjax.edit);
            }
        });
    });
    
    /**
     * ------------------------------------------------------------------------
     * Event Handler: Cancel Edit
     * ------------------------------------------------------------------------
     * Reverts changes by reloading the page.
     * Note: While we could fetch the original card via AJAX, a reload is a 
     * safer guarantee to reset the state and discard any dirty form inputs.
     */
    $(document).on('click', '.smart-convert-currency-unit-conversion-cancel-edit-ajax', function(e) {
        e.preventDefault();
        location.reload();
    });
    
    /**
     * Helper Function: Show Flash Message
     * * Generates a WordPress-style admin notice, injects it into the container,
     * scrolls the viewport to ensure visibility, and sets a timer for auto-dismissal.
     * * @param {string} message - The text content to display.
     * @param {string} type    - The context class (e.g., 'success', 'error').
     */
    function showFlashMessage(message, type) {
        // Construct standard WordPress admin notice markup
        var $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p><strong>' + message + '</strong></p></div>');
        $('.smart-convert-currency-unit-conversion-templates-container').prepend($notice);
        
        // UX: Smooth scroll to top to ensure the user sees the message
        $('html, body').animate({ scrollTop: 0 }, 300);
        
        // Cleanup: Auto-dismiss the notice after 5 seconds to reduce clutter
        setTimeout(function() {
            $notice.fadeOut(300, function() { $(this).remove(); });
        }, 5000);
    }
});