"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { ChevronDown, Search } from "lucide-react";

export interface Country {
  code: string;
  dial: string;
  name: string;
  flag: string;
}

export const COUNTRIES: Country[] = [
  // ── Gulf & Middle East (pinned first) ──────────────────
  { code: "SA", dial: "+966",  name: "Saudi Arabia",                flag: "🇸🇦" },
  { code: "AE", dial: "+971",  name: "UAE",                         flag: "🇦🇪" },
  { code: "KW", dial: "+965",  name: "Kuwait",                      flag: "🇰🇼" },
  { code: "QA", dial: "+974",  name: "Qatar",                       flag: "🇶🇦" },
  { code: "BH", dial: "+973",  name: "Bahrain",                     flag: "🇧🇭" },
  { code: "OM", dial: "+968",  name: "Oman",                        flag: "🇴🇲" },
  { code: "JO", dial: "+962",  name: "Jordan",                      flag: "🇯🇴" },
  { code: "LB", dial: "+961",  name: "Lebanon",                     flag: "🇱🇧" },
  { code: "IQ", dial: "+964",  name: "Iraq",                        flag: "🇮🇶" },
  { code: "SY", dial: "+963",  name: "Syria",                       flag: "🇸🇾" },
  { code: "YE", dial: "+967",  name: "Yemen",                       flag: "🇾🇪" },
  { code: "PS", dial: "+970",  name: "Palestine",                   flag: "🇵🇸" },
  // ── Africa ─────────────────────────────────────────────
  { code: "DZ", dial: "+213",  name: "Algeria",                     flag: "🇩🇿" },
  { code: "AO", dial: "+244",  name: "Angola",                      flag: "🇦🇴" },
  { code: "BJ", dial: "+229",  name: "Benin",                       flag: "🇧🇯" },
  { code: "BW", dial: "+267",  name: "Botswana",                    flag: "🇧🇼" },
  { code: "BF", dial: "+226",  name: "Burkina Faso",                flag: "🇧🇫" },
  { code: "BI", dial: "+257",  name: "Burundi",                     flag: "🇧🇮" },
  { code: "CM", dial: "+237",  name: "Cameroon",                    flag: "🇨🇲" },
  { code: "CV", dial: "+238",  name: "Cape Verde",                  flag: "🇨🇻" },
  { code: "CF", dial: "+236",  name: "Central African Republic",    flag: "🇨🇫" },
  { code: "TD", dial: "+235",  name: "Chad",                        flag: "🇹🇩" },
  { code: "KM", dial: "+269",  name: "Comoros",                     flag: "🇰🇲" },
  { code: "CG", dial: "+242",  name: "Congo",                       flag: "🇨🇬" },
  { code: "CD", dial: "+243",  name: "Congo (DRC)",                 flag: "🇨🇩" },
  { code: "CI", dial: "+225",  name: "Côte d'Ivoire",               flag: "🇨🇮" },
  { code: "DJ", dial: "+253",  name: "Djibouti",                    flag: "🇩🇯" },
  { code: "EG", dial: "+20",   name: "Egypt",                       flag: "🇪🇬" },
  { code: "GQ", dial: "+240",  name: "Equatorial Guinea",           flag: "🇬🇶" },
  { code: "ER", dial: "+291",  name: "Eritrea",                     flag: "🇪🇷" },
  { code: "SZ", dial: "+268",  name: "Eswatini",                    flag: "🇸🇿" },
  { code: "ET", dial: "+251",  name: "Ethiopia",                    flag: "🇪🇹" },
  { code: "GA", dial: "+241",  name: "Gabon",                       flag: "🇬🇦" },
  { code: "GM", dial: "+220",  name: "Gambia",                      flag: "🇬🇲" },
  { code: "GH", dial: "+233",  name: "Ghana",                       flag: "🇬🇭" },
  { code: "GN", dial: "+224",  name: "Guinea",                      flag: "🇬🇳" },
  { code: "GW", dial: "+245",  name: "Guinea-Bissau",               flag: "🇬🇼" },
  { code: "KE", dial: "+254",  name: "Kenya",                       flag: "🇰🇪" },
  { code: "LS", dial: "+266",  name: "Lesotho",                     flag: "🇱🇸" },
  { code: "LR", dial: "+231",  name: "Liberia",                     flag: "🇱🇷" },
  { code: "LY", dial: "+218",  name: "Libya",                       flag: "🇱🇾" },
  { code: "MG", dial: "+261",  name: "Madagascar",                  flag: "🇲🇬" },
  { code: "MW", dial: "+265",  name: "Malawi",                      flag: "🇲🇼" },
  { code: "ML", dial: "+223",  name: "Mali",                        flag: "🇲🇱" },
  { code: "MR", dial: "+222",  name: "Mauritania",                  flag: "🇲🇷" },
  { code: "MU", dial: "+230",  name: "Mauritius",                   flag: "🇲🇺" },
  { code: "MA", dial: "+212",  name: "Morocco",                     flag: "🇲🇦" },
  { code: "MZ", dial: "+258",  name: "Mozambique",                  flag: "🇲🇿" },
  { code: "NA", dial: "+264",  name: "Namibia",                     flag: "🇳🇦" },
  { code: "NE", dial: "+227",  name: "Niger",                       flag: "🇳🇪" },
  { code: "NG", dial: "+234",  name: "Nigeria",                     flag: "🇳🇬" },
  { code: "RW", dial: "+250",  name: "Rwanda",                      flag: "🇷🇼" },
  { code: "ST", dial: "+239",  name: "São Tomé & Príncipe",         flag: "🇸🇹" },
  { code: "SN", dial: "+221",  name: "Senegal",                     flag: "🇸🇳" },
  { code: "SC", dial: "+248",  name: "Seychelles",                  flag: "🇸🇨" },
  { code: "SL", dial: "+232",  name: "Sierra Leone",                flag: "🇸🇱" },
  { code: "SO", dial: "+252",  name: "Somalia",                     flag: "🇸🇴" },
  { code: "ZA", dial: "+27",   name: "South Africa",                flag: "🇿🇦" },
  { code: "SS", dial: "+211",  name: "South Sudan",                 flag: "🇸🇸" },
  { code: "SD", dial: "+249",  name: "Sudan",                       flag: "🇸🇩" },
  { code: "TZ", dial: "+255",  name: "Tanzania",                    flag: "🇹🇿" },
  { code: "TG", dial: "+228",  name: "Togo",                        flag: "🇹🇬" },
  { code: "TN", dial: "+216",  name: "Tunisia",                     flag: "🇹🇳" },
  { code: "UG", dial: "+256",  name: "Uganda",                      flag: "🇺🇬" },
  { code: "ZM", dial: "+260",  name: "Zambia",                      flag: "🇿🇲" },
  { code: "ZW", dial: "+263",  name: "Zimbabwe",                    flag: "🇿🇼" },
  // ── Americas ───────────────────────────────────────────
  { code: "AG", dial: "+1268", name: "Antigua & Barbuda",           flag: "🇦🇬" },
  { code: "AR", dial: "+54",   name: "Argentina",                   flag: "🇦🇷" },
  { code: "BS", dial: "+1242", name: "Bahamas",                     flag: "🇧🇸" },
  { code: "BB", dial: "+1246", name: "Barbados",                    flag: "🇧🇧" },
  { code: "BZ", dial: "+501",  name: "Belize",                      flag: "🇧🇿" },
  { code: "BO", dial: "+591",  name: "Bolivia",                     flag: "🇧🇴" },
  { code: "BR", dial: "+55",   name: "Brazil",                      flag: "🇧🇷" },
  { code: "CA", dial: "+1",    name: "Canada",                      flag: "🇨🇦" },
  { code: "CL", dial: "+56",   name: "Chile",                       flag: "🇨🇱" },
  { code: "CO", dial: "+57",   name: "Colombia",                    flag: "🇨🇴" },
  { code: "CR", dial: "+506",  name: "Costa Rica",                  flag: "🇨🇷" },
  { code: "CU", dial: "+53",   name: "Cuba",                        flag: "🇨🇺" },
  { code: "DM", dial: "+1767", name: "Dominica",                    flag: "🇩🇲" },
  { code: "DO", dial: "+1809", name: "Dominican Republic",          flag: "🇩🇴" },
  { code: "EC", dial: "+593",  name: "Ecuador",                     flag: "🇪🇨" },
  { code: "SV", dial: "+503",  name: "El Salvador",                 flag: "🇸🇻" },
  { code: "GD", dial: "+1473", name: "Grenada",                     flag: "🇬🇩" },
  { code: "GT", dial: "+502",  name: "Guatemala",                   flag: "🇬🇹" },
  { code: "GY", dial: "+592",  name: "Guyana",                      flag: "🇬🇾" },
  { code: "HT", dial: "+509",  name: "Haiti",                       flag: "🇭🇹" },
  { code: "HN", dial: "+504",  name: "Honduras",                    flag: "🇭🇳" },
  { code: "JM", dial: "+1876", name: "Jamaica",                     flag: "🇯🇲" },
  { code: "MX", dial: "+52",   name: "Mexico",                      flag: "🇲🇽" },
  { code: "NI", dial: "+505",  name: "Nicaragua",                   flag: "🇳🇮" },
  { code: "PA", dial: "+507",  name: "Panama",                      flag: "🇵🇦" },
  { code: "PY", dial: "+595",  name: "Paraguay",                    flag: "🇵🇾" },
  { code: "PE", dial: "+51",   name: "Peru",                        flag: "🇵🇪" },
  { code: "KN", dial: "+1869", name: "Saint Kitts & Nevis",         flag: "🇰🇳" },
  { code: "LC", dial: "+1758", name: "Saint Lucia",                 flag: "🇱🇨" },
  { code: "VC", dial: "+1784", name: "Saint Vincent & Grenadines",  flag: "🇻🇨" },
  { code: "SR", dial: "+597",  name: "Suriname",                    flag: "🇸🇷" },
  { code: "TT", dial: "+1868", name: "Trinidad & Tobago",           flag: "🇹🇹" },
  { code: "US", dial: "+1",    name: "United States",               flag: "🇺🇸" },
  { code: "UY", dial: "+598",  name: "Uruguay",                     flag: "🇺🇾" },
  { code: "VE", dial: "+58",   name: "Venezuela",                   flag: "🇻🇪" },
  // ── Asia & Pacific ─────────────────────────────────────
  { code: "AF", dial: "+93",   name: "Afghanistan",                 flag: "🇦🇫" },
  { code: "AM", dial: "+374",  name: "Armenia",                     flag: "🇦🇲" },
  { code: "AZ", dial: "+994",  name: "Azerbaijan",                  flag: "🇦🇿" },
  { code: "BD", dial: "+880",  name: "Bangladesh",                  flag: "🇧🇩" },
  { code: "BT", dial: "+975",  name: "Bhutan",                      flag: "🇧🇹" },
  { code: "BN", dial: "+673",  name: "Brunei",                      flag: "🇧🇳" },
  { code: "KH", dial: "+855",  name: "Cambodia",                    flag: "🇰🇭" },
  { code: "CN", dial: "+86",   name: "China",                       flag: "🇨🇳" },
  { code: "CY", dial: "+357",  name: "Cyprus",                      flag: "🇨🇾" },
  { code: "GE", dial: "+995",  name: "Georgia",                     flag: "🇬🇪" },
  { code: "IN", dial: "+91",   name: "India",                       flag: "🇮🇳" },
  { code: "ID", dial: "+62",   name: "Indonesia",                   flag: "🇮🇩" },
  { code: "IR", dial: "+98",   name: "Iran",                        flag: "🇮🇷" },
  { code: "IL", dial: "+972",  name: "Israel",                      flag: "🇮🇱" },
  { code: "JP", dial: "+81",   name: "Japan",                       flag: "🇯🇵" },
  { code: "KZ", dial: "+7",    name: "Kazakhstan",                  flag: "🇰🇿" },
  { code: "KG", dial: "+996",  name: "Kyrgyzstan",                  flag: "🇰🇬" },
  { code: "LA", dial: "+856",  name: "Laos",                        flag: "🇱🇦" },
  { code: "MO", dial: "+853",  name: "Macao",                       flag: "🇲🇴" },
  { code: "MY", dial: "+60",   name: "Malaysia",                    flag: "🇲🇾" },
  { code: "MV", dial: "+960",  name: "Maldives",                    flag: "🇲🇻" },
  { code: "MN", dial: "+976",  name: "Mongolia",                    flag: "🇲🇳" },
  { code: "MM", dial: "+95",   name: "Myanmar",                     flag: "🇲🇲" },
  { code: "NP", dial: "+977",  name: "Nepal",                       flag: "🇳🇵" },
  { code: "KP", dial: "+850",  name: "North Korea",                 flag: "🇰🇵" },
  { code: "PK", dial: "+92",   name: "Pakistan",                    flag: "🇵🇰" },
  { code: "PW", dial: "+680",  name: "Palau",                       flag: "🇵🇼" },
  { code: "PH", dial: "+63",   name: "Philippines",                 flag: "🇵🇭" },
  { code: "SG", dial: "+65",   name: "Singapore",                   flag: "🇸🇬" },
  { code: "LK", dial: "+94",   name: "Sri Lanka",                   flag: "🇱🇰" },
  { code: "KR", dial: "+82",   name: "South Korea",                 flag: "🇰🇷" },
  { code: "TW", dial: "+886",  name: "Taiwan",                      flag: "🇹🇼" },
  { code: "TJ", dial: "+992",  name: "Tajikistan",                  flag: "🇹🇯" },
  { code: "TH", dial: "+66",   name: "Thailand",                    flag: "🇹🇭" },
  { code: "TL", dial: "+670",  name: "Timor-Leste",                 flag: "🇹🇱" },
  { code: "TM", dial: "+993",  name: "Turkmenistan",                flag: "🇹🇲" },
  { code: "UZ", dial: "+998",  name: "Uzbekistan",                  flag: "🇺🇿" },
  { code: "VN", dial: "+84",   name: "Vietnam",                     flag: "🇻🇳" },
  { code: "AU", dial: "+61",   name: "Australia",                   flag: "🇦🇺" },
  { code: "FJ", dial: "+679",  name: "Fiji",                        flag: "🇫🇯" },
  { code: "KI", dial: "+686",  name: "Kiribati",                    flag: "🇰🇮" },
  { code: "MH", dial: "+692",  name: "Marshall Islands",            flag: "🇲🇭" },
  { code: "FM", dial: "+691",  name: "Micronesia",                  flag: "🇫🇲" },
  { code: "NR", dial: "+674",  name: "Nauru",                       flag: "🇳🇷" },
  { code: "NZ", dial: "+64",   name: "New Zealand",                 flag: "🇳🇿" },
  { code: "PG", dial: "+675",  name: "Papua New Guinea",            flag: "🇵🇬" },
  { code: "WS", dial: "+685",  name: "Samoa",                       flag: "🇼🇸" },
  { code: "SB", dial: "+677",  name: "Solomon Islands",             flag: "🇸🇧" },
  { code: "TO", dial: "+676",  name: "Tonga",                       flag: "🇹🇴" },
  { code: "TV", dial: "+688",  name: "Tuvalu",                      flag: "🇹🇻" },
  { code: "VU", dial: "+678",  name: "Vanuatu",                     flag: "🇻🇺" },
  // ── Europe ─────────────────────────────────────────────
  { code: "AL", dial: "+355",  name: "Albania",                     flag: "🇦🇱" },
  { code: "AD", dial: "+376",  name: "Andorra",                     flag: "🇦🇩" },
  { code: "AT", dial: "+43",   name: "Austria",                     flag: "🇦🇹" },
  { code: "BY", dial: "+375",  name: "Belarus",                     flag: "🇧🇾" },
  { code: "BE", dial: "+32",   name: "Belgium",                     flag: "🇧🇪" },
  { code: "BA", dial: "+387",  name: "Bosnia & Herzegovina",        flag: "🇧🇦" },
  { code: "BG", dial: "+359",  name: "Bulgaria",                    flag: "🇧🇬" },
  { code: "HR", dial: "+385",  name: "Croatia",                     flag: "🇭🇷" },
  { code: "CZ", dial: "+420",  name: "Czech Republic",              flag: "🇨🇿" },
  { code: "DK", dial: "+45",   name: "Denmark",                     flag: "🇩🇰" },
  { code: "EE", dial: "+372",  name: "Estonia",                     flag: "🇪🇪" },
  { code: "FI", dial: "+358",  name: "Finland",                     flag: "🇫🇮" },
  { code: "FR", dial: "+33",   name: "France",                      flag: "🇫🇷" },
  { code: "DE", dial: "+49",   name: "Germany",                     flag: "🇩🇪" },
  { code: "GR", dial: "+30",   name: "Greece",                      flag: "🇬🇷" },
  { code: "HU", dial: "+36",   name: "Hungary",                     flag: "🇭🇺" },
  { code: "IS", dial: "+354",  name: "Iceland",                     flag: "🇮🇸" },
  { code: "IE", dial: "+353",  name: "Ireland",                     flag: "🇮🇪" },
  { code: "IT", dial: "+39",   name: "Italy",                       flag: "🇮🇹" },
  { code: "XK", dial: "+383",  name: "Kosovo",                      flag: "🇽🇰" },
  { code: "LV", dial: "+371",  name: "Latvia",                      flag: "🇱🇻" },
  { code: "LI", dial: "+423",  name: "Liechtenstein",               flag: "🇱🇮" },
  { code: "LT", dial: "+370",  name: "Lithuania",                   flag: "🇱🇹" },
  { code: "LU", dial: "+352",  name: "Luxembourg",                  flag: "🇱🇺" },
  { code: "MT", dial: "+356",  name: "Malta",                       flag: "🇲🇹" },
  { code: "MD", dial: "+373",  name: "Moldova",                     flag: "🇲🇩" },
  { code: "MC", dial: "+377",  name: "Monaco",                      flag: "🇲🇨" },
  { code: "ME", dial: "+382",  name: "Montenegro",                  flag: "🇲🇪" },
  { code: "NL", dial: "+31",   name: "Netherlands",                 flag: "🇳🇱" },
  { code: "MK", dial: "+389",  name: "North Macedonia",             flag: "🇲🇰" },
  { code: "NO", dial: "+47",   name: "Norway",                      flag: "🇳🇴" },
  { code: "PL", dial: "+48",   name: "Poland",                      flag: "🇵🇱" },
  { code: "PT", dial: "+351",  name: "Portugal",                    flag: "🇵🇹" },
  { code: "RO", dial: "+40",   name: "Romania",                     flag: "🇷🇴" },
  { code: "RU", dial: "+7",    name: "Russia",                      flag: "🇷🇺" },
  { code: "SM", dial: "+378",  name: "San Marino",                  flag: "🇸🇲" },
  { code: "RS", dial: "+381",  name: "Serbia",                      flag: "🇷🇸" },
  { code: "SK", dial: "+421",  name: "Slovakia",                    flag: "🇸🇰" },
  { code: "SI", dial: "+386",  name: "Slovenia",                    flag: "🇸🇮" },
  { code: "ES", dial: "+34",   name: "Spain",                       flag: "🇪🇸" },
  { code: "SE", dial: "+46",   name: "Sweden",                      flag: "🇸🇪" },
  { code: "CH", dial: "+41",   name: "Switzerland",                 flag: "🇨🇭" },
  { code: "TR", dial: "+90",   name: "Turkey",                      flag: "🇹🇷" },
  { code: "UA", dial: "+380",  name: "Ukraine",                     flag: "🇺🇦" },
  { code: "GB", dial: "+44",   name: "United Kingdom",              flag: "🇬🇧" },
  { code: "VA", dial: "+379",  name: "Vatican City",                flag: "🇻🇦" },
];

