/**
 * Merchant-controlled site header.
 *
 * The merchant configures the header in the Brainerce dashboard under
 *   Sell → Content → Header
 *
 * Renders brand (logo or store-name fallback) + nav items + CTA + cart link,
 * with a `<details>` mobile menu that works without client-side JS. Everything
 * is generic — do NOT hardcode nav labels or logo paths here; the merchant
 * edits them in the dashboard and the change propagates within ~5 minutes.
 *
 * If `header` is null (404 from the API, or the merchant deleted the row),
 * we render a minimal static fallback with just the brand label and cart link
 * so the layout never collapses. New stores ship with a seeded HEADER row
 * from the backend (StoresService.seedDefaultContent), so the populated
 * branch is the common case.
 */
import * as React from 'react';
import { Menu } from 'lucide-react';
import type { Content } from 'brainerce';
import { Button } from '@/components/ui/button';
// Locale-aware links (client components — fine to render from this server
// component). `Link` is for the fixed internal links (brand → /). Everything the
// merchant configures goes through `SmartLink`: it keeps the locale prefix and
// soft-navigates for an internal path (no full page reload, 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 { 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';

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;
}

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';

  // Static fallback — runs when the Content API returned null (no HEADER row
  // for this store yet, or fetch failed). Keep the brand + cart so the page
  // always has a clickable home link and entry to checkout, but no nav since
  // the merchant hasn't defined any items.
  if (!header) {
    return (
      <header className="border-border bg-background/95 supports-[backdrop-filter]:bg-background/70 sticky top-0 z-40 border-b backdrop-blur">
        <div className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-4 px-4 sm:px-6 lg:px-8">
          <Link
            href="/"
            className="min-w-0 truncate text-lg font-semibold ltr:tracking-tight"
            aria-label={brandLabel}
          >
            {brandLabel}
          </Link>
          {/* Search lives in the fallback branch too — a store whose merchant
              has not seeded a HEADER row still needs to be searchable. */}
          <HeaderSearch className="hidden max-w-xs flex-1 sm:block" />
          <div className="flex items-center gap-2">
            <% if (i18nEnabled) { %>
            <LanguageSwitcher />
            <% } %>
            <RegionSwitcher />
            <HeaderAccount />
            <HeaderWishlist />
            <HeaderCart />
          </div>
        </div>
        {/* Narrow screens get the field on its own row rather than a cramped
            icon: the bar above is already three controls wide. */}
        <div className="mx-auto max-w-7xl px-4 pb-3 sm:hidden">
          <HeaderSearch />
        </div>
      </header>
    );
  }

  return (
    <header className="border-border bg-background/95 supports-[backdrop-filter]:bg-background/70 sticky top-0 z-40 border-b backdrop-blur">
      <div className="mx-auto flex h-16 max-w-7xl items-center justify-between gap-4 px-4 sm:px-6 lg:px-8">
        <Link
          href="/"
          className="flex min-w-0 items-center gap-2 font-semibold ltr:tracking-tight"
          aria-label={brandLabel}
        >
          {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-8 w-auto" />
          ) : (
            <span className="truncate text-lg">{brandLabel}</span>
          )}
        </Link>

        {navItems.length > 0 ? (
          <nav className="hidden items-center gap-8 md:flex">
            {navItems.map((item, idx) => (
              <SmartLink
                key={`${item.url}-${idx}`}
                href={item.url}
                className="text-foreground/80 hover:text-foreground text-sm font-medium transition-colors"
              >
                {item.label}
              </SmartLink>
            ))}
          </nav>
        ) : null}

        <HeaderSearch className="hidden max-w-xs flex-1 sm:block" />

        <div className="flex items-center gap-2">
          {cta ? (
            <Button asChild className="hidden sm:inline-flex">
              <SmartLink href={cta.url}>{cta.label}</SmartLink>
            </Button>
          ) : null}

          {/* With a menu, the switchers live there below `sm` (see the menu below): language,
              region, account, wishlist, cart and the menu button do not fit one 375px row, and
              the store name would be squeezed to nothing. `contents` keeps the row layout. */}
          <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
              menu button 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="text-foreground/80 hover:text-foreground hover:bg-muted/60 inline-flex h-9 w-9 cursor-pointer list-none items-center justify-center rounded-md transition-colors [&::-webkit-details-marker]:hidden">
                <Menu className="h-5 w-5" aria-hidden="true" />
                <span className="sr-only">Menu</span>
              </summary>
              <nav className="border-border bg-background absolute end-0 top-full z-50 mt-2 w-56 overflow-hidden rounded-lg border shadow-lg">
                <ul className="py-1">
                  {navItems.map((item, idx) => (
                    <li key={`m-${item.url}-${idx}`}>
                      <SmartLink
                        href={item.url}
                        className="text-foreground/80 hover:text-foreground hover:bg-muted block px-4 py-2 text-sm transition-colors"
                      >
                        {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="text-foreground/80 hover:text-foreground hover:bg-muted block px-4 py-2 text-sm transition-colors" />
                  </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 (and invisible) then. */}
                  <li className="flex flex-wrap items-center gap-2 px-4 py-2 empty:hidden sm:hidden">
                    <% if (i18nEnabled) { %>
                    <LanguageSwitcher />
                    <% } %>
                    <RegionSwitcher />
                  </li>
                </ul>
              </nav>
            </HeaderMobileMenu>
          ) : null}
        </div>
      </div>
      {/* Narrow screens get the field on its own row rather than a cramped
          icon: the bar above is already three controls wide. */}
      <div className="mx-auto max-w-7xl px-4 pb-3 sm:hidden">
        <HeaderSearch />
      </div>
    </header>
  );
}
