// Operator app shell header: brand + switcher + tabs + actions slot + Settings + identity + sign-out.
// Pure renderer (no fetching, no panel state) — the Root owns SettingsPanel. See COMPONENTS.md.
const { useState: useStateHeader, useRef: useRefHeader, useEffect: useEffectHeader } = React;

function AppHeader({ projects, currentProject, routeName, signedInUser, onSignOut, onOpenSettings, actions }) {
  const [switchOpen, setSwitchOpen] = useStateHeader(false);
  const switcherRef = useRefHeader(null);
  const slug = currentProject?.slug;

  // Standard dropdown dismissal — active only while open: click outside the
  // switcher (trigger + menu live inside switcherRef) or press Escape to close.
  useEffectHeader(() => {
    if (!switchOpen) return;
    const onDocMouseDown = (e) => {
      if (switcherRef.current && !switcherRef.current.contains(e.target)) setSwitchOpen(false);
    };
    const onKeyDown = (e) => { if (e.key === "Escape") setSwitchOpen(false); };
    document.addEventListener("mousedown", onDocMouseDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onDocMouseDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [switchOpen]);
  const tab = (name, label, path) => (
    <button
      onClick={() => window.navigate(path)}
      className={`px-3 py-1.5 text-sm font-bold rounded-lg transition-colors ${
        routeName === name ? "bg-neutral-900 text-white shadow-sm" : "text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100"
      }`}
    >{label}</button>
  );
  return (
    <header className="bg-white border-b border-neutral-200 px-6 py-3 flex items-center justify-between gap-4 sticky top-0 z-50">
      <div className="flex items-center gap-3 min-w-0">
        <button onClick={() => window.navigate("/")} className="bg-neutral-900 p-1.5 rounded-lg text-white shadow-inner" aria-label="All projects">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
            <rect x="6.5" y="5" width="11" height="9" rx="0.8" /><line x1="6.5" y1="9" x2="17.5" y2="9" /><line x1="12" y1="5" x2="12" y2="9" />
            <line x1="2.5" y1="17.5" x2="21.5" y2="17.5" /><circle cx="6" cy="20" r="1.4" /><circle cx="12" cy="20" r="1.4" /><circle cx="18" cy="20" r="1.4" />
          </svg>
        </button>
        <span className="font-bold tracking-tight text-neutral-800">Assembly Line</span>
        {/* project switcher */}
        <div className="relative" ref={switcherRef}>
          <button onClick={() => setSwitchOpen((v) => !v)} className="flex items-center gap-1 text-sm bg-indigo-50 text-indigo-700 border border-indigo-200 rounded-lg px-3 py-1.5 hover:bg-indigo-100">
            {currentProject ? currentProject.name : "All projects"} <span className="text-xs">▾</span>
          </button>
          {switchOpen && (
            <div className="absolute left-0 mt-1 w-64 bg-white border border-neutral-200 rounded-xl shadow-xl p-1 z-50">
              <button onClick={() => { setSwitchOpen(false); window.navigate("/"); }} className="w-full text-left text-sm px-3 py-2 rounded-lg text-neutral-600 hover:bg-neutral-50">All projects</button>
              {projects.map((p) => (
                <button key={p.slug} onClick={() => { setSwitchOpen(false); window.navigate(`/projects/${p.slug}`); }}
                  className={`w-full text-left text-sm px-3 py-2 rounded-lg hover:bg-neutral-50 ${p.slug === slug ? "bg-indigo-50 text-indigo-700 font-semibold" : "text-neutral-700"}`}>
                  {p.name}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* section tabs — only within a project */}
      <nav className="flex items-center gap-1">
        {slug && tab("board", "Live board", `/projects/${slug}`)}
        {slug && tab("plan", "Plan & timeline", `/projects/${slug}/plan`)}
        {slug && tab("reviews", "Reviews", `/projects/${slug}/reviews`)}
      </nav>

      <div className="flex items-center gap-3">
        {actions}
        {onOpenSettings && (
          <button onClick={onOpenSettings} className="flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-900 hover:bg-neutral-100 px-3 py-2 rounded-lg transition-colors" title="Notification settings">
            ⚙️ Settings
          </button>
        )}
        {signedInUser && <span className="text-sm text-neutral-500">Signed in as {signedInUser.username}</span>}
        {signedInUser && (
          <button onClick={onSignOut} className="text-sm font-medium text-neutral-600 hover:text-neutral-900 border border-neutral-200 rounded-lg px-3 py-1.5 hover:bg-neutral-100 transition-colors">Sign out</button>
        )}
      </div>
    </header>
  );
}

window.AppHeader = AppHeader;
