/**
 * PageSpark Plugin Builder — Admin UI
 *
 * Handles build and edit flows for AI-generated WordPress plugins.
 * Includes a retry loop (max 3 attempts) that passes previous errors
 * back to the API for self-correction.
 */
(function($) {
    'use strict';

    const MAX_ATTEMPTS = 3;

    const $buildSection = $('#pspb-build-section');
    const $editSection = $('#pspb-edit-section');
    const $editMode = $('#pspb-edit-mode');
    const $buildBtn = $('#pspb-build-btn');
    const $editBtn = $('#pspb-edit-btn');
    const $buildPrompt = $('#pspb-build-prompt');
    const $editPrompt = $('#pspb-edit-prompt');
    const $pluginSelect = $('#pspb-plugin-select');
    const $statusMessages = $('#pspb-status-messages');

    // --- Status Feed ---

    function addStatus(message, type) {
        type = type || 'info';
        var cls = 'pspb-status-' + type;
        var icon = '';
        if (type === 'success') icon = '<span class="dashicons dashicons-yes-alt"></span> ';
        else if (type === 'error') icon = '<span class="dashicons dashicons-dismiss"></span> ';
        else if (type === 'loading') icon = '<span class="spinner is-active" style="float:none;margin:0 6px 0 0;"></span> ';
        else icon = '<span class="dashicons dashicons-info-outline"></span> ';

        var $msg = $('<div class="pspb-status-msg ' + cls + '">' + icon + '<span>' + message + '</span></div>');
        $statusMessages.append($msg);
        $statusMessages.scrollTop($statusMessages[0].scrollHeight);
        return $msg;
    }

    function updateStatus($msg, message, type) {
        if (type) {
            $msg.removeClass('pspb-status-info pspb-status-success pspb-status-error pspb-status-loading');
            $msg.addClass('pspb-status-' + type);
        }
        var icon = '';
        if (type === 'success') icon = '<span class="dashicons dashicons-yes-alt"></span> ';
        else if (type === 'error') icon = '<span class="dashicons dashicons-dismiss"></span> ';
        else icon = '<span class="dashicons dashicons-info-outline"></span> ';
        $msg.html(icon + '<span>' + message + '</span>');
    }

    function clearStatus() {
        $statusMessages.empty();
    }

    // --- Mode Toggle ---

    $editMode.on('change', function() {
        if ($(this).is(':checked')) {
            $buildSection.hide();
            $editSection.show();
            loadPluginList();
        } else {
            $editSection.hide();
            $buildSection.show();
        }
    });

    $('#pspb-refresh-plugins').on('click', function() {
        loadPluginList();
    });

    // --- Plugin List ---

    function loadPluginList() {
        $pluginSelect.html('<option value="">Loading...</option>');

        $.post(ajaxurl, {
            action: 'pspb_list_plugins',
            nonce: pspb.nonce,
        }, function(response) {
            $pluginSelect.empty();
            if (response.success && response.data.length > 0) {
                $pluginSelect.append('<option value="">-- Select a plugin --</option>');
                $.each(response.data, function(i, plugin) {
                    var label = plugin.name + ' (v' + plugin.version + ')' + (plugin.active ? ' - Active' : '');
                    $pluginSelect.append('<option value="' + plugin.slug + '" data-file="' + plugin.file + '">' + label + '</option>');
                });
            } else {
                $pluginSelect.append('<option value="">No PageSpark plugins found</option>');
            }
        });
    }

    // --- Build Flow ---

    $buildBtn.on('click', function() {
        var prompt = $buildPrompt.val().trim();
        if (!prompt) {
            alert('Please describe the plugin you want to build.');
            return;
        }
        clearStatus();
        setButtonsDisabled(true);
        buildPlugin(prompt, [], 1);
    });

    function buildPlugin(prompt, previousErrors, attempt) {
        var $building = addStatus('Building plugin (attempt ' + attempt + '/' + MAX_ATTEMPTS + ')...', 'loading');

        $.post(ajaxurl, {
            action: 'pspb_build_plugin',
            nonce: pspb.nonce,
            prompt: prompt,
            previous_errors: previousErrors,
            attempt_number: attempt,
        }, function(response) {
            if (response.success && response.data.download_url) {
                updateStatus($building, 'Plugin built: ' + (response.data.metadata?.plugin_name || 'Unknown'), 'success');
                installPlugin(
                    response.data.download_url,
                    response.data.metadata?.plugin_name || '',
                    'install',
                    prompt,
                    previousErrors,
                    attempt
                );
            } else {
                var errorMsg = response.data || 'Build failed';
                if (typeof errorMsg === 'object') errorMsg = errorMsg.error || JSON.stringify(errorMsg);
                updateStatus($building, 'Build failed: ' + errorMsg, 'error');

                previousErrors.push(errorMsg);
                if (attempt < MAX_ATTEMPTS) {
                    addStatus('Retrying with error context...', 'info');
                    buildPlugin(prompt, previousErrors, attempt + 1);
                } else {
                    addStatus('All ' + MAX_ATTEMPTS + ' attempts failed. Try rephrasing your request.', 'error');
                    setButtonsDisabled(false);
                }
            }
        }).fail(function(xhr) {
            var errorMsg = 'Network error';
            try { errorMsg = JSON.parse(xhr.responseText).data || errorMsg; } catch(e) {}
            updateStatus($building, 'Request failed: ' + errorMsg, 'error');
            setButtonsDisabled(false);
        });
    }

    // --- Install Flow ---

    function installPlugin(downloadUrl, pluginName, mode, originalPrompt, previousErrors, attempt) {
        var $installing = addStatus('Installing plugin...', 'loading');

        $.post(ajaxurl, {
            action: 'pspb_install_plugin',
            nonce: pspb.nonce,
            download_url: downloadUrl,
            plugin_name: pluginName,
            mode: mode,
        }, function(response) {
            if (response.success) {
                updateStatus($installing, 'Plugin installed and activated!', 'success');
                addStatus('Done! "' + pluginName + '" is now active on your site.', 'success');
                setButtonsDisabled(false);
            } else {
                var errorMsg = response.data || 'Install failed';
                if (typeof errorMsg === 'object') errorMsg = errorMsg.error || JSON.stringify(errorMsg);
                updateStatus($installing, 'Install failed: ' + errorMsg, 'error');

                previousErrors.push('Install error: ' + errorMsg);
                if (attempt < MAX_ATTEMPTS) {
                    addStatus('Rebuilding with error context...', 'info');
                    if (mode === 'install') {
                        buildPlugin(originalPrompt, previousErrors, attempt + 1);
                    } else {
                        // For edits, the caller handles retries
                        setButtonsDisabled(false);
                    }
                } else {
                    addStatus('All ' + MAX_ATTEMPTS + ' attempts failed.', 'error');
                    setButtonsDisabled(false);
                }
            }
        }).fail(function(xhr) {
            var errorMsg = 'Network error during install';
            updateStatus($installing, errorMsg, 'error');
            setButtonsDisabled(false);
        });
    }

    // --- Edit Flow ---

    $editBtn.on('click', function() {
        var slug = $pluginSelect.val();
        var editPrompt = $editPrompt.val().trim();

        if (!slug) {
            alert('Please select a plugin to edit.');
            return;
        }
        if (!editPrompt) {
            alert('Please describe the changes you want to make.');
            return;
        }

        clearStatus();
        setButtonsDisabled(true);
        readAndEditPlugin(slug, editPrompt, [], 1);
    });

    function readAndEditPlugin(slug, editPrompt, previousErrors, attempt) {
        var $reading = addStatus('Reading plugin files...', 'loading');

        $.post(ajaxurl, {
            action: 'pspb_read_plugin_files',
            nonce: pspb.nonce,
            plugin_slug: slug,
        }, function(response) {
            if (response.success && response.data) {
                updateStatus($reading, 'Plugin files loaded (' + Object.keys(response.data).length + ' files)', 'success');
                editPlugin(response.data, slug, editPrompt, previousErrors, attempt);
            } else {
                updateStatus($reading, 'Failed to read plugin files: ' + (response.data || 'Unknown error'), 'error');
                setButtonsDisabled(false);
            }
        }).fail(function() {
            updateStatus($reading, 'Network error reading plugin files', 'error');
            setButtonsDisabled(false);
        });
    }

    function editPlugin(pluginFiles, slug, editPrompt, previousErrors, attempt) {
        var $editing = addStatus('Editing plugin (attempt ' + attempt + '/' + MAX_ATTEMPTS + ')...', 'loading');

        $.post(ajaxurl, {
            action: 'pspb_edit_plugin',
            nonce: pspb.nonce,
            plugin_files: JSON.stringify(pluginFiles),
            edit_prompt: editPrompt,
            previous_errors: previousErrors,
            attempt_number: attempt,
        }, function(response) {
            if (response.success && response.data.download_url) {
                updateStatus($editing, 'Plugin edited successfully', 'success');
                installPlugin(
                    response.data.download_url,
                    response.data.metadata?.plugin_name || slug,
                    'update',
                    editPrompt,
                    previousErrors,
                    attempt
                );
            } else {
                var errorMsg = response.data || 'Edit failed';
                if (typeof errorMsg === 'object') errorMsg = errorMsg.error || JSON.stringify(errorMsg);
                updateStatus($editing, 'Edit failed: ' + errorMsg, 'error');

                previousErrors.push(errorMsg);
                if (attempt < MAX_ATTEMPTS) {
                    addStatus('Retrying edit with error context...', 'info');
                    editPlugin(pluginFiles, slug, editPrompt, previousErrors, attempt + 1);
                } else {
                    addStatus('All ' + MAX_ATTEMPTS + ' edit attempts failed. Original plugin is still active.', 'error');
                    setButtonsDisabled(false);
                }
            }
        }).fail(function(xhr) {
            var errorMsg = 'Network error';
            updateStatus($editing, 'Request failed: ' + errorMsg, 'error');
            setButtonsDisabled(false);
        });
    }

    // --- Helpers ---

    function setButtonsDisabled(disabled) {
        $buildBtn.prop('disabled', disabled);
        $editBtn.prop('disabled', disabled);
    }

})(jQuery);
