'use client'

/**
 * The top strip and the sticky header.
 *
 * A client component for one reason: the phone menu opens and closes. Everything it shows is handed to
 * it already resolved — labels, hrefs, which link is the current page — so it holds no knowledge of the
 * CMS, no locale logic and no address of its own, and the server stays the only place that reads either.
 *
 * The language control is a LINK, not a button: it points at this same path in the other language. So it
 * works before hydration, it can be opened in a new tab, and a search engine follows it to the other
 * edition — which a button toggling localStorage would hide.
 */

import { useEffect, useRef, useState } from 'react'
import { Icon } from './icons'
import { ThemeToggle } from './Theme'

export type NavItem = { label: string; href: string; current: boolean }

type Props = {
  brand: string
  logo: string
  banner?: string | null
  nav: NavItem[]
  /** This same page in the other language, and what to call that language on the button. */
  altHref: string
  altLang: 'ar' | 'en'
  altLabel: string
  signIn?: { href: string; label: string } | null
  labels: { menu: string; light: string; dark: string; langSwitch: string }
  defaultTheme: 'light' | 'dark'
}

export function SiteHeader({ brand, logo, banner, nav, altHref, altLang, altLabel, signIn, labels, defaultTheme }: Props) {
  const [open, setOpen] = useState(false)
  const panel = useRef<HTMLElement | null>(null)

  // Escape closes it, and the focus goes back to the button that opened it — otherwise a keyboard user
  // is left in a panel that is no longer on screen.
  const button = useRef<HTMLButtonElement | null>(null)
  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false)
        button.current?.focus()
      }
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open])

  return (
    <>
      {banner ? <div className="topbar">{banner}</div> : null}
      <header className="site-header">
        <div className="container header-inner">
          <a className="brand-link" href={nav[0]?.href || '/'} aria-label={brand}>
            <img className="logo" src={logo} alt={brand} width={170} height={48} />
          </a>

          <nav className="nav" aria-label={brand}>
            {nav.map((n) => (
              <a key={n.href} className={n.current ? 'active' : undefined} href={n.href}
                 aria-current={n.current ? 'page' : undefined}>
                {n.label}
              </a>
            ))}
          </nav>

          <div className="tools">
            {/* hrefLang and lang let a browser and a crawler both see what this leads to. */}
            <a className="iconbtn langbtn" href={altHref} hrefLang={altLang} lang={altLang}
               aria-label={labels.langSwitch} title={labels.langSwitch}>
              {altLabel}
            </a>
            <ThemeToggle label={{ light: labels.light, dark: labels.dark }} fallback={defaultTheme} />
            {signIn ? (
              <a className="btn small secondary login" href={signIn.href} rel="noopener">
                <Icon name="signin" />
                {signIn.label}
              </a>
            ) : null}
            <button ref={button} className="iconbtn menubtn" type="button"
                    aria-expanded={open} aria-controls="mobilemenu" aria-label={labels.menu}
                    onClick={() => setOpen((v) => !v)}>
              <Icon name={open ? 'close' : 'menu'} />
            </button>
          </div>
        </div>

        <nav id="mobilemenu" ref={panel} className="mobilemenu" hidden={!open} aria-label={labels.menu}>
          {nav.map((n) => (
            <a key={n.href} href={n.href} aria-current={n.current ? 'page' : undefined} onClick={() => setOpen(false)}>
              {n.label}
            </a>
          ))}
          {signIn ? <a href={signIn.href} rel="noopener">{signIn.label}</a> : null}
        </nav>
      </header>
    </>
  )
}
