'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Menu, X, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { useSidebar } from './SidebarProvider';
import { getToolByHref } from '@/lib/tools';
import Logo from '@/components/Logo';

const iconBtn =
  'w-8 h-8 flex items-center justify-center rounded-lg text-muted-foreground/50 hover:text-foreground hover:bg-white/5 transition-all';

export function AppHeader() {
  const { toggle, isOpen, isCollapsed, toggleCollapse } = useSidebar();
  const pathname = usePathname();
  const tool = getToolByHref(pathname);

  return (
    <header className="h-14 border-b border-border/20 bg-background/8 backdrop-blur-xl sticky top-0 z-40 flex items-center justify-between px-4 gap-3">
      <div className="flex items-center gap-1.5 min-w-0">
        {/* Desktop: sidebar collapse toggle */}
        <button
          onClick={toggleCollapse}
          title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          className={cn(iconBtn, 'hidden lg:flex shrink-0')}
        >
          {isCollapsed
            ? <PanelLeftOpen className="w-4 h-4" />
            : <PanelLeftClose className="w-4 h-4" />
          }
        </button>

        {/* Mobile: logo home link */}
        <Link href="/" className="lg:hidden shrink-0">
          <Logo size={20} />
        </Link>

        {/* Current tool breadcrumb */}
        {tool && (
          <div className="flex items-center gap-1.5 min-w-0 ml-1">
            <span className="text-border/50 text-xs select-none">/</span>
            <span className="text-sm text-foreground/60 truncate font-mono">
              {tool.navTitle}
            </span>
          </div>
        )}
      </div>

      {/* Mobile: open/close sidebar */}
      <button
        onClick={toggle}
        title={isOpen ? 'Close menu' : 'Open menu'}
        className={cn(iconBtn, 'lg:hidden shrink-0')}
      >
        {isOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
      </button>
    </header>
  );
}
