let initialized = false;
let latestStatus = null;
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) {
    latestStatus = status;
    const summary = statusSummary(status);
    updateText("gatewayActivationSettingsStatus", summary.text, summary.kind);
    updateText("gatewayActivationStatus", summary.text, summary.kind);
    const button = element("btnOpenGatewayActivation");
    if (button)
        button.textContent = status.active ? "Gérer l'activation" : "Activer ce PC";
}
function renderTransientStatus(text, kind) {
    updateText("gatewayActivationStatus", text, kind);
}
function setActivationOpen(open) {
    const panel = element("gatewayActivationPanel");
    const backdrop = element("gatewayActivationBackdrop");
    if (panel)
        panel.hidden = !open;
    if (backdrop)
        backdrop.hidden = !open;
    if (open) {
        window.setTimeout(() => { var _a; return (_a = element("gatewayActivationCode")) === null || _a === void 0 ? void 0 : _a.focus(); }, 0);
    }
}
async function refreshStatus(showWhenRequired) {
    try {
        const status = await requestJson("/api/activation/status");
        renderStatus(status);
        if (showWhenRequired && status.needs_activation)
            setActivationOpen(true);
    }
    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 = "";
        window.setTimeout(() => setActivationOpen(false), 700);
    }
    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 openGatewayActivation() {
    setActivationOpen(true);
    if (latestStatus)
        renderStatus(latestStatus);
    void refreshStatus(false);
}
export function initGatewayActivation() {
    var _a, _b, _c, _d;
    if (initialized)
        return;
    initialized = true;
    (_a = element("gatewayActivationForm")) === null || _a === void 0 ? void 0 : _a.addEventListener("submit", (event) => {
        void submitActivation(event);
    });
    (_b = element("btnGatewayActivationLater")) === null || _b === void 0 ? void 0 : _b.addEventListener("click", () => {
        setActivationOpen(false);
    });
    (_c = element("btnOpenGatewayActivation")) === null || _c === void 0 ? void 0 : _c.addEventListener("click", () => {
        openGatewayActivation();
    });
    (_d = element("gatewayActivationBackdrop")) === null || _d === void 0 ? void 0 : _d.addEventListener("click", () => {
        setActivationOpen(false);
    });
    document.addEventListener("keydown", (event) => {
        const panel = element("gatewayActivationPanel");
        if (event.key === "Escape" && panel && !panel.hidden)
            setActivationOpen(false);
    });
    void refreshStatus(true);
}
