"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { AccountMenu } from "@/components/account-menu";
import { LogoutButton } from "@/components/logout-button";
import { PublicDesktopNav } from "@/components/public-desktop-nav";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { studioInfo } from "@/lib/site-data";

type NavItem = [string, string];

type HeaderSession = {
  role: "admin" | "member";
  email: string;
  name: string;
};

const publicPrimaryNav: NavItem[] = [
  ["Founder", "/founder"],
  ["Gallery", "/gallery"],
  ["Contact", "/contact"],
  ["Health form", "/health-form"],
];

const memberAccountItems: NavItem[] = [
  ["Dashboard", "/dashboard"],
];

const adminAccountItems: NavItem[] = [
  ["Admin", "/admin"],
  ["Dashboard", "/dashboard"],
];

const practiceNavItems: NavItem[] = [
  ["All services", "/services"],
  ["Classes", "/classes"],
  ["Healing", "/healing"],
  ["Meditation", "/meditation"],
  ["Retreats", "/retreats"],
  ["Programs", "/programs"],
];

const publicMobileBase: NavItem[] = [
  ["Founder", "/founder"],
  ...practiceNavItems,
  ["Gallery", "/gallery"],
  ["Contact", "/contact"],
  ["Health form", "/health-form"],
];

export function SiteHeader() {
  const [session, setSession] = useState<HeaderSession | null>(null);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const response = await fetch("/api/auth/session", { credentials: "same-origin" });
        if (!response.ok) return;
        const data = (await response.json()) as { session: HeaderSession | null };
        if (!cancelled) setSession(data.session);
      } catch {
        // Guest shell is fine if session lookup fails.
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const roleLabel = session?.role === "admin" ? "Admin" : session?.role === "member" ? "Member" : null;
  const accountItems = session?.role === "admin" ? adminAccountItems : memberAccountItems;
  const mobileNavItems: NavItem[] = session
    ? [...publicMobileBase, ["WhatsApp", studioInfo.whatsappUrl]]
    : [...publicMobileBase, ["WhatsApp", studioInfo.whatsappUrl], ["Member login", "/login"]];
  const desktopNav = publicPrimaryNav ?? [];

  return (
    <header className="glass-nav sticky top-0 z-50 relative">
      <nav className="mx-auto flex max-w-7xl items-center justify-between gap-2 px-3 py-3 sm:gap-3 sm:px-5 sm:py-4 lg:px-8">
        <Link href="/" className="flex min-w-0 max-w-[62%] items-center gap-2 sm:max-w-none sm:gap-3" aria-label="Zelosity home">
          <span className="relative size-9 shrink-0 overflow-hidden rounded-full bg-white/5 shadow-[0_8px_24px_rgba(0,0,0,0.28)] sm:size-11">
            <Image src="/zelosity/logo.png" alt="" fill sizes="44px" className="object-contain p-0.5" priority />
          </span>
          <span className="min-w-0">
            <span className="block truncate text-[15px] font-semibold tracking-[0.04em] text-[#f4f7f5] sm:text-base">
              Zelosity
            </span>
            <span className="mt-0.5 hidden text-xs tracking-[0.06em] text-[#d8c3a4] sm:block">
              A holistic wellness centre by Apurvaa
            </span>
          </span>
        </Link>

        <PublicDesktopNav items={desktopNav} />

        <div className="flex shrink-0 items-center gap-2 sm:gap-3">
          {!session ? (
            <Link
              href="/login"
              className="hidden px-2 py-2 text-[15px] font-medium tracking-wide text-[#f4f7f5]/90 transition hover:text-white sm:inline-flex"
            >
              Member login
            </Link>
          ) : null}
          {session?.role !== "admin" ? (
            <Link
              href="/contact#booking"
              className="btn-primary !min-h-10 !px-4 !py-2.5 text-[15px] font-semibold sm:!min-h-11 sm:!px-5"
            >
              Book now
            </Link>
          ) : null}
          {session ? (
            <span className="hidden sm:inline-flex">
              <AccountMenu label={roleLabel ?? "Account"} items={accountItems} />
            </span>
          ) : null}
        </div>
      </nav>
      <ThemeSwitcher className="site-theme-control hidden lg:flex" />
      <details className="mobile-menu lg:hidden">
        <summary className="mx-auto flex max-w-7xl cursor-pointer items-center justify-between px-4 py-3 text-sm font-semibold tracking-wide text-[#f4f7f5] sm:px-5">
          <span>Menu</span>
          <span className="text-xs uppercase tracking-[0.16em] text-[#c4a882]">{roleLabel || "Guest"}</span>
        </summary>
        <div className="mx-auto grid max-w-7xl gap-1 px-4 pb-4 sm:px-5">
          <div className="grid grid-cols-2 gap-1 sm:grid-cols-3">
            {mobileNavItems.map(([label, href]) => (
              <Link
                key={`${label}-${href}`}
                href={href}
                className="rounded-xl px-3 py-3 text-base font-medium text-[#e8efe9]/90 transition hover:bg-white/5 hover:text-white"
                {...(href.startsWith("http") ? { target: "_blank", rel: "noreferrer" } : {})}
              >
                {label}
              </Link>
            ))}
          </div>
          {session ? (
            <div className="mt-2 border-t border-white/10 pt-3">
              <p className="px-3 pb-1 text-xs uppercase tracking-[0.16em] text-[#c4a882]">{roleLabel} area</p>
              <div className="grid grid-cols-2 gap-1 sm:grid-cols-3">
                {accountItems.map(([label, href]) => (
                  <Link
                    key={`${label}-${href}`}
                    href={href}
                    className="rounded-xl px-3 py-3 text-base font-medium text-[#e8efe9]/90 transition hover:bg-white/5 hover:text-white"
                  >
                    {label}
                  </Link>
                ))}
              </div>
              <div className="pt-2">
                <LogoutButton />
              </div>
            </div>
          ) : null}
          <ThemeSwitcher className="mt-2 lg:hidden" />
        </div>
      </details>
    </header>
  );
}
