"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { nav, site } from "@/lib/site";
import { DownloadButton } from "./DownloadButton";
import {
  IconArrow,
  IconMenu,
  IconMoon,
  IconSun,
  IconWindows,
  IconX,
} from "./icons";

function navClass(pathname: string, href: string) {
  const active = pathname === href || pathname.startsWith(`${href}/`);
  return `nav-link${active ? " is-active" : ""}`;
}

export function Header() {
  const pathname = usePathname();
  const headerRef = useRef<HTMLElement>(null);
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const onResize = () => {
      if (window.innerWidth >= 1024) setDrawerOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setDrawerOpen(false);
    };
    window.addEventListener("resize", onResize);
    document.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("resize", onResize);
      document.removeEventListener("keydown", onKey);
    };
  }, []);

  useEffect(() => {
    if (!drawerOpen) return;
    // Lock body scroll while the mobile drawer is open and restore on close.
    const drawer = document.getElementById("drawer");
    const body = document.body;
    const scrollY = window.scrollY;
    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    const previousBody = {
      position: body.style.position,
      top: body.style.top,
      left: body.style.left,
      right: body.style.right,
      width: body.style.width,
      overflowY: body.style.overflowY,
      paddingRight: body.style.paddingRight,
    };

    body.style.position = "fixed";
    body.style.top = `-${scrollY}px`;
    body.style.left = "0";
    body.style.right = "0";
    body.style.width = "100%";
    body.style.overflowY = "hidden";
    if (scrollbarWidth > 0) {
      body.style.paddingRight = `${scrollbarWidth}px`;
    }

    const block = (event: Event) => {
      const target = event.target as Node | null;
      if (drawer && target && drawer.contains(target)) return;
      event.preventDefault();
    };
    document.addEventListener("wheel", block, { passive: false });
    document.addEventListener("touchmove", block, { passive: false });
    return () => {
      document.removeEventListener("wheel", block);
      document.removeEventListener("touchmove", block);
      body.style.position = previousBody.position;
      body.style.top = previousBody.top;
      body.style.left = previousBody.left;
      body.style.right = previousBody.right;
      body.style.width = previousBody.width;
      body.style.overflowY = previousBody.overflowY;
      body.style.paddingRight = previousBody.paddingRight;
      window.scrollTo(0, scrollY);
    };
  }, [drawerOpen]);

  useEffect(() => {
    const drawer = document.getElementById("drawer");
    const header = headerRef.current;
    if (!drawer || !header || !drawerOpen) return;
    drawer.style.height = `${window.innerHeight - header.getBoundingClientRect().bottom}px`;
  }, [drawerOpen]);

  function toggleTheme() {
    const root = document.documentElement;
    const next = root.getAttribute("data-bs-theme") === "dark" ? "light" : "dark";
    root.setAttribute("data-bs-theme", next);
    try {
      localStorage.setItem("gptdefend-theme", next);
    } catch {
      /* ignore */
    }
  }

  function closeDrawer() {
    setDrawerOpen(false);
  }

  const headerClass = [
    "site-header",
    scrolled ? "is-scrolled" : "",
    drawerOpen ? "drawer-open" : "",
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <>
      <div className="promo-bar">
        <div className="container">
          <span className="promo-dot" />
          <span>{site.name} for Windows is free while in beta</span>
          <DownloadButton>
            Get it now <IconArrow />
          </DownloadButton>
        </div>
      </div>

      <header
        ref={headerRef}
        className={headerClass}
        data-header
      >
        <div className="container header-inner">
          <Link className="logo" href="/" aria-label={`${site.name} home`}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              className="w-auto nav-logo-light"
              src="/assets/img/logo.svg"
              alt=""
            />
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              className="w-auto nav-logo-dark"
              src="/assets/img/logo-white.svg"
              alt=""
            />
          </Link>

          <nav className="main-nav" aria-label="Primary">
            <ul>
              {nav.map((item) => (
                <li key={item.key}>
                  <Link
                    className={navClass(pathname, item.href)}
                    href={item.href}
                  >
                    {item.label}
                  </Link>
                </li>
              ))}
            </ul>
          </nav>

          <div className="header-actions">
            <button
              className="icon-btn"
              type="button"
              data-theme-toggle
              aria-label="Switch color theme"
              onClick={toggleTheme}
            >
              <IconMoon className="i-moon" />
              <IconSun className="i-sun" />
            </button>
            <DownloadButton className="btn-av btn-lime d-none d-md-inline-flex">
              Free download{" "}
              <span className="btn-arrow">
                <IconArrow />
              </span>
            </DownloadButton>
            <button
              className="icon-btn burger"
              type="button"
              data-drawer-toggle
              aria-expanded={drawerOpen}
              aria-controls="drawer"
              aria-label={drawerOpen ? "Close menu" : "Open menu"}
              onClick={() => setDrawerOpen((open) => !open)}
            >
              <IconMenu className="i-open" />
              <IconX className="i-close" />
            </button>
          </div>
        </div>

        <div
          className={`drawer${drawerOpen ? " is-open" : ""}`}
          id="drawer"
        >
          <nav aria-label="Mobile">
            {nav.map((item) => (
              <Link
                key={item.key}
                className="top"
                href={item.href}
                onClick={closeDrawer}
              >
                {item.label}
              </Link>
            ))}
          </nav>
          <DownloadButton
            className="btn-av btn-lime btn-lg w-100"
            onClick={closeDrawer}
          >
            <IconWindows /> Download for Windows
          </DownloadButton>
        </div>
      </header>
    </>
  );
}
