import BaseView from "../core/BaseView.js";

export default class MenuView extends BaseView {

    onInit() {

        this.menuItems = this.props.menuItems || [];
    }

    template() {

        return `
            <ul class="main-menu">
                ${this.menuItems.map(item => `
                    <li class="menu-item">
                        <div class="menu-title" data-ref="menu-${item.id}">
                            <i class="${item.icon}"></i>
                            <span>${item.title}</span>
                        </div>

                        ${item.children && item.children.length ? `
                           <ul class="submenu">
                                ${item.children.map(c => `
                                   <li data-ref="menu-${c.id}" class="submenu-item">
                                       ${c.title}
                                   </li>
                                `).join("")}
                           </ul>
                        ` : ""}
                    </li>
                `).join("")}
            </ul>
        `;
    }

    onMounted() {

        this.menuItems.forEach(item => {

            this.ref(`menu-${item.id}`)?.addEventListener("click", () => {
                if (item.module) {
                    this.eventBus.emit("menu:open_module", item.module);
                }
            });

            (item.children || []).forEach(c => {
                this.ref(`menu-${c.id}`).addEventListener("click", () => {
                    this.eventBus.emit("menu:open_view", c);
                });
            });

        });

    }

}
