"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { DIAL_CODES, PINNED, flagEmoji, type DialCode } from "@/app/lib/dialCodes"; interface DialCodeSelectProps { /** Currently selected dial code, e.g. "+60". */ value: string; /** Called with the chosen dial code when the user selects an entry. */ onChange: (dialCode: string) => void; } const triggerClass = "rounded-xl px-2 py-3 text-sm font-semibold outline-none transition-all duration-200 flex-shrink-0 w-[92px] flex items-center justify-center gap-1 cursor-pointer"; /** PINNED entries first (in PINNED order), then the rest alphabetically by name. */ function orderedList(): DialCode[] { const pinned = PINNED .map((iso2) => DIAL_CODES.find((d) => d.iso2 === iso2)) .filter((d): d is DialCode => Boolean(d)); const rest = DIAL_CODES .filter((d) => !PINNED.includes(d.iso2)) .sort((a, b) => a.name.localeCompare(b.name)); return [...pinned, ...rest]; } const ORDERED = orderedList(); export default function DialCodeSelect({ value, onChange }: DialCodeSelectProps) { const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); // Track the chosen country so the trigger flag reflects the selection even // for shared dial codes (e.g. +1). Falls back to the first match of `value`. const [selectedIso2, setSelectedIso2] = useState(null); const rootRef = useRef(null); useEffect(() => { if (!open) return; const onDocClick = (e: MouseEvent) => { if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false); }; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; document.addEventListener("mousedown", onDocClick); document.addEventListener("keydown", onKey); return () => { document.removeEventListener("mousedown", onDocClick); document.removeEventListener("keydown", onKey); }; }, [open]); // Derive the trigger's country during render: prefer the explicitly chosen // country (so shared dial codes like +1 keep the right flag), but ignore it // once the controlled `value` no longer matches, falling back to the first // match of `value`. Deriving here avoids syncing state in an effect. const current = useMemo(() => { const chosen = DIAL_CODES.find((d) => d.iso2 === selectedIso2); if (chosen && chosen.dialCode === value) return chosen; return DIAL_CODES.find((d) => d.dialCode === value); }, [selectedIso2, value]); const items = useMemo(() => { const q = query.trim().toLowerCase(); if (!q) return ORDERED; return ORDERED.filter( (d) => d.name.toLowerCase().includes(q) || d.dialCode.includes(q), ); }, [query]); const select = (d: DialCode) => { setSelectedIso2(d.iso2); onChange(d.dialCode); setOpen(false); setQuery(""); }; return (
{open && (
setQuery(e.target.value)} className="w-full px-3 py-2 text-sm outline-none" style={{ background: "var(--bg-primary)", color: "var(--text-primary)", borderBottom: "1px solid var(--border-color)", }} />
    {items.map((d) => (
  • ))} {items.length === 0 && (
  • No matches
  • )}
)}
); }