/**
 * 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, ShoppingCart } from 'lucide-react';
import type { Content } from 'brainerce';
import { Button } from '@/components/ui/button';
// Locale-aware Link (client component — fine to render from this server
// component). Used for the static internal links (brand → /, cart) so the
// current locale prefix is preserved; merchant-configured nav items keep
// plain <a> since their URLs are arbitrary (may be external).
import { Link } from '@/core/lib/navigation';
import { HeaderAccount } from './header-account';
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="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 />
            <Link
              href="/cart"
              aria-label="Cart"
              className="text-foreground/80 hover:text-foreground hover:bg-muted/60 inline-flex h-9 w-9 items-center justify-center rounded-md transition-colors"
            >
              <ShoppingCart className="h-5 w-5" aria-hidden="true" />
            </Link>
          </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 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="text-lg">{brandLabel}</span>
          )}
        </Link>

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

          <% if (i18nEnabled) { %>
          <LanguageSwitcher />
          <% } %>
          <RegionSwitcher />

          <HeaderAccount />

          <Link
            href="/cart"
            aria-label="Cart"
            className="text-foreground/80 hover:text-foreground hover:bg-muted/60 inline-flex h-9 w-9 items-center justify-center rounded-md transition-colors"
          >
            <ShoppingCart className="h-5 w-5" aria-hidden="true" />
          </Link>

          {navItems.length > 0 ? (
            <details 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}`}>
                      <a
                        href={item.url}
                        className="text-foreground/80 hover:text-foreground hover:bg-muted block px-4 py-2 text-sm transition-colors"
                      >
                        {item.label}
                      </a>
                    </li>
                  ))}
                </ul>
              </nav>
            </details>
          ) : 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>
  );
}
