---
/**
 * LanguageSwitcherDropdown
 * Desktop language selector following the ThemeSelectorDropdown pattern.
 * Navigates to the equivalent page in the selected locale.
 */
import { cn } from '@/lib/cn';
import { languages, type Locale } from '@/i18n/ui';

interface Props {
  currentLocale?: Locale;
  class?: string;
}

const { currentLocale = 'de', class: className } = Astro.props;
const current = languages[currentLocale];
const allLanguages = Object.values(languages);
---

<div class={cn('relative lang-dropdown-wrapper', className)} data-current-locale={currentLocale}>
  <!-- Trigger -->
  <button
    type="button"
    id="lang-dropdown-trigger"
    aria-haspopup="true"
    aria-expanded="false"
    aria-label="Select language"
    class={cn(
      'inline-flex items-center gap-1.5 rounded-full border border-border-strong px-2.5 py-1.5',
      'text-foreground-muted hover:text-foreground hover:bg-secondary',
      'transition-colors duration-(--transition-fast)',
      'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2'
    )}
  >
    <span class="text-xs font-semibold tracking-wide uppercase">{current.code}</span>
    <svg
      class="lang-chevron h-3 w-3 shrink-0 transition-transform duration-200"
      xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
      fill="none" stroke="currentColor" stroke-width="2.5"
      stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6"/>
    </svg>
  </button>

  <!-- Dropdown panel -->
  <div
    id="lang-dropdown-panel"
    role="listbox"
    aria-label="Language"
    class={cn(
      'absolute right-0 top-full mt-2 z-50',
      'w-40 rounded-xl border border-border bg-background shadow-lg',
      'p-1.5',
      'hidden'
    )}
  >
    {allLanguages.map((lang) => (
      <button
        type="button"
        role="option"
        class="lang-option w-full flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-left
               hover:bg-secondary transition-colors duration-(--transition-fast)
               focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
        data-locale={lang.code}
        aria-selected={lang.code === currentLocale ? 'true' : 'false'}
      >
        <span class="text-xs font-bold tracking-wide uppercase text-foreground-muted">{lang.code}</span>
        <span class="font-medium text-foreground">{lang.name}</span>
      </button>
    ))}
  </div>
</div>

<style>
  .lang-option[aria-selected="true"] {
    background-color: var(--color-secondary);
  }
  .lang-option[aria-selected="true"] span:last-child {
    color: var(--color-brand-500);
    font-weight: 600;
  }
</style>

<script>
  function getLocalePath(targetLocale: string, currentPath: string): string {
    const nonDefault = ['fr', 'it', 'en'];
    let basePath = currentPath;
    for (const loc of nonDefault) {
      if (currentPath.startsWith(`/${loc}/`)) {
        basePath = currentPath.slice(loc.length + 1);
        break;
      } else if (currentPath === `/${loc}`) {
        basePath = '/';
        break;
      }
    }
    if (targetLocale === 'de') return basePath || '/';
    return basePath === '/' ? `/${targetLocale}/` : `/${targetLocale}${basePath}`;
  }

  function closeLangDropdown() {
    const panel = document.getElementById('lang-dropdown-panel');
    const trigger = document.getElementById('lang-dropdown-trigger');
    panel?.classList.add('hidden');
    trigger?.setAttribute('aria-expanded', 'false');
    trigger?.querySelector('.lang-chevron')?.classList.remove('rotate-180');
  }

  function initLangDropdown() {
    const trigger = document.getElementById('lang-dropdown-trigger');
    const panel = document.getElementById('lang-dropdown-panel');
    const wrapper = trigger?.closest('.lang-dropdown-wrapper') as HTMLElement | null;
    if (!trigger || !panel || !wrapper) return;
    if (trigger.dataset.langInit) return;
    trigger.dataset.langInit = 'true';

    // Bind language option clicks
    panel.querySelectorAll<HTMLButtonElement>('.lang-option').forEach((btn) => {
      btn.addEventListener('click', () => {
        const targetLocale = btn.dataset.locale!;
        const path = getLocalePath(targetLocale, window.location.pathname);
        closeLangDropdown();
        window.location.href = path;
      });
    });

    // Toggle dropdown
    trigger.addEventListener('click', (e) => {
      e.stopPropagation();
      const isOpen = !panel.classList.contains('hidden');
      if (isOpen) {
        closeLangDropdown();
      } else {
        panel.classList.remove('hidden');
        trigger.setAttribute('aria-expanded', 'true');
        trigger.querySelector('.lang-chevron')?.classList.add('rotate-180');
      }
    });

    // Close on outside click
    document.addEventListener('click', (e) => {
      if (!wrapper.contains(e.target as Node)) closeLangDropdown();
    });

    // Close on Escape
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') closeLangDropdown();
    });
  }

  initLangDropdown();
  document.addEventListener('astro:page-load', initLangDropdown);
  document.addEventListener('astro:after-swap', initLangDropdown);
</script>
