"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { CATEGORIES, slugifyCategory } from "./categories";
import { useSession } from "next-auth/react";
import MobileHeaderShrunk from "./MobileHeaderShrunk";

type HeaderProps = {
  forceScrolled?: boolean;
};

export default function MobileHeader({ forceScrolled = false }: HeaderProps) {
  const [isShrunk, setIsShrunk] = useState(forceScrolled);
  const { data: session, status } = useSession();
  const authLabel =
    status === "authenticated"
      ? session!.user.name || session!.user.email || "Account"
      : "Sign In / Sign Up";

  const categoryIcons: Record<string, string> = {
    Interior: "/categories/cat-interior.png",
    Tools: "/categories/cat-tools.png",
    Exterior: "/categories/cat-exterior.png",
    Drivetrain: "/categories/cat-drivetrain.png",
    Lighting: "/categories/cat-lighting.png",
    Suspension: "/categories/cat-suspension.png",
    Audio: "/categories/cat-audio.png",
    Performance: "/categories/cat-performance.png",
  };

  useEffect(() => {
    if (forceScrolled) {
      setIsShrunk(true);
      return;
    }

    const onScroll = () => setIsShrunk(window.scrollY > 120);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [forceScrolled]);

  if (isShrunk) {
    return <MobileHeaderShrunk />;
  }

  return (
    <header className="so-header so-header--mobile">
      <div className="container so-header__mobile">
        <div className="so-header__top">
          <Link href="/" className="so-header__logo-wrap">
            <img
              src="/icons/logo.png"
              className="so-header__logo"
              alt="Shifted Offroad"
            />
          </Link>
        </div>

        <div className="so-header__categories">
          <nav className="so-header__nav so-header__nav--mobile">
            {CATEGORIES.map((c) => (
              <Link
                key={c}
                href={`/category/${slugifyCategory(c)}`}
                className="so-navitem"
                style={{
                  backgroundImage: `url(${categoryIcons[c] || ""})`,
                }}
              >
                <span className="so-navitem__label">{c}</span>
              </Link>
            ))}
          </nav>
          <div className="so-header__mobile-tools">
            <input
              className="so-header__search"
              type="search"
              placeholder="Search"
              aria-label="Search"
            />
            <Link href="/login" className="so-auth-icon" aria-label="Sign in">
              <span className="so-auth-icon__glyph" aria-hidden="true" />
            </Link>
          </div>
        </div>
      </div>
    </header>
  );
}
