jQuery(document).ready(function ($) {

    // =======================================================
    // 1. INITIALIZATION & VARIABLES
    // =======================================================
    var $tagContainer = $('#sp-tags-container');
    var $hiddenInput = $('#sp_hidden_tags');
    var tagsData = {};

    // =======================================================
    // 2. EVENT LISTENERS (Bind these FIRST to ensure UI works)
    // =======================================================

    // Add Tag Button
    $(document).off('click', '#btn-add-tag').on('click', '#btn-add-tag', function (e) {
        e.preventDefault();
        renderTagRow('', ''); // Add empty row
    });

    // Remove Tag Button (Delegated)
    $tagContainer.on('click', '.btn-remove-tag', function (e) {
        e.preventDefault();
        $(this).closest('.sp-tag-row').remove();
        syncDomToState(); // Update hidden input immediately
    });

    // Input Changes (Delegated) - Realtime Sync
    $tagContainer.on('input change blur', 'input', function () {
        syncDomToState();
    });

    // Final Safety Net: Force Sync on Form Submit
    $('form').on('submit', function () {
        syncDomToState();
    });

    // =======================================================
    // 3. LOGIC & RENDERING
    // =======================================================

    // Load Data from Hidden Input (The Source of Truth)
    // [FIX] Prefer server-side injected variable (window.smallpict_tags_init) for reliability
    if (typeof window.smallpict_tags_init !== 'undefined' && window.smallpict_tags_init !== null) {
        tagsData = window.smallpict_tags_init;
    } else {
        try {
            var rawVal = $hiddenInput.val();
            if (rawVal) {
                var decodedVal = $('<textarea/>').html(rawVal).text();
                if (decodedVal && decodedVal.trim() !== '' && decodedVal !== '[]') {
                    tagsData = JSON.parse(decodedVal);
                }
            }
        } catch (e) {
            console.error("SmallPict: Error parsing initial JSON tags.", e);
            tagsData = {};
        }
    }

    // Render Initial State
    renderAllTags();

    function renderAllTags() {
        $tagContainer.empty();

        // Ensure tagsData is a valid object
        if (!tagsData || typeof tagsData !== 'object' || Array.isArray(tagsData)) {
            tagsData = {};
        }

        // Loop and render
        for (var key in tagsData) {
            if (tagsData.hasOwnProperty(key)) {
                renderTagRow(key, tagsData[key]);
            }
        }

        // Ensure hidden input is consistent with rendered data
        syncStateToInput();
    }

    function renderTagRow(key, val) {
        // Cast to string to avoid replace() errors on numbers
        var sKey = (key === null || key === undefined) ? '' : String(key);
        var sVal = (val === null || val === undefined) ? '' : String(val);

        // Escape quotes for the HTML attribute value
        var safeKey = sKey.replace(/"/g, '&quot;');
        var safeVal = sVal.replace(/"/g, '&quot;');

        var html = `
            <div class="sp-tag-row" style="display:flex; gap:10px; margin-bottom:8px; align-items:center;">
                <input type="text" class="sp-tag-key" value="${safeKey}" placeholder="Key" style="flex:1;">
                <input type="text" class="sp-tag-val" value="${safeVal}" placeholder="Value" style="flex:1;">
                <button type="button" class="button btn-remove-tag" style="color:#d63638; border-color:#d63638; width:30px; padding:0; text-align:center;">&times;</button>
            </div>
        `;
        $tagContainer.append(html);
    }

    // Sync: DOM Rows -> Global Object -> Hidden Input
    function syncDomToState() {
        var newTags = {};
        $('#sp-tags-container .sp-tag-row').each(function () {
            var k = $(this).find('.sp-tag-key').val().trim();
            var v = $(this).find('.sp-tag-val').val().trim();

            // Only save if Key is present
            if (k !== "") {
                newTags[k] = v;
            }
        });
        tagsData = newTags;
        syncStateToInput();
    }

    // Sync: Global Object -> Hidden Input String
    function syncStateToInput() {
        var jsonStr = JSON.stringify(tagsData);
        $hiddenInput.val(jsonStr);
    }


    // =======================================================
    // 4. AJAX ACTIONS (Deploy, etc)
    // =======================================================
    var $dependentButtons = $('#btn-update-config, #btn-test-connection');

    function handleAjaxAction(buttonId, actionName, opts = {}) {
        $(document).off('click', buttonId).on('click', buttonId, function (e) {
            e.preventDefault();
            var $btn = $(this);
            var $logBox = $('#sp-console-log');
            var originalText = $btn.text();

            $btn.prop('disabled', true).text('Processing...');
            $logBox.hide().removeClass('sp-success sp-error').html('');

            if (opts.lockOthers) $dependentButtons.prop('disabled', true);
            if (opts.loadingMsg) $logBox.show().html('<span class="spinner is-active" style="float:none;margin:0 5px 0 0;"></span> ' + opts.loadingMsg);

            $.ajax({
                url: smallpict_vars.url || ajaxurl,
                type: 'POST',
                timeout: 600000,
                data: { action: actionName, nonce: smallpict_vars.nonce },
                success: function (response) {
                    $btn.prop('disabled', false).text(originalText);
                    if (opts.lockOthers) $dependentButtons.prop('disabled', false);
                    $logBox.show();

                    if (response.success) {
                        $logBox.addClass('sp-success');
                        $logBox.html('<strong>✅ SUCCESS:</strong><br>' + response.data);
                        if (buttonId === '#btn-test-connection') $('#test-result').html(response.data).css('color', 'green');
                    } else {
                        $logBox.addClass('sp-error');
                        var msg = response.data || 'Unknown error occurred';
                        $logBox.html('<strong>❌ ERROR:</strong><br>' + msg);
                        if (buttonId === '#btn-test-connection') $('#test-result').text('Failed').css('color', 'red');
                    }
                },
                error: function (xhr, status, error) {
                    $btn.prop('disabled', false).text(originalText);
                    if (opts.lockOthers) $dependentButtons.prop('disabled', false);
                    $logBox.show().addClass('sp-error');

                    if (status === 'timeout') $logBox.html('<strong>⚠️ TIMEOUT:</strong> Process ran too long.');
                    else $logBox.html('<strong>❌ HTTP ERROR:</strong> ' + error);
                }
            });
        });
    }

    handleAjaxAction('#btn-create-lambda', 'smallpict_create_function', { lockOthers: true, loadingMsg: 'Deploying code...' });
    handleAjaxAction('#btn-update-config', 'smallpict_update_config');
    handleAjaxAction('#btn-test-connection', 'smallpict_test_connection', { loadingMsg: 'Testing...' });

});