import { useState } from "react";
import { useWeb } from "../WebContext";
import { cn } from "../WebUI";
import { BrandLogo } from "@/components/base/BrandLogo";
import { guestTicker } from "@/mocks/dshnGuestHome";
import type { WebScreen } from "../types";

/** Public + customer navigation. */
const NAV: { label: string; screen: WebScreen }[] = [
  { label: "الرئيسية", screen: "home" },
  { label: "المنشآت", screen: "businesses" },
  { label: "المنتجات", screen: "products" },
  { label: "الفرص الاستثمارية", screen: "opportunities" },
];

/** Investor navigation (no products; following + chats instead). */
const INV_NAV: { label: string; screen: WebScreen }[] = [
  { label: "الرئيسية", screen: "invHome" },
  { label: "المنشآت", screen: "businesses" },
  { label: "الفرص الاستثمارية", screen: "invOpps" },
  { label: "المتابعة", screen: "invFollowing" },
  { label: "المحادثات", screen: "invChats" },
];

const CHAT_UNREAD = 2;
const NOTIF_UNREAD = 3;

const AVATAR =
  "https://readdy.ai/api/search-image?query=Professional%20Saudi%20person%20portrait%20on%20light%20neutral%20background%2C%20minimal%20clean%20composition%2C%20soft%20natural%20light%2C%20corporate%20headshot%20photography%2C%20friendly%20expression&width=300&height=300&seq=dshn-web-user-avatar&orientation=squarish";

interface MenuItemDef {
  icon: string;
  label: string;
  screen: WebScreen;
}

const CUSTOMER_MENU: MenuItemDef[] = [
  { icon: "ri-user-line", label: "حسابي", screen: "profile" },
  { icon: "ri-file-list-3-line", label: "طلباتي", screen: "orders" },
  { icon: "ri-heart-line", label: "المفضلة", screen: "favorites" },
];

const INVESTOR_MENU: MenuItemDef[] = [
  { icon: "ri-user-line", label: "حسابي", screen: "invProfile" },
];

/**
 * One desktop header for public + customer + investor pages, driven by the
 * active role. A news ticker strip always sits directly under the header.
 */
