'use client';

import { persistLocale } from '@/lib/localization/client';
import {
  localeSwitchUrl,
  locales,
  routeIdFromPathname,
  type Locale,
} from '@/lib/localization/config';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import styles from './LocalePill.module.css';

const langLabels: Record<Locale, string> = { en: 'EN', fr: 'FR', ar: 'AR' };
const langFlags: Record<Locale, string> = { en: '🇺🇸', fr: '🇫🇷', ar: '🇲🇦' };

interface Props {
  locale: Locale;
}

export function LocalePill({ locale }: Props) {
  const pathname = usePathname();
  const router = useRouter();
  const menuRef = useRef<HTMLDivElement | null>(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (!menuRef.current?.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const switchLocale = (next: Locale) => {
    setOpen(false);
    persistLocale(next);
    const routeId = routeIdFromPathname(pathname) ?? 'home';
    const target = localeSwitchUrl(new URL(window.location.href), next, routeId);
    router.push(`${target.pathname}${target.search}${target.hash}`);
  };

  const otherLocales = locales.filter((l) => l !== locale);

  return (
    <div ref={menuRef} className={styles.wrap}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={styles.button}
        aria-expanded={open}
        aria-haspopup="menu"
      >
        <span aria-hidden="true">{langFlags[locale]}</span>
        <span>{langLabels[locale]}</span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className={`${styles.chevron} ${open ? styles.chevronOpen : ''}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
        </svg>
      </button>
      {open && (
        <div className={styles.menu}>
          {otherLocales.map((l) => (
            <button
              key={l}
              type="button"
              onClick={() => switchLocale(l)}
              className={styles.option}
            >
              <span aria-hidden="true">{langFlags[l]}</span>
              <span>{langLabels[l]}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
