/**
 * Merchant-controlled site header.
 *
 * The merchant configures the header in the Brainerce dashboard under
 *   Sell → Content → Header
 *
 * Sticky, translucent warm-white bar: brand (serif) at the start, nav in the
 * middle (desktop), actions at the end (language / account / cart / mobile
 * menu). Everything is generic — nav labels and logo come from the dashboard.
 * If `header` is null we render the same chrome with just brand + actions so
 * the layout never collapses.
 */
import * as React from 'react';
// `Link` is for the fixed internal link (brand → /). Everything the merchant
// configures goes through `SmartLink`: it keeps the locale prefix and
// soft-navigates for an internal path (so the cart state survives), and renders
// a plain <a> for an external URL, mailto: or tel:.
import { Link, SmartLink } from '@/core/lib/navigation';
import type { Content } from 'brainerce';
import { HeaderAccount } from './header-account';
import { HeaderCart } from './header-cart';
import { HeaderWishlist, HeaderWishlistMenuItem } from './header-wishlist';
import { HeaderMobileMenu } from './header-mobile-menu';
import { HeaderSearch } from './header-search';
<% if (i18nEnabled) { %>
import { LanguageSwitcher } from '@/ui/layout/language-switcher';
<% } %>
import { RegionSwitcher } from '@/ui/layout/region-switcher';
import { IconMenu } from '@/ui/shared/icons';
import { resolveNavUrl } from '@/ui/layout/nav-url';

interface SiteHeaderProps {
  /** Pre-fetched header payload (server-side). `null` triggers static fallback. */
  header: Content<'HEADER'> | null;
  /** Fallback brand label when the merchant hasn't uploaded a logo yet. */
  storeName?: string;
}

function Brand({
  logo,
  brandLabel,
}: {
  logo?: { src: string; alt: string } | null;
  brandLabel: string;
}) {
  return (
    <Link
      href="/"
      aria-label={brandLabel}
      className="flex min-w-0 shrink items-center gap-2 rounded-lg"
    >
      {logo ? (
        // eslint-disable-next-line @next/next/no-img-element -- merchant-supplied URL, dynamic optimization handled by CDN
        <img src={logo.src} alt={logo.alt} className="h-9 w-auto object-contain" />
      ) : (
        <span className="truncate font-display text-xl font-semibold leading-none text-foreground sm:text-2xl">
          {brandLabel}
        </span>
      )}
    </Link>
  );
}

export function SiteHeader({ header, storeName }: SiteHeaderProps) {
  const data = header?.data;
  const logo = data?.logo;
  const navItems = data?.navItems ?? [];
  const cta = data?.cta;
  const brandLabel = logo?.alt || storeName || 'Store';

  return (
    <header className="sticky top-0 z-40 border-b bg-background/90 backdrop-blur supports-[backdrop-filter]:bg-background/80">
      <div className="container-page flex h-16 items-center justify-between gap-4 sm:h-[4.5rem]">
        <Brand logo={logo ?? null} brandLabel={brandLabel} />

        {navItems.length > 0 && (
          <nav aria-label="Main" className="hidden md:block">
            <ul className="flex items-center gap-1">
              {navItems.map((item, idx) => (
                <li key={`${item.url}-${idx}`}>
                  <SmartLink
                    href={resolveNavUrl(item.url)}
                    className="rounded-full px-4 py-2 text-sm font-medium text-foreground/80 transition-colors hover:bg-secondary hover:text-foreground"
                  >
                    {item.label}
                  </SmartLink>
                </li>
              ))}
            </ul>
          </nav>
        )}

        <div className="flex items-center gap-1 sm:gap-2">
          {/* Collapses to an icon button below `sm` — see header-search.tsx. */}
          <HeaderSearch />
          {cta ? (
            <SmartLink
              href={resolveNavUrl(cta.url)}
              className="btn-primary btn-sm hidden lg:inline-flex"
            >
              {cta.label}
            </SmartLink>
          ) : null}
          {/* With a menu, the switchers live there below `sm` (see the menu below): language,
              region, search, account, wishlist, cart and the menu button do not fit one 375px
              row. `contents` keeps the row layout from `sm` up. */}
          <div className={navItems.length > 0 ? 'hidden sm:contents' : 'contents'}>
<% if (i18nEnabled) { %>
            <LanguageSwitcher />
<% } %>
            <RegionSwitcher />
          </div>
          <HeaderAccount />
          {/* With a menu, the wishlist link lives there below `sm`: the icon would push the burger
              off a 375px screen on a store with language + region switchers. */}
          <HeaderWishlist hideOnMobile={navItems.length > 0} />
          <HeaderCart />

          {navItems.length > 0 && (
            <HeaderMobileMenu className="group relative md:hidden">
              <summary
                className="flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-full text-foreground transition-colors hover:bg-secondary [&::-webkit-details-marker]:hidden"
                aria-label="Menu"
              >
                <IconMenu size={20} />
              </summary>
              <nav
                aria-label="Mobile"
                className="absolute end-0 top-12 z-50 w-56 rounded-xl border bg-background p-2 shadow-lg"
              >
                <ul className="flex flex-col">
                  {navItems.map((item, idx) => (
                    <li key={`m-${item.url}-${idx}`}>
                      <SmartLink
                        href={resolveNavUrl(item.url)}
                        className="block rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-secondary"
                      >
                        {item.label}
                      </SmartLink>
                    </li>
                  ))}
                  {/* The header icon is hidden below `sm`; this is the way to the wishlist there. */}
                  <li className="sm:hidden">
                    <HeaderWishlistMenuItem className="block rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-secondary" />
                  </li>
                  {/* Below `sm` the header's own switchers are hidden. Both render nothing on a
                      store with one language / one region, so the row is empty (invisible) then. */}
                  <li className="flex flex-wrap items-center gap-2 px-3 py-2 empty:hidden sm:hidden">
<% if (i18nEnabled) { %>
                    <LanguageSwitcher />
<% } %>
                    <RegionSwitcher />
                  </li>
                  {cta ? (
                    <li className="mt-1 border-t pt-2">
                      <SmartLink
                        href={resolveNavUrl(cta.url)}
                        className="block rounded-lg px-3 py-2.5 text-sm font-semibold text-primary transition-colors hover:bg-secondary"
                      >
                        {cta.label}
                      </SmartLink>
                    </li>
                  ) : null}
                </ul>
              </nav>
            </HeaderMobileMenu>
          )}
        </div>
      </div>
    </header>
  );
}
