"use client";

import Image from "next/image";
import Link from "next/link";
import { Bell, ChevronDown, Gift, Globe2, Heart, LifeBuoy, LogOut, MapPin, Menu, Search, User, UserRound, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { CategoryIcon } from "@/components/shared/category-icon";
import { pickLocalizedText } from "@/lib/utils/i18n";
import { useAuth } from "@/providers/auth-provider";
import { useCategoriesQuery, useCountriesQuery, useCouponsQuery, useLanguagesQuery, usePublicSettingsQuery, useStoresQuery } from "@/hooks/queries/api-hooks";
import { useLocale } from "@/providers/locale-provider";

const links = [
  { href: "/", labelAr: "الرئيسية", labelEn: "Home" },
  { href: "/coupons", labelAr: "الكوبونات", labelEn: "Coupons" },
  { href: "/stores", labelAr: "المتاجر", labelEn: "Stores" },
  { href: "/cashback", labelAr: "كاش باك", labelEn: "Cashback" },
];

function toFlagEmoji(isoCode?: string | null) {
  if (!isoCode || isoCode.length < 2) {
    return "";
  }

  const code = isoCode.slice(0, 2).toUpperCase();
  return code.replace(/./g, (char) => String.fromCodePoint(127397 + char.charCodeAt(0)));
}

function resolveFlagUrl(flag?: string | null): string | null {
  const value = typeof flag === "string" ? flag.trim() : "";
  if (!value) {
    return null;
  }

  if (value.startsWith("http://") || value.startsWith("https://")) {
    return value;
  }

  const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/+$/, "") || "";
  const backendPublicBase = apiBaseUrl.includes("/api")
    ? apiBaseUrl.slice(0, apiBaseUrl.indexOf("/api"))
    : apiBaseUrl;

  const normalizedValue = value.replace(/^\/+/, "");
  const normalizedPath = normalizedValue.startsWith("flags/") && normalizedValue.endsWith(".png")
    ? normalizedValue.replace(/\.png$/i, ".webp")
    : normalizedValue;
  const normalized = `/${normalizedPath}`;
  return backendPublicBase ? `${backendPublicBase}${normalized}` : normalized;
}

function countryLabel(country: { name_ar: string; name_en: string }, isArabic: boolean) {
  return isArabic ? country.name_ar : country.name_en;
}

function findSetting(settings: Array<{ key: string; value: string | null }>, key: string): string {
  return settings.find((item) => item.key === key)?.value?.trim() || "";
}

