// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { Toast } from "./Toast.js";

const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

class ApiKeyManager {
    constructor() {
        this.card = document.querySelector("[data-api-key-card]");
        if (!this.card) return;
        this.valueEl = this.card.querySelector("[data-api-key]");
        this.bindReveal();
        this.bindCopy();
        this.bindRegenerate();
    }

    get key() {
        return this.valueEl ? this.valueEl.dataset.key || "" : "";
    }

    set key(value) {
        if (this.valueEl) this.valueEl.dataset.key = value;
    }

    render(masked) {
        if (!this.valueEl) return;
        this.valueEl.dataset.masked = masked ? "true" : "false";
        this.valueEl.textContent = masked ? "•".repeat(12) : this.key;
    }

    bindReveal() {
        const btn = this.card.querySelector("[data-api-key-reveal]");
        if (!btn) return;
        btn.addEventListener("click", () => {
            const masked = this.valueEl.dataset.masked !== "false";
            this.render(!masked);
            btn.textContent = masked ? "Hide" : "Reveal";
        });
    }

    bindCopy() {
        const btn = this.card.querySelector("[data-api-key-copy]");
        if (!btn) return;
        btn.addEventListener("click", async () => {
            try {
                await navigator.clipboard.writeText(this.key);
                Toast.flash(btn, "Copied", 1500);
            } catch {
                Toast.flash(btn, "Copy failed", 1500);
            }
        });
    }

    bindRegenerate() {
        const btn = this.card.querySelector("[data-regen-api-key]");
        if (!btn) return;
        btn.addEventListener("click", async () => {
            const ok = await window.app.dialog.confirm({
                title: "Regenerate API key",
                message: "Regenerate your API key? The current key stops working immediately.",
                confirmLabel: "Regenerate",
                danger: true,
            });
            if (!ok) return;
            btn.disabled = true;
            try {
                const result = await Http.postJson("/profile/regenerate-api-key", {});
                if (!result || !UUID_PATTERN.test(result.api_key || "")) {
                    Toast.flash(btn, "Invalid response", 2000, "Regenerate");
                    return;
                }
                this.key = result.api_key;
                this.render(false);
                const reveal = this.card.querySelector("[data-api-key-reveal]");
                if (reveal) reveal.textContent = "Hide";
                Toast.flash(btn, "Regenerated", 2000, "Regenerate");
            } catch {
                Toast.flash(btn, "Error", 2000, "Regenerate");
            } finally {
                btn.disabled = false;
            }
        });
    }
}

window.ApiKeyManager = ApiKeyManager;
export { ApiKeyManager };