export default function WebTopHeader() {
  const { role, screen, jump, lang, setLang, openAuth, logout, cartCount } = useWeb();
  const isInvestor = role === "investor";
  const isCustomer = role === "customer" || role === "business";
  const nav = isInvestor ? INV_NAV : NAV;
  const [menuOpen, setMenuOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [query, setQuery] = useState("");

  const runSearch = () => {
    setQuery("");
    setMobileOpen(false);
    jump(isInvestor ? "invOpps" : "products");
  };

  return (
    <header className="sticky top-0 inset-x-0 z-50 bg-background-50 border-b border-background-200">
      <div className="w-full max-w-[1280px] mx-auto px-4 md:px-8 h-[72px] flex items-center gap-3">
        <button
          type="button"
          onClick={() => jump(isInvestor ? "invHome" : "home")}
          className="flex items-center gap-2.5 cursor-pointer shrink-0"
        >
          <BrandLogo className="w-[46px] h-[33px] text-foreground-950" />
          <span className="font-heading font-bold text-[18px] text-foreground-950 hidden sm:block">دشن</span>
        </button>

        <nav className="hidden lg:flex items-center gap-0.5 ms-2">
          {nav.map((n) => (
            <button
              key={n.label}
              type="button"
              onClick={() => jump(n.screen)}
              className={cn(
                "px-3.5 h-10 rounded-full text-[14px] font-medium transition-colors cursor-pointer whitespace-nowrap",
                screen === n.screen ? "bg-background-200 text-foreground-950" : "text-foreground-600 hover:text-foreground-950",
              )}
            >
              {n.label}
            </button>
          ))}
        </nav>

        <div className="flex items-center gap-1.5 ms-auto">
          {/* search field */}
          <div className="hidden lg:flex items-center gap-2 h-10 w-[210px] xl:w-[250px] px-3.5 rounded-full bg-background-100 border border-background-200 focus-within:border-foreground-400 transition-colors">
            <i className="ri-search-line text-[18px] text-foreground-500 leading-none shrink-0" />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") runSearch();
              }}
              placeholder={isInvestor ? "ابحث عن فرصة أو منشأة" : "ابحث عن منشأة أو منتج"}
              className="flex-1 min-w-0 bg-transparent text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
            />
          </div>

          {isInvestor ? (
            <>
              <IconBtn icon="ri-notification-3-line" label="الإشعارات" badge={NOTIF_UNREAD} onClick={() => jump("invNotifications")} />
              <LangToggle lang={lang} setLang={setLang} />
              <AvatarMenu
                open={menuOpen}
                setOpen={setMenuOpen}
                items={INVESTOR_MENU}
                onNavigate={(s) => {
                  setMenuOpen(false);
                  jump(s);
                }}
                onLogout={() => {
                  setMenuOpen(false);
                  logout();
                  jump("home");
                }}
              />
            </>
          ) : isCustomer ? (
            <>
              <IconBtn icon="ri-chat-3-line" label="المحادثات" badge={CHAT_UNREAD} onClick={() => jump("chats")} />
              <IconBtn icon="ri-shopping-bag-3-line" label="سلة المشتريات" badge={cartCount} onClick={() => jump("cart")} />
              <IconBtn icon="ri-notification-3-line" label="الإشعارات" badge={NOTIF_UNREAD} onClick={() => jump("notifications")} />
              <LangToggle lang={lang} setLang={setLang} />
              <AvatarMenu
                open={menuOpen}
                setOpen={setMenuOpen}
                items={CUSTOMER_MENU}
                onNavigate={(s) => {
                  setMenuOpen(false);
                  jump(s);
                }}
                onLogout={() => {
                  setMenuOpen(false);
                  logout();
                  jump("home");
                }}
              />
            </>
          ) : (
            <>
              <IconBtn icon="ri-shopping-bag-3-line" label="سلة المشتريات" badge={cartCount} onClick={() => jump("cart")} />
              <LangToggle lang={lang} setLang={setLang} />
              <button
                type="button"
                onClick={() => openAuth()}
                className="ms-1 h-10 px-5 rounded-full bg-primary-500 text-background-50 text-[13.5px] font-semibold inline-flex items-center justify-center hover:bg-primary-600 transition-colors cursor-pointer whitespace-nowrap"
              >
                تسجيل / دخول
              </button>
            </>
          )}

          <button
            type="button"
            aria-label="القائمة"
            onClick={() => setMobileOpen((o) => !o)}
            className="lg:hidden w-10 h-10 rounded-full flex items-center justify-center text-foreground-950 hover:bg-background-200 cursor-pointer"
          >
            <i className={cn(mobileOpen ? "ri-close-line" : "ri-menu-line", "text-[22px] leading-none")} />
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="lg:hidden bg-background-50 border-t border-background-200">
          <div className="w-full max-w-[1280px] mx-auto px-4 py-3 flex flex-col gap-1">
            <div className="flex items-center gap-2 h-11 px-4 rounded-full bg-background-100 border border-background-200 mb-1">
              <i className="ri-search-line text-[18px] text-foreground-500 leading-none shrink-0" />
              <input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") runSearch();
                }}
                placeholder={isInvestor ? "ابحث عن فرصة أو منشأة" : "ابحث عن منشأة أو منتج"}
                className="flex-1 min-w-0 bg-transparent text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
              />
            </div>
            {nav.map((n) => (
              <button
                key={n.label}
                type="button"
                onClick={() => {
                  setMobileOpen(false);
                  jump(n.screen);
                }}
                className="h-11 px-4 rounded-[12px] text-start text-[14.5px] font-medium text-foreground-800 hover:bg-background-200 cursor-pointer"
              >
                {n.label}
              </button>
            ))}
          </div>
        </div>
      )}

      <Ticker />
    </header>
  );
}

