@php($user = auth()->user())
<div class="client-profile-menu">
    <button type="button" class="client-profile-trigger" id="profileMenuBtn"
            aria-expanded="false" aria-haspopup="true" aria-controls="profileDropdown"
            title="{{ $user->name }}">
        <span class="client-profile-info">
            <span class="client-profile-name">{{ $user->name }}</span>
            <span class="client-profile-role">{{ $user->role->label() }}</span>
        </span>
        <span class="client-avatar" aria-hidden="true">
            <svg width="18" height="18" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
            </svg>
        </span>
    </button>
    <div class="client-profile-dropdown" id="profileDropdown" role="menu" hidden>
        <a href="{{ route('client.profile.edit') }}" class="client-profile-dropdown-item" role="menuitem">Edit Profile</a>
        <a href="{{ route('client.profile.password') }}" class="client-profile-dropdown-item" role="menuitem">Change Password</a>
        <form method="POST" action="{{ route('logout') }}" class="client-profile-dropdown-form" role="none">
            @csrf
            <button type="submit" class="client-profile-dropdown-item client-profile-dropdown-logout" role="menuitem">
                Logout
            </button>
        </form>
    </div>
</div>

@once
@push('scripts')
<script>
(function () {
    const btn = document.getElementById('profileMenuBtn');
    const menu = document.getElementById('profileDropdown');
    if (!btn || !menu) return;

    function closeMenu() {
        menu.hidden = true;
        btn.setAttribute('aria-expanded', 'false');
    }

    function openMenu() {
        menu.hidden = false;
        btn.setAttribute('aria-expanded', 'true');
    }

    function toggleMenu() {
        if (menu.hidden) openMenu();
        else closeMenu();
    }

    btn.addEventListener('click', (e) => {
        e.stopPropagation();
        toggleMenu();
    });

    document.addEventListener('click', (e) => {
        if (!menu.hidden && !btn.contains(e.target) && !menu.contains(e.target)) {
            closeMenu();
        }
    });

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') closeMenu();
    });

    menu.querySelectorAll('a, button[type="submit"]').forEach((el) => {
        el.addEventListener('click', () => closeMenu());
    });
})();
</script>
@endpush
@endonce
