"use client";
import { useState, useEffect, useRef, KeyboardEvent } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import {
  Menu,
  Search,
  Mic,
  Upload,
  Bell,
  User,
  UserPlus,
  Globe,
  ChevronDown,
  Check,
  X,
  ShoppingBag,
  Heart,
  MessageCircle,
} from "lucide-react";
import { useWishlist } from "@/lib/WishlistContext";
import { useMessaging } from "@/lib/MessagingContext";
import { cn } from "@/utils/cn";
import { TEXT } from "@/branding";
import { IMAGES } from "@/branding/images";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { setQuery, performSearch } from "@/store/slices/searchSlice";
import { fetchNotifications } from "@/store/slices/notificationSlice";
import { fetchMarketplaceCategories } from "@/store/slices/marketplaceCategorySlice";
import { useTranslation, type Language } from "@/i18n";
import { ThemeToggle } from "@/components/common/ThemeToggle";

interface HeaderProps {
  onMenuToggle: () => void;
}

/* ── Language dropdown ──────────────────────────────────────────────────── */
const LANGS: { code: Language; label: string; name: string }[] = [
  { code: "en", label: "EN", name: "English" },
  { code: "hi", label: "हि", name: "हिंदी" },
  { code: "gu", label: "ગુ", name: "ગુજરાતી" },
];