function LangToggle({ lang, setLang }: { lang: string; setLang: (l: "ar" | "en") => void }) {
  return (
    <div className="flex items-center rounded-full p-0.5 text-[12.5px] font-semibold bg-background-200">
      <button
        type="button"
        onClick={() => setLang("ar")}
        className={cn("px-2.5 h-7 rounded-full cursor-pointer transition-colors", lang === "ar" ? "bg-primary-500 text-background-50" : "text-foreground-600")}
      >
        ع
      </button>
      <button
        type="button"
        onClick={() => setLang("en")}
        className={cn("px-2.5 h-7 rounded-full cursor-pointer transition-colors", lang === "en" ? "bg-primary-500 text-background-50" : "text-foreground-600")}
      >
        EN
      </button>
    </div>
  );
}

function AvatarMenu({
  open,
  setOpen,
  items,
  onNavigate,
  onLogout,
}: {
  open: boolean;
  setOpen: (v: boolean) => void;
  items: MenuItemDef[];
  onNavigate: (screen: WebScreen) => void;
  onLogout: () => void;
}) {
  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 h-10 ps-1 pe-2.5 rounded-full bg-background-100 border border-background-200 hover:border-background-300 transition-colors cursor-pointer"
      >
        <span className="w-8 h-8 rounded-full overflow-hidden bg-background-200 shrink-0">
          <img src={AVATAR} alt="حسابي" className="w-full h-full object-cover object-top" />
        </span>
        <i className={cn("ri-arrow-down-s-line text-[18px] leading-none text-foreground-700 transition-transform", open && "rotate-180")} />
      </button>

      {open && (
        <>
          <button type="button" aria-label="إغلاق" onClick={() => setOpen(false)} className="fixed inset-0 z-40 cursor-default" />
          <div className="absolute end-0 top-[calc(100%+10px)] w-52 z-50 bg-background-100 border border-background-200 rounded-[16px] p-1.5">
            {items.map((it) => (
              <MenuItem key={it.label} icon={it.icon} label={it.label} onClick={() => onNavigate(it.screen)} />
            ))}
            <div className="h-px bg-background-200 my-1" />
            <MenuItem icon="ri-logout-box-r-line" label="تسجيل الخروج" danger onClick={onLogout} />
          </div>
        </>
      )}
    </div>
  );
}

function Ticker() {
  const items = [...guestTicker, ...guestTicker];
  return (
    <div className="bg-secondary-100 border-t border-background-200">
      <div className="w-full max-w-[1280px] mx-auto px-4 md:px-8 h-10 flex items-center overflow-hidden">
        <div className="h-full flex items-center gap-1.5 bg-secondary-500 text-secondary-950 px-3.5 shrink-0">
          <i className="ri-flashlight-fill text-[14px] leading-none" />
          <span className="text-[11.5px] font-bold whitespace-nowrap">آخر التدشينات</span>
        </div>
        <div className="flex-1 overflow-hidden">
          <div className="flex items-center gap-6 animate-ticker w-max ps-5">
            {items.map((text, i) => (
              <span key={`${text}-${i}`} className="flex items-center gap-6 text-[12.5px] font-medium text-secondary-900 whitespace-nowrap">
                {text}
                <span className="w-1.5 h-1.5 rounded-full bg-secondary-700/50" />
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function IconBtn({ icon, label, badge, onClick }: { icon: string; label: string; badge?: number; onClick: () => void }) {
  return (
    <button
      type="button"
      aria-label={label}
      onClick={onClick}
      className="relative w-10 h-10 rounded-full hidden sm:flex items-center justify-center text-foreground-950 hover:bg-background-200 transition-colors cursor-pointer"
    >
      <i className={cn(icon, "text-[20px] leading-none")} />
      {badge !== undefined && badge > 0 && (
        <span className="absolute top-1 end-1 min-w-[17px] h-[17px] px-1 rounded-full bg-accent-700 text-background-50 text-[10px] font-bold flex items-center justify-center">
          {badge}
        </span>
      )}
    </button>
  );
}

function MenuItem({ icon, label, onClick, danger }: { icon: string; label: string; onClick: () => void; danger?: boolean }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "w-full h-10 px-3 rounded-[12px] flex items-center gap-2.5 text-[13.5px] font-medium cursor-pointer transition-colors",
        danger ? "text-danger-600 hover:bg-danger-50" : "text-foreground-800 hover:bg-background-200",
      )}
    >
      <i className={cn(icon, "text-[17px] leading-none")} />
      {label}
    </button>
  );
}