export class EmojiPicker {
    constructor(textarea) {
        this.textarea = textarea;
        this.picker = null;
        this.wrapper = null;
        this.build();
    }

    build() {
        this.wrapper = document.createElement("div");
        this.wrapper.className = "emoji-picker-wrapper";
        this.wrapper.style.display = "none";
        this.wrapper.style.position = "absolute";
        this.wrapper.style.bottom = "100%";
        this.wrapper.style.right = "0";
        this.wrapper.style.zIndex = "2000";

        const picker = document.createElement("emoji-picker");
        picker.style.width = "320px";
        picker.style.height = "350px";
        this.wrapper.appendChild(picker);

        picker.addEventListener("emoji-click", (event) => {
            this.insert(event.detail.unicode);
            this.hide();
        });

        this.picker = picker;

        const parent = this.textarea.parentElement;
        if (parent) {
            parent.style.position = "relative";
            parent.appendChild(this.wrapper);
        }
    }

    insert(unicode) {
        const ta = this.textarea;
        const start = ta.selectionStart;
        const end = ta.selectionEnd;
        const text = ta.value;
        ta.value = text.substring(0, start) + unicode + text.substring(end);
        const newPos = start + unicode.length;
        ta.setSelectionRange(newPos, newPos);
        ta.focus();
        ta.dispatchEvent(new Event("input", { bubbles: true }));
    }

    toggle() {
        if (this.wrapper.style.display === "none") {
            this.wrapper.style.display = "block";
        } else {
            this.wrapper.style.display = "none";
        }
    }

    hide() {
        this.wrapper.style.display = "none";
    }
}
window.EmojiPicker = EmojiPicker;
