// retoor <retoor@molodetz.nl>

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

class AiCorrection {
    constructor() {
        this.root = document.querySelector("[data-ai-correction]");
        if (!this.root) return;
        this.username = this.root.dataset.username;
        this.toggle = this.root.querySelector("[data-ai-correction-toggle]");
        this.mode = this.root.querySelector("[data-ai-correction-sync]");
        this.prompt = this.root.querySelector("[data-ai-correction-prompt]");
        this.status = this.root.querySelector("[data-ai-correction-status]");
        this.save = this.root.querySelector("[data-ai-correction-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-correction`, {
                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 correction settings saved", "success");
        } catch (error) {
            this.setStatus("Could not save", "error");
            this.flash("Could not save AI correction 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.AiCorrection = AiCorrection;
export { AiCorrection };
