'use client'

import * as React from 'react'
import Image from 'next/image'
import { useTheme } from 'next-themes'
import { AnimatePresence, motion } from 'framer-motion'
import { Menu, Search, X, Sun, Moon, ChevronDown, ArrowUpRight } from 'lucide-react'
import { useRouter, ROUTE_META, type RouteKey } from '@/lib/router'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'

/* ------------------------------------------------------------------ */
/*  Navigation data                                                    */
/* ------------------------------------------------------------------ */

interface NavLink {
  label: string
  key?: RouteKey
  children?: { label: string; key: RouteKey }[]
}

const NAV_GROUPS: Record<string, { label: string; key: RouteKey }[]> = {
  Company: [
    { label: 'About', key: 'about' },
    { label: 'Investors', key: 'investors' },
    { label: 'Careers', key: 'careers' },
    { label: 'News', key: 'news' },
    { label: 'Contact', key: 'contact' },
  ],
  'Science & Innovation': [
    { label: 'Research & Development', key: 'research' },
    { label: 'Specialty Medicines', key: 'specialty' },
    { label: 'Advanced Vitamins', key: 'vitamins' },
    { label: 'Biotechnology', key: 'biotechnology' },
    { label: 'Innovation', key: 'innovation' },
  ],
  'Materials & Operations': [
    { label: 'Pharmaceutical Raw Materials', key: 'api' },
    { label: 'Manufacturing', key: 'manufacturing' },
    { label: 'Quality Assurance', key: 'quality' },
    { label: 'CDMO Services', key: 'cdmo' },
  ],
  Responsibility: [
    { label: 'Sustainability', key: 'sustainability' },
    { label: 'Knowledge Center', key: 'knowledge' },
  ],
  Legal: [
    { label: 'Privacy Policy', key: 'privacy' },
    { label: 'Terms of Use', key: 'terms' },
    { label: 'Cookie Settings', key: 'cookies' },
    { label: 'Pharmacovigilance', key: 'pharmacovigilance' },
  ],
}

const DESKTOP_NAV: NavLink[] = [
  {
    label: 'Company',
    children: NAV_GROUPS['Company'],
  },
  {
    label: 'Science',
    children: [
      NAV_GROUPS['Science & Innovation'][0],
      NAV_GROUPS['Science & Innovation'][4],
      NAV_GROUPS['Science & Innovation'][3],
    ],
  },
  {
    label: 'Therapies',
    key: 'specialty',
  },
  {
    label: 'Responsibility',
    key: 'sustainability',
  },
  {
    label: 'News',
    key: 'news',
  },
]

/* ------------------------------------------------------------------ */
/*  Header component                                                   */
/* ------------------------------------------------------------------ */

