import React, { useState, useEffect, useRef } from 'react';
import { Search, Menu, X, ArrowUpRight, MessageCircle, Scale, Building2, User } from 'lucide-react';
import { Logo, BRAND } from './Brand';
import { SearchDialog } from './SearchDialog';
import { useComparison } from '../context/ComparisonContext';

interface LayoutProps {
  currentPath: string;
  onNavigate: (path: string) => void;
  children: React.ReactNode;
}

export function Layout({ currentPath, onNavigate, children }: LayoutProps) {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const { selectedSlugs, setDrawerOpen } = useComparison();
  const mobileMenuRef = useRef<HTMLDivElement>(null);
  const mobileTriggerRef = useRef<HTMLButtonElement>(null);

  // Grouped navigation to clearly distinguish individual learning from corporate training
  const primaryNavLinks = [
    { label: 'Programmes', to: '/programmes', group: 'individual' },
    { label: 'How Learning Works', to: '/learning', group: 'individual' },
    { label: 'Career Support', to: '/career-support', group: 'individual' },
    { label: 'For Organisations', to: '/organisations', group: 'corporate' },
    { label: 'About', to: '/about', group: 'academy' },
  ];

  const handleNav = (to: string) => {
    onNavigate(to);
    setMobileMenuOpen(false);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Body scroll lock & Escape listener for mobile drawer
  useEffect(() => {
    if (!mobileMenuOpen) return;

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setMobileMenuOpen(false);
        mobileTriggerRef.current?.focus();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [mobileMenuOpen]);

  return (
    <div className="min-h-screen flex flex-col bg-background text-foreground font-sans">
      {/* Accessible Skip-to-Content Link */}
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-4 focus:z-50 focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-xl focus:shadow-lg focus:outline-none focus:ring-2 focus:ring-accent font-bold text-xs"
      >
        Skip to main content
      </a>

      {/* Header Landmark */}
      <header className="sticky top-0 z-40 bg-background/95 backdrop-blur-md border-b border-border">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 h-20 flex items-center justify-between gap-4">
          {/* Logo */}
          <a
            href="#/"
            onClick={(e) => {
              if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                e.preventDefault();
                handleNav('/');
              }
            }}
            className="flex items-center gap-3 cursor-pointer group text-left min-h-[44px] select-none"
            aria-label="PANIA Digital Academy Home"
          >
            <Logo className="h-10 w-auto" />
          </a>

          {/* Desktop Nav Links (Semantic Links) */}
          <nav className="hidden lg:flex items-center gap-7 text-sm font-medium" aria-label="Main Navigation">
            {primaryNavLinks.map((link) => {
              const active = currentPath === link.to || (link.to !== '/' && currentPath.startsWith(link.to));
              const isCorporate = link.group === 'corporate';

              return (
                <a
                  key={link.to}
                  href={`#${link.to}`}
                  onClick={(e) => {
                    if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                      e.preventDefault();
                      handleNav(link.to);
                    }
                  }}
                  aria-current={active ? 'page' : undefined}
                  className={`transition-colors py-1 relative min-h-[44px] flex items-center select-none ${
                    active
                      ? 'text-primary font-bold'
                      : isCorporate
                      ? 'text-teal font-semibold hover:text-primary'
                      : 'text-foreground/80 hover:text-foreground'
                  }`}
                >
                  {isCorporate && (
                    <span className="w-1.5 h-1.5 rounded-full bg-teal mr-1.5" aria-hidden="true" />
                  )}
                  <span>{link.label}</span>
                  {active && (
                    <span className="absolute bottom-2 left-0 right-0 h-0.5 bg-accent rounded-full" />
                  )}
                </a>
              );
            })}
          </nav>

          {/* Desktop Actions */}
          <div className="hidden lg:flex items-center gap-3">
            {/* Quick Search Button (⌘K) */}
            <button
              onClick={() => setSearchOpen(true)}
              className="flex items-center gap-2.5 min-h-[44px] px-3.5 py-2 rounded-full border border-border bg-card text-xs text-muted-foreground hover:border-primary/40 hover:text-foreground transition-all cursor-pointer shadow-2xs"
              aria-label="Search programmes"
            >
              <Search className="h-3.5 w-3.5" aria-hidden="true" />
              <span>Search programmes...</span>
              <kbd className="font-mono text-[10px] bg-secondary px-1.5 py-0.5 rounded border border-border">
                ⌘K
              </kbd>
            </button>

            {/* Compare Tracks Button */}
            <button
              onClick={() => setDrawerOpen(true)}
              className="flex items-center gap-1.5 min-h-[44px] px-3.5 py-2 rounded-full border border-border bg-card text-xs text-foreground hover:border-primary/40 transition cursor-pointer shadow-2xs"
              title="Compare Courses Side-by-Side"
              aria-label={`Compare tracks (${selectedSlugs.length} selected)`}
            >
              <Scale className="h-3.5 w-3.5 text-primary" aria-hidden="true" />
              <span>Compare</span>
              {selectedSlugs.length > 0 && (
                <span className="w-4 h-4 rounded-full bg-accent text-accent-foreground text-[10px] font-bold flex items-center justify-center">
                  {selectedSlugs.length}
                </span>
              )}
            </button>

            {/* WhatsApp CTA Pill */}
            <a
              href={BRAND.whatsapp}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 min-h-[44px] rounded-full px-5 py-2.5 text-xs font-semibold bg-accent text-accent-foreground hover:brightness-95 transition shadow-2xs"
            >
              <MessageCircle className="h-3.5 w-3.5" aria-hidden="true" />
              <span>WhatsApp</span>
            </a>
          </div>

          {/* Mobile Menu Trigger & Search (Touch Targets >= 44px) */}
          <div className="flex items-center gap-2 lg:hidden">
            <button
              onClick={() => setDrawerOpen(true)}
              className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-full border border-border bg-card text-foreground hover:bg-muted active:scale-95 transition cursor-pointer relative"
              aria-label={`Compare tracks (${selectedSlugs.length} selected)`}
              title="Compare tracks"
            >
              <Scale className="h-4 w-4 text-primary" aria-hidden="true" />
              {selectedSlugs.length > 0 && (
                <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-accent text-accent-foreground text-[10px] font-bold flex items-center justify-center">
                  {selectedSlugs.length}
                </span>
              )}
            </button>

            <button
              onClick={() => setSearchOpen(true)}
              className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-full border border-border bg-card text-foreground hover:bg-muted active:scale-95 transition cursor-pointer"
              aria-label="Search programmes"
            >
              <Search className="h-4 w-4" aria-hidden="true" />
            </button>

            <button
              ref={mobileTriggerRef}
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="min-w-[44px] min-h-[44px] flex items-center justify-center rounded-full border border-border bg-card text-foreground hover:bg-muted active:scale-95 transition cursor-pointer"
              aria-expanded={mobileMenuOpen}
              aria-label="Toggle navigation menu"
            >
              {mobileMenuOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
            </button>
          </div>
        </div>

        {/* Mobile Full Drawer */}
        {mobileMenuOpen && (
          <div
            ref={mobileMenuRef}
            role="dialog"
            aria-modal="true"
            aria-label="Mobile Navigation Menu"
            className="lg:hidden fixed inset-0 top-20 z-50 bg-background px-6 py-6 flex flex-col justify-between overflow-y-auto animate-in fade-in duration-150"
          >
            <div className="space-y-6">
              {/* Individual Learning Section */}
              <div className="space-y-2">
                <p className="text-xs font-bold uppercase tracking-wider text-teal flex items-center gap-1.5">
                  <User className="w-3.5 h-3.5" />
                  <span>For Individuals</span>
                </p>
                <div className="space-y-1">
                  <a
                    href="#/programmes"
                    onClick={(e) => {
                      if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                        e.preventDefault();
                        handleNav('/programmes');
                      }
                    }}
                    className="block text-2xl font-bold py-2 text-foreground hover:text-primary text-left w-full"
                  >
                    Programmes Catalogue
                  </a>
                  <a
                    href="#/learning"
                    onClick={(e) => {
                      if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                        e.preventDefault();
                        handleNav('/learning');
                      }
                    }}
                    className="block text-2xl font-bold py-2 text-foreground hover:text-primary text-left w-full"
                  >
                    How Learning Works
                  </a>
                  <a
                    href="#/career-support"
                    onClick={(e) => {
                      if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                        e.preventDefault();
                        handleNav('/career-support');
                      }
                    }}
                    className="block text-2xl font-bold py-2 text-foreground hover:text-primary text-left w-full"
                  >
                    Career Support & CV
                  </a>
                </div>
              </div>

              {/* Corporate Training Section */}
              <div className="space-y-2 pt-4 border-t border-border/60">
                <p className="text-xs font-bold uppercase tracking-wider text-primary flex items-center gap-1.5">
                  <Building2 className="w-3.5 h-3.5" />
                  <span>For Organisations</span>
                </p>
                <div className="space-y-1">
                  <a
                    href="#/organisations"
                    onClick={(e) => {
                      if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                        e.preventDefault();
                        handleNav('/organisations');
                      }
                    }}
                    className="block text-2xl font-bold py-2 text-foreground hover:text-primary text-left w-full"
                  >
                    Corporate Upskilling
                  </a>
                  <a
                    href="#/organisations/aws-workshops"
                    onClick={(e) => {
                      if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                        e.preventDefault();
                        handleNav('/organisations/aws-workshops');
                      }
                    }}
                    className="block text-xl font-bold py-1.5 text-muted-foreground hover:text-foreground text-left w-full"
                  >
                    AWS Workshops for Teams
                  </a>
                </div>
              </div>

              {/* Academy & Contact */}
              <div className="space-y-1 pt-4 border-t border-border/60">
                <a
                  href="#/about"
                  onClick={(e) => {
                    if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                      e.preventDefault();
                      handleNav('/about');
                    }
                  }}
                  className="block text-lg font-semibold py-1.5 text-foreground hover:text-primary text-left w-full"
                >
                  About PANIA
                </a>
                <a
                  href="#/contact"
                  onClick={(e) => {
                    if (!e.ctrlKey && !e.metaKey && e.button === 0) {
                      e.preventDefault();
                      handleNav('/contact');
                    }
                  }}
                  className="block text-lg font-semibold py-1.5 text-foreground hover:text-primary text-left w-full"
                >
                  Contact & Admissions
                </a>
              </div>
            </div>

            <div className="pt-6 mt-auto space-y-3">
              <a
                href={BRAND.whatsapp}
                target="_blank"
                rel="noreferrer"
                className="w-full min-h-[48px] bg-accent text-accent-foreground rounded-full px-5 py-3 text-center font-bold block text-sm shadow-sm flex items-center justify-center gap-2"
              >
                <MessageCircle className="w-4 h-4" />
                <span>Chat on WhatsApp (+254 101 936 893)</span>
              </a>

              <p className="text-xs text-muted-foreground text-center">
                Fully online · Nairobi, Kenya · Admissions Open
              </p>
            </div>
          </div>
        )}
      </header>

      {/* Main Page Slot with Semantic Landmark and Focus Target */}
      <main id="main-content" tabIndex={-1} className="flex-1 focus:outline-none">
        {children}
      </main>

      {/* Footer Landmark */}
      <footer className="bg-primary text-primary-foreground mt-16 border-t border-primary/20">
        <div className="mx-auto max-w-7xl px-6 py-14 grid gap-10 md:grid-cols-4">
          {/* Col 1 */}
          <div className="space-y-4">
            <div className="bg-card rounded-2xl p-4 inline-block shadow-sm">
              <Logo className="h-12 w-auto" />
            </div>
            <p className="text-sm text-primary-foreground/80 leading-relaxed max-w-xs">
              {BRAND.tagline}
            </p>
            <p className="text-xs text-primary-foreground/60">
              Delivered fully online via Zoom, Google Meet & WhatsApp cohort groups.
            </p>
          </div>

          {/* Col 2 */}
          <div className="space-y-3">
            <p className="text-xs font-bold uppercase tracking-wider text-accent">Programmes</p>
            <ul className="text-sm space-y-2">
              <li>
                <a href="#/programmes" onClick={(e) => { e.preventDefault(); handleNav('/programmes'); }} className="hover:text-accent transition-colors text-left block">
                  All 22 Programmes
                </a>
              </li>
              <li>
                <a href="#/programmes?subject=cloud" onClick={(e) => { e.preventDefault(); handleNav('/programmes?subject=cloud'); }} className="hover:text-accent transition-colors text-left block">
                  Cloud Computing
                </a>
              </li>
              <li>
                <a href="#/programmes?subject=ai" onClick={(e) => { e.preventDefault(); handleNav('/programmes?subject=ai'); }} className="hover:text-accent transition-colors text-left block">
                  AI & Data Science
                </a>
              </li>
              <li>
                <a href="#/career-support" onClick={(e) => { e.preventDefault(); handleNav('/career-support'); }} className="hover:text-accent transition-colors text-left block">
                  Career Support & CV
                </a>
              </li>
            </ul>
          </div>

          {/* Col 3 */}
          <div className="space-y-3">
            <p className="text-xs font-bold uppercase tracking-wider text-accent">For Teams & Academy</p>
            <ul className="text-sm space-y-2">
              <li>
                <a href="#/organisations" onClick={(e) => { e.preventDefault(); handleNav('/organisations'); }} className="hover:text-accent transition-colors text-left block">
                  Corporate Training
                </a>
              </li>
              <li>
                <a href="#/organisations/aws-workshops" onClick={(e) => { e.preventDefault(); handleNav('/organisations/aws-workshops'); }} className="hover:text-accent transition-colors text-left block">
                  AWS Workshops for Teams
                </a>
              </li>
              <li>
                <a href="#/about" onClick={(e) => { e.preventDefault(); handleNav('/about'); }} className="hover:text-accent transition-colors text-left block">
                  About the Academy
                </a>
              </li>
              <li>
                <a href="#/learning" onClick={(e) => { e.preventDefault(); handleNav('/learning'); }} className="hover:text-accent transition-colors text-left block">
                  Online Learning Delivery
                </a>
              </li>
              <li>
                <a href="#/contact" onClick={(e) => { e.preventDefault(); handleNav('/contact'); }} className="hover:text-accent transition-colors text-left block">
                  Contact & Enquiries
                </a>
              </li>
            </ul>
          </div>

          {/* Col 4 */}
          <div className="text-sm space-y-2.5">
            <p className="text-xs font-bold uppercase tracking-wider text-accent">Connect</p>
            <a href={`mailto:${BRAND.email}`} className="block hover:text-accent transition-colors">
              {BRAND.email}
            </a>
            <a href={BRAND.phoneHref} className="block hover:text-accent transition-colors">
              {BRAND.phone}
            </a>
            <a
              href={BRAND.whatsapp}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 hover:text-accent transition-colors text-accent font-semibold pt-1"
            >
              <MessageCircle className="h-4 w-4" aria-hidden="true" />
              <span>Official WhatsApp Desk</span>
              <ArrowUpRight className="h-3 w-3" aria-hidden="true" />
            </a>
            <p className="text-primary-foreground/70 text-xs pt-2">{BRAND.location}</p>
          </div>
        </div>

        {/* Bottom line */}
        <div className="mx-auto max-w-7xl px-6 pb-8 text-xs text-primary-foreground/60 flex flex-col sm:flex-row items-center justify-between gap-3 border-t border-white/10 pt-4">
          <p>© {new Date().getFullYear()} PANIA Digital Academy · Fully Online Digital Academy · Nairobi, Kenya</p>
          <div className="flex flex-wrap items-center gap-4">
            <a href="#/about" onClick={(e) => { e.preventDefault(); handleNav('/about'); }} className="hover:text-accent transition-colors">About</a>
            <a href="#/learning" onClick={(e) => { e.preventDefault(); handleNav('/learning'); }} className="hover:text-accent transition-colors">Delivery</a>
            <a href="#/learner-access" onClick={(e) => { e.preventDefault(); handleNav('/learner-access'); }} className="hover:text-accent transition-colors">Learner Access</a>
            <a href="#/privacy" onClick={(e) => { e.preventDefault(); handleNav('/privacy'); }} className="hover:text-accent transition-colors">Privacy</a>
            <a href="#/terms" onClick={(e) => { e.preventDefault(); handleNav('/terms'); }} className="hover:text-accent transition-colors">Terms</a>
            <a href="/sitemap.xml" target="_blank" rel="noopener noreferrer" className="hover:text-accent transition-colors">Sitemap</a>
            <a href="#/contact" onClick={(e) => { e.preventDefault(); handleNav('/contact'); }} className="hover:text-accent transition-colors">Enquiries</a>
          </div>
        </div>
      </footer>

      {/* Search Dialog */}
      <SearchDialog
        open={searchOpen}
        onOpenChange={setSearchOpen}
        onNavigate={handleNav}
      />
    </div>
  );
}
