<?php
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\Navigation;
use Magento\Cms\Block\BlockByIdentifier as CmsBlock;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Template $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var HyvaCsp $hyvaCsp */

/** @var Navigation $viewModelNavigation */
$viewModelNavigation = $viewModels->require(Navigation::class, $block);
/** @var HeroiconsSolid $heroiconsSolid */
$heroiconsSolid = $viewModels->require(HeroiconsSolid::class);

$canOpenOnHover = $block->getOpenTopLevelMenuOnHover();
$showTopLevelAllLink = $block->getShowTopLevelAllLink() !== null ? $block->getShowTopLevelAllLink() : true;
$topMenuCtaItem = $block->getTopMenuCtaItem();

$menu = $viewModelNavigation->getNavigation(5);
$block->setData('cache_tags', $viewModelNavigation->getIdentities());
?>

<nav
    class="3xl:max-w-screen-2xl navigation hidden lg:block 2xl:container mx-auto text-white"
    aria-label="<?= $escaper->escapeHtmlAttr(__('Main menu')) ?>"
    x-data="initMenuDesktop"
    x-ref="nav-desktop"
    @load.window="setActiveMenu"
>
    <ul class="container flex flex-wrap gap-x-8 justify-between px-6 2xl:px-0">
        <?php foreach ($menu as $item): ?>
            <?php if (!empty($item['childData'])): ?>
                <li
                    class="level-0 "
                    x-data="initMenuDesktopItem"
                    @click.outside="close"
                    @keydown.escape="close"
                    <?php if ($canOpenOnHover): ?>
                        @mouseenter="canHoverOpen"
                        @mouseleave="canHoverClose"
                    <?php endif ?>
                >
                    <?php $menuId = 'desktop-menu-' . str_replace('-node', '', $item['id']) ?>
                    <a href="<?= $escaper->escapeUrl($item['url']) ?>"
                       class="level-0 group w-full font-semibold flex justify-between items-center px-1 pt-4 pb-[calc(theme(padding.4)_-_3px)]
                           font-inter text-sm 2xl:text-base"
                       aria-expanded="false"
                       :aria-expanded="open"
                       aria-controls="<?= $escaper->escapeHtml($menuId) ?>"
                    >
                        <?= $escaper->escapeHtml($item['name']) ?>
                        <?= $heroiconsSolid->chevronDownHtml(
                            'transition group-aria-expanded:rotate-180 text-white group-aria-expanded:text-inherit',
                            24,
                            24,
                            ['aria-hidden' => 'true']
                        ) ?>
                    </a>
                    <div
                        id="<?= $escaper->escapeHtml($menuId) ?>"
                        class="mt-0.5 max-w-screen-2xl z-30 absolute inset-x-0 flex gap-8 container py-6 min-h-64 border-t border-slate-100
                            rounded-b-md bg-white shadow-md overflow-auto text-black"
                        x-show="open"
                        x-transition
                        x-cloak
                    >
                        <div class="grow flex flex-col justify-between">
                            <ul class="columns-3xs">
                                <?php foreach ($item['childData'] as $subMenu): ?>
                                    <li class="break-inside-avoid pb-4">
                                        <a
                                            href="<?= $escaper->escapeUrl($subMenu['url']) ?>"
                                            class="level-1 block py-1 font-inter font-medium hover:underline aria-[current=page]:underline font-semibold border-b border-slate-300"
                                        ><?= $escaper->escapeHtml($subMenu['name']) ?></a>
                                        <?php if (!empty($subMenu['childData'])): ?>
                                            <ul>
                                                <?php foreach (array_slice($subMenu['childData'], 0, 5) as $subMenuItems): ?>
                                                    <li>
                                                        <a
                                                            href="<?= $escaper->escapeUrl($subMenuItems['url']) ?>"
                                                            class="level-2 block py-1 font-inter hover:underline aria-[current=page]:underline text-gray-700"
                                                        ><?= $escaper->escapeHtml($subMenuItems['name']) ?></a>
                                                    </li>
                                                <?php endforeach; ?>
                                            </ul>
                                            <?php if (count($subMenu['childData']) > 5): ?>
                                                <div class="font-semibold underline">
                                                    <a
                                                        href="<?= $escaper->escapeUrl($subMenu['url']) ?>"
                                                        class="level-0 block pt-3 hover:underline aria-[current=page]:underline"
                                                    ><?= $escaper->escapeHtml(__('Show More')) ?></a>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                            <!--                            --><?php //if ($showTopLevelAllLink): ?>
                            <!--                                <div class="mt-4 border-t border-slate-100 font-semibold underline">-->
                            <!--                                    <a-->
                            <!--                                        href="--><?php //= $escaper->escapeUrl($item['url']) ?><!--"-->
                            <!--                                        class="level-0 block pt-3 hover:underline aria-[current=page]:underline"-->
                            <!--                                    >--><?php //= $escaper->escapeHtml(__('See all %1', $item['name'])) ?><!--</a>-->
                            <!--                                </div>-->
                            <!--                            --><?php //endif; ?>
                        </div>
                        <!--                        --><?php
                        //                        $cmsBlockHtml = $this->getLayout()
                        //                            ->createBlock(CmsBlock::class)
                        //                            ->setIdentifier($menuId)
                        //                            ->toHtml();
                        //                        if (!empty($cmsBlockHtml)):
                        //?>
