<template>
    <li>
        <div
            tabindex="0"
            class="tb-map-filter-item"
            :class="{ 'is-selected': item && currentFilter && item.path === currentFilter.path }"
            @click.prevent="onClick(item)"
        >
            <slot name="icon">
                <div
                    v-if="item && item.style"
                    class="tb-map-filter-item__icon"
                >
                    <img
                        :src="item.style.iconUrl"
                        alt=""
                    >
                </div>
            </slot>

            <div class="tb-map-filter-item__name">
                {{ item.title }}
            </div>

            <button
                @click="showChildren = !showChildren"
                class="tb-map-filter-item__toggle-icon"
                :aria-label="lang.toggleSubMenu"
                v-if="item.children && item.children.length > 0"
            >
                <svg class="c-icon" aria-hidden="true" data-icon-open>
                    <use xlink:href="#tb-map-expand" />
                </svg>
            </button>
        </div>

        <ul
            class="tb-map-filter-menu__sub-items"
            :class="{ 'is-target': showChildren }"
            v-if="item.children && item.children.length > 0"
        >
            <tb-map-filter-menu-item
                v-for="(child, index) in item.children"
                :key="index"
                :item="child"
                :current-filter="currentFilter"
                @activate="filter => $emit('activate', filter)"
            />
        </ul>
    </li>
</template>
<script>
export default {
    name: 'TbMapFilterMenuItem',

    props: {
        item: { type: Object, required: true },
        lang: { type: Object, required: true },
        currentFilter: {
            required: true,
            validator: value => typeof value === 'object' || value === null,
        },
    },

    data: () => ({
        showChildren: false,
    }),

    watch: {
        item: {
            immediate: true,
            handler(item) {
                for (const child of item.children || []) {
                    if (child === this.currentFilter) {
                        this.showChildren = true;
                        return;
                    }
                }
            },
        },
    },

    methods: {
        onClick() {
            this.$emit('activate', this.item);
        },
    },
};
</script>