export function Header() {
  const { navigate, route: currentRoute } = useRouter()
  const { theme, setTheme } = useTheme()

  /* ---- scroll state ---- */
  const [scrolled, setScrolled] = React.useState(false)
  const [readingProgress, setReadingProgress] = React.useState(0)
  const [mobileOpen, setMobileOpen] = React.useState(false)
  const [searchOpen, setSearchOpen] = React.useState(false)
  const [searchQuery, setSearchQuery] = React.useState('')
  const [hoveredDropdown, setHoveredDropdown] = React.useState<string | null>(null)
  const [mounted, setMounted] = React.useState(false)

  React.useEffect(() => { setMounted(true) }, [])

  React.useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY
      setScrolled(y > 30)
      const docHeight = document.documentElement.scrollHeight - window.innerHeight
      setReadingProgress(docHeight > 0 ? (y / docHeight) * 100 : 0)
    }
    onScroll()
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => window.removeEventListener('scroll', onScroll)
  }, [])

  /* lock body when mobile menu is open */
  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : ''
    return () => { document.body.style.overflow = '' }
  }, [mobileOpen])

  /* close mobile menu on route change */
  React.useEffect(() => {
    setMobileOpen(false)
    setSearchOpen(false)
  }, [currentRoute])

  /* text is light (white) when not scrolled */
  const headerTextLight = !scrolled

  const headerTextClass = headerTextLight
    ? 'text-white'
    : 'text-foreground'

  /* ---- search results ---- */
  const searchResults = React.useMemo(() => {
    if (!searchQuery.trim()) return (Object.keys(ROUTE_META) as RouteKey[]).map((k) => ({ key: k, meta: ROUTE_META[k] }))
    const q = searchQuery.toLowerCase()
    return (Object.keys(ROUTE_META) as RouteKey[])
      .filter((k) => {
        const m = ROUTE_META[k]
        return (
          m.title.toLowerCase().includes(q) ||
          m.description.toLowerCase().includes(q) ||
          m.short.toLowerCase().includes(q) ||
          m.group.toLowerCase().includes(q)
        )
      })
      .map((k) => ({ key: k, meta: ROUTE_META[k] }))
  }, [searchQuery])

  /* ---- handlers ---- */
  const goTo = React.useCallback(
    (key: RouteKey) => {
      navigate(key)
      setHoveredDropdown(null)
    },
    [navigate],
  )

  const toggleTheme = React.useCallback(() => {
    setTheme(theme === 'dark' ? 'light' : 'dark')
  }, [theme, setTheme])

  return (
    <>
      {/* Skip-to-content link */}
      <a
        href="#main"
        className="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[200] focus:rounded-md focus:bg-primary focus:px-4 focus:py-2 focus:text-primary-foreground"
      >
        Skip to content
      </a>

      {/* Reading progress bar */}
      <div className="fixed top-0 left-0 z-[110] h-[3px] w-full">
        <div
          className="h-full bg-emerald-500 transition-[width] duration-150 ease-linear"
          style={{ width: `${readingProgress}%` }}
        />
      </div>

      <header
        className={cn(
          'fixed inset-x-0 top-0 z-[100] transition-all duration-500 ease-in-out',
          scrolled
            ? 'bg-background/95 backdrop-blur-xl shadow-sm'
            : 'bg-[#0b1f1b]/70 backdrop-blur-xl',
        )}
      >
        {/* ---- Top bar ---- */}
        <div
          className={cn(
            'flex h-9 items-center justify-between px-4 text-xs transition-colors duration-500 lg:px-8',
            scrolled ? 'text-muted-foreground' : 'text-white/80',
          )}
        >
          <span className="hidden sm:inline">
            Advancing health through precision science
          </span>
          <span className="sm:hidden" />
          <div className="flex items-center gap-3">
            <button
              onClick={() => goTo('investors')}
              className={cn(
                'transition-colors hover:underline',
                headerTextLight
                  ? 'hover:text-white'
                  : 'hover:text-foreground',
              )}
            >
              Investors
            </button>
            <span className={headerTextLight ? 'text-white/40' : 'text-muted-foreground/40'}>|
            </span>
            <button
              onClick={() => goTo('careers')}
              className={cn(
                'transition-colors hover:underline',
                headerTextLight
                  ? 'hover:text-white'
                  : 'hover:text-foreground',
              )}
            >
              Careers
            </button>
            <span className={headerTextLight ? 'text-white/40' : 'text-muted-foreground/40'}>|
            </span>
            <button
              onClick={() => goTo('contact')}
              className={cn(
                'transition-colors hover:underline',
                headerTextLight
                  ? 'hover:text-white'
                  : 'hover:text-foreground',
              )}
            >
              Contact
            </button>
          </div>
        </div>

        {/* ---- Main nav area ---- */}
        <div className="flex h-[76px] items-center justify-between px-4 lg:px-8">
          {/* Logo */}
          <button
            onClick={() => goTo('home')}
            className="relative flex-shrink-0 focus:outline-none"
            aria-label="Espandiar Pharmaceuticals — Home"
          >
            <Image
              src="/logo.png"
              alt="Espandiar Pharmaceuticals"
              width={360}
              height={120}
              className={cn(
                'h-24 w-auto object-contain transition-all duration-500',
                headerTextLight && 'brightness-0 invert',
              )}
              priority
            />
          </button>

          {/* Desktop nav links */}
          <nav className="hidden items-center gap-1 xl:flex" aria-label="Main navigation">
            {DESKTOP_NAV.map((item) => (
              <div
                key={item.label}
                className="relative"
                onMouseEnter={() => item.children && setHoveredDropdown(item.label)}
                onMouseLeave={() => setHoveredDropdown(null)}
              >
                {item.children ? (
                  <button
                    className={cn(
                      'flex items-center gap-1 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-white/10',
                      headerTextClass,
                    )}
                    aria-haspopup="true"
                    aria-expanded={hoveredDropdown === item.label}
                  >
                    {item.label}
                    <ChevronDown className="h-3.5 w-3.5" />
                  </button>
                ) : (
                  <button
                    onClick={() => goTo(item.key!)}
                    className={cn(
                      'flex items-center gap-1 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-white/10',
                      headerTextClass,
                      currentRoute === item.key && (headerTextLight ? 'text-emerald-300' : 'text-emerald-600'),
                    )}
                  >
                    {item.label}
                  </button>
                )}

                {/* Dropdown */}
                {item.children && hoveredDropdown === item.label && (
                  <div className="absolute left-0 top-full pt-2">
                    <div
                      className={cn(
                        'min-w-[220px] rounded-xl border bg-background p-2 shadow-xl transition-colors duration-300',
                        scrolled ? 'border-border' : 'border-border/50',
                      )}
                    >
                      {item.children.map((child) => (
                        <button
                          key={child.key}
                          onClick={() => goTo(child.key)}
                          className={cn(
                            'flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent',
                            currentRoute === child.key
                              ? 'bg-accent text-accent-foreground font-medium'
                              : 'text-foreground',
                          )}
                        >
                          <span>{child.label}</span>
                          <ArrowUpRight className="h-3.5 w-3.5 text-muted-foreground" />
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            ))}
          </nav>

          {/* Right actions */}
          <div className="flex items-center gap-1.5">
            {/* Theme toggle */}
            <button
              onClick={toggleTheme}
              className={cn(
                'flex h-9 w-9 items-center justify-center rounded-md transition-colors',
                headerTextLight
                  ? 'text-white hover:bg-white/10'
                  : 'text-foreground hover:bg-accent',
              )}
              aria-label="Toggle theme"
            >
              {mounted && theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
            </button>

            {/* Search */}
            <button
              onClick={() => setSearchOpen(true)}
              className={cn(
                'flex h-9 w-9 items-center justify-center rounded-md transition-colors',
                headerTextLight
                  ? 'text-white hover:bg-white/10'
                  : 'text-foreground hover:bg-accent',
              )}
              aria-label="Search"
            >
              <Search className="h-4 w-4" />
            </button>

            {/* Portal access button – hidden on small screens */}
            <Button
              variant={headerTextLight ? 'outline' : 'default'}
              size="sm"
              className={cn(
                'hidden sm:inline-flex',
                headerTextLight &&
                  'border-white/30 text-white bg-white/10 hover:bg-white/20 hover:text-white',
              )}
              onClick={() => goTo('contact')}
            >
              Portal access
            </Button>

            {/* Hamburger menu – hidden on xl+ */}
            <button
              onClick={() => setMobileOpen(true)}
              className={cn(
                'flex h-9 w-9 items-center justify-center rounded-md transition-colors xl:hidden',
                headerTextLight
                  ? 'text-white hover:bg-white/10'
                  : 'text-foreground hover:bg-accent',
              )}
              aria-label="Open menu"
            >
              <Menu className="h-5 w-5" />
            </button>
          </div>
        </div>
      </header>

      {/* ---- Mobile mega menu ---- */}
      <AnimatePresence>
        {mobileOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="fixed inset-0 z-[120] bg-black/60 backdrop-blur-sm"
              onClick={() => setMobileOpen(false)}
            />

            {/* Slide-in panel */}
            <motion.div
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: 'spring', damping: 30, stiffness: 300 }}
              className="fixed inset-y-0 right-0 z-[130] flex w-[320px] max-w-[85vw] flex-col bg-background shadow-2xl"
            >
              {/* Panel header */}
              <div className="flex h-[76px] items-center justify-between border-b px-4">
                <Image
                  src="/logo.png"
                  alt="Espandiar Pharmaceuticals"
                  width={180}
                  height={60}
                  className="h-12 w-auto object-contain"
                />
                <button
                  onClick={() => setMobileOpen(false)}
                  className="flex h-9 w-9 items-center justify-center rounded-md hover:bg-accent"
                  aria-label="Close menu"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              {/* Panel body – scrollable */}
              <div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4">
                {Object.entries(NAV_GROUPS).map(([group, items]) => (
                  <div key={group} className="mb-6">
                    <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                      {group}
                    </h3>
                    <ul className="space-y-1">
                      {items.map((item) => (
                        <li key={item.key}>
                          <button
                            onClick={() => goTo(item.key)}
                            className={cn(
                              'flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent',
                              currentRoute === item.key
                                ? 'bg-accent text-accent-foreground font-medium'
                                : 'text-foreground',
                            )}
                          >
                            <span>{item.label}</span>
                            <ArrowUpRight className="h-3.5 w-3.5 text-muted-foreground" />
                          </button>
                        </li>
                      ))}
                    </ul>
                  </div>
                ))}
              </div>

              {/* Panel footer */}
              <div className="border-t px-4 py-4">
                <Button
                  variant="default"
                  className="w-full"
                  onClick={() => goTo('contact')}
                >
                  Portal access
                </Button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* ---- Search overlay ---- */}
      <AnimatePresence>
        {searchOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="fixed inset-0 z-[140] bg-black/70 backdrop-blur-sm"
              onClick={() => setSearchOpen(false)}
            />
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.25 }}
              className="fixed inset-x-0 top-0 z-[150]"
            >
              <div className="mx-auto mt-20 max-w-xl px-4">
                <div className="overflow-hidden rounded-2xl border bg-background shadow-2xl">
                  {/* Search input */}
                  <div className="flex items-center gap-3 border-b px-5 py-4">
                    <Search className="h-5 w-5 flex-shrink-0 text-muted-foreground" />
                    <input
                      type="text"
                      placeholder="Search pages…"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground"
                      autoFocus
                    />
                    <button
                      onClick={() => setSearchOpen(false)}
                      className="flex h-8 w-8 items-center justify-center rounded-md hover:bg-accent"
                      aria-label="Close search"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>

                  {/* Search results */}
                  <div className="max-h-80 overflow-y-auto">
                    {searchQuery.trim() && searchResults.length === 0 && (
                      <p className="px-5 py-8 text-center text-sm text-muted-foreground">
                        No results for &ldquo;{searchQuery}&rdquo;
                      </p>
                    )}
                    {searchResults.map(({ key, meta }) => (
                      <button
                        key={key}
                        onClick={() => {
                          goTo(key)
                          setSearchOpen(false)
                          setSearchQuery('')
                        }}
                        className={cn(
                          'flex w-full items-start gap-3 border-b px-5 py-3.5 text-left transition-colors last:border-b-0 hover:bg-accent',
                          currentRoute === key && 'bg-accent',
                        )}
                      >
                        <span className="mt-0.5 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-emerald-100 text-[10px] font-semibold text-emerald-700">
                          {meta.short.slice(0, 2).toUpperCase()}
                        </span>
                        <div className="min-w-0">
                          <p className="truncate text-sm font-medium text-foreground">
                            {meta.title}
                          </p>
                          <p className="mt-0.5 line-clamp-1 text-xs text-muted-foreground">
                            {meta.description}
                          </p>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  )
}
