// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/cr_icon/cr_icon.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import { debounceEnd } from 'chrome://resources/js/util.js';
import { CrLitElement } from 'chrome://resources/lit/v3_0/lit.rollup.js';
import { emojiData as rawEmojiData } from './emoji_data.js';
import { getCss } from './skills_emoji_picker.css.js';
import { getHtml } from './skills_emoji_picker.html.js';
function processEmojiData(data) {
    const categoryMap = new Map();
    data.forEach(categoryGroup => {
        const categoryEmojis = [];
        categoryGroup.emoji.forEach(emoji => {
            categoryEmojis.push({
                emoji: String.fromCodePoint(...emoji.base),
                name: emoji.shortcodes[0] ?
                    emoji.shortcodes[0].replace(/:/g, '').replace(/-/g, ' ') :
                    '',
                shortcodes: emoji.shortcodes,
                category: categoryGroup.group,
            });
        });
        categoryMap.set(categoryGroup.group, categoryEmojis);
    });
    return { categoryMap };
}
let defaultProcessedData = null;
function getDefaultProcessedData() {
    if (!defaultProcessedData) {
        defaultProcessedData =
            processEmojiData(rawEmojiData);
    }
    return defaultProcessedData;
}
export class SkillsEmojiPickerElement extends CrLitElement {
    static get is() {
        return 'skills-emoji-picker';
    }
    static get styles() {
        return getCss();
    }
    render() {
        return getHtml.bind(this)();
    }
    static get properties() {
        return {
            searchQuery_: { type: String },
            groupedEmojis_: { type: Object },
        };
    }
    #searchQuery__accessor_storage = '';
    get searchQuery_() { return this.#searchQuery__accessor_storage; }
    set searchQuery_(value) { this.#searchQuery__accessor_storage = value; }
    #groupedEmojis__accessor_storage = new Map();
    get groupedEmojis_() { return this.#groupedEmojis__accessor_storage; }
    set groupedEmojis_(value) { this.#groupedEmojis__accessor_storage = value; }
    categoryMap_ = new Map();
    debouncedUpdateGroups_;
    documentClickListener_;
    searchDebounceDelayMs_ = 200;
    constructor() {
        super();
        this.documentClickListener_ = this.onOutsideClick_.bind(this);
        this.debouncedUpdateGroups_ =
            debounceEnd(() => this.updateGroups_(), this.searchDebounceDelayMs_);
    }
    connectedCallback() {
        super.connectedCallback();
        if (this.categoryMap_.size === 0) {
            const processed = getDefaultProcessedData();
            this.categoryMap_ = processed.categoryMap;
            this.updateGroups_();
        }
        requestAnimationFrame(() => {
            if (this.isConnected) {
                document.addEventListener('click', this.documentClickListener_);
            }
        });
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        document.removeEventListener('click', this.documentClickListener_);
    }
    firstUpdated() {
        this.$.searchInput.focus();
    }
    setSearchDebounceDelayMsForTesting(delay) {
        this.searchDebounceDelayMs_ = delay;
        this.debouncedUpdateGroups_ =
            debounceEnd(() => this.updateGroups_(), this.searchDebounceDelayMs_);
    }
    setEmojiData(value) {
        const processed = processEmojiData(value);
        this.categoryMap_ = processed.categoryMap;
        this.updateGroups_();
    }
    onOutsideClick_(event) {
        if (!event.composedPath().includes(this)) {
            this.fire('picker-close');
        }
    }
    updateGroups_() {
        if (!this.searchQuery_) {
            this.groupedEmojis_ = this.categoryMap_;
            return;
        }
        const query = this.searchQuery_.toLowerCase();
        const groups = new Map();
        for (const [category, emojis] of this.categoryMap_) {
            const filtered = emojis.filter(emoji => emoji.name.toLowerCase().includes(query) ||
                emoji.shortcodes.some(s => s.toLowerCase().includes(query)));
            if (filtered.length > 0) {
                groups.set(category, filtered);
            }
        }
        this.groupedEmojis_ = groups;
    }
    onSearchInputValueChanged_(event) {
        this.searchQuery_ = event.detail.value;
        this.debouncedUpdateGroups_();
    }
    onEmojiClick_(event) {
        const emoji = event.currentTarget.dataset['emoji'];
        this.fire('emoji-selected', { emoji });
    }
    onKeydown_(event) {
        if (event.key === 'Escape') {
            event.stopPropagation();
            event.preventDefault();
            this.fire('picker-close');
            return;
        }
        const buttons = Array.from(this.shadowRoot.querySelectorAll('.emoji-button'));
        if (buttons.length === 0) {
            return;
        }
        const currentIndex = buttons.indexOf(this.shadowRoot.activeElement);
        let nextIndex = -1;
        if (currentIndex === -1) {
            if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
                nextIndex = 0;
            }
        }
        else {
            switch (event.key) {
                case 'ArrowLeft':
                case 'ArrowUp':
                    nextIndex = Math.max(0, currentIndex - 1);
                    break;
                case 'ArrowRight':
                case 'ArrowDown':
                    nextIndex = Math.min(buttons.length - 1, currentIndex + 1);
                    break;
                default:
                    break;
            }
        }
        const nextButton = buttons[nextIndex];
        if (nextButton) {
            event.preventDefault();
            nextButton.focus();
            nextButton.scrollIntoView({ block: 'nearest' });
        }
    }
    getEmojiCategories_() {
        return Array.from(this.groupedEmojis_.keys());
    }
    getEmojisByCategory_(category) {
        return this.groupedEmojis_.get(category) || [];
    }
}
customElements.define(SkillsEmojiPickerElement.is, SkillsEmojiPickerElement);
