---
import { withBase } from "../islands/base-path.ts";
import type { LocaleSwitchOption } from "../../core/types.ts";
import Icon from "../Icon.astro";

interface Props {
  options: LocaleSwitchOption[];
  label: string;
  untranslatedLabel: string;
}

const { options, label, untranslatedLabel } = Astro.props;
const current = options.find((option) => option.current);

const iconButton =
  "inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-full border border-border bg-background px-3 text-muted-foreground text-sm transition-colors hover:border-foreground hover:text-foreground";
const menuRowClass =
  "flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-start text-muted-foreground text-sm transition-colors hover:bg-muted hover:text-foreground aria-[current=true]:text-foreground";
---

{
  options.length > 1 && (
    <details class="group relative">
      <summary
        aria-label={label}
        class={`${iconButton} list-none [&::-webkit-details-marker]:hidden`}
      >
        <Icon name="globe" size={16} />
        {/* Collapses to the globe icon below `lg`, matching the search field. */}
        <span class="max-lg:hidden">{current?.label ?? label}</span>
        <Icon
          class="transition-transform group-open:rotate-180"
          name="chevron-down"
          size={14}
        />
      </summary>
      <div class="absolute end-0 z-50 mt-2 min-w-44 rounded-blume border border-border bg-background p-1 shadow-xl">
        {options.map((option) => (
          <a
            aria-current={option.current ? "true" : undefined}
            class={menuRowClass}
            href={withBase(option.href)}
            hreflang={option.code}
            lang={option.code}
          >
            <span class="flex-1">{option.label}</span>
            {option.untranslated && (
              <span class="text-muted-foreground text-xs italic">
                {untranslatedLabel}
              </span>
            )}
            {option.current && <Icon name="check" size={14} />}
          </a>
        ))}
      </div>
    </details>
  )
}
