(function () {
    "use strict";

    var catalog = null;
    var currentStep = 1;
    var totalSteps = 4;

    // Selections: { stt: {model, config}, llm: {model, config}, tts: {model, config} }
    var selections = { stt: null, llm: null, tts: null };
    var selectedTransport = "websocket";

    // Step -> model type mapping
    var stepTypes = { 1: "stt", 2: "llm", 3: "tts" };

    // --- Open / Close ---

    function openWizard() {
        var overlay = document.getElementById("wizard-overlay");
        overlay.classList.remove("hidden");
        currentStep = 1;
        selections = { stt: null, llm: null, tts: null };
        selectedTransport = "websocket";
        var spEl = document.getElementById("wizard-system-prompt");
        if (spEl) spEl.value = "";
        // Reset transport toggle
        var transportBtns = document.querySelectorAll(".transport-opt");
        transportBtns.forEach(function (btn) {
            btn.classList.toggle("selected", btn.dataset.transport === "websocket");
        });
        showStep(1);
        fetchCatalog();
    }

    function closeWizard() {
        document.getElementById("wizard-overlay").classList.add("hidden");
    }

    // --- Step navigation ---

    function showStep(step) {
        currentStep = step;
        // Update step indicators
        document.querySelectorAll(".wizard-step-indicator").forEach(function (el) {
            var s = parseInt(el.dataset.step, 10);
            el.classList.remove("active", "completed");
            if (s === step) el.classList.add("active");
            else if (s < step) el.classList.add("completed");
        });
        // Show/hide step content
        document.querySelectorAll(".wizard-body .wizard-step-content").forEach(function (el) {
            el.classList.toggle("hidden", parseInt(el.dataset.step, 10) !== step);
        });
        // Back button visibility
        var backBtn = document.getElementById("wizard-back-btn");
        backBtn.classList.toggle("hidden", step === 1);
        // Next button text
        var nextBtn = document.getElementById("wizard-next-btn");
        if (step === 4) {
            nextBtn.textContent = "Create Agent";
        } else {
            nextBtn.textContent = "Next";
        }
        // Hide footer on progress
        var footer = document.querySelector(".wizard-footer");
        footer.classList.remove("hidden");

        // Render review on step 4
        if (step === 4) {
            renderReview();
        }
    }

    // --- Fetch catalog ---

    async function fetchCatalog() {
        // Clear all card containers
        ["wizard-stt-cards", "wizard-llm-cards", "wizard-tts-cards"].forEach(function (id) {
            var el = document.getElementById(id);
            if (el) el.innerHTML = '<div class="wizard-loading">Loading...</div>';
        });
        try {
            var resp = await fetch("/api/catalog");
            if (!resp.ok) throw new Error("Failed to fetch catalog");
            var data = await resp.json();
            catalog = data.catalog || data;
            renderStepCards("stt", catalog.stt || [], "wizard-stt-cards");
            renderStepCards("llm", catalog.llm || [], "wizard-llm-cards");
            renderStepCards("tts", catalog.tts || [], "wizard-tts-cards");
        } catch (e) {
            ["wizard-stt-cards", "wizard-llm-cards", "wizard-tts-cards"].forEach(function (id) {
                var el = document.getElementById(id);
                if (el) el.innerHTML = '<div class="wizard-error">' + e.message + "</div>";
            });
        }
    }

    function renderStepCards(type, models, containerId) {
        var container = document.getElementById(containerId);
        if (!container) return;
        container.innerHTML = "";
        if (!models || models.length === 0) {
            container.innerHTML = '<div class="wizard-error">No models available</div>';
            return;
        }
        models.forEach(function (model) {
            var card = document.createElement("div");
            card.className = "wizard-model-card";
            card.dataset.type = type;
            card.dataset.name = model.name;
            var kindBadge = model.kind === "local"
                ? '<span class="wizard-badge local">Local</span>'
                : '<span class="wizard-badge cloud">Cloud</span>';
            var dlSize = model.estimated_download_mb;
            var sizeInfo = dlSize
                ? '<span class="wizard-model-size">' + (dlSize >= 1000 ? (dlSize / 1000).toFixed(1) + " GB" : dlSize + " MB") + "</span>"
                : "";
            card.innerHTML =
                '<div class="wizard-card-header">' +
                    '<span class="wizard-card-name">' + (model.display_name || model.name) + "</span>" +
                    kindBadge +
                "</div>" +
                '<div class="wizard-card-desc">' + (model.description || "") + "</div>" +
                sizeInfo;
            card.addEventListener("click", function () {
                selectModel(type, model, card);
            });

            // Pre-select if already chosen
            if (selections[type] && selections[type].model.name === model.name) {
                card.classList.add("selected");
            }

            container.appendChild(card);
        });
    }

    function selectModel(type, model, cardEl) {
        // Deselect other cards of same type
        document.querySelectorAll('.wizard-model-card[data-type="' + type + '"]').forEach(function (c) {
            c.classList.remove("selected");
        });
        cardEl.classList.add("selected");
        selections[type] = { model: model, config: {} };

        // Render inline config if model has config_fields
        var configId = "wizard-" + type + "-config";
        var configContainer = document.getElementById(configId);
        if (!configContainer) return;
        configContainer.innerHTML = "";

        // HuggingFace download notice for local models
        var existingNotice = configContainer.parentElement.querySelector(".wizard-hf-notice");
        if (existingNotice) existingNotice.remove();
        if (model.kind === "local") {
            var notice = document.createElement("div");
            notice.className = "wizard-hf-notice";
            var msg = 'This model will be downloaded from <strong>HuggingFace</strong> on first use.';
            var needsGpu = model.description && model.description.toLowerCase().indexOf("gpu") !== -1;
            if (needsGpu) {
                msg += ' Requires a <strong>CUDA GPU</strong>.';
            }
            notice.innerHTML = '\u2139\ufe0f ' + msg;
            configContainer.parentElement.insertBefore(notice, configContainer);
        }

        var fields = model.config_fields;
        if (!fields || fields.length === 0) return;

        fields.forEach(function (field) {
            var group = document.createElement("div");
            group.className = "wizard-field-group";
            group.dataset.fieldName = field.name;
            if (field.depends_on) {
                var depField, depValue;
                if (field.depends_on.field) {
                    depField = field.depends_on.field;
                    depValue = field.depends_on.value;
                } else {
                    var keys = Object.keys(field.depends_on);
                    depField = keys[0];
                    depValue = field.depends_on[depField];
                }
                group.dataset.dependsOn = depField;
                group.dataset.dependsOnValue = depValue;
                group.classList.add("hidden");
            }

            var label = document.createElement("label");
            label.className = "wizard-field-label";
            label.textContent = field.label || field.name;
            if (field.env_var) {
                var hint = document.createElement("span");
                hint.className = "wizard-env-hint";
                hint.textContent = "env: " + field.env_var;
                label.appendChild(hint);
            }
            group.appendChild(label);

            var input;
            if (field.type === "select" && field.options) {
                input = document.createElement("select");
                input.className = "wizard-input";
                field.options.forEach(function (opt) {
                    var o = document.createElement("option");
                    o.value = opt.value !== undefined ? opt.value : opt;
                    o.textContent = opt.label !== undefined ? opt.label : opt;
                    input.appendChild(o);
                });
            } else {
                input = document.createElement("input");
                input.className = "wizard-input";
                input.type = field.type === "secret" ? "password" : "text";
                if (field.placeholder) input.placeholder = field.placeholder;
                if (field.default !== undefined) input.value = field.default;
            }
            input.name = type + "." + field.name;
            input.dataset.modelType = type;
            input.dataset.fieldName = field.name;
            input.dataset.fieldType = field.type || "text";
            input.addEventListener("change", function () {
                updateDependencies(configContainer);
            });
            group.appendChild(input);
            configContainer.appendChild(group);
        });
        updateDependencies(configContainer);
    }

    function updateDependencies(container) {
        container.querySelectorAll(".wizard-field-group[data-depends-on]").forEach(function (group) {
            var depField = group.dataset.dependsOn;
            var depValue = group.dataset.dependsOnValue;
            var depInput = container.querySelector('.wizard-input[data-field-name="' + depField + '"]');
            if (depInput) {
                group.classList.toggle("hidden", depInput.value !== depValue);
            }
        });
    }

    // --- Step 4: Review ---

    function renderReview() {
        var summary = document.getElementById("wizard-review-summary");
        summary.innerHTML = "";
        var typeLabels = { stt: "Speech-to-Text", llm: "Language Model", tts: "Text-to-Speech" };
        ["stt", "llm", "tts"].forEach(function (type) {
            var sel = selections[type];
            var card = document.createElement("div");
            card.className = "wizard-review-card";
            if (sel && sel.model) {
                var kindLabel = sel.model.kind === "local" ? "Local" : "Cloud";
                card.innerHTML =
                    '<div class="wizard-review-card-type">' + typeLabels[type] + "</div>" +
                    '<div class="wizard-review-card-name">' + (sel.model.display_name || sel.model.name) + "</div>" +
                    '<div class="wizard-review-card-detail">' + kindLabel + "</div>";
            } else {
                card.innerHTML =
                    '<div class="wizard-review-card-type">' + typeLabels[type] + "</div>" +
                    '<div class="wizard-review-card-name" style="color:var(--error)">Not selected</div>';
            }
            summary.appendChild(card);
        });

        // VAD auto-selection
        var vadCard = document.createElement("div");
        vadCard.className = "wizard-review-card";
        vadCard.innerHTML =
            '<div class="wizard-review-card-type">Voice Activity Detection</div>' +
            '<div class="wizard-review-card-name">Silero VAD</div>' +
            '<div class="wizard-review-card-detail">Auto-selected (Local)</div>';
        summary.appendChild(vadCard);

        // Reset progress section
        var progressSection = document.getElementById("wizard-progress-section");
        progressSection.classList.add("hidden");
        document.getElementById("wizard-step4-actions").innerHTML = "";
    }

    // --- Gather config values from inline config inputs ---

    function gatherConfigValues(type) {
        var configId = "wizard-" + type + "-config";
        var container = document.getElementById(configId);
        if (!container) return { config: {}, secrets: {} };
        var config = {};
        var secrets = {};
        container.querySelectorAll(".wizard-input").forEach(function (input) {
            var fieldName = input.dataset.fieldName;
            var val = input.value;
            if (!val) return;
            if (input.dataset.fieldType === "secret") {
                secrets[fieldName] = val;
            } else {
                config[fieldName] = val;
            }
        });
        return { config: config, secrets: secrets };
    }

    // --- Create agent ---

    async function createAgent() {
        var nameInput = document.getElementById("wizard-agent-name");
        var name = nameInput.value.trim();
        if (!name) {
            showWizardError("Please enter an agent name");
            return;
        }

        // Validate all selections
        for (var t in selections) {
            if (!selections[t]) {
                showWizardError("Please select a " + t.toUpperCase() + " model (Step " + (t === "stt" ? "1" : t === "llm" ? "2" : "3") + ")");
                return;
            }
        }

        // Build payload
        var models = {};
        var allSecrets = {};
        var pipelineMap = {};

        ["stt", "llm", "tts"].forEach(function (type) {
            var sel = selections[type];
            var gathered = gatherConfigValues(type);
            var modelConfig = Object.assign({}, gathered.config);
            modelConfig["class"] = sel.model.name;
            modelConfig["type"] = type;
            models[sel.model.name] = modelConfig;
            pipelineMap[type] = sel.model.name;
            if (Object.keys(gathered.secrets).length > 0) {
                allSecrets[sel.model.name] = gathered.secrets;
            }
        });

        // Auto-add silero VAD
        pipelineMap.vad = "silero";
        models["silero"] = { "class": "silero", "type": "vad" };

        var systemPrompt = document.getElementById("wizard-system-prompt").value.trim();
        if (!systemPrompt) {
            showWizardError("Please enter a system prompt");
            return;
        }
        var payload = { name: name, pipeline: pipelineMap, models: models, secrets: allSecrets, system_prompt: systemPrompt, transport: selectedTransport };

        // Show progress
        var footer = document.querySelector(".wizard-footer");
        footer.classList.add("hidden");
        var progressSection = document.getElementById("wizard-progress-section");
        progressSection.classList.remove("hidden");
        var logEl = document.getElementById("wizard-progress-log");
        var barEl = document.getElementById("wizard-progress-bar");
        var actionsEl = document.getElementById("wizard-step4-actions");
        logEl.textContent = "";
        barEl.style.width = "0%";
        actionsEl.innerHTML = "";

        appendLog(logEl, "Creating agent '" + name + "'...");

        try {
            var resp = await fetch("/api/agents", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
            });
            if (!resp.ok) {
                var err = await resp.json().catch(function () { return {}; });
                throw new Error(err.detail || "Failed to create agent");
            }
            appendLog(logEl, "Agent created. Preparing models...");
        } catch (e) {
            // Show error but let user rename and retry
            progressSection.classList.add("hidden");
            footer.classList.remove("hidden");
            showWizardError(e.message);
            // Focus the name input so user can rename
            nameInput.focus();
            nameInput.select();
            return;
        }

        // Connect WebSocket for preparation progress
        var protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
        var wsUrl = protocol + "//" + window.location.host + "/ws/agent-prepare?name=" + encodeURIComponent(name);
        var prepWs = new WebSocket(wsUrl);

        prepWs.onmessage = function (event) {
            var data;
            try {
                data = JSON.parse(event.data);
            } catch (e) {
                appendLog(logEl, event.data);
                return;
            }
            if (data.progress !== undefined) {
                barEl.style.width = data.progress + "%";
            }
            if (data.message) {
                appendLog(logEl, data.message);
            }
            if (data.status === "complete") {
                barEl.style.width = "100%";
                appendLog(logEl, "Agent ready!");
                actionsEl.innerHTML =
                    '<button class="wizard-btn wizard-btn-primary" id="wizard-activate-btn">Activate Agent</button>' +
                    ' <button class="wizard-btn wizard-btn-secondary" id="wizard-done-btn">Close</button>';
                document.getElementById("wizard-activate-btn").addEventListener("click", function () {
                    activateFromWizard(name);
                });
                document.getElementById("wizard-done-btn").addEventListener("click", function () {
                    closeWizard();
                    if (window.RoohAI && window.RoohAI.loadAgents) window.RoohAI.loadAgents();
                });
            } else if (data.status === "error") {
                appendLog(logEl, "ERROR: " + (data.message || "Preparation failed"));
                actionsEl.innerHTML =
                    '<button class="wizard-btn wizard-btn-secondary" id="wizard-close-err-btn">Close</button>';
                document.getElementById("wizard-close-err-btn").addEventListener("click", closeWizard);
            }
        };

        prepWs.onerror = function () {
            appendLog(logEl, "WebSocket connection error");
        };

        prepWs.onclose = function () {
            if (barEl.style.width !== "100%") {
                appendLog(logEl, "Connection closed");
            }
        };
    }

    function appendLog(logEl, msg) {
        var line = document.createElement("div");
        line.className = "wizard-log-line";
        line.textContent = msg;
        logEl.appendChild(line);
        logEl.scrollTop = logEl.scrollHeight;
    }

    function showWizardError(msg) {
        var existing = document.querySelector(".wizard-inline-error");
        if (existing) existing.remove();
        var el = document.createElement("div");
        el.className = "wizard-inline-error";
        el.textContent = msg;
        var step = document.querySelector(".wizard-step-content:not(.hidden)");
        if (step) step.prepend(el);
        setTimeout(function () { el.remove(); }, 3000);
    }

    async function activateFromWizard(name) {
        closeWizard();
        // Use the activation loading overlay from app.js if available
        if (window.RoohAI && window.RoohAI.showActivationLoading) {
            window.RoohAI.showActivationLoading(name);
        }
        try {
            var resp = await fetch("/api/agents/" + encodeURIComponent(name) + "/activate", {
                method: "POST"
            });
            if (!resp.ok) throw new Error("Activation failed");
            var data = await resp.json();
            // Update transport mode from activation response
            if (window.RoohAI && window.RoohAI.setTransportMode) {
                window.RoohAI.setTransportMode(data.transport || "websocket");
            }
            if (window.RoohAI && window.RoohAI.hideActivationLoading) window.RoohAI.hideActivationLoading();
            if (window.RoohAI && window.RoohAI.loadAgents) window.RoohAI.loadAgents();
            var modeLabel = (data.transport === "webrtc") ? "WebRTC" : "WebSocket";
            if (window.RoohAI && window.RoohAI.toast) window.RoohAI.toast("Agent '" + name + "' activated (" + modeLabel + ")", "success");
        } catch (e) {
            if (window.RoohAI && window.RoohAI.hideActivationLoading) window.RoohAI.hideActivationLoading();
            if (window.RoohAI && window.RoohAI.toast) window.RoohAI.toast("Failed to activate: " + e.message, "error");
        }
    }

    // --- Validation for Next ---

    function validateStep(step) {
        var type = stepTypes[step];
        if (!type) return true; // step 4 has no type
        if (!selections[type]) {
            showWizardError("Please select a " + type.toUpperCase() + " model before continuing");
            return false;
        }
        return true;
    }

    // --- Wire up events ---

    function init() {
        var createBtn = document.getElementById("create-agent-btn");
        if (createBtn) createBtn.addEventListener("click", openWizard);

        var closeBtn = document.getElementById("wizard-close-btn");
        if (closeBtn) closeBtn.addEventListener("click", closeWizard);

        // Overlay click to close
        var ov = document.getElementById("wizard-overlay");
        if (ov) {
            ov.addEventListener("click", function (e) {
                if (e.target === ov) closeWizard();
            });
        }

        // Next button
        var nextBtn = document.getElementById("wizard-next-btn");
        if (nextBtn) {
            nextBtn.addEventListener("click", function () {
                if (currentStep < 4) {
                    if (!validateStep(currentStep)) return;
                    showStep(currentStep + 1);
                } else {
                    // Step 4: create agent
                    createAgent();
                }
            });
        }

        // Transport toggle buttons
        document.querySelectorAll(".transport-opt").forEach(function (btn) {
            btn.addEventListener("click", function () {
                document.querySelectorAll(".transport-opt").forEach(function (b) {
                    b.classList.remove("selected");
                });
                btn.classList.add("selected");
                selectedTransport = btn.dataset.transport;
            });
        });

        // Back button
        var backBtn = document.getElementById("wizard-back-btn");
        if (backBtn) {
            backBtn.addEventListener("click", function () {
                if (currentStep > 1) {
                    showStep(currentStep - 1);
                }
            });
        }
    }

    // Expose for interop
    window.RoohAIWizard = {
        open: openWizard,
        close: closeWizard
    };

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", init);
    } else {
        init();
    }
})();
