jQuery(document).ready(function($) {
'use strict';
/**
 * Smart Convert – Currency & Unit Conversion - Custom Units Manager
 *
 * Handles the UI interactions for adding, editing, and deleting custom units.
 *
 * @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
 */
    const $form = $('#smart-convert-currency-unit-conversion-add-unit-form');

    // If the form is not present in the DOM, terminate execution to prevent errors.
    if (!$form.length) return;

    /**
     * Configuration Data Injection.
     * * @var {Array} unitsDataList - Array of existing unit objects (label/value pairs) passed from PHP via wp_localize_script.
     * @var {string} nonce - Security nonce for AJAX verification.
     */
    const unitsDataList = (typeof SmartConvertCurrencyUnitConversionUnitsData !== 'undefined' && SmartConvertCurrencyUnitConversionUnitsData.list) ? SmartConvertCurrencyUnitConversionUnitsData.list : [];
    const nonce = (typeof SmartConvertCurrencyUnitConversionUnitsData !== 'undefined') ? SmartConvertCurrencyUnitConversionUnitsData.nonce : '';
    
    // Safety check for localized strings to prevent "undefined" errors if PHP isn't updated yet
    // Added new keys for dynamic JS translations
    const strings = (typeof SmartConvertCurrencyUnitConversionUnitsData !== 'undefined' && SmartConvertCurrencyUnitConversionUnitsData.strings) ? SmartConvertCurrencyUnitConversionUnitsData.strings : {
        titleError: 'Attention',
        titleSuccess: 'Success',
        titleConfirm: 'Confirmation',
        btnOk: 'OK',
        btnCancel: 'Cancel',
        btnDelete: 'Yes, Delete',
        titleEdit: 'Edit Custom Unit',
        titleAdd: 'Add Custom Unit',
        btnUpdate: 'Update Unit',
        btnSave: 'Save Custom Unit',
        errorServer: 'Server Error: ',
        errorGeneric: 'Error: ',
        validationOk: 'OK'
    };

    // ==========================================================================
    // 0. UI UTILITIES (MODAL & CONFIRM)
    // ==========================================================================

    /**
     * Displays a custom modal overlay instead of the native alert().
     * Matches the visual style of smart-convert-currency-unit-conversion-ajax-update.js and smart-convert-currency-unit-conversion-admin.css.
     * * @param {string} message - The message to display.
     * @param {string} type - 'error' or 'success'.
     */
    function showScpAlert(message, type = 'error') {
        const isError = type === 'error';
        // USE LOCALIZED STRINGS
        const title = isError ? strings.titleError : strings.titleSuccess;
        const icon = isError ? '⚠️' : '✅';
        
        // Define button styles inline to ensure they match plugin theme (Coral/White)
        const btnStyle = isError 
            ? 'background: #fff; border: 1px solid #dcdcde; color: #1A2F45;' // Secondary style
            : 'background-color: #FF6B81; border-color: #FF6B81; color: #fff;'; // Primary style (Coral)

        // Remove any existing overlay to prevent stacking
        $('#smart-convert-currency-unit-conversion-alert-overlay').remove();

        const html = `
        <div id="smart-convert-currency-unit-conversion-alert-overlay" style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(240, 240, 241, 0.85); backdrop-filter:blur(8px); -webkit-backdrop-filter:blur(8px); z-index:100001; display:flex; justify-content:center; align-items:center;">
            <div class="smart-convert-currency-unit-conversion-modal-card" style="animation: scpPopIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); max-width: 400px;">
                <div class="smart-convert-currency-unit-conversion-spinner-icon" style="font-style:normal; margin-bottom: 20px; display:block; line-height:1;">${icon}</div>
                <h3 style="margin-top:0;">${title}</h3>
                <div class="smart-convert-currency-unit-conversion-update-details" style="margin-bottom: 25px; font-size: 1rem; color: #50667d; line-height: 1.5;">
                    ${message}
                </div>
                <button class="button smart-convert-currency-unit-conversion-alert-close-btn" style="min-width: 120px; justify-content: center; ${btnStyle}">${strings.btnOk}</button>
            </div>
        </div>`;

        $('body').append(html);

        // Bind close event
        const $overlay = $('#smart-convert-currency-unit-conversion-alert-overlay');
        const close = function() { $overlay.fadeOut(300, function() { $(this).remove(); }); };
        
        $overlay.find('.smart-convert-currency-unit-conversion-alert-close-btn').on('click', function(e) {
            e.preventDefault();
            close();
        });

        $overlay.on('click', function(e) {
            if (e.target === this) close();
        });
    }

    /**
     * Displays a custom confirmation modal instead of native confirm().
     * * @param {string} message - The question to ask.
     * @param {Function} onConfirm - Callback to execute when user clicks "Yes".
     */
    function showScpConfirm(message, onConfirm) {
        $('#smart-convert-currency-unit-conversion-alert-overlay').remove();

        const html = `
        <div id="smart-convert-currency-unit-conversion-alert-overlay" style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(240, 240, 241, 0.85); backdrop-filter:blur(8px); -webkit-backdrop-filter:blur(8px); z-index:100001; display:flex; justify-content:center; align-items:center;">
            <div class="smart-convert-currency-unit-conversion-modal-card" style="animation: scpPopIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); max-width: 400px;">
                <div class="smart-convert-currency-unit-conversion-spinner-icon" style="font-style:normal; margin-bottom: 25px; display:block; line-height:1;">❓</div>
                
                <h3 style="margin-top:0;">${strings.titleConfirm}</h3>
                <div class="smart-convert-currency-unit-conversion-update-details" style="margin-bottom: 25px; font-size: 1rem; color: #50667d; line-height: 1.5;">
                    ${message}
                </div>
                
                <div style="display:flex; justify-content:center; gap:15px;">
                    <button class="button smart-convert-currency-unit-conversion-confirm-cancel" style="min-width: 100px; justify-content: center; background: #fff; border: 1px solid #dcdcde; color: #1A2F45;">${strings.btnCancel}</button>
                    
                    <button class="button button-primary smart-convert-currency-unit-conversion-confirm-yes" style="min-width: 100px; justify-content: center; background-color: #FF6B81; border-color: #FF6B81; color: #fff;">${strings.btnDelete}</button>
                </div>
            </div>
        </div>`;

        $('body').append(html);
        const $overlay = $('#smart-convert-currency-unit-conversion-alert-overlay');
        const close = function() { $overlay.fadeOut(200, function() { $(this).remove(); }); };

        // Bind events
        $overlay.find('.smart-convert-currency-unit-conversion-confirm-yes').on('click', function(e) {
            e.preventDefault();
            onConfirm(); // Execute the callback
            close();
        });

        $overlay.find('.smart-convert-currency-unit-conversion-confirm-cancel').on('click', function(e) {
            e.preventDefault();
            close();
        });

        $overlay.on('click', function(e) {
            if (e.target === this) close();
        });
    }

    // ==========================================================================
    // 0. AUTOCOMPLETE INITIALIZATION
    // ==========================================================================

    /**
     * Initializes jQuery UI Autocomplete for unit selection inputs.
     * * This function binds a visible text input to a hidden value input. It ensures that 
     * when a user selects a unit from the dropdown, the internal ID is stored.
     * It also handles the edge case where a user types a valid name but does not click 
     * the dropdown item, or clears the field.
     *
     * @param {string} selector - CSS selector for the visible text input.
     * @param {string} hiddenSelector - CSS selector for the hidden input storing the unit ID/Code.
     */
    function initAutocomplete(selector, hiddenSelector) {
        $(selector).autocomplete({
            source: unitsDataList,
            minLength: 0, // Allow opening the dropdown even with empty input
            appendTo: ".smart-convert-currency-unit-conversion-custom-units-card", // Scopes the dropdown to the specific card for styling context
            
            // Event: User explicitly selects an item from the list
            select: function(event, ui) {
                event.preventDefault();
                $(selector).val(ui.item.label);
                $(hiddenSelector).val(ui.item.val).trigger('change'); // Trigger change to update button state
            },

            // Event: Value changes (blur or selection)
            change: function(event, ui) {
                // Logic handles manual typing without explicit menu selection
                if (!ui.item) {
                    const val = $(this).val();
                    // Attempt to find a matching unit in the dataset by label or value code
                    const match = unitsDataList.find(i => i.label === val || i.val === val);
                    
                    if (match) {
                        // valid match found, sync hidden input
                        $(hiddenSelector).val(match.val).trigger('change');
                    } else {
                        // No match found; if input is empty, clear hidden value.
                        if(!val) $(hiddenSelector).val('').trigger('change');
                    }
                } else {
                    $(hiddenSelector).trigger('change'); 
                }
            }
        }).on('focus', function() {
            // Force search on focus to show all available options immediately
            $(this).autocomplete('search', ''); 
        });
    }

    // Initialize autocomplete for both "From" (Source) and "To" (Target) unit fields
    initAutocomplete('#smart_convert_currency_unit_conversion_existing_from_display', '#smart_convert_currency_unit_conversion_existing_from_val');
    initAutocomplete('#smart_convert_currency_unit_conversion_existing_to_display', '#smart_convert_currency_unit_conversion_existing_to_val');

    // ==========================================================================
    // 1. EDIT MODE LOGIC
    // ==========================================================================

    /**
     * Handler for the "Edit" button on existing custom units.
     * * Fetches unit details via AJAX and populates the form.
     */
    $(document).on('click', '.smart-convert-currency-unit-conversion-edit-unit-ajax', function(e) {
        e.preventDefault();
        const id = $(this).data('id');
        
        // Smooth scroll to the form section to ensure the user sees the editing context
        $('html, body').animate({
            scrollTop: $(".smart-convert-currency-unit-conversion-custom-units-card").offset().top - 50
        }, 500);

        // Visual feedback: dim the form while loading data
        $(".smart-convert-currency-unit-conversion-custom-units-card").css('opacity', '0.6');

        // Request unit details from the server
        $.post(ajaxurl, {
            action: 'smart_convert_currency_unit_conversion_ajax_get_unit_details',
            id: id,
            _wpnonce: nonce
        }, function(response) {
            $(".smart-convert-currency-unit-conversion-custom-units-card").css('opacity', '1');
            
            if (response.success) {
                const data = response.data;
                populateForm(data);
            } else {
                showScpAlert(response.data.message, 'error');
            }
        });
    });

    /**
     * Populates the form fields with data received from the server.
     * * This function handles the complex logic of switching between "New Unit" and 
     * "Existing Unit" modes depending on how the unit was originally saved.
     *
     * @param {Object} data - The unit data object returned from the AJAX call.
     */
    function populateForm(data) {
        // Set the hidden ID field (0 indicates creation, >0 indicates update)
        $('#smart_convert_currency_unit_conversion_edit_id').val(data.id);
        
        // Update UI labels to reflect "Edit" context (TRANSLATED)
        $('#smart-convert-currency-unit-conversion-form-title').text(strings.titleEdit); 
        $('#smart-convert-currency-unit-conversion-save-unit-btn').text(strings.btnUpdate);
        $('#smart-convert-currency-unit-conversion-cancel-edit-btn').show();

        // --- Logic for the 'FROM' (Source) side ---
        if (data.is_custom == 1 && data.unit_from_name) {
            // Case: The source unit is a custom created unit.
            // Switch radio to 'new' and populate text fields.
            $('input[name="mode_from"][value="new"]').prop('checked', true);
            $('input[name="new_from_name"]').val(data.unit_from_name);
            $('input[name="new_from_code"]').val(data.unit_from);
            $('input[name="new_from_symbol_before"]').val(data.symbol_from_before);
            $('input[name="new_from_symbol_after"]').val(data.symbol_from_after);
        } else {
            // Case: The source unit is a standard/existing database unit.
            // Switch radio to 'existing' and set autocomplete values.
            $('input[name="mode_from"][value="existing"]').prop('checked', true);
            $('#smart_convert_currency_unit_conversion_existing_from_val').val(data.unit_from);
            
            // Resolve label from the dataset for display purposes
            const match = unitsDataList.find(i => i.val === data.unit_from);
            $('#smart_convert_currency_unit_conversion_existing_from_display').val(match ? match.label : data.unit_from);
        }
        // Apply visual state (show/hide fields based on mode)
        toggleMode('from');

        // --- Logic for the 'TO' (Target) side ---
        if (data.is_custom == 1 && data.unit_to_name) {
            $('input[name="mode_to"][value="new"]').prop('checked', true);
            $('input[name="new_to_name"]').val(data.unit_to_name);
            $('input[name="new_to_code"]').val(data.unit_to);
            $('input[name="new_to_symbol_before"]').val(data.symbol_to_before);
            $('input[name="new_to_symbol_after"]').val(data.symbol_to_after);
        } else {
            $('input[name="mode_to"][value="existing"]').prop('checked', true);
            $('#smart_convert_currency_unit_conversion_existing_to_val').val(data.unit_to);
            const match = unitsDataList.find(i => i.val === data.unit_to);
            $('#smart_convert_currency_unit_conversion_existing_to_display').val(match ? match.label : data.unit_to);
        }
        toggleMode('to');

        // Conversion Factor: Parse float to strip insignificant trailing zeros (cleaner UX)
        $('#smart_convert_currency_unit_conversion_factor').val(parseFloat(data.factor));
        
        // Refresh the math equation preview and validate button state
        updateEquation();
        checkButtonState();
    }

    /**
     * Handler for the Cancel button.
     * Reverts the form to the default "Add New Unit" state.
     */
    $('#smart-convert-currency-unit-conversion-cancel-edit-btn').on('click', function() {
        resetForm();
    });

    /**
     * Resets the entire form to its initial state.
     * * This clears inputs, resets the ID to 0 (Create Mode), restores default text,
     * and specifically ensures that "Code" inputs are writable again (they are locked during edit).
     */
    function resetForm() {
        $form[0].reset(); // HTMLFormElement.reset() clears standard inputs
        
        // Reset hidden ID to 0 (indicates Create Mode)
        $('#smart_convert_currency_unit_conversion_edit_id').val('0');
        
        // Reset UI text labels (TRANSLATED)
        $('#smart-convert-currency-unit-conversion-form-title').text(strings.titleAdd); 
        $('#smart-convert-currency-unit-conversion-save-unit-btn').text(strings.btnSave);
        $('#smart-convert-currency-unit-conversion-cancel-edit-btn').hide();

        // Clear hidden values for autocomplete fields (not cleared by form.reset())
        $('#smart_convert_currency_unit_conversion_existing_from_val').val('');
        $('#smart_convert_currency_unit_conversion_existing_to_val').val('');
        
        // Set default mode back to 'existing' for both sides
        $('input[name="mode_from"][value="existing"]').prop('checked', true);
        $('input[name="mode_to"][value="existing"]').prop('checked', true);
        
        // Unlock 'Code' inputs (removing read-only attributes used in Edit mode)
        $('.smart-convert-currency-unit-conversion-code-input').prop('readonly', false).removeClass('disabled-look');
        
        // Refresh UI state
        toggleMode('from');
        toggleMode('to');
        updateEquation();
        checkButtonState();
    }

    // ==========================================================================
    // 2. IMPORT / EXPORT HANDLERS
    // ==========================================================================

    $('#smart-convert-currency-unit-conversion-btn-export').on('click', function() {
        window.location.href = ajaxurl + '?action=smart_convert_currency_unit_conversion_ajax_export_units&_wpnonce=' + nonce;
    });

    $('#smart-convert-currency-unit-conversion-btn-import').on('click', function() {
        $('#smart-convert-currency-unit-conversion-import-form').slideToggle();
    });

    // AJAX Import submission
    $('#smart-convert-currency-unit-conversion-import-form').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        formData.append('action', 'smart_convert_currency_unit_conversion_ajax_import_units');
        formData.append('_wpnonce', nonce);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false, // Required for FormData
            contentType: false, // Required for FormData
            success: function(res) {
                if (res.success) {
                    showScpAlert(res.data.message, 'success');
                    
                    // Delay reload slightly to let user read the success message
                    setTimeout(() => { location.reload(); }, 1500);
                } else {
                    showScpAlert(res.data.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                // Translated Server Error
                showScpAlert(strings.errorServer + error, 'error');
            }
        });
    });

    // ==========================================================================
    // 3. UI HELPER: TOGGLE MODE (NEW VS EXISTING)
    // ==========================================================================

    /**
     * Toggles the visibility and state of fields based on the selected mode (Existing vs New).
     * * This function manages the "slide" animation between panels and handles the 
     * `disabled` property of inputs. Disabling hidden inputs is crucial to prevent 
     * them from being validated or submitted.
     * * @param {string} side - 'from' or 'to' indicating which column to toggle.
     */
    function toggleMode(side) {
        const mode = $(`input[name="mode_${side}"]:checked`).val();
        const $container = $(`.smart-convert-currency-unit-conversion-unit-column-${side}`);
        const isEditMode = $('#smart_convert_currency_unit_conversion_edit_id').val() != '0';
        
        // Update visual active state on the radio button container
        $(`input[name="mode_${side}"]`).closest('label').removeClass('active');
        $(`input[name="mode_${side}"]:checked`).closest('label').addClass('active');

        if (mode === 'existing') {
            // --- EXISTING MODE SELECTED ---
            $container.find('.smart-convert-currency-unit-conversion-field-existing').slideDown(200);
            $container.find('.smart-convert-currency-unit-conversion-field-new').slideUp(200);
            
            // Disable 'New' fields to exclude them from validation checks
            $container.find('.smart-convert-currency-unit-conversion-field-new input').prop('disabled', true).removeClass('smart-convert-currency-unit-conversion-input-error');
            
            // Enable 'Existing' fields (autocomplete + hidden ID)
            $container.find('.smart-convert-currency-unit-conversion-autocomplete-input').prop('disabled', false);
            $container.find('input[type="hidden"]').prop('disabled', false);
        } else {
            // --- NEW MODE SELECTED ---
            $container.find('.smart-convert-currency-unit-conversion-field-existing').slideUp(200);
            $container.find('.smart-convert-currency-unit-conversion-field-new').slideDown(200);
            
            // Enable 'New' input fields
            $container.find('.smart-convert-currency-unit-conversion-field-new input').prop('disabled', false);
            
            // CRITICAL: Code field logic
            // If we are in Edit Mode, the unique identifier (Code) must NOT be editable 
            // to preserve database integrity. If creating new, it is editable.
            if (isEditMode) {
                 $container.find('.smart-convert-currency-unit-conversion-code-input').prop('readonly', true).addClass('disabled-look');
            } else {
                 $container.find('.smart-convert-currency-unit-conversion-code-input').prop('readonly', false).removeClass('disabled-look');
            }

            // Disable 'Existing' fields
            $container.find('.smart-convert-currency-unit-conversion-autocomplete-input').prop('disabled', true);
            $container.find('input[type="hidden"]').prop('disabled', true);
            
            // Immediately validate required fields in the now-visible section
            $container.find('.smart-convert-currency-unit-conversion-validate-required:visible').each(function() {
                validateFieldVisual($(this));
            });
        }
        updateEquation();
        checkButtonState();
    }
    
    // ==========================================================================
    // 4. PREVIEW GENERATOR
    // ==========================================================================

    /**
     * Builds the HTML string for a single side of the conversion equation preview.
     * * @param {string} val - The numeric value to display (usually '1' or the input factor).
     * @param {string} side - 'from' or 'to'.
     * @returns {string} HTML string containing the formatted value, symbol, and unit code.
     */
    function buildPreviewString(val, side) {
        const mode = $(`input[name="mode_${side}"]:checked`).val();
        let html = '';

        if (mode === 'existing') {
            // Extract the short code from the label format "Name (code)" if possible
            let text = $(`#smart_convert_currency_unit_conversion_existing_${side}_display`).val();
            if (!text) text = '...';
            const match = text.match(/\(([^)]+)\)$/);
            const shortText = match ? match[1] : text;
            html = `<span class="smart-convert-currency-unit-conversion-val">${val}</span> <span class="smart-convert-currency-unit-conversion-unit">${shortText}</span>`;
        } else {
            // Build string from manual inputs: Symbol Before + Value + Symbol After + Code
            const symBefore = $(`input[name="new_${side}_symbol_before"]`).val();
            const symAfter  = $(`input[name="new_${side}_symbol_after"]`).val();
            const code      = $(`input[name="new_${side}_code"]`).val();
            
            if (symBefore) html += `<span class="smart-convert-currency-unit-conversion-sym">${symBefore}</span>`;
            html += `<span class="smart-convert-currency-unit-conversion-val">${val}</span>`;
            if (symAfter) html += `<span class="smart-convert-currency-unit-conversion-sym">${symAfter}</span>`;
            // Only show code if no symbols are defined, as a fallback visual
            if (!symBefore && !symAfter && code) {
                html += ` <span class="smart-convert-currency-unit-conversion-code">${code}</span>`;
            }
        }
        return html;
    }

    /**
     * Updates the mathematical equation displayed at the bottom of the card.
     * Example: "1 kg = 2.2046 lb"
     * * This function is reactive; it rebuilds the DOM elements whenever inputs change.
     */
    function updateEquation() {
        // Left side is always base 1
        $('.eq-left').html(buildPreviewString('1', 'from'));
        const $rightContainer = $('.eq-right');
        
        // Detach the input factor field to preserve its event listeners and value
        // while we clear the container.
        const $input = $('#smart_convert_currency_unit_conversion_factor').detach(); 
        
        $rightContainer.empty();
        
        const modeTo = $('input[name="mode_to"]:checked').val();
        
        if (modeTo === 'existing') {
            let text = $('#smart_convert_currency_unit_conversion_existing_to_display').val();
            if (!text) text = '...';
            const match = text.match(/\(([^)]+)\)$/);
            const shortText = match ? match[1] : text;
            $rightContainer.append($input).append(` <span class="preview-wrap">${shortText}</span>`);
        } else {
            const symBefore = $('input[name="new_to_symbol_before"]').val();
            const symAfter  = $('input[name="new_to_symbol_after"]').val();
            const code      = $('input[name="new_to_code"]').val();
            
            if (symBefore) $rightContainer.append(`<span class="preview-wrap smart-convert-currency-unit-conversion-sym">${symBefore}</span>`);
            $rightContainer.append($input);
            if (symAfter) {
                $rightContainer.append(`<span class="preview-wrap smart-convert-currency-unit-conversion-sym">${symAfter}</span>`);
            } else if (!symBefore && code) {
                $rightContainer.append(` <span class="preview-wrap smart-convert-currency-unit-conversion-code">${code}</span>`);
            }
        }
    }

    // Attach listeners for real-time preview updates
    $form.on('keyup change', 'input:not(#smart_convert_currency_unit_conversion_factor), select', updateEquation);
    $('input[name="mode_from"]').on('change', () => toggleMode('from'));
    $('input[name="mode_to"]').on('change', () => toggleMode('to'));

    // ==========================================================================
    // 5. VISUAL VALIDATION
    // ==========================================================================

    /**
     * Checks a specific field's validity and applies/removes error CSS classes.
     * * @param {jQuery} $field - The input element to check.
     * @returns {boolean} True if valid, False otherwise.
     */
    function validateFieldVisual($field) {
        // If hidden or disabled, it's considered valid (ignored)
        if ($field.is(':hidden') || $field.prop('disabled')) {
            $field.removeClass('smart-convert-currency-unit-conversion-input-error');
            return true;
        }
        const val = $field.val().trim();
        let isValid = true;
        
        // Basic "Required" check
        if ($field.hasClass('smart-convert-currency-unit-conversion-validate-required') && val === '') {
            $field.addClass('smart-convert-currency-unit-conversion-input-error');
            isValid = false;
        } else {
            // Only remove error class if it's NOT a duplicate code error (handled by AJAX)
            if (!$field.hasClass('smart-convert-currency-unit-conversion-code-duplicate')) {
                $field.removeClass('smart-convert-currency-unit-conversion-input-error');
            }
        }
        return isValid;
    }

    // Trigger validation on blur or input
    $form.on('blur input', 'input.smart-convert-currency-unit-conversion-validate-required', function() {
        validateFieldVisual($(this));
        checkButtonState();
    });

    // ==========================================================================
    // 6. AJAX UNIQUE CODE CHECK
    // ==========================================================================
    
    let debounceTimer = null;

    /**
     * Monitors the 'Code' input fields to ensure uniqueness in the database.
     * Uses a debounce timer to prevent spamming the server with requests on every keystroke.
     */
    $('.smart-convert-currency-unit-conversion-code-input').on('input', function() {
        // If read-only (Edit mode), do not perform check
        if ($(this).prop('readonly')) return;

        const $input = $(this);
        const $msg = $input.siblings('.smart-convert-currency-unit-conversion-validation-msg');
        
        clearTimeout(debounceTimer);
        
        // Sanitize input: lowercase, alphanumeric only, max 20 chars
        let val = $input.val();
        val = val.toLowerCase().replace(/[^a-z0-9]/g, '').substring(0, 20);
        $input.val(val);

        if (val === '') {
            $msg.text('').removeClass('error ok');
            $input.removeClass('smart-convert-currency-unit-conversion-code-duplicate');
            validateFieldVisual($input);
            checkButtonState();
            return;
        }

        // Wait 500ms after last keystroke before sending AJAX request
        debounceTimer = setTimeout(() => {
            $.post(ajaxurl, {
                action: 'smart_convert_currency_unit_conversion_check_unit_code',
                code: val,
                _wpnonce: nonce
            }, function(response) {
                if (!response.success) {
                    // Code exists - Error
                    $msg.removeClass('ok').addClass('error').text(response.data.message);
                    $input.addClass('smart-convert-currency-unit-conversion-input-error smart-convert-currency-unit-conversion-code-duplicate');
                } else {
                    // Code available - OK (TRANSLATED)
                    $msg.removeClass('error').addClass('ok').text(strings.validationOk);
                    $input.removeClass('smart-convert-currency-unit-conversion-code-duplicate smart-convert-currency-unit-conversion-input-error');
                }
                checkButtonState();
            });
        }, 500);
    });

    // ==========================================================================
    // 7. BUTTON STATE MANAGEMENT
    // ==========================================================================

    /**
     * Global validator for the "Save/Update" button.
     * * Iterates through all validation conditions (empty required fields, invalid numbers,
     * duplicate codes) and enables/disables the submit button accordingly.
     */
    function checkButtonState() {
        const $submit = $('#smart-convert-currency-unit-conversion-save-unit-btn');
        let isValid = true;
        
        // Check visible required text inputs
        $form.find('input.smart-convert-currency-unit-conversion-validate-required:visible').each(function() {
            if ($(this).val().trim() === '') isValid = false;
        });

        // Check hidden ID inputs if mode is 'existing'
        if ($('input[name="mode_from"]:checked').val() === 'existing') {
            if ($('#smart_convert_currency_unit_conversion_existing_from_val').val() === '') isValid = false;
        }
        if ($('input[name="mode_to"]:checked').val() === 'existing') {
            if ($('#smart_convert_currency_unit_conversion_existing_to_val').val() === '') isValid = false;
        }
        
        // Check conversion factor (must be positive number)
        const factor = parseFloat($('#smart_convert_currency_unit_conversion_factor').val());
        if (isNaN(factor) || factor <= 0) isValid = false;
        
        // Check for duplicate code flags
        if ($('.smart-convert-currency-unit-conversion-code-duplicate').length > 0) isValid = false;

        // Update button UI
        $submit.prop('disabled', !isValid);
        if (isValid) $submit.removeClass('disabled'); else $submit.addClass('disabled');
    }
    
    // Attach check triggers
    $('#smart_convert_currency_unit_conversion_existing_from_val, #smart_convert_currency_unit_conversion_existing_to_val').on('change', checkButtonState);
    $('#smart_convert_currency_unit_conversion_factor').on('input', checkButtonState);

    // ==========================================================================
    // 8. FORM SUBMISSION
    // ==========================================================================

    $form.on('submit', function(e) {
        e.preventDefault();
        const $btn = $('#smart-convert-currency-unit-conversion-save-unit-btn');
        const $spinner = $btn.next('.spinner');
        
        // Lock UI during submission
        $btn.prop('disabled', true);
        $spinner.addClass('is-active');
        
        let data = $(this).serialize();
        data += '&action=smart_convert_currency_unit_conversion_ajax_save_custom_unit';
        data += '&_wpnonce=' + nonce; 

        $.post(ajaxurl, data, function(response) {
            $spinner.removeClass('is-active');
            
            if (response.success) {
                // Replaced standard page reload logic to ensure consistency
                window.scrollTo(0, 0);

                const currentUrl = window.location.href.split('#')[0];
                window.location.href = currentUrl;
            } else {
                let msg = response.data.message || 'Unknown Error';
                showScpAlert(msg, 'error');
                $btn.prop('disabled', false);
            }
        }).fail(function(xhr, status, error) {
            $spinner.removeClass('is-active');
            $btn.prop('disabled', false);
            // Translated Error
            showScpAlert(strings.errorGeneric + error, 'error');
        });
    });
    
    // ==========================================================================
    // 9. DELETE ACTION (MODIFIED)
    // ==========================================================================

    $(document).on('click', '.smart-convert-currency-unit-conversion-delete-unit-ajax', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const id = $btn.data('id');

        // Removed native confirm(), replaced with async custom modal
        // AND NOW USING LOCALIZED CONFIRMATION MESSAGE from PHP
        // (Note: SmartConvertCurrencyUnitConversionUnitsData.strings vs strings const - using const for consistency)
        showScpConfirm(strings.confirmDelete, function() {
            
            $btn.prop('disabled', true); 
            
            $.post(ajaxurl, { 
                action: 'smart_convert_currency_unit_conversion_ajax_delete_custom_unit', 
                id: id, 
                _wpnonce: nonce 
            }, function(res){
                if(res.success) {
                    location.reload();
                } else {
                    showScpAlert(res.data.message, 'error');
                    $btn.prop('disabled', false);
                }
            });
        });
    });

    // Initial run to set correct UI state on page load
    toggleMode('from');
    toggleMode('to');
    updateEquation();
});