export class FormManager {
    constructor() {
        this.initPostForm();
        this.initCommentForms();
        this.initFormDisable();
        this.initAutoSubmitSelects();
    }

    initPostForm() {
        const form = document.getElementById("create-post-form");
        if (!form) {
            return;
        }
        const content = form.querySelector("#post-content");
        const title = form.querySelector("#post-title");
        const contentCount = form.querySelector("#post-content-count");
        const titleCount = form.querySelector("#post-title-count");

        if (content && contentCount) {
            content.addEventListener("input", () => {
                contentCount.textContent = `${content.value.length}/2000`;
            });
        }
        if (title && titleCount) {
            title.addEventListener("input", () => {
                titleCount.textContent = `${title.value.length}/500`;
            });
        }

        form.addEventListener("submit", () => {
            const btn = form.querySelector("button[type='submit']");
            if (btn) {
                btn.disabled = true;
                btn.textContent = "Posting...";
            }
        });
    }

    initCommentForms() {
        document.querySelectorAll(".comment-form").forEach((form) => {
            const textarea = form.querySelector("textarea");
            if (!textarea) {
                return;
            }
            textarea.addEventListener("input", () => {
                textarea.style.height = "auto";
                textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;
            });
        });
    }

    initFormDisable() {
        document.querySelectorAll("form").forEach((form) => {
            form.addEventListener("submit", () => {
                const btn = form.querySelector("button[type='submit']");
                if (btn) {
                    btn.disabled = true;
                }
            });
        });
    }

    initAutoSubmitSelects() {
        document.querySelectorAll("[data-auto-submit]").forEach((select) => {
            select.addEventListener("change", () => {
                const form = select.closest("form");
                if (form) form.submit();
            });
        });
    }
}
