"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { useAuth } from "@/components/auth/AuthProvider";
import { UserMenu } from "@/components/auth/UserMenu";
import { Button } from "./Button";
import { Logo } from "./Logo";
import { cn } from "@/lib/cn";

const links = [
  { href: "/paid-posts", label: "Paid Posts" },
  { href: "/#creators", label: "Creators" },
  { href: "/signup?role=brand", label: "Brands", id: "brands" },
  { href: "/#pricing", label: "Getting started" },
  { href: "/contact", label: "Contact" },
  { href: "/signup", label: "Search" },
];

function pathOf(href: string) {
  return (href.split("#")[0] || "/").split("?")[0] || "/";
}

function AuthActions({ compact = false }: { compact?: boolean }) {
  const pathname = usePathname();
  const { user } = useAuth();

  if (user) {
    return <UserMenu compact={compact} />;
  }

  if (compact) {
    return (
      <>
        <Button href="/signin" variant="secondary">
          Log in
        </Button>
        <Button href="/signup">Get started</Button>
      </>
    );
  }

  return (
    <>
      <Button
        href="/signin"
        variant="secondary"
        className="px-[1.1rem] text-[0.9rem]"
        aria-current={pathname === "/signin" ? "page" : undefined}
      >
        Log in
      </Button>
      <Button href="/signup" className="px-[1.1rem] text-[0.9rem] max-nav:hidden" aria-current={pathname === "/signup" ? "page" : undefined}>
        Get started
      </Button>
    </>
  );
}

export function Header() {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [stuck, setStuck] = useState(false);

  useEffect(() => {
    setOpen(false);
  }, [pathname]);

  useEffect(() => {
    document.body.classList.toggle("overflow-hidden", open);
    return () => document.body.classList.remove("overflow-hidden");
  }, [open]);

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

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  const isPage = (href: string) => {
    if (href.includes("#")) return false;
    return pathname === pathOf(href);
  };

  const navClass = (href: string) =>
    cn("hover:text-primary", isPage(href) && "font-semibold text-primary");

  return (
    <header
      className={cn(
        "sticky top-0 z-60 border-b border-line bg-bg/86 backdrop-blur-md",
        stuck && "shadow-[0_8px_24px_-20px_rgba(23,37,84,0.5)]",
      )}
      id="nav"
    >
      <nav className="mx-auto flex h-header w-full max-w-page items-center gap-8 px-4 md:px-6" aria-label="Primary">
        <Logo />
        <div className="ml-auto hidden gap-5 text-[0.92rem] text-ink-60 nav:flex">
          {links.map((l) => (
            <Link
              key={l.id ?? l.label}
              className={navClass(l.href)}
              href={l.href}
              aria-current={isPage(l.href) ? "page" : undefined}
            >
              {l.label}
            </Link>
          ))}
        </div>
        <div className="flex items-center gap-2.5 max-[560px]:hidden max-nav:ml-auto max-nav:mr-2.5">
          <AuthActions />
        </div>
        <button
          type="button"
          className="ml-auto hidden size-11 shrink-0 items-center justify-center rounded-pv border-[1.5px] border-line text-primary hover:border-primary max-nav:inline-flex max-nav:ml-0 max-[560px]:ml-auto"
          aria-expanded={open}
          aria-controls="mobile-navigation"
          aria-label={open ? "Close navigation" : "Open navigation"}
          onClick={() => setOpen((v) => !v)}
        >
          <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" width="22" height="22">
            {open ? (
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            ) : (
              <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
            )}
          </svg>
        </button>
      </nav>
      <div
        className={cn(
          "border-t border-line bg-bg p-4 nav:hidden",
          open
            ? "fixed inset-x-0 top-[70px] bottom-0 z-59 flex h-[calc(100dvh-70px)] flex-col overflow-y-auto"
            : "hidden",
        )}
        id="mobile-navigation"
        hidden={!open}
      >
        {links.map((l) => (
          <Link
            key={`m-${l.id ?? l.label}`}
            className={cn(
              "block border-b border-line p-3 text-[0.95rem] text-black/72 hover:text-primary",
              isPage(l.href) && "font-semibold text-primary",
            )}
            href={l.href}
            aria-current={isPage(l.href) ? "page" : undefined}
            onClick={() => setOpen(false)}
          >
            {l.label}
          </Link>
        ))}
        <div className="mt-auto flex flex-col gap-2.5 pt-4 text-center">
          <AuthActions compact />
        </div>
      </div>
    </header>
  );
}
