/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useRef, useEffect } from 'react';
import { Menu, HelpCircle, LogOut, ChevronDown, Mail, QrCode, User } from 'lucide-react';
import { MainSection } from '../types';

interface HeaderProps {
  // Admin nav context — unused by the bar itself, optional so the Header can be
  // reused by the user store page which has no MainSection routing.
  currentSection?: MainSection;
  setCurrentSection?: (section: MainSection) => void;
  isCoimbatoreView?: boolean;
  onToggleSidebar: () => void;
  isSidebarOpen: boolean;
  onHelpClick: () => void;
  onLogoutClick: () => void;
  /** When provided, shows a "My Account" item in the profile dropdown (user store page). */
  onAccountClick?: () => void;
  /** When provided, shows a Store QR button on the right of the navbar (user store page). */
  onQrClick?: () => void;
  /** Signed-in user shown in the profile dropdown. */
  profile: { name: string; role: string; email: string };
  /** Optional store context to display next to the sidebar toggle. */
  storeContext?: {
    storeName: string;
    branchName?: string;
    icon?: React.ElementType;
  };
}

export default function Header({
  onToggleSidebar,
  isSidebarOpen,
  onHelpClick,
  onLogoutClick,
  onAccountClick,
  onQrClick,
  profile,
  storeContext
}: HeaderProps) {
  const [showProfileDropdown, setShowProfileDropdown] = useState(false);
  const profileRef = useRef<HTMLDivElement>(null);

  // Close the profile dropdown on any click/tap outside of it.
  useEffect(() => {
    if (!showProfileDropdown) return;
    const handlePointerDown = (e: MouseEvent | TouchEvent) => {
      if (profileRef.current && !profileRef.current.contains(e.target as Node)) {
        setShowProfileDropdown(false);
      }
    };
    document.addEventListener('mousedown', handlePointerDown);
    document.addEventListener('touchstart', handlePointerDown);
    return () => {
      document.removeEventListener('mousedown', handlePointerDown);
      document.removeEventListener('touchstart', handlePointerDown);
    };
  }, [showProfileDropdown]);

  const initials =
    profile.name
      .split(' ')
      .map((w) => w[0])
      .filter(Boolean)
      .slice(0, 2)
      .join('')
      .toUpperCase() || 'NA';

  return (
    <header className="bg-[#662582] flex justify-between items-center w-full px-container-margin py-md fixed top-0 right-0 left-0 z-50 h-16 text-white">
      {/* Brand & Desktop Navigation Tabs */}
      <div className="flex items-center gap-sm sm:gap-md md:pl-0 pl-1 min-w-0">
        {/* Brand cell — width mirrors the sidebar rail (64px collapsed / 256px expanded) so the logo/toggle sit directly above it */}
        <div
          className={`flex items-center shrink-0 transition-all duration-300 ${
            isSidebarOpen ? 'gap-sm sm:gap-md md:w-64' : 'gap-sm md:w-16 md:justify-center'
          }`}
        >
          {/* Brand Logo — full wordmark when sidebar open, icon only when collapsed */}
          <span className="select-none flex items-center shrink-0 -ml-1">
            <img
              src={isSidebarOpen ? '/logo.png' : '/favicon.png'}
              alt="nearledaily logo"
              className={`w-auto object-contain transition-all duration-300 ${isSidebarOpen ? 'h-6 sm:h-7' : 'h-8 sm:h-9'}`}
            />
          </span>

          {/* Sidebar toggle (Burger Menu).
              ml-auto when open pins it to the trailing edge of the brand cell,
              and since that cell's width tracks the sidebar exactly (256px open
              / 64px collapsed) the button lands on the sidebar's own edge — the
              seam between the panel and the header. Left to sit inline after
              the wordmark it floated in the middle of the open panel instead,
              and pushed outside the cell it drifted past the seam by the flex
              gap. Anchoring to the cell needs no pixel offsets and holds if
              either width changes.

              Collapsed the cell is only 64px and centred, so the natural
              inline position already sits beside the icon logo, which is itself
              aligned over the sidebar's icon rail. */}
          <button
            onClick={onToggleSidebar}
            title={isSidebarOpen ? 'Close sidebar' : 'Open sidebar'}
            aria-label={isSidebarOpen ? 'Close sidebar' : 'Open sidebar'}
            aria-expanded={isSidebarOpen}
            className={`rounded-full hover:bg-purple-800 transition-colors cursor-pointer text-white shrink-0 ${
              isSidebarOpen ? 'md:ml-auto p-1.5 sm:p-2' : 'p-1.5'
            }`}
          >
            <Menu size={18} />
          </button>
        </div>

        {/* Dynamic Store Name Context */}
        {storeContext && (
          <div className="flex flex-col ml-0.5 sm:ml-1 pl-2 sm:pl-3 py-0.5 select-none min-w-0">
            <span className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-base md:text-lg font-bold tracking-tight text-white leading-tight truncate max-w-[110px] xs:max-w-[150px] sm:max-w-none">
              {storeContext.icon && <storeContext.icon size={16} className="text-purple-300 shrink-0 hidden xs:inline" />}
              <span className="truncate">{storeContext.storeName}</span>
            </span>
            {storeContext.branchName && (
              <span className="text-[9px] sm:text-[10px] font-medium text-purple-200 tracking-wider uppercase leading-tight truncate max-w-[100px] sm:max-w-none">
                {storeContext.branchName}
              </span>
            )}
          </div>
        )}
      </div>

      {/* Global Actions Bar */}
      <div className="flex items-center gap-md">
        {/* Store QR — opens the QR modal (user store page only) */}
        {onQrClick && (
          <button
            onClick={onQrClick}
            title="Store QR code"
            aria-label="Store QR code"
            className="p-2 rounded-full hover:bg-purple-800 transition-colors cursor-pointer text-white"
          >
            <QrCode size={18} />
          </button>
        )}

        {/* User profile with dropdown */}
        <div className="relative" ref={profileRef}>
          <button
            onClick={() => setShowProfileDropdown(!showProfileDropdown)}
            className="group flex items-center gap-2.5 pl-1 pr-1 sm:pr-2.5 py-1 rounded-full bg-white/10 hover:bg-white/15 border border-white/15 backdrop-blur-sm focus:ring-2 focus:ring-purple-300/60 outline-none cursor-pointer transition-all duration-150 active:scale-[0.98]"
          >
            {/* Initials avatar with live status dot */}
            <span className="relative shrink-0">
              <span className="w-9 h-9 rounded-full bg-white/15 ring-2 ring-white/30 flex items-center justify-center text-xs font-bold text-white tracking-wide">
                {initials}
              </span>
              <span className="absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full bg-emerald-400 ring-2 ring-[#662582]" />
            </span>

            {/* Identity (hidden on small screens) */}
            <span className="hidden sm:flex flex-col items-start leading-tight">
              <span className="text-xs font-bold text-white truncate max-w-[130px]">{profile.name}</span>
              <span className="text-[10px] text-purple-200 font-medium truncate max-w-[130px]">{profile.role}</span>
            </span>

            <ChevronDown
              size={15}
              className={`hidden sm:block text-purple-200 transition-transform duration-200 ${showProfileDropdown ? 'rotate-180' : ''}`}
            />
          </button>

          {showProfileDropdown && (
            <div className="absolute right-0 mt-2.5 w-72 bg-white border border-slate-200/80 rounded-2xl shadow-2xl shadow-purple-950/15 z-50 text-slate-700 animate-in fade-in slide-in-from-top-2 duration-200 overflow-hidden">
              {/* Gradient profile header */}
              <div className="relative px-4 py-4 bg-gradient-to-br from-[#662582] via-purple-800 to-purple-950 text-white overflow-hidden">
                <div className="absolute -top-8 -right-8 w-28 h-28 bg-purple-400/20 rounded-full blur-2xl pointer-events-none" />
                <div className="relative flex items-center gap-3">
                  <span className="relative shrink-0">
                    <span className="w-12 h-12 rounded-full bg-white/15 ring-2 ring-white/40 shadow-md flex items-center justify-center text-base font-bold text-white tracking-wide">
                      {initials}
                    </span>
                    <span className="absolute bottom-0 right-0 w-3 h-3 rounded-full bg-emerald-400 ring-2 ring-purple-900" />
                  </span>
                  <div className="min-w-0">
                    <p className="font-bold text-sm text-white truncate">{profile.name}</p>
                    <span className="inline-block mt-1 text-[9px] font-bold uppercase tracking-wider text-purple-100 bg-white/15 border border-white/20 px-2 py-0.5 rounded-full">
                      {profile.role}
                    </span>
                  </div>
                </div>
                <div className="relative mt-3 flex items-center gap-1.5 text-[11px] text-purple-100 font-medium truncate">
                  <Mail size={12} className="shrink-0 text-purple-200" />
                  <span className="truncate">{profile.email}</span>
                </div>
              </div>

              {/* Account actions (moved here from the sidebar) */}
              <div className="p-2 flex flex-col gap-0.5">
                {onAccountClick && (
                  <button
                    onClick={() => { setShowProfileDropdown(false); onAccountClick(); }}
                    className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 cursor-pointer transition-colors group/item"
                  >
                    <span className="h-7 w-7 rounded-lg bg-purple-50 text-[#662582] ring-1 ring-purple-100 flex items-center justify-center group-hover/item:scale-110 transition-transform">
                      <User size={14} />
                    </span>
                    My Account
                  </button>
                )}
                <button
                  onClick={() => { setShowProfileDropdown(false); onHelpClick(); }}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 cursor-pointer transition-colors group/item"
                >
                  <span className="h-7 w-7 rounded-lg bg-slate-100 text-slate-500 ring-1 ring-slate-200 flex items-center justify-center group-hover/item:scale-110 transition-transform">
                    <HelpCircle size={14} />
                  </span>
                  Help Center
                </button>
                <div className="my-1 h-px bg-slate-100" />
                <button
                  onClick={() => { setShowProfileDropdown(false); onLogoutClick(); }}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-xs font-semibold text-rose-600 hover:bg-rose-50 cursor-pointer transition-colors group/item"
                >
                  <span className="h-7 w-7 rounded-lg bg-rose-50 text-rose-500 ring-1 ring-rose-100 flex items-center justify-center group-hover/item:scale-110 transition-transform">
                    <LogOut size={14} />
                  </span>
                  Log Out
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
