import { useState } from 'react';
import { Link, NavLink } from 'react-router';
import { Menu } from 'lucide-react';
import { EditableTitle } from '@/components/EditableTitle';
// import { Menu, Terminal } from 'lucide-react'; // Terminal used by the commented-out web inspector button
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import type { DockItem } from '../Dock';
import { useIsTouch } from '../useIsTouch';
import { UserMenu } from './UserMenu';
import { JobsIndicator } from './JobsIndicator';
import { RescanButton } from '../Rescan/RescanButton';
import { usePageTitle } from '@/state/usePageTitle';
// import { BugReportButton } from '../BugReport/BugReportButton';

// Center title: click to rename this browser tab. The name is kept in sessionStorage, so it survives a
// refresh and navigation and dies with the tab — see usePageTitle. `allowEmpty` is what makes clearing
// the field hand the tab back to the route's own name.
function EditablePageTitle() {
  const [title, rename] = usePageTitle();

  return (
    <EditableTitle
      value={title}
      onCommit={rename}
      allowEmpty
      ariaLabel="Tab name"
      hint="Click to rename this tab — clear it to go back to the page name"
      className="pointer-events-auto max-w-[50vw] cursor-text truncate text-base font-bold text-[#1d2724] transition-opacity hover:opacity-70 md:text-xl"
      inputClassName="pointer-events-auto max-w-[50vw] border-b border-[#1d2724]/40 bg-transparent text-center text-base font-bold text-[#1d2724] outline-none md:text-xl"
    />
  );
}

type HeaderProps = {
  dockItems?: DockItem[];
  /**
   * Stand down for a panel that has taken the whole window. `display: none` rather than an unmount: the
   * header holds a half-typed tab rename and its own popovers, and a panel going fullscreen is not a
   * reason to throw those away. It is `fixed`, so hiding it costs no layout shift either.
   */
  hidden?: boolean;
};

export function Header({ dockItems, hidden }: HeaderProps) {
  const [open, setOpen] = useState(false);
  const isTouch = useIsTouch();

  return (
    <header className={`fixed z-10 w-full ${hidden ? 'hidden' : ''}`}>
      <div
        className="relative shrink-0 border-b backdrop-blur-xl shadow-lg px-3 py-2 md:px-6 md:py-3 flex items-center justify-between"
        style={{ backgroundColor: 'rgba(255, 255, 255, 0.25)', borderColor: 'rgba(255, 255, 255, 0.35)' }}
      >
        {/* Centered, editable page title */}
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <EditablePageTitle />
        </div>
        <div className="flex items-center gap-2">
          {isTouch && dockItems && (
            <button onClick={() => setOpen(true)} className="p-1.5 rounded-md hover:bg-white/20 transition-colors">
              <Menu className="h-5 w-5 text-white" />
            </button>
          )}
          <Link to="/">
            <img
              src="/officer-logo.svg"
              alt="Officer"
              className="h-8 md:h-12 w-auto"
              style={{ transform: 'skew(-15deg, -2deg)' }}
            />
          </Link>
        </div>
        <div className="flex items-center gap-2">
          {/* Web inspector (eruda dev console) — hidden
          <button
            onClick={() => (window as any).eruda?.show()}
            className="flex h-8 w-8 items-center justify-center rounded-full bg-black/20 text-duck-dark transition-transform hover:scale-110"
            aria-label="Dev console"
          >
            <Terminal size={16} />
          </button>
          */}
          {/* Bug Report — hidden */}
          {/* <BugReportButton /> */}
          <JobsIndicator />
          <RescanButton />
          <UserMenu />
        </div>
      </div>

      {isTouch && dockItems && (
        <Sheet open={open} onOpenChange={setOpen}>
          <SheetContent side="left">
            <SheetHeader>
              <SheetTitle>Navigation</SheetTitle>
            </SheetHeader>
            <nav className="flex flex-col gap-1 mt-4 px-2">
              {dockItems.map((item) => (
                // `end` only for Home — see the note in Dock.tsx. Everything else wants the ancestor
                // match so a detail route keeps its entry highlighted.
                <NavLink
                  key={item.to}
                  to={item.to}
                  end={item.to === '/'}
                  onClick={() => setOpen(false)}
                  className={({ isActive }) =>
                    `flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors ${isActive ? 'bg-white/20' : 'hover:bg-white/10'}`
                  }
                >
                  {({ isActive }) => (
                    <>
                      <div
                        className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
                        style={{
                          background: item.color,
                          boxShadow: isActive ? `0 0 12px ${item.color}40` : 'none',
                        }}
                      >
                        {item.image ? (
                          <img src={item.image} alt="" className="h-5 w-5 object-contain" />
                        ) : (
                          item.icon && <item.icon className="h-4 w-4 text-white" />
                        )}
                      </div>
                      <span className={`text-sm ${isActive ? 'text-white font-medium' : 'text-white/80'}`}>
                        {item.label}
                      </span>
                    </>
                  )}
                </NavLink>
              ))}
            </nav>
          </SheetContent>
        </Sheet>
      )}
    </header>
  );
}