function LangDropdown() {
  const { lang, setLang, t } = useTranslation();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node))
        setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const current = LANGS.find((l) => l.code === lang) ?? LANGS[0];

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        aria-label={t("lang_changeLanguage")}
        title={t("lang_changeLanguage")}
        className="flex items-center gap-1 h-8 px-2.5 rounded-lg transition-all"
        style={{
          background: open ? "var(--btn-ghost-hover)" : "var(--btn-ghost)",
          border: "1px solid var(--border)",
          color: "var(--text-muted)",
        }}
        onMouseEnter={(e) => {
          if (!open)
            (e.currentTarget as HTMLButtonElement).style.background =
              "var(--btn-ghost-hover)";
        }}
        onMouseLeave={(e) => {
          if (!open)
            (e.currentTarget as HTMLButtonElement).style.background =
              "var(--btn-ghost)";
        }}
      >
        <Globe size={13} strokeWidth={1.7} />
        <span className="text-[11px] font-semibold hidden sm:block">
          {current.label}
        </span>
        <ChevronDown
          size={11}
          strokeWidth={2}
          className="transition-transform duration-150"
          style={{ transform: open ? "rotate(180deg)" : "rotate(0deg)" }}
        />
      </button>

      {open && (
        <div
          className="absolute right-0 top-[calc(100%+6px)] z-[100] rounded-xl overflow-hidden py-1"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
            boxShadow: "0 8px 28px rgba(0,0,0,0.35)",
            minWidth: 130,
          }}
        >
          {LANGS.map(({ code, label, name }) => {
            const active = lang === code;
            return (
              <button
                key={code}
                onClick={() => {
                  setLang(code);
                  setOpen(false);
                }}
                className="w-full flex items-center gap-2.5 px-3 py-2 text-left transition-all"
                style={{
                  background: active
                    ? "rgba(var(--accent-rgb),0.1)"
                    : "transparent",
                  color: active ? "var(--accent)" : "var(--text-secondary)",
                }}
                onMouseEnter={(e) => {
                  if (!active)
                    (e.currentTarget as HTMLButtonElement).style.background =
                      "var(--btn-ghost-hover)";
                }}
                onMouseLeave={(e) => {
                  if (!active)
                    (e.currentTarget as HTMLButtonElement).style.background =
                      "transparent";
                }}
              >
                <span
                  className="w-7 text-center text-[11px] font-black rounded"
                  style={{
                    background: active ? "var(--accent)" : "var(--deep)",
                    color: active ? "#fff" : "var(--text-muted)",
                    padding: "1px 4px",
                  }}
                >
                  {label}
                </span>
                <span className="text-[12px] font-medium flex-1">{name}</span>
                {active && (
                  <Check
                    size={12}
                    strokeWidth={2.5}
                    style={{ color: "var(--accent)" }}
                  />
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ── Header ─────────────────────────────────────────────────────────────── */
export function Header({ onMenuToggle }: HeaderProps) {
  const [focused, setFocused] = useState(false);
  const [mobileSearchOpen, setMobileSearchOpen] = useState(false);
  const [searchVal, setSearchVal] = useState("");
  const router = useRouter();
  const pathname = usePathname();
  const dispatch = useAppDispatch();
  const isSearchPage = pathname === "/search";
  const isAuthenticated = useAppSelector((s) => s.auth.isAuthenticated);
  const unreadCount = useAppSelector((s) => s.notifications.unreadCount);
  const { t } = useTranslation();
  const { count: wishlistCount } = useWishlist();
  const { totalUnread: msgUnread } = useMessaging();

  /* Pre-fetch notifications only when logged in */
  useEffect(() => {
    if (isAuthenticated) dispatch(fetchNotifications(1));
  }, [dispatch, isAuthenticated]);

  const handleSearch = () => {
    const q = searchVal.trim();
    if (!q) return;
    dispatch(setQuery(q));
    dispatch(performSearch(q));
    setMobileSearchOpen(false);
    router.push(`/search?q=${encodeURIComponent(q)}`);
  };

  /* Shared search bar content */
  const SearchBar = (
    <div
      className="flex items-center h-9 rounded-full pl-3   transition-all duration-150 border"
      style={{
        background: "var(--deep)",
        borderColor: focused ? "rgba(var(--accent-rgb),0.55)" : "var(--border)",
        boxShadow: focused ? "0 0 0 3px rgba(var(--accent-rgb),0.12)" : "none",
      }}
    >
      <Mic
        size={14}
        className="mr-2 shrink-0"
        style={{ color: "var(--text-muted)" }}
      />
      <input
        type="text"
        placeholder={t("search_placeholder")}
        className="flex-1 bg-transparent border-0 outline-none text-xs"
        style={{ color: "var(--text-primary)" }}
        value={searchVal}
        onChange={(e) => setSearchVal(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
          if (e.key === "Enter") handleSearch();
        }}
      />
      <button
        className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 transition-all"
        style={{ background: "var(--accent)" }}
        onClick={handleSearch}
      >
        <Search size={14} color="#fff" />
      </button>
    </div>
  );

  return (
    <>
      <header
        className="sticky top-0 z-50 h-14 border-b"
        style={{ background: "var(--bg)", borderColor: "var(--border)" }}
      >
        {/* ── Desktop layout (md+) ──────────────────────────────────────── */}
        <div
          className="hidden md:grid h-full items-center"
          style={{
            gridTemplateColumns: "auto 1fr auto",
            gap: "24px",
            padding: "0 18px",
          }}
        >
          {/* Left */}
          <div className="flex items-center gap-3.5">
            <button
              onClick={onMenuToggle}
              className="w-9 h-9 rounded-full flex items-center justify-center transition-colors"
              style={{ background: "var(--btn-ghost)" }}
              onMouseEnter={(e) =>
                (e.currentTarget.style.background = "var(--btn-ghost-hover)")
              }
              onMouseLeave={(e) =>
                (e.currentTarget.style.background = "var(--btn-ghost)")
              }
              aria-label="Menu"
            >
              <Menu
                size={20}
                strokeWidth={1.6}
                style={{ color: "var(--text-primary)" }}
              />
            </button>
            <Link href="/" className="flex items-center">
              <Image
                src={IMAGES.logoBlack}
                alt={TEXT.app.name}
                width={120}
                height={36}
                className="block dark:hidden shrink-0 object-contain"
                style={{ height: 36, width: "auto" }}
                priority
              />
              <Image
                src={IMAGES.logoWhite}
                alt={TEXT.app.name}
                width={120}
                height={36}
                className="hidden dark:block shrink-0 object-contain"
                style={{ height: 36, width: "auto" }}
                priority
              />
            </Link>
          </div>

          {/* Center search */}
          <div
            className={cn(
              "max-w-2xl w-full mx-auto",
              isSearchPage && "invisible pointer-events-none",
            )}
          >
            {SearchBar}
          </div>

          {/* Right */}
          <div className="flex items-center gap-2">
            {isAuthenticated && (
              <button
                onClick={() => { dispatch(fetchMarketplaceCategories()); router.push("/marketplace"); }}
                aria-label="Marketplace"
                title="Marketplace"
                className="flex items-center gap-1.5 h-8 px-3 rounded-full text-[11px] font-bold transition-all active:scale-95"
                style={{
                  background:
                    "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)",
                  border: "none",
                  color: "#fff",
                  boxShadow: "0 2px 8px rgba(252,0,0,0.25)",
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.boxShadow =
                    "0 4px 14px rgba(252,0,0,0.4)";
                  (e.currentTarget as HTMLButtonElement).style.transform =
                    "translateY(-1px)";
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.boxShadow =
                    "0 2px 8px rgba(252,0,0,0.25)";
                  (e.currentTarget as HTMLButtonElement).style.transform = "none";
                }}
              >
                <ShoppingBag size={13} strokeWidth={2} />
                <span className="hidden lg:inline">Marketplace</span>
              </button>
            )}
            {/* Wishlist */}
            {/* <button
              onClick={() => router.push("/wishlist")}
              aria-label="Wishlist"
              title="Wishlist"
              className="relative flex items-center justify-center w-8 h-8 rounded-full transition-all active:scale-95"
              style={{ background: "rgba(var(--accent-rgb),0.08)" }}
            >
              <Heart
                size={15}
                strokeWidth={1.8}
                className={
                  wishlistCount > 0 ? "fill-[#fc0000] text-[#fc0000]" : ""
                }
                style={
                  wishlistCount === 0 ? { color: "var(--text-muted)" } : {}
                }
              />
              {wishlistCount > 0 && (
                <span className="absolute -top-1 -right-1 min-w-[16px] h-4 rounded-full bg-[var(--accent)] text-white text-[9px] font-bold flex items-center justify-center px-0.5">
                  {wishlistCount}
                </span>
              )}
            </button> */}
            {/* Messages */}
            {/* <button
              onClick={() => router.push("/messages")}
              aria-label="Messages"
              title="Messages"
              className="relative flex items-center justify-center w-8 h-8 rounded-full transition-all active:scale-95"
              style={{ background: "rgba(var(--accent-rgb),0.08)" }}
            >
              <MessageCircle
                size={15}
                strokeWidth={1.8}
                style={{
                  color: msgUnread > 0 ? "var(--accent)" : "var(--text-muted)",
                }}
              />
              {msgUnread > 0 && (
                <span className="absolute -top-1 -right-1 min-w-[16px] h-4 rounded-full bg-[var(--accent)] text-white text-[9px] font-bold flex items-center justify-center px-0.5">
                  {msgUnread > 9 ? "9+" : msgUnread}
                </span>
              )}
            </button> */}
            <LangDropdown />
            <ThemeToggle />
            {isAuthenticated ? (
              <>
                <button
                  className="w-9 h-9 rounded-full flex items-center justify-center transition-colors"
                  style={{ background: "var(--btn-ghost)" }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.background =
                      "var(--btn-ghost-hover)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.background = "var(--btn-ghost)")
                  }
                  aria-label="Upload"
                  onClick={() => router.push("/upload")}
                >
                  <Upload
                    size={16}
                    strokeWidth={1.6}
                    style={{ color: "var(--text-primary)" }}
                  />
                </button>
                <button
                  className="w-9 h-9 rounded-full flex items-center justify-center transition-colors relative"
                  style={{ background: "var(--btn-ghost)" }}
                  onMouseEnter={(e) =>
                    (e.currentTarget.style.background =
                      "var(--btn-ghost-hover)")
                  }
                  onMouseLeave={(e) =>
                    (e.currentTarget.style.background = "var(--btn-ghost)")
                  }
                  aria-label="Notifications"
                  onClick={() => router.push("/notification")}
                >
                  <Bell
                    size={16}
                    strokeWidth={1.6}
                    style={{ color: "var(--text-primary)" }}
                  />
                  {unreadCount > 0 && (
                    <span
                      className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 rounded-full flex items-center justify-center text-[9px] font-bold text-[#ffffff] px-1"
                      style={{
                        background: "var(--accent)",
                        border: "2px solid var(--bg)",
                      }}
                    >
                      {unreadCount > 99 ? "99+" : unreadCount}
                    </span>
                  )}
                </button>
                <button
                  className="w-8 h-8 rounded-full flex items-center justify-center text-[#ffffff] text-xs font-semibold shrink-0"
                  onClick={() => router.push("/profile")}
                  style={{
                    background:
                      "linear-gradient(135deg, var(--accent), #9b2d8b)",
                  }}
                >
                  <User size={14} color="#fff" />
                </button>
              </>
            ) : (
              <Link
                href="/auth/signup"
                className="flex items-center gap-1.5 h-8 px-4 rounded-full text-[12px] font-bold transition-all active:scale-95"
                style={{
                  background:
                    "linear-gradient(135deg, var(--accent), var(--accent)cc)",
                  boxShadow: "0 4px 14px rgba(var(--accent-rgb),0.35)",
                  color: "var(--text-muted)",
                }}
              >
                <UserPlus size={13} strokeWidth={2.5} />
                <span>{t("nav_signUp")}</span>
              </Link>
            )}
          </div>
        </div>

        {/* ── Mobile layout (< md) ──────────────────────────────────────── */}
        <div className="flex md:hidden items-center h-full gap-2 px-3">
          {/* Menu toggle (opens sidebar for secondary nav items) */}
          <button
            onClick={onMenuToggle}
            className="w-9 h-9 rounded-full flex items-center justify-center transition-colors shrink-0"
            style={{ background: "var(--btn-ghost)" }}
            aria-label="Menu"
          >
            <Menu
              size={20}
              strokeWidth={1.6}
              style={{ color: "var(--text-primary)" }}
            />
          </button>

          {/* Logo — grows to fill center space */}
          <Link href="/" className="flex items-center flex-1 min-w-0">
            <Image
              src={IMAGES.logoBlack}
              alt={TEXT.app.name}
              width={100}
              height={30}
              className="block dark:hidden shrink-0 object-contain"
              style={{ height: 28, width: "auto" }}
              priority
            />
            <Image
              src={IMAGES.logoWhite}
              alt={TEXT.app.name}
              width={100}
              height={30}
              className="hidden dark:block shrink-0 object-contain"
              style={{ height: 28, width: "auto" }}
              priority
            />
          </Link>

          {/* Right actions — compact */}
          <div className="flex items-center gap-1 shrink-0">
            {/* Marketplace */}
            {isAuthenticated && (
              <button
                className="w-9 h-9 rounded-full flex items-center justify-center transition-all active:scale-95"
                style={{
                  background:
                    "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)",
                  boxShadow: "0 2px 6px rgba(252,0,0,0.3)",
                }}
                aria-label="Marketplace"
                onClick={() => { dispatch(fetchMarketplaceCategories()); router.push("/marketplace"); }}
              >
                <ShoppingBag
                  size={17}
                  strokeWidth={1.8}
                  style={{ color: "#fff" }}
                />
              </button>
            )}

            {/* Messages */}
            {/* <button
              className="w-9 h-9 rounded-full flex items-center justify-center transition-colors relative"
              style={{ background: "rgba(var(--accent-rgb),0.08)" }}
              aria-label="Messages"
              onClick={() => router.push("/messages")}
            >
              <MessageCircle
                size={18}
                strokeWidth={1.6}
                style={{
                  color: msgUnread > 0 ? "var(--accent)" : "var(--text-muted)",
                }}
              />
              {msgUnread > 0 && (
                <span
                  className="absolute -top-0.5 -right-0.5 min-w-[14px] h-3.5 rounded-full flex items-center justify-center text-[8px] font-bold text-white px-0.5"
                  style={{
                    background: "var(--accent)",
                    border: "1.5px solid var(--bg)",
                  }}
                >
                  {msgUnread > 9 ? "9+" : msgUnread}
                </span>
              )}
            </button> */}
            {/* Search icon */}
            <button
              className="w-9 h-9 rounded-full flex items-center justify-center transition-colors"
              style={{ background: "var(--btn-ghost)" }}
              aria-label="Search"
              onClick={() => setMobileSearchOpen(true)}
            >
              <Search
                size={18}
                strokeWidth={1.6}
                style={{ color: "var(--text-primary)" }}
              />
            </button>

            {isAuthenticated ? (
              <>
                {/* Notifications */}
                <button
                  className="w-9 h-9 rounded-full flex items-center justify-center transition-colors relative"
                  style={{ background: "var(--btn-ghost)" }}
                  aria-label="Notifications"
                  onClick={() => router.push("/notification")}
                >
                  <Bell
                    size={18}
                    strokeWidth={1.6}
                    style={{ color: "var(--text-primary)" }}
                  />
                  {unreadCount > 0 && (
                    <span
                      className="absolute -top-0.5 -right-0.5 min-w-[14px] h-3.5 rounded-full flex items-center justify-center text-[8px] font-bold text-white px-0.5"
                      style={{
                        background: "var(--accent)",
                        border: "1.5px solid var(--bg)",
                      }}
                    >
                      {unreadCount > 9 ? "9+" : unreadCount}
                    </span>
                  )}
                </button>
              </>
            ) : (
              <Link
                href="/auth/login"
                className="flex items-center gap-1 h-8 px-3 rounded-full text-[11px] font-bold transition-all active:scale-95"
                style={{
                  background:
                    "linear-gradient(135deg, var(--accent), var(--accent)cc)",
                  color: "#fff",
                }}
              >
                <UserPlus size={12} strokeWidth={2.5} />
                <span>{t("nav_login")}</span>
              </Link>
            )}
          </div>
        </div>
      </header>

      {/* ── Mobile search overlay ─────────────────────────────────────────── */}
      {mobileSearchOpen && (
        <div
          className="fixed inset-0 z-[70] md:hidden flex flex-col"
          style={{ background: "var(--bg)" }}
        >
          <div
            className="flex items-center gap-2 px-3 h-14 border-b"
            style={{ borderColor: "var(--border)" }}
          >
            <div className="flex-1">{SearchBar}</div>
            <button
              className="w-9 h-9 rounded-full flex items-center justify-center shrink-0"
              style={{ background: "var(--btn-ghost)" }}
              onClick={() => setMobileSearchOpen(false)}
              aria-label="Close search"
            >
              <X
                size={18}
                strokeWidth={1.6}
                style={{ color: "var(--text-primary)" }}
              />
            </button>
          </div>
        </div>
      )}
    </>
  );
}
