{#
  Category Navigation Components
  ==============================
  Category browsing sidebar and menu for shop navigation.

  Usage:
    {% from 'shared/macros/storefront/category-nav.html' import category_nav, category_tree, category_menu %}
#}


{#
  Category Navigation
  ===================
  Sidebar category navigation with nested categories.

  Parameters:
    - categories_var: Alpine.js expression for categories array (default: 'categories')
    - current_var: Alpine.js expression for current category (default: 'currentCategory')
    - show_count: Show product counts (default: true)
    - collapsible: Make nested categories collapsible (default: true)
    - max_depth: Maximum nesting depth to show (default: 3)

  Expected category object:
    {
      id: 1,
      name: 'Electronics',
      slug: 'electronics',
      url: '/category/electronics',
      product_count: 150,
      children: [...]
    }

  Usage:
    {{ category_nav(categories_var='categories', show_count=true) }}
#}
{% macro category_nav(
    categories_var='categories',
    current_var='currentCategory',
    show_count=true,
    collapsible=true,
    max_depth=3
) %}
<nav
    x-data="{
        expandedCategories: new Set(),
        toggleCategory(id) {
            if (this.expandedCategories.has(id)) {
                this.expandedCategories.delete(id);
            } else {
                this.expandedCategories.add(id);
            }
        },
        isExpanded(id) {
            return this.expandedCategories.has(id);
        },
        isActive(category) {
            return {{ current_var }}?.id === category.id || {{ current_var }}?.slug === category.slug;
        },
        isParentOfActive(category) {
            if (!category.children?.length) return false;
            return category.children.some(child =>
                this.isActive(child) || this.isParentOfActive(child)
            );
        }
    }"
    x-init="
        // Auto-expand parent of active category
        const expandParents = (cats) => {
            cats.forEach(cat => {
                if (isParentOfActive(cat)) {
                    expandedCategories.add(cat.id);
                }
                if (cat.children?.length) expandParents(cat.children);
            });
        };
        expandParents({{ categories_var }} || []);
    "
    class="space-y-1"
    aria-label="Category navigation"
>
    <template x-for="category in {{ categories_var }}" :key="category.id">
        {{ _category_item(current_var, show_count, collapsible, 0, max_depth) }}
    </template>
</nav>
{% endmacro %}


{#
  Internal: Category Item (recursive)
#}
{% macro _category_item(current_var, show_count, collapsible, depth, max_depth) %}
<div class="relative">
    <div class="flex items-center">
        {# Category Link #}
        <a
            :href="category.url || '/category/' + category.slug"
            class="flex-1 flex items-center justify-between px-3 py-2 text-sm rounded-lg transition-colors"
            :class="{
                'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 font-medium': isActive(category),
                'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700': !isActive(category)
            }"
            :style="'padding-left: ' + ({{ depth }} * 12 + 12) + 'px'"
        >
            <span x-text="category.name"></span>
            {% if show_count %}
            <span
                x-show="category.product_count !== undefined"
                class="text-xs text-gray-500 dark:text-gray-400"
                x-text="'(' + category.product_count + ')'"
            ></span>
            {% endif %}
        </a>

        {# Expand/Collapse Button #}
        {% if collapsible %}
        <button
            x-show="category.children?.length && {{ depth }} < {{ max_depth - 1 }}"
            type="button"
            @click.prevent="toggleCategory(category.id)"
            class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            :aria-expanded="isExpanded(category.id)"
        >
            <span
                x-html="$icon('chevron-right', 'w-4 h-4 transition-transform')"
                :class="isExpanded(category.id) && 'rotate-90'"
            ></span>
        </button>
        {% endif %}
    </div>

    {# Nested Categories #}
    {% if depth < max_depth - 1 %}
    <div
        x-show="{{ 'isExpanded(category.id)' if collapsible else 'true' }} && category.children?.length"
        x-transition
        class="mt-1"
    >
        <template x-for="child in category.children" :key="child.id">
            <div x-data="{ category: child }">
                {{ _category_item(current_var, show_count, collapsible, depth + 1, max_depth) }}
            </div>
        </template>
    </div>
    {% endif %}
</div>
{% endmacro %}


{#
  Category Tree (Flat List)
  =========================
  Simple flat list of categories without nesting.

  Parameters:
    - categories_var: Alpine.js expression for categories
    - current_var: Alpine.js expression for current category
    - show_count: Show product counts (default: true)
    - layout: 'vertical' | 'horizontal' (default: 'vertical')

  Usage:
    {{ category_tree(categories_var='topCategories', layout='horizontal') }}
#}
{% macro category_tree(
    categories_var='categories',
    current_var='currentCategory',
    show_count=true,
    layout='vertical'
) %}
<nav
    class="{{ 'flex flex-wrap gap-2' if layout == 'horizontal' else 'space-y-1' }}"
    aria-label="Categories"
>
    <template x-for="category in {{ categories_var }}" :key="category.id">
        <a
            :href="category.url || '/category/' + category.slug"
            class="{{ 'px-4 py-2 rounded-full text-sm font-medium' if layout == 'horizontal' else 'block px-3 py-2 text-sm rounded-lg' }} transition-colors"
            :class="{
                '{{ 'bg-purple-600 text-white' if layout == 'horizontal' else 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 font-medium' }}': {{ current_var }}?.id === category.id || {{ current_var }}?.slug === category.slug,
                '{{ 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600' if layout == 'horizontal' else 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700' }}': {{ current_var }}?.id !== category.id && {{ current_var }}?.slug !== category.slug
            }"
        >
            <span x-text="category.name"></span>
            {% if show_count %}
            <span
                x-show="category.product_count !== undefined"
                class="ml-1 text-xs {{ 'opacity-75' if layout == 'horizontal' else 'text-gray-500 dark:text-gray-400' }}"
                x-text="'(' + category.product_count + ')'"
            ></span>
            {% endif %}
        </a>
    </template>
</nav>
{% endmacro %}


{#
  Category Menu (Dropdown/Mega Menu)
  ==================================
  Horizontal category menu for header navigation.

  Parameters:
    - categories_var: Alpine.js expression for categories
    - show_all_link: Show "All Categories" link (default: true)
    - all_link_url: URL for all categories (default: '/categories')

  Usage:
    {{ category_menu(categories_var='mainCategories') }}
#}
{% macro category_menu(
    categories_var='categories',
    show_all_link=true,
    all_link_url='/categories'
) %}
<nav class="relative" x-data="{ openMenu: null }">
    <ul class="flex items-center gap-1">
        {% if show_all_link %}
        <li>
            <a
                href="{{ all_link_url }}"
                class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-purple-600 dark:hover:text-purple-400 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
                <span x-html="$icon('view-grid', 'w-5 h-5')"></span>
                All Categories
            </a>
        </li>
        {% endif %}

        <template x-for="category in {{ categories_var }}" :key="category.id">
            <li class="relative" @mouseenter="openMenu = category.id" @mouseleave="openMenu = null">
                <a
                    :href="category.url || '/category/' + category.slug"
                    class="flex items-center gap-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-purple-600 dark:hover:text-purple-400 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                >
                    <span x-text="category.name"></span>
                    <span x-show="category.children?.length" x-html="$icon('chevron-down', 'w-4 h-4')"></span>
                </a>

                {# Dropdown for subcategories #}
                <div
                    x-show="openMenu === category.id && category.children?.length"
                    x-transition:enter="transition ease-out duration-100"
                    x-transition:enter-start="opacity-0 transform -translate-y-2"
                    x-transition:enter-end="opacity-100 transform translate-y-0"
                    x-transition:leave="transition ease-in duration-75"
                    x-transition:leave-start="opacity-100"
                    x-transition:leave-end="opacity-0"
                    class="absolute left-0 top-full mt-1 w-56 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-2 z-50"
                    style="display: none;"
                >
                    <template x-for="child in category.children" :key="child.id">
                        <a
                            :href="child.url || '/category/' + child.slug"
                            class="flex items-center justify-between px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-purple-600 dark:hover:text-purple-400"
                        >
                            <span x-text="child.name"></span>
                            <span x-show="child.product_count" class="text-xs text-gray-500" x-text="child.product_count"></span>
                        </a>
                    </template>

                    {# View All Link #}
                    <div class="border-t border-gray-200 dark:border-gray-700 mt-2 pt-2">
                        <a
                            :href="category.url || '/category/' + category.slug"
                            class="flex items-center px-4 py-2 text-sm font-medium text-purple-600 dark:text-purple-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            View all <span x-text="category.name" class="ml-1"></span>
                            <span x-html="$icon('arrow-right', 'w-4 h-4 ml-auto')"></span>
                        </a>
                    </div>
                </div>
            </li>
        </template>
    </ul>
</nav>
{% endmacro %}


{#
  Mobile Category Drawer
  ======================
  Full-screen category navigation for mobile devices.

  Parameters:
    - categories_var: Alpine.js expression for categories
    - show_var: Alpine.js variable for drawer visibility (default: 'showCategoryDrawer')

  Usage:
    {{ category_drawer(categories_var='categories', show_var='showCategoryDrawer') }}
#}
{% macro category_drawer(
    categories_var='categories',
    show_var='showCategoryDrawer'
) %}
<div
    x-show="{{ show_var }}"
    x-transition:enter="transition ease-out duration-300"
    x-transition:enter-start="opacity-0"
    x-transition:enter-end="opacity-100"
    x-transition:leave="transition ease-in duration-200"
    x-transition:leave-start="opacity-100"
    x-transition:leave-end="opacity-0"
    class="fixed inset-0 z-50 lg:hidden"
    style="display: none;"
>
    {# Backdrop #}
    <div
        @click="{{ show_var }} = false"
        class="absolute inset-0 bg-black/50"
    ></div>

    {# Drawer Panel #}
    <div
        x-show="{{ show_var }}"
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="-translate-x-full"
        x-transition:enter-end="translate-x-0"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="translate-x-0"
        x-transition:leave-end="-translate-x-full"
        class="absolute left-0 top-0 bottom-0 w-80 max-w-[85vw] bg-white dark:bg-gray-800 shadow-xl"
        x-data="{ selectedCategory: null, categoryStack: [] }"
    >
        {# Header #}
        <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
            <button
                x-show="categoryStack.length > 0"
                type="button"
                @click="selectedCategory = categoryStack.pop()"
                class="p-2 -ml-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
            >
                <span x-html="$icon('arrow-left', 'w-5 h-5')"></span>
            </button>
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white" x-text="selectedCategory?.name || 'Categories'"></h2>
            <button
                type="button"
                @click="{{ show_var }} = false"
                class="p-2 -mr-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
            >
                <span x-html="$icon('x', 'w-5 h-5')"></span>
            </button>
        </div>

        {# Category List #}
        <div class="overflow-y-auto h-[calc(100%-60px)]">
            <template x-if="!selectedCategory">
                <ul class="py-2">
                    <template x-for="category in {{ categories_var }}" :key="category.id">
                        <li>
                            <a
                                :href="category.children?.length ? '#' : (category.url || '/category/' + category.slug)"
                                @click.prevent="category.children?.length ? (categoryStack.push(null), selectedCategory = category) : (window.location.href = category.url || '/category/' + category.slug)"
                                class="flex items-center justify-between px-4 py-3 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                            >
                                <span x-text="category.name"></span>
                                <span x-show="category.children?.length" x-html="$icon('chevron-right', 'w-5 h-5 text-gray-400')"></span>
                            </a>
                        </li>
                    </template>
                </ul>
            </template>

            <template x-if="selectedCategory">
                <ul class="py-2">
                    {# View All in Category #}
                    <li>
                        <a
                            :href="selectedCategory.url || '/category/' + selectedCategory.slug"
                            class="flex items-center px-4 py-3 text-purple-600 dark:text-purple-400 font-medium hover:bg-gray-100 dark:hover:bg-gray-700"
                        >
                            <span>View all <span x-text="selectedCategory.name"></span></span>
                        </a>
                    </li>
                    <li class="border-t border-gray-200 dark:border-gray-700 my-2"></li>
                    <template x-for="child in selectedCategory.children" :key="child.id">
                        <li>
                            <a
                                :href="child.children?.length ? '#' : (child.url || '/category/' + child.slug)"
                                @click.prevent="child.children?.length ? (categoryStack.push(selectedCategory), selectedCategory = child) : (window.location.href = child.url || '/category/' + child.slug)"
                                class="flex items-center justify-between px-4 py-3 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                            >
                                <span x-text="child.name"></span>
                                <span x-show="child.children?.length" x-html="$icon('chevron-right', 'w-5 h-5 text-gray-400')"></span>
                            </a>
                        </li>
                    </template>
                </ul>
            </template>
        </div>
    </div>
</div>
{% endmacro %}
