let initialized = false;
let statusLoaded = false;
function element(id) {
    return document.getElementById(id);
}
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
async function requestJson(path, init) {
    const response = await fetch(path, {
        credentials: "same-origin",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        ...init,
    });
    const text = await response.text();
    let payload = {};
    if (text) {
        try {
            payload = JSON.parse(text);
        }
        catch (_error) {
            payload = {};
        }
    }
    if (!response.ok) {
        const message = isRecord(payload) && typeof payload.error === "string"
            ? payload.error
            : response.statusText;
        throw new Error(message || "Erreur d'activation Datafix");
    }
    if (!isRecord(payload)) {
        throw new Error("Réponse d'activation Datafix invalide");
    }
    return payload;
}
function statusSummary(status) {
    if (status.active) {
        const device = status.device_name ? ` pour ${status.device_name}` : "";
        return { text: `Ce PC est activé${device}.`, kind: "success" };
    }
    if (status.needs_activation) {
        return {
            text: status.error || "Ce PC doit être activé pour utiliser les fonctions AI.",
            kind: "warning",
        };
    }
    if (status.configured && !status.reachable) {
        return {
            text: status.error || "Activation enregistrée. La passerelle Datafix est momentanément injoignable.",
            kind: "warning",
        };
    }
    return { text: "Activation Datafix requise pour utiliser les fonctions AI.", kind: "neutral" };
}
function updateText(id, text, kind) {
    const target = element(id);
    if (!target)
        return;
    target.textContent = text;
    target.dataset.kind = kind;
}
function renderStatus(status) {
    const summary = statusSummary(status);
    updateText("gatewayActivationSettingsStatus", summary.text, summary.kind);
    updateText("gatewayActivationStatus", summary.text, summary.kind);
}
function renderTransientStatus(text, kind) {
    updateText("gatewayActivationStatus", text, kind);
}
async function refreshStatus() {
    try {
        const status = await requestJson("/api/activation/status");
        renderStatus(status);
    }
    catch (error) {
        const message = error instanceof Error ? error.message : "Vérification de l'activation impossible";
        updateText("gatewayActivationSettingsStatus", message, "error");
        renderTransientStatus(message, "error");
    }
}
async function submitActivation(event) {
    event.preventDefault();
    const input = element("gatewayActivationCode");
    const submit = element("btnGatewayActivationSubmit");
    const code = String((input === null || input === void 0 ? void 0 : input.value) || "").trim();
    if (!code) {
        renderTransientStatus("Saisissez le code d'activation Datafix.", "error");
        input === null || input === void 0 ? void 0 : input.focus();
        return;
    }
    if (submit)
        submit.disabled = true;
    if (input)
        input.disabled = true;
    renderTransientStatus("Activation en cours…", "neutral");
    try {
        const status = await requestJson("/api/activation", {
            method: "POST",
            body: JSON.stringify({ activation_code: code }),
        });
        renderStatus(status);
        if (input)
            input.value = "";
    }
    catch (error) {
        const message = error instanceof Error ? error.message : "Activation Datafix impossible";
        renderTransientStatus(message, "error");
    }
    finally {
        if (submit)
            submit.disabled = false;
        if (input)
            input.disabled = false;
    }
}
export function initGatewayActivation() {
    var _a;
    if (initialized)
        return;
    initialized = true;
    (_a = element("gatewayActivationForm")) === null || _a === void 0 ? void 0 : _a.addEventListener("submit", (event) => {
        void submitActivation(event);
    });
}
/** Load activation status when the Gateway Activation settings tab is opened. */
export function loadGatewayActivationStatus(force = false) {
    if (!force && statusLoaded)
        return;
    statusLoaded = true;
    void refreshStatus();
}
