// retoor <retoor@molodetz.nl>

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

class AwardGiver {
    constructor() {
        this.btn = document.querySelector("[data-award-give]");
        this.modal = document.getElementById("award-give-modal");
        if (!this.btn || !this.modal) return;
        this.form = this.modal.querySelector("form");
        this.textarea = this.modal.querySelector('textarea[name="description"]');
        this.counter = this.modal.querySelector("[data-award-char-count]");
        this.btn.addEventListener("click", () => this.open());
        if (this.form) {
            this.form.addEventListener("submit", (event) => this.submit(event));
        }
        if (this.textarea) {
            this.textarea.addEventListener("input", () => this.updateCounter());
            this.updateCounter();
        }
    }

    open() {
        if (this.btn.disabled) return;
        this.modal.classList.add("visible");
        if (this.textarea) {
            this.textarea.focus();
        }
    }

    updateCounter() {
        if (!this.counter || !this.textarea) return;
        const max = Number(this.textarea.getAttribute("maxlength") || 125);
        const length = this.textarea.value.length;
        this.counter.textContent = `${length}/${max}`;
    }

    async submit(event) {
        event.preventDefault();
        const username = this.btn.dataset.username;
        const description = (this.textarea?.value || "").trim();
        if (!description) return;
        const submitBtn = this.form.querySelector('button[type="submit"]');
        if (submitBtn) submitBtn.disabled = true;
        try {
            await Http.postJson(`/profile/${username}/award`, { description });
            this.modal.classList.remove("visible");
            if (this.form) this.form.reset();
            this.updateCounter();
            await window.app.dialog.alert({
                title: "Award submitted",
                message: `Your award for @${username} is being created. They will be notified when it is ready.`,
            });
        } catch {
            await window.app.dialog.alert({
                title: "Award failed",
                message: "Could not submit the award. Try again later.",
            });
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    }
}

window.AwardGiver = AwardGiver;
export { AwardGiver };