"use strict";
var BrowserAgentOptions;
(function (BrowserAgentOptions) {
    const fields = {
        serverUrl: byId("serverUrl"),
        authToken: byId("authToken"),
        model: byId("model"),
        requestTimeoutMs: byId("requestTimeoutMs"),
        maxSteps: byId("maxSteps"),
        maxDomTextChars: byId("maxDomTextChars"),
        maxScreenshotWidth: byId("maxScreenshotWidth"),
        captureDom: byId("captureDom"),
        captureScreenshot: byId("captureScreenshot"),
        autopilot: byId("autopilot")
    };
    const developerMode = byId("developerMode");
    const debugLiveApi = byId("debugLiveApi");
    const statusEl = byId("status");
    const testResult = byId("testResult");
    const healthDot = byId("healthDot");
    const healthText = byId("healthText");
    const healthLink = byId("healthLink");
    document.addEventListener("DOMContentLoaded", () => {
        byId("saveConfig").addEventListener("click", saveConfig);
        byId("testConfig").addEventListener("click", testConfig);
        byId("checkHealth").addEventListener("click", checkHealth);
        developerMode.addEventListener("change", () => {
            chrome.storage.local.set({ developerMode: developerMode.checked });
        });
        debugLiveApi.addEventListener("change", async () => {
            await chrome.storage.local.set({ [BrowserAgent.DEBUG_LIVE_API_KEY]: debugLiveApi.checked });
            applyDebugLiveApiUiState();
            // Reflect the override in the visible Server URL field immediately.
            await loadConfig();
            renderBackendStatus();
        });
        loadConfig();
        loadDeveloperMode();
        loadDebugLiveApi();
    });
    function renderBackendStatus() {
        const url = debugLiveApi.checked
            ? BrowserAgent.LIVE_BACKEND_URL
            : (fields.serverUrl.value.trim() || BrowserAgent.BUILD_BACKEND_URL);
        const label = debugLiveApi.checked ? "Live API" : "Local dev backend";
        setStatus(`${label}: ${url}`);
    }
    async function loadDeveloperMode() {
        const stored = await chrome.storage.local.get("developerMode");
        developerMode.checked = Boolean(stored.developerMode);
    }
    async function loadDebugLiveApi() {
        const stored = await chrome.storage.local.get(BrowserAgent.DEBUG_LIVE_API_KEY);
        debugLiveApi.checked = Boolean(stored[BrowserAgent.DEBUG_LIVE_API_KEY]);
        applyDebugLiveApiUiState();
    }
    function applyDebugLiveApiUiState() {
        // When the override is active the Server URL field is read-only so
        // editing it doesn't accidentally overwrite the stored dev URL.
        fields.serverUrl.readOnly = debugLiveApi.checked;
        fields.serverUrl.title = debugLiveApi.checked
            ? "Controlled by 'Debug: use live API'. Toggle that off to edit."
            : "";
    }
    async function loadConfig() {
        const response = await chrome.runtime.sendMessage({ type: "GET_CONFIG" });
        if (response.ok) {
            renderConfig(response.config);
            renderBackendStatus();
            // Auto-check health on load if URL is configured
            if (response.config.serverUrl) {
                await checkHealth();
            }
        }
        else {
            setStatus("Could not load configuration.");
        }
    }
    async function saveConfig() {
        const config = collectConfig();
        if (debugLiveApi.checked) {
            // Preserve the original (dev) serverUrl underneath the live-API
            // override so toggling debug off restores it.
            const stored = await chrome.storage.local.get(BrowserAgent.CONFIG_KEY);
            const previous = stored[BrowserAgent.CONFIG_KEY];
            if (previous?.serverUrl)
                config.serverUrl = previous.serverUrl;
        }
        const response = await chrome.runtime.sendMessage({
            type: "SAVE_CONFIG",
            payload: { config }
        });
        if (response.ok) {
            renderConfig(response.config);
            setStatus("Configuration saved.");
        }
        else {
            setStatus(response.error?.message || "Configuration save failed.");
        }
    }
    async function testConfig() {
        const btn = byId("testConfig");
        btn.textContent = "Testing…";
        btn.setAttribute("disabled", "true");
        showTestResult("", null);
        await saveConfig();
        const response = await chrome.runtime.sendMessage({
            type: "TEST_CONFIG",
            payload: { config: collectConfig() }
        });
        btn.textContent = "Test Config";
        btn.removeAttribute("disabled");
        if (response.ok) {
            const data = response.data;
            const lines = [
                "✅ Config test passed.",
                `Provider: ${data?.provider || "unknown"}`,
                `Model: ${data?.model || "unknown"}`,
                `Response: ${data?.message || "ready"}`,
                data?.usage?.total_tokens ? `Tokens used: ${data.usage.total_tokens}` : ""
            ].filter(Boolean).join("\n");
            showTestResult(lines, true);
            setStatus("Test Config passed.");
        }
        else {
            const err = response.error;
            const lines = [
                `❌ ${err?.message || "Config test failed."}`,
                err?.code ? `Code: ${err.code}` : "",
                err?.suggestion ? `Hint: ${err.suggestion}` : ""
            ].filter(Boolean).join("\n");
            showTestResult(lines, false);
            setStatus("Test Config failed.");
        }
    }
    async function checkHealth() {
        const serverUrl = fields.serverUrl.value.trim();
        if (!serverUrl) {
            setHealthState("warn", "Enter a Server URL first.", null);
            return;
        }
        const btn = byId("checkHealth");
        btn.textContent = "Checking…";
        btn.setAttribute("disabled", "true");
        setHealthState("", "Checking…", null);
        try {
            const base = serverUrl.replace(/\/+$/, "");
            const url = `${base}/health`;
            const res = await fetch(url, { cache: "no-store" });
            const data = await res.json();
            // Update the "Open API" link to point to real URL
            healthLink.href = url;
            healthLink.textContent = "Open ↗";
            if (res.ok && data.ok) {
                const detail = [
                    `Provider: ${data.provider || "unknown"}`,
                    `API key: ${data.hasApiKey ? "✓ set" : "✗ missing"}`,
                    `Default model: ${data.defaultModel || "?"}`,
                    `Host: ${data.apiHost || "?"}`
                ].join(" · ");
                setHealthState("ok", `Server healthy — ${detail}`, url);
            }
            else {
                setHealthState("err", `Server responded with ${res.status}: ${JSON.stringify(data).slice(0, 100)}`, url);
            }
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            setHealthState("err", `Could not reach server: ${msg}`, null);
        }
        finally {
            btn.textContent = "Check API Health";
            btn.removeAttribute("disabled");
        }
    }
    function setHealthState(state, text, url) {
        healthDot.className = `health-dot${state ? " " + state : ""}`;
        healthText.textContent = text;
        if (url) {
            healthLink.href = url;
            healthLink.style.display = "";
        }
        else {
            healthLink.style.display = "none";
        }
    }
    function showTestResult(text, ok) {
        if (!text) {
            testResult.className = "test-result";
            testResult.textContent = "";
            return;
        }
        testResult.textContent = text;
        testResult.className = `test-result visible ${ok === true ? "ok" : ok === false ? "err" : ""}`;
    }
    function renderConfig(config) {
        fields.serverUrl.value = config.serverUrl;
        fields.authToken.value = config.authToken;
        fields.model.value = config.model;
        fields.requestTimeoutMs.value = String(config.requestTimeoutMs);
        fields.maxSteps.value = String(config.maxSteps);
        fields.maxDomTextChars.value = String(config.maxDomTextChars);
        fields.maxScreenshotWidth.value = String(config.maxScreenshotWidth);
        fields.captureDom.checked = config.captureDom;
        fields.captureScreenshot.checked = config.captureScreenshot;
        fields.autopilot.checked = config.autopilot;
    }
    function collectConfig() {
        return BrowserAgent.mergeConfig({
            serverUrl: fields.serverUrl.value.trim(),
            authToken: fields.authToken.value.trim(),
            model: fields.model.value.trim(),
            requestTimeoutMs: Number(fields.requestTimeoutMs.value),
            maxSteps: Number(fields.maxSteps.value),
            maxDomTextChars: Number(fields.maxDomTextChars.value),
            maxScreenshotWidth: Number(fields.maxScreenshotWidth.value),
            captureDom: fields.captureDom.checked,
            captureScreenshot: fields.captureScreenshot.checked,
            autopilot: fields.autopilot.checked
        });
    }
    function setStatus(message) {
        statusEl.textContent = message;
    }
    function byId(id) {
        const element = document.getElementById(id);
        if (!element)
            throw new Error(`Missing element #${id}`);
        return element;
    }
})(BrowserAgentOptions || (BrowserAgentOptions = {}));
//# sourceMappingURL=options.js.map