import { contentRenderer } from "./ContentRenderer.js";
import { MentionInput } from "./MentionInput.js";
import { EmojiPicker } from "./EmojiPicker.js";
import { AttachmentUploader } from "./AttachmentUploader.js";

export class ContentEnhancer {
    constructor() {
        this.initContentRenderer();
        this.initEmojiPickers();
        this.initMentionInputs();
        this.initImageFallbacks();
        this.initAttachmentManagers();
    }

    initContentRenderer() {
        document.querySelectorAll("[data-render]").forEach((el) => {
            contentRenderer.applyTo(el);
        });
        contentRenderer.highlightAll();
    }

    initEmojiPickers() {
        document.querySelectorAll(".comment-form textarea, .emoji-picker-target").forEach((textarea) => {
            if (textarea.dataset.emojiInitialized) return;
            textarea.dataset.emojiInitialized = "true";

            const btn = document.createElement("button");
            btn.type = "button";
            btn.className = "emoji-toggle-btn";
            btn.title = "Add emoji";
            btn.innerHTML = "\u{1F600}";

            const picker = new EmojiPicker(textarea);
            btn.addEventListener("click", () => picker.toggle());

            const parent = textarea.parentElement;
            if (parent) {
                const actions = parent.querySelector(".comment-form-actions");
                if (actions) {
                    actions.style.position = "relative";
                    actions.appendChild(picker.wrapper);
                    actions.insertBefore(btn, actions.firstChild);
                }
            }
        });
    }

    initMentionInputs() {
        document.querySelectorAll("[data-mention]").forEach((el) => {
            if (el.dataset.mentionInitialized) return;
            el.dataset.mentionInitialized = "true";
            new MentionInput(el);
        });
    }

    initImageFallbacks() {
        document.querySelectorAll(".image-fallback").forEach((img) => {
            img.addEventListener("error", () => {
                const container = img.closest(".news-card-image, .news-detail-image") || img.parentElement;
                if (container) container.style.display = "none";
            });
        });
    }

    initAttachmentManagers() {
        document.querySelectorAll(".attachment-upload-container").forEach((container) => {
            if (container.dataset.attachmentInitialized) return;
            container.dataset.attachmentInitialized = "true";
            const form = container.closest("form");
            if (form) {
                form.dataset.maxSize = container.dataset.maxSize;
                form.dataset.maxFiles = container.dataset.maxFiles;
                form.dataset.allowedTypes = container.dataset.allowedTypes || "";
                new AttachmentUploader(form);
            }
        });
    }
}