<!--                        <div class="max-w-[30%]">-->
                            <!--                                --><?php //= /** @noEscape */ $cmsBlockHtml?>
                            <!-- Example of including an image or other content -->
                            <!-- <img src="images/slider1.png" alt="Example Image" class="w-full h-auto rounded shadow"> -->
<!--                            <img src="--><?php //= $this->getViewFileUrl('images/bathroom-menu.jpeg'); ?><!--" alt="">-->

<!--                        </div>-->
                        <!--                        --><?php //endif;?>
                    </div>
                </li>
            <?php else: ?>
                <li>
                    <a
                        href="<?= $escaper->escapeUrl($item['url']) ?>"
                        title="<?= $escaper->escapeHtmlAttr($item['name']) ?>"
                        class="level-0 font-semibold font-inter text-sm 2xl:text-base flex py-4
                            <?= $item['name'] === $topMenuCtaItem ? 'bg-red text-white px-6 hover:bg-maroon' : '' ?>"
                    >
                        <?= $escaper->escapeHtml($item['name']) ?>
                    </a>
                </li>
            <?php endif; ?>
        <?php endforeach; ?>
    </ul>
</nav>

<script>
    function initMenuDesktop() {
        return {
            setActiveMenu() {
                Array.from(this.$root.querySelectorAll('a'))
                    .filter(link => link.href === window.location.href.split('?')[0])
                    .forEach(item => {
                            item.setAttribute('aria-current', 'page');

                            for (let level = 0; level < 3; level++) {
                                const closestMenu = item.closest(`.level-${level}`);

                                if (closestMenu) {
                                    const button = closestMenu.querySelector('button');
                                    if (button) {
                                        button.setAttribute('data-has-current', '');
                                    }
                                }
                            }
                        }
                    );
            }
        }
    }

    function initMenuDesktopItem() {
        return {
            open: false,
            canHover(func) {
                return window.matchMedia('(hover: hover) and (pointer: fine)').matches;
            },
            canHoverOpen() {
                if (!this.canHover()) return;
                this.open = true;
            },
            canHoverClose() {
                if (!this.canHover()) return;
                this.open = false;
            },
            toggle() {
                this.open = !this.open;
            },
            close() {
                this.open = false;
            }
        }
    }

    window.addEventListener('alpine:init', () => {
        Alpine.data('initMenuDesktop', initMenuDesktop);
        Alpine.data('initMenuDesktopItem', initMenuDesktopItem);
    }, { once: true })
</script>
<?php $hyvaCsp->registerInlineScript() ?>
