{{-- Pan-African currency picker, persists to localStorage, fires `currency-changed`.
     The dropdown is teleported to <body> and positioned fixed, so no ancestor's
     overflow-hidden or stacking context can clip it. --}}
<div x-data="{
        open: false,
        code: window.MW.code(),
        top: 0,
        right: 0,
        place() {
            const r = $refs.trigger.getBoundingClientRect();
            this.top = r.bottom + 8;
            this.right = window.innerWidth - r.right;
        },
        toggle() { this.open = !this.open; if (this.open) this.place(); },
     }"
     @currency-changed.window="code = $event.detail.code"
     @click.outside="open = false"
     @keydown.escape.window="open = false"
     @scroll.window="open = false"
     class="relative inline-block">
    <button x-ref="trigger" type="button" @click="toggle()"
            class="flex items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-bold text-navy-800 shadow-brand ring-1 ring-navy-100 transition hover:ring-wise-300">
        <x-icon name="globe" class="h-4 w-4 text-wise-600" />
        <span x-text="code"></span>
        <x-icon name="chevron-down" class="h-3.5 w-3.5 text-navy-400 transition-transform" x-bind:class="open && 'rotate-180'" />
    </button>

    <template x-teleport="body">
        <div x-cloak x-show="open"
             x-transition:enter="transition ease-out duration-150" x-transition:enter-start="opacity-0 -translate-y-1" x-transition:enter-end="opacity-100 translate-y-0"
             :style="`position:fixed; top:${top}px; right:${right}px; z-index:95;`"
             class="w-56 rounded-2xl bg-white p-2 shadow-brand-lg ring-1 ring-navy-100">
            <p class="px-3 pb-1 pt-1.5 text-[10px] font-bold uppercase tracking-[0.18em] text-navy-400">I think in…</p>
            <template x-for="(meta, c) in window.MW.currencies" :key="c">
                <button type="button" @click="window.MW.setCurrency(c); open = false"
                        class="flex w-full items-center justify-between rounded-xl px-3 py-2 text-left text-sm transition hover:bg-wise-50"
                        :class="code === c && 'bg-wise-50'">
                    <span>
                        <span class="block font-bold text-navy-900" x-text="c"></span>
                        <span class="text-xs text-navy-500" x-text="meta.name"></span>
                    </span>
                    <svg x-show="code === c" class="h-4 w-4 text-wise-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                </button>
            </template>
        </div>
    </template>
</div>
