<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\Navigation;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

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

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);

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

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

$uniqueId = '_' . uniqid();
$maxLevel = $block->getmaxLevel() ?: 3;

// Order is important here: 1. build the menu data, 2. then set the cache tags from the view model identities
$menu = $viewModelNavigation->getNavigation(2 + $maxLevel);
$block->setData('cache_tags', $viewModelNavigation->getIdentities());

$additionalMenuItemsBefore = $block->getAdditionalMenuItemsBefore() ?: [];
$additionalMenuItemsAfter = $block->getAdditionalMenuItems() ?: [
    'contact' => [
        'name' => __('Contact'),
        'url' => '/contact'
    ],
];

$showSettingsNav = $block->getShowSettingsNav() !== null ? $block->getShowSettingsNav() : true;
$showSearch = $block->getShowSearch() !== null ? $block->getShowSearch() : true;
$showSocials = $block->getShowSocials() !== null ? $block->getShowSocials() : true;

$itemClasses = "flex items-center font-inter gap-1 py-3 px-6 text-black border-b aria-[current=page]:text-blue-700 aria-[current=page]:font-bold -outline-offset-1";
$itemIconSize = 20;
?>

<div class="navigation lg:hidden" x-data="initMobileMenu" @sub-menu-state-change.window="hasActiveSubMenu">
    <button
        type="button"
        class="align-middle absolute top-3 md:top-4 left-1.5 z-20 md:mt-1 "
        aria-label="<?= $escaper->escapeHtmlAttr(__('Open menu')) ?>"
        aria-controls="mobileMenu"
        @click="open"
    >
        <?= $heroicons->menuHtml('', 32, 32, ["aria-hidden" => "true"]) ?>
    </button>

    <dialog
        id="mobileMenu"
        class="overflow-hidden mt-0 max-h-full h-screen w-full ml-0 open:flex flex-col transition ease-out duration-300 open:duration-500"
        x-show="isOpen"
        x-htmldialog.noscroll="close"
        x-transition:enter-start="-translate-x-full"
        x-transition:enter-end="translate-x-0"
        x-transition:leave-start="translate-x-0"
        x-transition:leave-end="-translate-x-full"
    >
        <div class="border-b border-slate-200 sticky top-0 bg-white z-20">
            <div class="flex items-center gap-2 py-4 px-6 justify-between">
                <div><?= $block->getChildHtml('logo') ?></div>
                <button
                    type="button"
                    @click="close"
                    class="ms-auto p-2"
                    aria-label="<?= $escaper->escapeHtmlAttr(__('Close menu')) ?>"
                >
                    <?= $heroicons->xHtml('', 24, 24, ["aria-hidden" => "true"]) ?>
                </button>
            </div>

            <?php if ($showSearch && $block->getChildHtml('search')):?>
                <div class="pb-2 px-6"><?= $block->getChildHtml('search')?></div>
            <?php endif;?>
        </div>
        <div class="grow relative text-slate-500 overflow-y-auto overflow-x-hidden" :style="lockWrapperScroll">
            <nav
                aria-label="<?= $escaper->escapeHtmlAttr(__('Mobile Main Menu')) ?>"
                class="overflow-y-auto max-h-[calc(100vh-250px)]"
            >
            <ul>
                    <?php foreach ($additionalMenuItemsBefore as $item): ?>
                        <li data-level="0">
                            <a
                                href="<?= $escaper->escapeUrl($item['url']) ?>"
                                class="<?= $escaper->escapeHtmlAttr($itemClasses) ?>"
                                <?php if (array_key_exists('external', $item)): ?>
                                    target="_blank"
                                    rel="noopener noreferrer"
                                <?php endif; ?>
                            ><?= $escaper->escapeHtml($item['name']) ?></a>
                        </li>
                    <?php endforeach; ?>
                    <?php foreach ($menu as $item): ?>
                        <?= $block->getLayout()->getBlock('topmenu_mobile_item')
                            ->setItem($item)
                            ->setLevel(0)
                            ->setItemClasses($itemClasses)
                            ->toHtml() ?>
                    <?php endforeach; ?>
                    <?php foreach ($additionalMenuItemsAfter as $item): ?>
                        <li data-level="0">
                            <a
                                href="<?= $escaper->escapeUrl($item['url']) ?>"
                                class="text-black font-medium <?= $escaper->escapeHtmlAttr($itemClasses) ?>"
                                <?php if (array_key_exists('external', $item)): ?>
                                    target="_blank"
                                    rel="noopener noreferrer"
                                <?php endif; ?>
                            ><?= $escaper->escapeHtml($item['name']) ?></a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </nav>
            <?php if ($showSettingsNav): ?>
                <nav aria-label="<?= $escaper->escapeHtmlAttr(__('Mobile Store Settings')) ?>" :inert="isSubMenuOpen">
                    <p class="uppercase text-xs pt-6 pb-3 px-6"><?= $escaper->escapeHtml(__('Settings')) ?></p>
                    <?= $block->getChildHtml('store-language-switcher') ?>
                    <?= $block->getChildHtml('currency-switcher') ?>
                    <a
                        href="<?= $escaper->escapeUrl($block->getUrl('customer/account/index')) ?>"
                        class="<?= $escaper->escapeHtmlAttr($itemClasses) ?>"
                    >
                        <?= $heroiconsSolid->userCircleHtml('', $itemIconSize, $itemIconSize, ['aria-hidden' => 'true']); ?>
                        <?= $escaper->escapeHtml(__('My Account')) ?>
                    </a>
            </nav>
            <?php endif; ?>
        </div>
        <div class="bg-white border-t-2 bottom-0 sticky z-20">
            <?php if ($showSocials): ?>
                <?= $block->getChildHtml('socials') ?>
            <?php endif; ?>
            <?= $block->getChildHtml('additional') ?>
        </div>

    </dialog>
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('initMobileMenu', () => ({
            isOpen: false,
            isSubMenuOpen: false,
            isOverflowing: false,
            init() {
                Array.from(this.$root.querySelectorAll('a')).forEach(link => {
                    if (link.href === `${window.location.origin}${window.location.pathname}`) {
                        link.setAttribute('aria-current', 'page');
                    }
                });
            },
            open() {
                this.isOpen = true;
            },
            close() {
                this.isOpen = false;
            },
            lockWrapperScroll() {
                return this.isSubMenuOpen ? { overflow: 'hidden' } : {}
            },
            hasActiveSubMenu() {
                this.isSubMenuOpen = !!this.$root.querySelector('[data-open]');
            }
        }));

        Alpine.data('initMobileSubMenu', () => ({
            isOpen: false,
            open() {
                this.isOpen = true;
                this.$root.setAttribute('data-open', '');
                this.$nextTick(() => {
                    this.$dispatch('sub-menu-state-change');
                    this.$refs.closeSubMenuBtn.focus();
                    this.toggleInert();
                })
            },
            close() {
                this.isOpen = false;
                this.$root.removeAttribute('data-open');
                this.toggleInert();
                this.$nextTick(() => {
                    this.$dispatch('sub-menu-state-change')
                    this.$refs.openSubMenuBtn.focus();
                })
            },
            toggleInert() {
                const items = this.$root.parentElement.children;

                for (item of items) {
                    if (item.hasAttribute('data-open')) continue;
                    item.toggleAttribute('inert', this.isOpen);
                }
            }
        }));
    });
</script>
<?php $hyvaCsp->registerInlineScript() ?>
