"use client";

import Image from "next/image";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import LanguageSelection from "@/components/shared/LanguageSelection";
import AttendanceScanButton from "@/components/layout/AttendanceScanButton";
import { CloseIcon } from "./headerIcons";
import { useHeader } from "./useHeader";
import HeaderMobileMenu from "./HeaderMobileMenu";
import HeaderDesktopNav from "./HeaderDesktopNav";
import { NotificationBadge } from "./headerParts";
import HeaderProfileDropdown from "./HeaderProfileDropdown";

// Inline SVGs instead of react-icons — avoids icon library chunks in the layout bundle

const Header = () => {
  const { t } = useTranslation();
  const {
    pathname,
    menuOpen,
    setMenuOpen,
    dropdownOpen,
    setDropdownOpen,
    language,
    unreadCount,
    isLoggedIn,
    isVolunteer,
    isOrganizer,
    profilePicUrl,
    defaultProfilePic,
    handleLogout,
    handleLogoutAll,
    hasOtherAccounts,
    close,
  } = useHeader();

  return (
    <nav
      className="bg-white w-full z50 sticky top-0"
      /*
       * The nav dropdowns closed on `onMouseLeave` and nothing else, so a
       * keyboard user who opened one had no way to dismiss it without
       * tabbing all the way through. Escape closes it, which is what a menu
       * is expected to answer, and it is bound here rather than on each
       * trigger because keydown bubbles from whichever item has focus.
       *
       * jsx-a11y's strict preset reports the mouse handler on a `<nav>`;
       * leaving on hover has no keyboard counterpart to add, and Escape is
       * the counterpart for closing.
       */
      onKeyDown={(event) => {
        if (event.key === "Escape") setDropdownOpen(null);
      }}
      onMouseLeave={() => setDropdownOpen(null)}
    >
      {/*
        `ltr:flex-row-reverse` pins the header's physical layout: the logo sits
        on the right and the notification / language / profile group on the
        left, in Arabic *and* in English.

        RTL already lays out that way on its own, so only the English side is
        reversed — which is why the variant is `ltr:` rather than a hardcoded
        `flex-row-reverse` that would flip Arabic back the wrong way. Source
        order is untouched, so the DOM still reads logo → nav → account for
        screen readers and keyboard tabbing.
      */}
      <div className="2xl:w-[83%] laptopmain:w-[88%] laptop:w-[87%] lg:w-[90%] laptopitm:w-[90%] w-[90%] container-fluid mx-auto flex ltr:flex-row-reverse justify-between items-center 2xl:py-4  laptop:py-5 laptopmain:py-4 lg:py-5 py-5 mobilescreen:py-3 mobilescreen:pb-1">
        {/* Logo */}
        <div>
          <Link href="/" onClick={close}>
            <Image
              src="/assets/auth/logo.svg"
              alt="Fursa"
              width={148}
              height={60}
              className="2xl:w-[108px] laptopmain:w-[100px] h-[60px] mobilescreen:h-[44px] mediumscreen1:w-[100px] laptop:w-[100px] lg:w-[100px] extrasmall:!w-[80px] mobilescreen:w-[100px]"
              preload={true}
              loading="eager"
              unoptimized
            />
          </Link>
        </div>

        {/* Desktop Menu */}
        <HeaderDesktopNav
          pathname={pathname}
          isLoggedIn={isLoggedIn}
          isVolunteer={isVolunteer}
          close={close}
          dropdownOpen={dropdownOpen}
          setDropdownOpen={setDropdownOpen}
          unreadCount={unreadCount}
        />

        {/* Desktop Buttons */}
        <div
          className={`hidden mediumscreen:flex items-center ${language === "ar" ? "gap-4" : "space-x-4"}`}
        >
          {/* Only participants scan — an organizer displays the printed code.
              The button renders nothing unless a session is live right now. */}
          <AttendanceScanButton enabled={isVolunteer} />
          {(isVolunteer || isOrganizer) && (
            <NotificationBadge close={close} unreadCount={unreadCount} />
          )}
          <LanguageSelection />
          {!isLoggedIn ? (
            <Link
              href="/login"
              className="h-[40px] mediumscreen3:h-[34px] cursor-pointer flex"
              onClick={close}
            >
              {/* A `<span>`, not a `<button>`: this is one navigation control,
                  and a `<button>` inside the `<Link>`'s `<a>` is invalid
                  content — two overlapping Tab stops for one destination, with
                  the inner one announced as a button that does nothing of its
                  own. `HeaderMobileMenu` already renders the same control this
                  way. `flex items-center` restores the vertical centring a
                  `<button>` applied by default, so the pill is unchanged. */}
              <span className="bg-primary-5 h-full text-white px-6 rounded-xl text-base font-semibold hover:opacity-90 transition-opacity flex items-center">
                {t("COMMON.SIGN_IN")}
              </span>
            </Link>
          ) : (
            <HeaderProfileDropdown
              isVolunteerUser={isVolunteer}
              pathname={pathname}
              profilePicUrl={profilePicUrl} defaultProfilePic={defaultProfilePic}
              dropdownOpen={dropdownOpen}
              setDropdownOpen={setDropdownOpen}
              close={close}
              handleLogout={handleLogout}
              handleLogoutAll={handleLogoutAll}
              hasOtherAccounts={hasOtherAccounts}
            />
          )}
        </div>

        {/* Mobile Menu Button */}
        {/* Same physical pin as the row above: the menu bars sit at the far
            left in both languages (client, 2026-10-15). RTL already puts the
            last child there; `ltr:flex-row-reverse` does it in English, so
            the group reads bars → language → bell → scan left to right in
            both, with the DOM order left alone. */}
        <div className="mediumscreen:hidden flex ltr:flex-row-reverse gap-5 items-center">
          {/* Mobile is where scanning actually happens — same gate, smaller icon. */}
          <AttendanceScanButton enabled={isVolunteer} mobile />
          {(isVolunteer || isOrganizer) && (
            <NotificationBadge close={close} unreadCount={unreadCount} mobile />
          )}
          <LanguageSelection />
          <button
            onClick={() => {
              setMenuOpen(!menuOpen);
              setDropdownOpen(null);
            }}
            aria-label={
              menuOpen
                ? t("COMMON.CLOSE_MENU") || "Close menu"
                : t("COMMON.OPEN_MENU") || "Open menu"
            }
            aria-expanded={menuOpen}
            className="focus:outline-none"
          >
            {menuOpen ? (
              <CloseIcon
                className="text-primary-5 font-bold text-[30px]"
                aria-hidden="true"
              />
            ) : (
              <Image
                src="/assets/auth/lucide-menu.svg"
                alt=""
                width={32}
                height={32}
                className="w-8 xss:w-[36px]"
                aria-hidden="true"
                unoptimized
              />
            )}
          </button>
        </div>
      </div>

      {/* Mobile Menu */}
      {menuOpen && (
        <HeaderMobileMenu
          pathname={pathname}
          isLoggedIn={isLoggedIn}
          isVolunteer={isVolunteer}
          close={close}
          handleLogout={handleLogout}
          handleLogoutAll={handleLogoutAll}
          dropdownOpen={dropdownOpen}
          setDropdownOpen={setDropdownOpen}
          profilePicUrl={profilePicUrl}
          defaultProfilePic={defaultProfilePic}
          unreadCount={unreadCount}
        />
      )}
    </nav>
  );
};

export default Header;
