<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes. All rights reserved.
 * See COPYING.txt for license details.
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\LucideIcons;
use Hyva\Theme\ViewModel\HyvaCsp;
use Magento\Customer\Block\Account\Customer;
use Magento\Framework\Escaper;

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

/** @var LucideIcons $lucideIcons */
$lucideIcons = $viewModels->require(LucideIcons::class);
?>

<div
    class="relative inline-block"
    x-data="initCustomerMenu"
    x-bind="eventListeners"
>
    <button
        type="button"
        id="customer-menu"
        class="btn bg-transparent border-transparent p-1"
        @click="toggleOpen"
        :aria-expanded="open"
        aria-label="<?= $escaper->escapeHtmlAttr(__('My Account')) ?>"
        aria-haspopup="true"
    >
        <?= $lucideIcons->userHtml('', 24, 24, ['aria-hidden' => 'true']); ?>
    </button>
    <nav
        class="z-10 absolute right-0 w-40 sm:w-48 mt-2 lg:mt-3 -me-4 py-2 px-1 rounded-md shadow-lg bg-white overflow-auto"
        aria-labelledby="customer-menu"
        x-show="open"
        x-transition
        x-cloak
    >
        <?php if ($block->customerLoggedIn()): ?>
            <?= $block->getChildHtml('header.customer.logged.in.links') ?>
        <?php else: ?>
            <?= $block->getChildHtml('header.customer.logged.out.links') ?>
        <?php endif; ?>
    </nav>
</div>
<script>
    function initCustomerMenu() {
        return hyva.createBooleanObject('open', false, {
            eventListeners: {
                ['@pageshow.window'](event) {
                    if (event.persisted) {
                        this.setOpenFalse()
                    }
                },
                ['@keyup.escape']() {
                    this.setOpenFalse()
                },
                ['@click.outside']() {
                    this.setOpenFalse()
                }
            }
        })
    }
    window.addEventListener('alpine:init', () => Alpine.data('initCustomerMenu', initCustomerMenu), {once: true})
</script>
<?php $hyvaCsp->registerInlineScript() ?>