// retoor <retoor@molodetz.nl>

import { TextInput } from "./TextInput.js";
import { DomUtils } from "./DomUtils.js";
import { assetUrl } from "./assetVersion.js";

const EMOJI_DATA_SOURCE = assetUrl("/static/vendor/emoji-picker-element/data.json");

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.setAttribute("data-source", EMOJI_DATA_SOURCE);
        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) {
        TextInput.insertAtCursor(this.textarea, unicode);
    }

    toggle() {
        DomUtils.toggle(this.wrapper);
    }

    hide() {
        DomUtils.hide(this.wrapper);
    }
}
window.EmojiPicker = EmojiPicker;