function parseValue(val: string): { country: Country; local: string } {
  const def = COUNTRIES[0];
  if (!val) return { country: def, local: "" };
  const sorted = [...COUNTRIES].sort((a, b) => b.dial.length - a.dial.length);
  for (const c of sorted) {
    if (val.startsWith(c.dial)) return { country: c, local: val.slice(c.dial.length) };
  }
  return { country: def, local: val };
}

interface PhoneInputProps {
  value: string;
  onChange: (val: string) => void;
  placeholder?: string;
  className?: string;
  height?: string;
  variant?: "booking" | "dashboard";
  autoFocus?: boolean;
  disabled?: boolean;
}

export default function PhoneInput({
  value,
  onChange,
  placeholder = "5X XXX XXXX",
  className = "",
  height = "h-[52px]",
  variant = "booking",
  autoFocus,
  disabled,
}: PhoneInputProps) {
  const { country: initCountry, local: initLocal } = parseValue(value);
  const [country, setCountry] = useState<Country>(initCountry);
  const [local, setLocal]     = useState(initLocal);
  const [open, setOpen]       = useState(false);
  const [search, setSearch]   = useState("");
  // For fixed-position dropdown
  const [dropPos, setDropPos] = useState({ top: 0, left: 0, width: 280 });

  const btnRef    = useRef<HTMLButtonElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const wrapRef   = useRef<HTMLDivElement>(null);

  // Sync outward
  useEffect(() => {
    onChange(local.trim() ? `${country.dial}${local.trim()}` : "");
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [country, local]);

  // Calculate fixed position when opening
  const openDropdown = useCallback(() => {
    if (!btnRef.current) return;
    const rect = btnRef.current.getBoundingClientRect();
    setDropPos({
      top: rect.bottom + 6,
      left: rect.left,
      width: Math.max(280, rect.width + 120),
    });
    setOpen(true);
    setSearch("");
  }, []);

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      const target = e.target as Node;
      if (wrapRef.current?.contains(target)) return;
      // Check if click is inside the fixed dropdown (by class)
      const drop = document.getElementById("phone-country-drop");
      if (drop?.contains(target)) return;
      setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  // Focus search after open
  useEffect(() => {
    if (open) setTimeout(() => searchRef.current?.focus(), 40);
  }, [open]);

  // Reposition on scroll/resize
  useEffect(() => {
    if (!open) return;
    const reposition = () => {
      if (!btnRef.current) return;
      const rect = btnRef.current.getBoundingClientRect();
      setDropPos({ top: rect.bottom + 6, left: rect.left, width: Math.max(280, rect.width + 120) });
    };
    window.addEventListener("scroll", reposition, true);
    window.addEventListener("resize", reposition);
    return () => { window.removeEventListener("scroll", reposition, true); window.removeEventListener("resize", reposition); };
  }, [open]);

  const filtered = COUNTRIES.filter(
    (c) =>
      c.name.toLowerCase().includes(search.toLowerCase()) ||
      c.dial.includes(search) ||
      c.code.toLowerCase().includes(search.toLowerCase())
  );

  const isBooking = variant === "booking";

  const borderBase = isBooking
    ? "border-[#e2e8f0] focus-within:border-[#4f46e5]"
    : "border-gray-200 focus-within:border-[#6366f1]";

  const inputCls = isBooking
    ? "text-[#0f172a] placeholder-[#cbd5e1] bg-white"
    : "text-gray-800 placeholder-gray-300 bg-white";

  return (
    <div ref={wrapRef} className={`relative flex w-full rounded-xl border-[1.5px] transition-colors duration-150 overflow-hidden ${borderBase} ${className}`}>
      {/* Country button */}
      <button
        ref={btnRef}
        type="button"
        onClick={openDropdown}
        disabled={disabled}
        className={`
          flex items-center gap-1.5 px-3 shrink-0 border-r border-[#e2e8f0]
          ${isBooking ? "bg-[#f8fafc] hover:bg-[#f1f5f9]" : "bg-gray-50 hover:bg-gray-100"}
          transition-colors disabled:opacity-50 disabled:cursor-not-allowed
          ${height}
        `}
      >
        <span className="text-xl leading-none">{country.flag}</span>
        <span className={`font-semibold text-[13px] ${isBooking ? "text-[#475569]" : "text-gray-600"}`}>
          {country.dial}
        </span>
        <ChevronDown
          size={12}
          className={`${isBooking ? "text-[#94a3b8]" : "text-gray-400"} transition-transform duration-200 ${open ? "rotate-180" : ""}`}
        />
      </button>

      {/* Phone input */}
      <input
        type="tel"
        value={local}
        onChange={(e) => setLocal(e.target.value.replace(/[^\d\s\-()+]/g, ""))}
        placeholder={placeholder}
        autoFocus={autoFocus}
        disabled={disabled}
        style={{ outline: "none" }}
        className={`flex-1 px-4 text-[15px] font-medium ${inputCls} disabled:opacity-50 ${height}`}
      />

      {/* Dropdown — rendered via fixed positioning to escape any overflow:hidden */}
      {open && (
        <div
          id="phone-country-drop"
          style={{ position: "fixed", top: dropPos.top, left: dropPos.left, width: dropPos.width, zIndex: 99999 }}
          className="bg-white rounded-2xl shadow-2xl shadow-black/12 border border-[#e2e8f0] overflow-hidden"
        >
          {/* Search */}
          <div className="p-2 border-b border-[#f1f5f9]">
            <div className="flex items-center gap-2 bg-[#f8fafc] rounded-xl px-3 py-2">
              <Search size={13} className="text-[#94a3b8] shrink-0" />
              <input
                ref={searchRef}
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search country or code…"
                style={{ outline: "none" }}
                className="flex-1 bg-transparent text-[13px] text-[#0f172a] placeholder-[#94a3b8] font-medium"
              />
              {search && (
                <button onClick={() => setSearch("")} className="text-[#94a3b8] hover:text-[#475569] text-xs">✕</button>
              )}
            </div>
          </div>

          {/* List */}
          <div className="max-h-60 overflow-y-auto py-1">
            {filtered.length === 0 ? (
              <div className="text-center py-6 text-[12px] text-[#94a3b8]">No results for &quot;{search}&quot;</div>
            ) : (
              filtered.map((c) => (
                <button
                  key={c.code}
                  type="button"
                  onClick={() => { setCountry(c); setOpen(false); setSearch(""); }}
                  className={`w-full flex items-center gap-3 px-4 py-2.5 hover:bg-[#f8fafc] transition-colors text-left ${
                    c.code === country.code ? "bg-[#eef2ff]" : ""
                  }`}
                >
                  <span className="text-lg leading-none w-6 text-center">{c.flag}</span>
                  <span className="flex-1 text-[13px] font-medium text-[#0f172a] truncate">{c.name}</span>
                  <span className="text-[12px] font-bold text-[#94a3b8] shrink-0">{c.dial}</span>
                  {c.code === country.code && (
                    <span className="w-1.5 h-1.5 rounded-full bg-[#4f46e5] shrink-0" />
                  )}
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