export function MainHeader() {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [categoriesOpen, setCategoriesOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [quickSearchOpen, setQuickSearchOpen] = useState(false);
  const [countryMenuOpen, setCountryMenuOpen] = useState(false);
  const [mobileCountryMenuOpen, setMobileCountryMenuOpen] = useState(false);
  const quickSearchRef = useRef<HTMLDivElement | null>(null);
  const countryMenuDesktopRef = useRef<HTMLDivElement | null>(null);
  const countryMenuMobileRef = useRef<HTMLDivElement | null>(null);

  const router = useRouter();
  const { isAuthenticated, logout } = useAuth();
  const { locale, setLocale, selectedCountryId, setSelectedCountryId } = useLocale();
  const isClient = useSyncExternalStore(
    () => () => {},
    () => true,
    () => false,
  );
  const effectiveLocale = isClient ? locale : "ar";
  const isArabic = effectiveLocale === "ar";

  const categoriesQuery = useCategoriesQuery({ per_page: 80, country_id: selectedCountryId || undefined });
  const countriesQuery = useCountriesQuery();
  const languagesQuery = useLanguagesQuery();
  const publicSettingsQuery = usePublicSettingsQuery(["app_logo_url", "app_name_ar", "app_name_en"]);
  const storesQuery = useStoresQuery({ per_page: 100, country_id: selectedCountryId || undefined, sort: "sort_order" });
  const couponsQuery = useCouponsQuery({ per_page: 100, country_id: selectedCountryId || undefined, sort: "latest" });

  const categories = useMemo(() => categoriesQuery.data?.items || [], [categoriesQuery.data?.items]);

  const columns = useMemo(() => {
    if (categories.length === 0) {
      return [] as Array<typeof categories>;
    }

    const chunk = Math.ceil(categories.length / 4);
    return Array.from({ length: 4 }, (_, index) => categories.slice(index * chunk, (index + 1) * chunk)).filter((group) => group.length > 0);
  }, [categories]);

  const couponsCountByCategory = useMemo(() => {
    const counts: Record<number, number> = {};
    const storeCategoryById = new Map<number, number>();

    (storesQuery.data?.items || []).forEach((store) => {
      if (store.id && store.category_id) {
        storeCategoryById.set(store.id, store.category_id);
      }
    });

    (couponsQuery.data?.items || []).forEach((coupon) => {
      const categoryId = storeCategoryById.get(coupon.store_id);
      if (!categoryId) {
        return;
      }
      counts[categoryId] = (counts[categoryId] || 0) + 1;
    });

    return counts;
  }, [storesQuery.data?.items, couponsQuery.data?.items]);

  const selectedLanguage = useMemo(() => {
    return (languagesQuery.data || []).find((language) => language.code === effectiveLocale) || null;
  }, [effectiveLocale, languagesQuery.data]);

  const branding = useMemo(() => {
    const settings = publicSettingsQuery.data || [];
    return {
      logoUrl: findSetting(settings, "app_logo_url"),
      nameAr: findSetting(settings, "app_name_ar") || "وفرلي كوبون",
      nameEn: findSetting(settings, "app_name_en") || "Waffarly Coupon",
    };
  }, [publicSettingsQuery.data]);

  const selectedCountry = useMemo(
    () => (countriesQuery.data || []).find((country) => country.id === selectedCountryId) || null,
    [countriesQuery.data, selectedCountryId],
  );

  const selectedCountryFlag = selectedCountry ? toFlagEmoji(selectedCountry.iso_code) : "";

  const normalizedQuery = query.trim().toLowerCase();

  const quickStoreResults = useMemo(() => {
    if (!normalizedQuery) {
      return [];
    }

    return (storesQuery.data?.items || [])
      .filter((store) => {
        const ar = (store.name_ar || "").toLowerCase();
        const en = (store.name_en || "").toLowerCase();
        return ar.includes(normalizedQuery) || en.includes(normalizedQuery);
      })
      .slice(0, 6);
  }, [normalizedQuery, storesQuery.data?.items]);

  const quickCouponResults = useMemo(() => {
    if (!normalizedQuery) {
      return [];
    }

    return (couponsQuery.data?.items || [])
      .filter((coupon) => {
        const ar = (coupon.title_ar || "").toLowerCase();
        const en = (coupon.title_en || "").toLowerCase();
        const code = (coupon.code || "").toLowerCase();
        return ar.includes(normalizedQuery) || en.includes(normalizedQuery) || code.includes(normalizedQuery);
      })
      .slice(0, 6);
  }, [normalizedQuery, couponsQuery.data?.items]);

  useEffect(() => {
    const onOutsideClick = (event: MouseEvent) => {
      if (quickSearchRef.current && !quickSearchRef.current.contains(event.target as Node)) {
        setQuickSearchOpen(false);
      }

      const clickedInsideDesktop = countryMenuDesktopRef.current?.contains(event.target as Node);
      const clickedInsideMobile = countryMenuMobileRef.current?.contains(event.target as Node);
      if (!clickedInsideDesktop && !clickedInsideMobile) {
        setCountryMenuOpen(false);
        setMobileCountryMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", onOutsideClick);
    return () => document.removeEventListener("mousedown", onOutsideClick);
  }, []);

  const hasQuickSearchResults = quickStoreResults.length > 0 || quickCouponResults.length > 0;
  const userMenuItems = [
    { href: "/notifications", labelAr: "التنبيهات", labelEn: "Notifications", icon: Bell },
    { href: "/favorites", labelAr: "المفضلة", labelEn: "Favorites", icon: Heart },
    { href: "/affiliate", labelAr: "الأفلييت", labelEn: "Affiliate", icon: Gift },
    { href: "/account", labelAr: "حسابي", labelEn: "My Account", icon: UserRound },
    { href: "/pages/faq", labelAr: "مساعدة", labelEn: "Help", icon: LifeBuoy },
  ];

  return (
    <header className="sticky top-0 z-50 border-b border-[var(--border)] bg-white">
      <div className="border-b border-[var(--border)] bg-[#f8fafc]">
        <div className="container-shell flex h-8 items-center justify-between text-[11px] text-slate-500">
          <p>{isArabic ? "أحدث كوبونات اليوم" : "Today's latest coupons"}</p>
          <p>{isArabic ? "وفر أكثر مع كل طلب" : "Save more on every order"}</p>
        </div>
      </div>

      <div className="container-shell py-3">
        <div className="flex items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <button type="button" onClick={() => setOpen((s) => !s)} className="rounded-lg border border-[var(--border)] p-2 md:hidden">
              {open ? <X size={18} /> : <Menu size={18} />}
            </button>
            <Link href="/" className="flex items-center gap-2">
              <span className="flex h-8 w-8 items-center justify-center overflow-hidden rounded-full bg-[var(--primary)] text-sm font-extrabold text-white">
                {branding.logoUrl ? (
                  <Image src={branding.logoUrl} alt="logo" width={32} height={32} unoptimized className="h-full w-full object-cover" />
                ) : (
                  "و"
                )}
              </span>
              <span className="text-sm font-black text-[var(--primary)]">{isArabic ? branding.nameAr : branding.nameEn}</span>
            </Link>
          </div>

          <nav className="relative hidden items-center gap-4 text-sm font-semibold text-slate-700 lg:flex">
            {links.map((link) => (
              <Link key={link.href} href={link.href} className="transition hover:text-[var(--primary)]">
                {isArabic ? link.labelAr : link.labelEn}
              </Link>
            ))}

            <div className="relative" onMouseEnter={() => setCategoriesOpen(true)} onMouseLeave={() => setCategoriesOpen(false)}>
              <button type="button" className="inline-flex items-center gap-1 rounded-full border border-transparent px-2.5 py-1.5 transition hover:border-[var(--border)] hover:text-[var(--primary)]">
                {isArabic ? "الأقسام" : "Categories"}
              </button>

              {categoriesOpen ? (
                <div className="absolute top-full z-50 mt-0.5 w-[760px] rounded-2xl border border-[var(--border)] bg-white p-4 shadow-lg">
                  <div className="grid grid-cols-4 gap-4">
                    {columns.map((group, colIndex) => (
                      <div key={`col-${colIndex}`} className="space-y-1.5">
                        {group.map((category) => (
                          <Link
                            key={`cat-${category.id}`}
                            href={`/categories/${category.slug}`}
                            className="flex items-center justify-between rounded-xl px-2 py-2 transition hover:bg-[#eef4ff]"
                          >
                            <div className="flex min-w-0 items-center gap-2">
                              <CategoryIcon
                                image={category.icon || category.image}
                                nameAr={category.name_ar}
                                nameEn={category.name_en}
                                iconSize={18}
                                containerClassName="h-7 w-7 rounded-lg"
                                imageClassName="h-5 w-5"
                                iconClassName="h-5 w-5"
                              />
                              <span className="truncate text-xs text-slate-700">{pickLocalizedText(category, "name_ar", "name_en", locale, category.name_ar)}</span>
                            </div>
                            <span className="text-[11px] text-slate-400">
                              {(couponsCountByCategory[category.id] ?? category.coupons_count ?? 0)} {isArabic ? "" : ""}
                            </span>
                          </Link>
                        ))}
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}
            </div>
          </nav>

          <div className="hidden max-w-md flex-1 lg:block">
            <div className="relative" ref={quickSearchRef}>
              <Input
                value={query}
                onChange={(event) => {
                  const next = event.target.value;
                  setQuery(next);
                  setQuickSearchOpen(next.trim().length > 0);
                }}
                onFocus={() => setQuickSearchOpen(query.trim().length > 0)}
                placeholder={isArabic ? "ابحث عن كوبون، متجر أو كود" : "Search coupon, store or code"}
                className="ps-10"
                onKeyDown={(event) => {
                  if (event.key === "Enter" && query.trim()) {
                    router.push(`/search?q=${encodeURIComponent(query.trim())}`);
                    setQuickSearchOpen(false);
                  }
                }}
              />
              <Search className="absolute start-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />

              {quickSearchOpen ? (
                <div className="absolute start-0 top-full z-50 mt-2 w-full overflow-hidden rounded-2xl border border-[var(--border)] bg-white shadow-xl">
                  {hasQuickSearchResults ? (
                    <div className="max-h-[420px] overflow-y-auto p-2">
                      {quickStoreResults.length > 0 ? (
                        <div className="mb-2">
                          <p className="px-2 py-1 text-[11px] font-bold uppercase tracking-wide text-slate-500">
                            {isArabic ? "متاجر" : "Stores"}
                          </p>
                          <div className="space-y-1">
                            {quickStoreResults.map((store) => (
                              <button
                                key={`quick-store-${store.id}`}
                                type="button"
                                className="flex w-full items-center gap-2 rounded-xl px-2 py-2 text-start transition hover:bg-[#eef4ff]"
                                onClick={() => {
                                  router.push(`/stores/${store.slug}`);
                                  setQuickSearchOpen(false);
                                  setQuery("");
                                }}
                              >
                                <span className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[var(--border)] bg-white">
                                  {store.logo ? (
                                    <Image src={store.logo} alt={store.name_en || "Store"} width={36} height={36} unoptimized className="h-full w-full object-cover" />
                                  ) : (
                                    <span className="text-[10px] font-bold text-slate-600">
                                      {(store.name_en || store.name_ar || "S").slice(0, 2)}
                                    </span>
                                  )}
                                </span>
                                <span className="min-w-0 truncate text-xs font-semibold text-slate-700">
                                  {pickLocalizedText(store, "name_ar", "name_en", locale, store.name_en || store.name_ar)}
                                </span>
                              </button>
                            ))}
                          </div>
                        </div>
                      ) : null}

                      {quickCouponResults.length > 0 ? (
                        <div>
                          <p className="px-2 py-1 text-[11px] font-bold uppercase tracking-wide text-slate-500">
                            {isArabic ? "كوبونات" : "Coupons"}
                          </p>
                          <div className="space-y-1">
                            {quickCouponResults.map((coupon) => (
                              <button
                                key={`quick-coupon-${coupon.id}`}
                                type="button"
                                className="flex w-full items-center gap-2 rounded-xl px-2 py-2 text-start transition hover:bg-[#eef4ff]"
                                onClick={() => {
                                  router.push(`/coupons/${coupon.id}`);
                                  setQuickSearchOpen(false);
                                  setQuery("");
                                }}
                              >
                                <span className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[var(--border)] bg-white">
                                  {coupon.store?.logo ? (
                                    <Image src={coupon.store.logo} alt={coupon.store?.name_en || "Store"} width={36} height={36} unoptimized className="h-full w-full object-cover" />
                                  ) : (
                                    <span className="text-[10px] font-bold text-slate-600">
                                      {(coupon.store?.name_en || coupon.store?.name_ar || "C").slice(0, 2)}
                                    </span>
                                  )}
                                </span>
                                <div className="min-w-0">
                                  <p className="truncate text-xs font-semibold text-slate-700">
                                    {pickLocalizedText(coupon, "title_ar", "title_en", locale, isArabic ? "كوبون خصم" : "Coupon")}
                                  </p>
                                  <p className="truncate text-[11px] text-slate-500">{coupon.code || (isArabic ? "عرض" : "Deal")}</p>
                                </div>
                              </button>
                            ))}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  ) : (
                    <p className="px-3 py-3 text-xs text-slate-500">
                      {isArabic ? "لا توجد نتائج مطابقة." : "No matching results."}
                    </p>
                  )}
                </div>
              ) : null}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <div className="hidden items-center gap-2 sm:flex">
              <div className="relative" ref={countryMenuDesktopRef}>
                <MapPin className="pointer-events-none absolute start-2 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                <button
                  type="button"
                  className="inline-flex h-8 min-w-[140px] items-center gap-1 rounded-full border border-[var(--border)] bg-white pe-2 ps-8 text-xs font-semibold text-slate-700"
                  onClick={() => setCountryMenuOpen((prev) => !prev)}
                >
                  {selectedCountry ? (
                    <>
                      {resolveFlagUrl(selectedCountry.flag) ? (
                        <Image
                          src={resolveFlagUrl(selectedCountry.flag)!}
                          alt={selectedCountry.iso_code}
                          width={16}
                          height={12}
                          unoptimized
                          className="h-3 w-4 rounded-[2px] object-cover"
                        />
                      ) : (
                        <span className="text-xs">{selectedCountryFlag || "🏳️"}</span>
                      )}
                      <span className="max-w-[90px] truncate">{countryLabel(selectedCountry, isArabic)}</span>
                    </>
                  ) : (
                    <span>{isArabic ? "اختر الدولة" : "Select country"}</span>
                  )}
                  <ChevronDown size={12} />
                </button>

                {countryMenuOpen ? (
                  <div className="absolute start-0 top-full z-50 mt-2 w-56 overflow-hidden rounded-2xl border border-[var(--border)] bg-white p-1.5 shadow-xl">
                    {(countriesQuery.data || []).map((country) => (
                      <button
                        key={`country-opt-${country.id}`}
                        type="button"
                        className={`flex w-full items-center gap-2 rounded-xl px-2 py-2 text-start text-xs font-semibold transition ${
                          selectedCountryId === country.id ? "bg-[#eef4ff] text-[var(--primary)]" : "text-slate-700 hover:bg-[#f8fafc]"
                        }`}
                        onClick={() => {
                          setSelectedCountryId(country.id);
                          setCountryMenuOpen(false);
                        }}
                      >
                        {resolveFlagUrl(country.flag) ? (
                          <Image src={resolveFlagUrl(country.flag)!} alt={country.iso_code} width={18} height={12} unoptimized className="h-3.5 w-[18px] rounded-[2px] object-cover" />
                        ) : (
                          <span className="text-sm">{toFlagEmoji(country.iso_code) || "🏳️"}</span>
                        )}
                        <span className="truncate">{countryLabel(country, isArabic)}</span>
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>

              <button
                className="inline-flex h-8 items-center gap-1 rounded-full border border-[var(--border)] px-3 text-xs font-semibold text-slate-700"
                type="button"
                onClick={() => setLocale(locale === "ar" ? "en" : "ar")}
                title={selectedLanguage?.name || "Change language"}
              >
                <Globe2 size={14} />
                <span suppressHydrationWarning>{isArabic ? "EN" : "AR"}</span>
              </button>
            </div>

            {isAuthenticated ? (
              <div className="relative hidden sm:block" onMouseEnter={() => setUserMenuOpen(true)} onMouseLeave={() => setUserMenuOpen(false)}>
                <button
                  type="button"
                  className="inline-flex items-center gap-2 rounded-full bg-[#059669] px-4 py-2 text-xs font-semibold text-white"
                >
                  <User size={14} />
                  {isArabic ? "حسابي" : "My Account"}
                  <ChevronDown size={13} />
                </button>

                {userMenuOpen ? (
                  <div className="absolute end-0 top-full z-50 mt-2 w-56 overflow-hidden rounded-2xl border border-[var(--border)] bg-white py-2 shadow-xl">
                    {userMenuItems.map((item) => {
                      const Icon = item.icon;
                      return (
                        <Link
                          key={item.href}
                          href={item.href}
                          className="flex items-center gap-2 px-3 py-2 text-xs font-semibold text-slate-700 transition hover:bg-[#eef4ff] hover:text-[var(--primary)]"
                        >
                          <Icon size={14} />
                          {isArabic ? item.labelAr : item.labelEn}
                        </Link>
                      );
                    })}
                    <button
                      type="button"
                      className="flex w-full items-center gap-2 px-3 py-2 text-xs font-semibold text-rose-600 transition hover:bg-rose-50"
                      onClick={async () => {
                        await logout();
                        setUserMenuOpen(false);
                        router.push("/login");
                      }}
                    >
                      <LogOut size={14} />
                      {isArabic ? "تسجيل خروج" : "Logout"}
                    </button>
                  </div>
                ) : null}
              </div>
            ) : (
              <Link href="/login" className="hidden rounded-full bg-[#f59e0b] px-4 py-2 text-xs font-semibold text-white sm:block">
                {isArabic ? "تسجيل الدخول" : "Login"}
              </Link>
            )}
            <Link href={isAuthenticated ? "/account" : "/login"} className="rounded-full border border-[var(--border)] p-2 sm:hidden">
              <User size={15} />
            </Link>
          </div>
        </div>

        {open ? (
          <div className="mt-3 space-y-2 rounded-2xl border border-[var(--border)] bg-white p-3 lg:hidden">
            <div className="relative">
              <Input
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder={isArabic ? "ابحث" : "Search"}
                className="ps-10"
                onKeyDown={(event) => {
                  if (event.key === "Enter" && query.trim()) {
                    router.push(`/search?q=${encodeURIComponent(query.trim())}`);
                    setOpen(false);
                  }
                }}
              />
              <Search className="absolute start-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
            </div>

            <div className="grid grid-cols-2 gap-2">
              {[...links.map((link) => ({ href: link.href, labelAr: link.labelAr, labelEn: link.labelEn })), { href: "/categories", labelAr: "الأقسام", labelEn: "Categories" }].map((link) => (
                <Link key={`mobile-${link.href}`} href={link.href} className="rounded-xl border border-[var(--border)] px-3 py-2 text-sm font-semibold" onClick={() => setOpen(false)}>
                  {isArabic ? link.labelAr : link.labelEn}
                </Link>
              ))}
            </div>

            <div className="grid grid-cols-2 gap-2">
              <div className="relative" ref={countryMenuMobileRef}>
                <button
                  type="button"
                  className="inline-flex h-10 w-full items-center justify-between rounded-xl border border-[var(--border)] bg-white px-3 text-sm font-semibold text-slate-700"
                  onClick={() => setMobileCountryMenuOpen((prev) => !prev)}
                >
                  <span className="inline-flex items-center gap-2">
                    {selectedCountry && resolveFlagUrl(selectedCountry.flag) ? (
                      <Image src={resolveFlagUrl(selectedCountry.flag)!} alt={selectedCountry.iso_code} width={18} height={12} unoptimized className="h-3.5 w-[18px] rounded-[2px] object-cover" />
                    ) : (
                      <span className="text-sm">{selectedCountryFlag || "🏳️"}</span>
                    )}
                    <span>{selectedCountry ? countryLabel(selectedCountry, isArabic) : (isArabic ? "اختر الدولة" : "Select country")}</span>
                  </span>
                  <ChevronDown size={14} />
                </button>

                {mobileCountryMenuOpen ? (
                  <div className="absolute start-0 top-full z-50 mt-2 w-full overflow-hidden rounded-xl border border-[var(--border)] bg-white p-1.5 shadow-xl">
                    {(countriesQuery.data || []).map((country) => (
                      <button
                        key={`mobile-country-opt-${country.id}`}
                        type="button"
                        className={`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-start text-sm transition ${
                          selectedCountryId === country.id ? "bg-[#eef4ff] text-[var(--primary)]" : "text-slate-700 hover:bg-[#f8fafc]"
                        }`}
                        onClick={() => {
                          setSelectedCountryId(country.id);
                          setMobileCountryMenuOpen(false);
                        }}
                      >
                        {resolveFlagUrl(country.flag) ? (
                          <Image src={resolveFlagUrl(country.flag)!} alt={country.iso_code} width={18} height={12} unoptimized className="h-3.5 w-[18px] rounded-[2px] object-cover" />
                        ) : (
                          <span className="text-sm">{toFlagEmoji(country.iso_code) || "🏳️"}</span>
                        )}
                        <span className="truncate">{countryLabel(country, isArabic)}</span>
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>

              <button
                className="inline-flex h-10 items-center justify-center gap-2 rounded-xl border border-[var(--border)] text-sm font-semibold"
                type="button"
                onClick={() => setLocale(locale === "ar" ? "en" : "ar")}
              >
                <Globe2 size={14} />
                <span suppressHydrationWarning>{isArabic ? "English" : "العربية"}</span>
              </button>
            </div>

            <Button className="w-full" onClick={() => router.push(isAuthenticated ? "/account" : "/login")}>
              {isAuthenticated ? (isArabic ? "الذهاب للحساب" : "Go to account") : (isArabic ? "تسجيل الدخول" : "Login")}
            </Button>
            {isAuthenticated ? (
              <>
                <div className="grid grid-cols-2 gap-2">
                  {userMenuItems.map((item) => {
                    const Icon = item.icon;
                    return (
                      <Link
                        key={`mobile-menu-${item.href}`}
                        href={item.href}
                        className="inline-flex items-center gap-2 rounded-xl border border-[var(--border)] px-3 py-2 text-sm font-semibold text-slate-700"
                        onClick={() => setOpen(false)}
                      >
                        <Icon size={14} />
                        {isArabic ? item.labelAr : item.labelEn}
                      </Link>
                    );
                  })}
                </div>
                <Button
                  variant="secondary"
                  className="w-full"
                  onClick={async () => {
                    await logout();
                    setOpen(false);
                    router.push("/login");
                  }}
                >
                  <LogOut size={14} />
                  {isArabic ? "تسجيل خروج" : "Logout"}
                </Button>
              </>
            ) : null}
          </div>
        ) : null}
      </div>
    </header>
  );
}
