// retoor <retoor@molodetz.nl>

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

class AiModifier {
    constructor() {
        this.root = document.querySelector("[data-ai-modifier]");
        if (!this.root) return;
        this.username = this.root.dataset.username;
        this.toggle = this.root.querySelector("[data-ai-modifier-toggle]");
        this.mode = this.root.querySelector("[data-ai-modifier-sync]");
        this.prompt = this.root.querySelector("[data-ai-modifier-prompt]");
        this.status = this.root.querySelector("[data-ai-modifier-status]");
        this.save = this.root.querySelector("[data-ai-modifier-save]");
        if (this.save) this.save.addEventListener("click", () => this.submit());
    }

    async submit() {
        if (!this.toggle || !this.prompt) return;
        this.save.disabled = true;
        this.setStatus("Saving...", "");
        try {
            await Http.send(`/profile/${this.username}/ai-modifier`, {
                enabled: this.toggle.checked ? "true" : "false",
                sync: this.mode && this.mode.value === "sync" ? "true" : "false",
                prompt: this.prompt.value,
            });
            this.setStatus("Saved", "success");
            this.flash("AI modifier settings saved", "success");
        } catch (error) {
            this.setStatus("Could not save", "error");
            this.flash("Could not save AI modifier settings", "error");
        } finally {
            this.save.disabled = false;
        }
    }

    setStatus(message, type) {
        if (!this.status) return;
        this.status.textContent = message;
        this.status.dataset.state = type;
    }

    flash(message, type) {
        if (window.app && window.app.toast) {
            window.app.toast.show(message, { type });
        }
    }
}

window.AiModifier = AiModifier;
export { AiModifier };
