import React, { useEffect, useState, useRef } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  MenuIcon,
  XIcon,
  ChevronDownIcon,
  ExternalLinkIcon } from
'lucide-react';
import { AnimatePresence, motion } from 'framer-motion';

const platformLinks = [
  { label: 'For Providers', hash: 'providers' },
  { label: 'Online Learning', hash: 'online' },
  { label: 'In-Person Training', hash: 'in-person' },
  { label: 'Blended Programs', hash: 'blended' },
  { label: 'For Companies', hash: 'companies' },
  { label: 'Integrations', hash: 'integrations' }];


function withInstantScroll(fn: () => void) {
  const root = document.documentElement;
  const prev = root.style.scrollBehavior;
  root.style.scrollBehavior = 'auto';
  fn();
  root.style.scrollBehavior = prev;
}

function scrollToSection(hash: string) {
  const el = document.getElementById(hash);
  if (!el) return;
  // Instant + scrollIntoView so section[id] { scroll-margin-top } still applies
  withInstantScroll(() => el.scrollIntoView({ block: 'start' }));
}

export function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [platformOpen, setPlatformOpen] = useState(false);
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const dropdownRef = useRef<HTMLDivElement>(null);
  const pendingHashRef = useRef<string | null>(null);

  const closeMenu = () => {
    setOpen(false);
    setPlatformOpen(false);
  };

  const goToPlatformSection = (hash: string) => (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (pathname !== '/') {
      // Leave other pages — App ScrollToTop handles the hash after Home mounts
      navigate({ pathname: '/', hash: `#${hash}` });
      closeMenu();
      return;
    }

    // Already on home: if the mobile drawer is open, scroll after body unlock.
    // Desktop dropdown never sets `open`, so it must scroll immediately.
    if (open) {
      pendingHashRef.current = hash;
      closeMenu();
      return;
    }

    closeMenu();
    if (window.location.hash !== `#${hash}`) {
      navigate({ pathname: '/', hash: `#${hash}` }, { replace: true });
    }
    requestAnimationFrame(() => scrollToSection(hash));
  };

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if (
      dropdownRef.current &&
      !dropdownRef.current.contains(e.target as Node))
      {
        setPlatformOpen(false);
      }
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  useEffect(() => {
    closeMenu();
  }, [pathname]);

  // Lock page scroll while the mobile menu is open — prevents missed taps
  useEffect(() => {
    if (!open) return;

    const scrollY = window.scrollY;
    const { body } = document;
    body.style.position = 'fixed';
    body.style.top = `-${scrollY}px`;
    body.style.left = '0';
    body.style.right = '0';
    body.style.width = '100%';
    body.style.overflow = 'hidden';

    return () => {
      body.style.position = '';
      body.style.top = '';
      body.style.left = '';
      body.style.right = '';
      body.style.width = '';
      body.style.overflow = '';

      const hash = pendingHashRef.current;
      if (hash) {
        pendingHashRef.current = null;
        if (window.location.hash !== `#${hash}`) {
          navigate({ pathname: '/', hash: `#${hash}` }, { replace: true });
        }
        // Skip restoring the old offset — jump straight to the section
        requestAnimationFrame(() => {
          requestAnimationFrame(() => scrollToSection(hash));
        });
        return;
      }

      withInstantScroll(() => window.scrollTo(0, scrollY));
    };
  }, [open, navigate]);

  const solid = scrolled || open;
  const onDark = !solid;
  const linkClass = (active = false) =>
  `text-sm font-medium transition-colors ${active ? onDark ? 'text-brand-bright' : 'text-brand-deep' : onDark ? 'text-white/75 hover:text-white' : 'text-brand-ink/70 hover:text-brand-deep'}`;

  const mobileLinkClass =
  'flex min-h-12 w-full items-center rounded-xl px-3 text-base font-medium text-brand-ink/85 active:bg-brand-mist';

  return (
    <header
      className={`print-hidden fixed inset-x-0 top-0 z-50 ${solid ? 'border-b border-brand-ink/10 bg-white' : 'bg-transparent'}`}>
      
      <nav
        className="mx-auto flex h-16 max-w-7xl items-center justify-between px-4 sm:px-6 lg:px-8"
        aria-label="Main navigation">
        
        <Link to="/" className="flex items-center gap-2.5" onClick={closeMenu}>
          <img
            src={solid ? '/logo-tgreen.svg' : '/logo-white-outline.svg'}
            alt="IntellectOne logo"
            className="h-8 w-8 rounded-lg" />
          
          <span
            className={`font-display text-lg font-bold tracking-tight ${solid ? 'text-brand-ink' : 'text-white'}`}>
            
            intellect<span className="text-brand-bright">ONE</span>
          </span>
        </Link>

        <div className="hidden items-center gap-7 lg:flex">
          <div className="relative" ref={dropdownRef}>
            <button
              type="button"
              onClick={() => setPlatformOpen(!platformOpen)}
              aria-expanded={platformOpen}
              aria-haspopup="true"
              className={`flex items-center gap-1 ${linkClass(platformOpen)}`}>
              
              Platform
              <ChevronDownIcon
                size={14}
                className={`transition-transform ${platformOpen ? 'rotate-180' : ''}`}
                aria-hidden="true" />
              
            </button>
            <AnimatePresence>
              {platformOpen &&
              <motion.div
                initial={{ opacity: 0, y: 6 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: 6 }}
                transition={{ duration: 0.18 }}
                className="absolute left-0 top-full mt-3 w-56 rounded-2xl border border-brand-ink/10 bg-white p-2 shadow-lift"
                role="menu">
                
                  {platformLinks.map((link) =>
                <a
                  key={link.hash}
                  href={`/#${link.hash}`}
                  role="menuitem"
                  onClick={goToPlatformSection(link.hash)}
                  className="block rounded-xl px-4 py-2.5 text-sm font-medium text-brand-ink/75 transition-colors hover:bg-brand-mist hover:text-brand-deep">
                  
                      {link.label}
                    </a>
                )}
                </motion.div>
              }
            </AnimatePresence>
          </div>

          <Link to="/pricing" className={linkClass(pathname === '/pricing')}>
            Pricing
          </Link>
          <Link to="/compare" className={linkClass(pathname === '/compare')}>
            Compare
          </Link>
          <Link
            to="/course-services"
            className={linkClass(pathname === '/course-services' || pathname === '/request-course-services')}>
            
            Course services
          </Link>
          <a
            href="https://app.intellectone.com"
            target="_blank"
            rel="noopener noreferrer"
            className={`flex items-center gap-1.5 ${linkClass()}`}>
            
            Course Catalog
            <ExternalLinkIcon size={13} aria-hidden="true" />
          </a>
        </div>

        <div className="hidden items-center gap-3 lg:flex">
          <Link
            to="/become-a-provider"
            className={`text-sm font-semibold transition-colors ${solid ? 'text-brand-deep hover:text-brand-ink' : 'text-brand-bright hover:text-white'}`}>
            
            Become a provider
          </Link>
          <Link
            to="/book-a-demo"
            className="rounded-full bg-brand-bright px-5 py-2 text-sm font-semibold text-brand-ink transition-colors hover:bg-white">
            
            Book a demo
          </Link>
        </div>

        <button
          type="button"
          className={`-mr-2 flex h-12 w-12 items-center justify-center lg:hidden ${solid ? 'text-brand-ink' : 'text-white'}`}
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open}
          aria-controls="mobile-nav"
          aria-label={open ? 'Close menu' : 'Open menu'}>
          
          {open ? <XIcon size={24} /> : <MenuIcon size={24} />}
        </button>
      </nav>

      {open &&
      <div
        id="mobile-nav"
        className="fixed inset-x-0 top-16 z-50 h-[calc(100dvh-4rem)] overflow-y-auto overscroll-contain border-t border-brand-ink/10 bg-white px-4 pb-8 pt-2 lg:hidden"
        style={{ WebkitOverflowScrolling: 'touch' }}>
        
          <p className="px-3 pb-1 pt-2 text-xs font-bold uppercase tracking-[0.18em] text-brand-ink/40">
            Platform
          </p>
          <div className="flex flex-col">
            {platformLinks.map((link) =>
          <a
            key={link.hash}
            href={`/#${link.hash}`}
            onClick={goToPlatformSection(link.hash)}
            className={mobileLinkClass}>
            
                {link.label}
              </a>
          )}
          </div>
          <div className="mt-2 flex flex-col border-t border-brand-ink/10 pt-2">
            <Link
            to="/pricing"
            onClick={closeMenu}
            className={mobileLinkClass}>
            
              Pricing
            </Link>
            <Link
            to="/compare"
            onClick={closeMenu}
            className={mobileLinkClass}>
            
              Compare
            </Link>
            <Link
            to="/course-services"
            onClick={closeMenu}
            className={mobileLinkClass}>
            
              Course services
            </Link>
            <a
            href="https://app.intellectone.com"
            target="_blank"
            rel="noopener noreferrer"
            className={`${mobileLinkClass} gap-1.5`}>
            
              Course Catalog
              <ExternalLinkIcon size={14} aria-hidden="true" />
            </a>
          </div>
          <div className="mt-4 flex flex-col gap-3 border-t border-brand-ink/10 px-1 pt-5">
            <Link
            to="/book-a-demo"
            onClick={closeMenu}
            className="flex min-h-12 items-center justify-center rounded-full bg-brand-bright px-5 text-center text-base font-semibold text-brand-ink">
            
              Book a demo
            </Link>
            <Link
            to="/become-a-provider"
            onClick={closeMenu}
            className="flex min-h-12 items-center justify-center rounded-full border border-brand-deep/30 px-5 text-center text-base font-semibold text-brand-deep">
            
              Become a provider
            </Link>
          </div>
        </div>
      }
    </header>);

}
