// retoor <retoor@molodetz.nl>

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

class InteractionsPref {
    constructor() {
        this.root = document.querySelector("[data-interactions]");
        if (!this.root) return;
        this.username = this.root.dataset.username;
        this.toggle = this.root.querySelector("[data-interactions-toggle]");
        this.status = this.root.querySelector("[data-interactions-status]");
        this.save = this.root.querySelector("[data-interactions-save]");
        this.reset = this.root.querySelector("[data-interactions-reset]");
        if (this.save) this.save.addEventListener("click", () => this.submit(false));
        if (this.reset) this.reset.addEventListener("click", () => this.submit(true));
    }

    async submit(reset) {
        if (!this.toggle) return;
        if (this.save) this.save.disabled = true;
        if (this.reset) this.reset.disabled = true;
        this.setStatus("Saving...", "");
        try {
            const body = reset
                ? { reset: "true", enabled: "false" }
                : {
                      enabled: this.toggle.checked ? "true" : "false",
                      reset: "false",
                  };
            const result = await Http.send(
                `/profile/${this.username}/interactions`,
                body
            );
            if (result && result.data) {
                this.toggle.checked = !!result.data.enabled;
            }
            this.setStatus(reset ? "Using site default" : "Saved", "success");
            this.flash(
                reset
                    ? "Interactive widgets follow the site default"
                    : "Interactive widget preference saved",
                "success"
            );
        } catch (error) {
            this.setStatus("Could not save", "error");
            this.flash("Could not save interactive widget preference", "error");
        } finally {
            if (this.save) this.save.disabled = false;
            if (this.reset) this.reset.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.InteractionsPref = InteractionsPref;
export { InteractionsPref };
