"use client";

import Image from "next/image";
import Link from "next/link";
import { useSyncExternalStore } from "react";

import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { Button } from "@/components/ui/button";
import { Typography } from "@/components/ui/typography";
import { useTranslation } from "@/hooks/useTranslation";
import { getAuthToken, decodeTokenRole } from "@/lib/auth/session";
import { ADMIN_ROLES, SUPPLIER_ROLES } from "@/lib/constants/auth";
import { ROUTES } from "@/lib/constants/routes";

import { HomeMobileNav } from "./HomeMobileNav";
import { NAV_LINKS } from "./lib/content";

// No native "the auth cookie changed" event exists, but every login/logout in
// this app is followed by a route navigation, which already re-renders this
// component and re-reads the snapshot below — so a no-op subscription is safe.
function subscribeToAuth() {
  return () => {};
}

function getDashboardHref(): string | null {
  const token = getAuthToken();
  if (!token) return null;
  const role = decodeTokenRole(token);
  if (!role) return null;
  if (ADMIN_ROLES.includes(role)) return ROUTES.ADMIN.DASHBOARD;
  if (SUPPLIER_ROLES.includes(role)) return ROUTES.SUPPLIER.DASHBOARD;
  return null;
}

// The auth cookie isn't readable during SSR, so the server snapshot is always
// "not authenticated" — matches useSyncExternalStore's hydration-safe contract.
function getServerDashboardHref() {
  return null;
}

/**
 * Landing-page navigation. Logo at the inline-start edge, links + auth CTAs at
 * inline-end — a plain flex row mirrors LTR/RTL for free. Full nav on `lg+`;
 * below that, the shared shadcn sidebar drawer (`HomeMobileNav`). Sticky +
 * translucent (glass) so content scrolls under it. Auth-aware: a signed-in user
 * sees "Dashboard" instead of the two provider CTAs.
 */
export function Header() {
  const { t } = useTranslation();
  const dashboardHref = useSyncExternalStore(
    subscribeToAuth,
    getDashboardHref,
    getServerDashboardHref,
  );

  return (
    <header className="sticky top-0 z-50 border-b border-border bg-white/80 backdrop-blur-md">
      <div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 py-3 sm:px-6 lg:px-8">
        <Link
          href={ROUTES.HOME}
          className="flex shrink-0 items-center"
          aria-label="Washy"
        >
          <Image
            src="/icon/horizontal_icon.png"
            alt="Washy"
            width={500}
            height={152}
            className="h-8 w-auto sm:h-9"
            priority
          />
        </Link>

        {/* Desktop nav */}
        <nav className="hidden items-center gap-1 lg:flex">
          {NAV_LINKS.map((link) => (
            <a
              key={link.key}
              href={link.href}
              className="rounded-lg px-3 py-2 text-secondary-text transition-colors hover:bg-accent hover:text-primary-blue"
            >
              <Typography
                as="span"
                variant="body"
                color="inherit"
                className="font-medium"
              >
                {t(`home.nav.${link.key}`)}
              </Typography>
            </a>
          ))}
        </nav>

        <div className="flex shrink-0 items-center gap-2">
          <div className="hidden items-center gap-2 lg:flex">
            {dashboardHref ? (
              <Link
                // href={dashboardHref}
                href={"#"}
              >
                <Button>{t("dashboard.title")}</Button>
              </Link>
            ) : (
              <>
                <Link
                  // href={ROUTES.AUTH.LOGIN}
                  href={"#"}
                >
                  <Button variant="secondary">
                    {t("home.nav.providerLogin")}
                  </Button>
                </Link>
                <Link
                  //  href={ROUTES.AUTH.REGISTER_PROVIDER}
                  href={"#"}
                >
                  <Button>{t("home.nav.registerProvider")}</Button>
                </Link>
              </>
            )}
          </div>
          <LanguageSwitcher />
          <HomeMobileNav dashboardHref={dashboardHref} />
        </div>
      </div>
    </header>
  );
}
