"use client";

import Link from "next/link";
import Image from "next/image";
import { images } from "@/branding/images";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import { LocaleSwitcher } from "@/components/ui/LocaleSwitcher";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchNavCategories } from "@/store/slices/navCategorySlice";
import { fetchProfile } from "@/store/slices/profileSlice";
import { slugify } from "@/lib/utils/slugify";
import type { AuthUser } from "@/types/api/auth.types";

interface HeaderProps {
  locale: string;
  activePage?: string;
}

export function Header({ locale }: HeaderProps) {
  const { t } = useTranslation("common");
  const router = useRouter();
  const pathname = usePathname();
  const dispatch = useAppDispatch();
  const { items: categories, isLoaded } = useAppSelector(
    (s) => s.navCategories,
  );
  const profileUser = useAppSelector((s) => s.profile.user);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [authUser, setAuthUser] = useState<AuthUser | null>(null);

  useEffect(() => {
    setAuthUser(getStoredUser());
  }, []);

  useEffect(() => {
    if (!isLoaded) dispatch(fetchNavCategories());
  }, [isLoaded, dispatch]);

  // Fetch fresh profile (for up-to-date avatar) once auth user is known
  useEffect(() => {
    if (authUser && !profileUser) dispatch(fetchProfile());
  }, [authUser, profileUser, dispatch]);

  const href = (path: string) => path;

  function isActive(segment: string): boolean {
    if (segment === "home") {
      return pathname === "/" || pathname === "/home";
    }
    return pathname.includes(segment);
  }

  const a = (segment: string) =>
    `nav-link${isActive(segment) ? " active" : ""}`;
  const aa = (segment: string) =>
    `nav-link nav-link-app${isActive(segment) ? " active" : ""}`;
  const ma = (segment: string) =>
    `mob-nav-link${isActive(segment) ? " active" : ""}`;

  function goSearch() {
    router.push(href("/search"));
    setMobileMenuOpen(false);
  }

  function closeMobileMenu() {
    setMobileMenuOpen(false);
  }

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        router.push(href("/search"));
      }
      if (e.key === "Escape") {
        setMobileMenuOpen(false);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [router]);

  useEffect(() => {
    if (mobileMenuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileMenuOpen]);

  return (
    <>
      <nav className="nav">
        {/* ── Row 1: logo + utilities ── */}
        <div className="wrap nav-row flex">
          <Link href={href("/")} className="logo" onClick={closeMobileMenu}>
            <Image
              src={images.appLogo}
              alt="DTNews"
              width={120}
              height={50}
              priority
              style={{ objectFit: "contain", height: 50, width: "auto" }}
            />
          </Link>

          <div className="nav-right">
            <button
              className="search"
              aria-label={t("nav.search_placeholder")}
              onClick={goSearch}
            >
              <svg className="icn-14" viewBox="0 0 24 24">
                <circle cx="11" cy="11" r="8" />
                <line x1="21" y1="21" x2="16.65" y2="16.65" />
              </svg>
              <span className="search-label">
                {t("nav.search_placeholder")}
              </span>
            </button>
            <LocaleSwitcher />
            {authUser ? (
              <Link
                href={href("/profile")}
                className="nav-avatar"
                aria-label="My profile"
              >
                {(() => {
                  const avatarImg = profileUser?.image && !profileUser.image.includes("no_img")
                    ? profileUser.image
                    : authUser.image && !authUser.image.includes("no_img")
                      ? authUser.image
                      : null;
                  const displayName = profileUser?.full_name ?? authUser.full_name;
                  return avatarImg ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={avatarImg}
                      alt={displayName}
                      style={{
                        width: 34,
                        height: 34,
                        borderRadius: "50%",
                        objectFit: "cover",
                        border: "2px solid var(--brand)",
                      }}
                    />
                  ) : (
                    <span
                      style={{
                        width: 34,
                        height: 34,
                        borderRadius: "50%",
                        background: "var(--brand)",
                        color: "#fff",
                        display: "inline-flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: 13,
                        fontWeight: 700,
                        flexShrink: 0,
                      }}
                    >
                      {displayName
                        .trim()
                        .split(" ")
                        .filter(Boolean)
                        .map((w: string) => w[0])
                        .slice(0, 2)
                        .join("")
                        .toUpperCase()}
                    </span>
                  );
                })()}
              </Link>
            ) : (
              <Link href={href("/login")} className="btn-app btn-app-desk">
                {t("nav.login")}
              </Link>
            )}
            <button
              className="mob-menu-btn"
              aria-label="Open navigation menu"
              onClick={() => setMobileMenuOpen(true)}
            >
              <svg viewBox="0 0 24 24">
                <line x1="3" y1="6" x2="21" y2="6" />
                <line x1="3" y1="12" x2="21" y2="12" />
                <line x1="3" y1="18" x2="21" y2="18" />
              </svg>
            </button>
          </div>
        </div>

        {/* ── Row 2: nav links ── */}
        <div className="wrap border-t border-border">
          <div className="nav-links">
            <Link className={a("home")} href={href("/")}>
              {t("nav.home")}
            </Link>
            {categories.map((cat) => {
              const slug = slugify(cat.name);
              return (
                <Link
                  key={cat.id}
                  className={a(`/category/${slug}`)}
                  href={href(`/category/${slug}`)}
                >
                  {cat.name}
                </Link>
              );
            })}

            <span className="nav-sep" aria-hidden="true" />

            <Link className={aa("/topics")} href={href("/topics")}>
              <svg className="nav-ico" viewBox="0 0 24 24">
                <rect x="3" y="3" width="7" height="7" rx="1.5" />
                <rect x="14" y="3" width="7" height="7" rx="1.5" />
                <rect x="3" y="14" width="7" height="7" rx="1.5" />
                <rect x="14" y="14" width="7" height="7" rx="1.5" />
              </svg>
              {t("nav.topics")}
            </Link>

            <Link className={aa("/feeds")} href={href("/feeds")}>
              <svg className="nav-ico" viewBox="0 0 24 24">
                <path d="M4 11a9 9 0 0 1 9 9M4 4a16 16 0 0 1 16 16" />
                <circle cx="5" cy="19" r="1.6" />
              </svg>
              {t("nav.feeds")}
            </Link>

            <Link className={aa("/shorts")} href={href("/shorts")}>
              <svg className="nav-ico" viewBox="0 0 24 24">
                <path d="M13 2L4 14h7l-1 8 9-12h-7z" />
              </svg>
              {t("nav.shorts")}
            </Link>

            <span className="nav-sep" aria-hidden="true" />

            <Link className={a("/epaper")} href={href("/epaper")}>
              {t("nav.epaper")}
            </Link>
          </div>
        </div>
      </nav>

      {mobileMenuOpen && (
        <div
          className="mob-nav open"
          role="dialog"
          aria-modal="true"
          aria-label="Navigation menu"
        >
          <div
            className="mob-nav-backdrop"
            onClick={closeMobileMenu}
            aria-hidden="true"
          />
          <div className="mob-nav-panel">
            <div className="mob-nav-head">
              <Link href={href("/")} className="logo" onClick={closeMobileMenu}>
                <Image
                  src={images.appLogo}
                  alt="DTNews"
                  width={120}
                  height={36}
                  style={{ objectFit: "contain", height: 36, width: "auto" }}
                />
              </Link>
              <button
                className="mob-close-btn"
                aria-label="Close navigation menu"
                onClick={closeMobileMenu}
              >
                <svg viewBox="0 0 24 24">
                  <line x1="18" y1="6" x2="6" y2="18" />
                  <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>

            <nav className="mob-nav-links">
              <Link
                className={ma("home")}
                href={href("/")}
                onClick={closeMobileMenu}
              >
                {t("nav.home")}
              </Link>
              {categories.map((cat) => {
                const slug = slugify(cat.name);
                return (
                  <Link
                    key={cat.id}
                    className={ma(`/category/${slug}`)}
                    href={href(`/category/${slug}`)}
                    onClick={closeMobileMenu}
                  >
                    {cat.name}
                  </Link>
                );
              })}

              <div className="mob-nav-sep" aria-hidden="true" />

              <Link
                className={ma("/topics")}
                href={href("/topics")}
                onClick={closeMobileMenu}
              >
                {t("nav.topics")}
              </Link>
              <Link
                className={ma("/feeds")}
                href={href("/feeds")}
                onClick={closeMobileMenu}
              >
                {t("nav.feeds")}
              </Link>
              <Link
                className={ma("/shorts")}
                href={href("/shorts")}
                onClick={closeMobileMenu}
              >
                {t("nav.shorts")}
              </Link>

              <div className="mob-nav-sep" aria-hidden="true" />

              <Link
                className={ma("/epaper")}
                href={href("/epaper")}
                onClick={closeMobileMenu}
              >
                {t("nav.epaper")}
              </Link>

              <div className="mob-nav-sep" aria-hidden="true" />

              <button
                className="mob-nav-link mob-search-btn"
                onClick={goSearch}
              >
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <circle cx="11" cy="11" r="8" />
                  <line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
                {t("nav.search_placeholder")}
              </button>
            </nav>

            <div className="mob-nav-bottom">
              {authUser ? (
                <Link
                  href={href("/profile")}
                  className="mob-login-btn"
                  onClick={closeMobileMenu}
                  style={{ display: "flex", alignItems: "center", gap: 10 }}
                >
                  {authUser.image && !authUser.image.includes("no_img") ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={authUser.image}
                      alt={authUser.full_name}
                      style={{
                        width: 28,
                        height: 28,
                        borderRadius: "50%",
                        objectFit: "cover",
                      }}
                    />
                  ) : (
                    <span
                      style={{
                        width: 28,
                        height: 28,
                        borderRadius: "50%",
                        background: "var(--brand)",
                        color: "#fff",
                        display: "inline-flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: 11,
                        fontWeight: 700,
                        flexShrink: 0,
                      }}
                    >
                      {authUser.full_name
                        .trim()
                        .split(" ")
                        .filter(Boolean)
                        .map((w) => w[0])
                        .slice(0, 2)
                        .join("")
                        .toUpperCase()}
                    </span>
                  )}
                  {authUser.full_name}
                </Link>
              ) : (
                <Link
                  href={href("/login")}
                  className="mob-login-btn"
                  onClick={closeMobileMenu}
                >
                  {t("nav.login")}
                </Link>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
