'use client'

import { useState, useEffect, useRef, useLayoutEffect, useCallback } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { motion } from 'framer-motion'
import MobileMenu from './MobileMenu'
import Logo from '@/components/Logo'
import AuthEntryModal from '@/components/auth/AuthEntryModal'
import { isAdminEmail } from '@/lib/admin-config'

function UserCircleIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} aria-hidden>
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z"
      />
    </svg>
  )
}

/** Sylwetka użytkownika (wypełnienie) — w kolistym tle oznacza stan zalogowany. */
function UserCircleSolidIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
      <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
    </svg>
  )
}

/** Ikona importu / moderacji ogłoszeń (panel admina). */
function ImportModerationIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} aria-hidden>
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M7.5 11.25 12 15.75m0 0 4.5-4.5M12 15.75V3.75"
      />
    </svg>
  )
}

/** Prawa strona nagłówka — ikona + „Zaloguj się / Załóż konto” (modal) albo wypełnione kółko profilu (`light` = nad hero). */
function HomeAuthBooksyRow({
  light,
  session,
  status,
  variant = 'default',
  onOpenAuthModal,
  authModalOpen,
  showAdminImport,
}: {
  light: boolean
  session?: { user?: { email?: string | null; isAdmin?: boolean } } | null
  status: 'loading' | 'authenticated' | 'unauthenticated'
  variant?: 'default' | 'mobileHeader'
  onOpenAuthModal: () => void
  authModalOpen: boolean
  showAdminImport?: boolean
}) {
  const border = light ? 'border-white' : 'border-gray-700'
  const iconBoxDefault = 'size-8 shrink-0 lg:size-9'
  const iconGlyph = 'size-[1.05rem] lg:size-[1.15rem]'
  const iconStroke = light ? 'text-white' : 'text-[color:var(--logo-color-dark)]'
  /** Ikona przy hamburgerze (mobile): dopasowana wizualnie do przycisku menu. */
  const iconBoxMobile = 'flex size-9 shrink-0 items-center justify-center'

  if (status === 'loading') {
    return (
      <span className={`text-sm ${light ? 'text-white/70' : 'text-gray-500'}`} aria-live="polite">
        …
      </span>
    )
  }

  if (session) {
    const sessionLinkTone = light
      ? 'text-white focus-visible:ring-white/80 focus-visible:ring-offset-transparent'
      : 'text-gray-800 focus-visible:ring-[color:var(--logo-color-dark)] focus-visible:ring-offset-white'
    const mobileHeaderProfile = variant === 'mobileHeader'
    const filledIconBox = light
      ? 'border-0 bg-white text-[color:var(--logo-color-dark)]'
      : 'border-0 bg-[color:var(--logo-color-dark)] text-white'
    const outlineIconBox = light
      ? 'border-2 border-white/90 bg-white/10 text-white'
      : 'border-2 border-[color:var(--logo-color-dark)] bg-white text-[color:var(--logo-color-dark)]'
    const iconRowGap = mobileHeaderProfile ? 'gap-1' : 'gap-1.5 sm:gap-2'

    return (
      <div className={`flex items-center ${iconRowGap}`}>
        {showAdminImport ? (
          <Link
            href="/admin"
            className={`flex rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-offset-2 ${sessionLinkTone} ${
              mobileHeaderProfile ? 'min-h-[44px] min-w-[44px] items-center justify-center' : 'items-center justify-center'
            }`}
            aria-label="Import ogłoszeń OLX"
            title="Import OLX"
          >
            <span
              className={`flex items-center justify-center rounded-full ${outlineIconBox} ${mobileHeaderProfile ? iconBoxMobile : iconBoxDefault}`}
            >
              <ImportModerationIcon className={mobileHeaderProfile ? 'size-[1.1rem]' : iconGlyph} />
            </span>
          </Link>
        ) : null}
        <Link
          href="/profil"
          className={`flex rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-offset-2 ${sessionLinkTone} ${
            mobileHeaderProfile ? 'min-h-[44px] min-w-[44px] items-center justify-center' : 'items-center justify-center'
          }`}
          aria-label="Profil"
        >
          <span
            className={`flex items-center justify-center rounded-full ${filledIconBox} ${mobileHeaderProfile ? iconBoxMobile : iconBoxDefault}`}
          >
            <UserCircleSolidIcon className={mobileHeaderProfile ? 'size-[1.1rem]' : iconGlyph} />
          </span>
        </Link>
      </div>
    )
  }

  const comboLabel =
    light
      ? 'text-white drop-shadow-sm'
      : 'text-gray-800'

  const focusRing =
    light
      ? 'focus-visible:ring-2 focus-visible:ring-white/90 focus-visible:ring-offset-2 focus-visible:ring-offset-transparent'
      : 'focus-visible:ring-2 focus-visible:ring-[color:var(--logo-color-dark)] focus-visible:ring-offset-2 focus-visible:ring-offset-white'

  if (variant === 'mobileHeader') {
    return (
      <button
        type="button"
        onClick={onOpenAuthModal}
        className={`flex min-h-[44px] min-w-0 max-w-[11.5rem] items-center gap-2 rounded-lg text-left outline-none sm:max-w-none sm:gap-2.5 ${focusRing}`}
        aria-haspopup="dialog"
        aria-expanded={authModalOpen}
        aria-controls="auth-entry-dialog"
      >
        <span className={`${iconBoxMobile} shrink-0 rounded-full border-2 ${border} ${iconStroke}`} aria-hidden>
          <UserCircleIcon className="size-[1.1rem]" />
        </span>
        <span className={`min-w-0 truncate text-[9px] font-medium leading-none sm:text-[10px] ${comboLabel}`}>
          Zaloguj się / Załóż konto
        </span>
      </button>
    )
  }

  return (
    <button
      type="button"
      onClick={onOpenAuthModal}
      className={`flex max-w-[min(100%,18rem)] items-center gap-2 rounded-lg text-left outline-none sm:gap-2.5 lg:max-w-none ${focusRing}`}
      aria-label="Zaloguj się lub załóż konto"
      aria-haspopup="dialog"
      aria-expanded={authModalOpen}
      aria-controls="auth-entry-dialog"
    >
      <span
        className={`flex shrink-0 items-center justify-center rounded-full border-2 ${border} ${iconBoxDefault} ${iconStroke}`}
        aria-hidden
      >
        <UserCircleIcon className={iconGlyph} />
      </span>
      <span className={`min-w-0 text-[10px] font-medium leading-tight sm:text-[10.5px] md:text-[11px] lg:text-[11.5px] tracking-tight ${comboLabel}`}>
        Zaloguj się / Załóż konto
      </span>
    </button>
  )
}

/** Między linkami desktop — większe odstępy; na bardzo wąskim oknie zostaje poziomy scroll listy. */
const navMenuGap = 'gap-x-4 md:gap-x-5 lg:gap-x-6 xl:gap-x-8 2xl:gap-x-[2.65rem]'

const navLinks = [
  { href: '/', label: 'Giełda łodzi' },
  { href: '/wynajem', label: 'Wynajem' },
  { href: '/wyposazenie', label: 'Wyposażenie' },
  { href: '/serwis', label: 'Serwis' },
  { href: '/blog', label: 'Blog' },
  { href: '/kontakt', label: 'Kontakt' },
]

const authLinksLoggedIn = [{ href: '/profil', label: 'Konto' }] as const
const authLinksAdmin = [{ href: '/admin/import', label: 'Import OLX' }] as const

const navMenuTypoCore =
  'whitespace-nowrap text-xs font-medium tracking-normal transition-colors sm:text-[0.8125rem] lg:text-sm'

/** Środek nagłówka nad hero — szerszy odstęp między wyrazami w etykietach („Giełda łodzi”). */
const navHeroMenuLinkClass = `${navMenuTypoCore} [word-spacing:0.16em] sm:[word-spacing:0.19em] lg:[word-spacing:0.26em] 2xl:[word-spacing:0.32em]`

export default function Header() {
  const pathname = usePathname()
  const { data: session, status } = useSession()
  const [scrolled, setScrolled] = useState(false)
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  const [authModalOpen, setAuthModalOpen] = useState(false)
  /** Tailwind `md` — poniżej zawsze układ „mobile” (hamburger); od md pomiar szerokości. */
  const [isMinMd, setIsMinMd] = useState(false)
  /** Od md: true, gdy linki nie mieszczą się w środkowej kolumnie (nie sztywny lg). */
  const [navOverflows, setNavOverflows] = useState(false)

  const navRef = useRef<HTMLElement>(null)
  const centerCellRef = useRef<HTMLDivElement>(null)
  const measureNavRef = useRef<HTMLUListElement>(null)
  /** Strona główna (`/`) pokazuje giełdę — ten sam wygląd chrome co przy `/sklep`. */
  const lightTextOnScroll =
    pathname === '/' || pathname === '/sklep' || pathname === '/blog' || pathname === '/kontakt'
  const darkTextForContrast =
    pathname.startsWith('/sklep/') ||
    pathname.startsWith('/blog/') ||
    pathname === '/logowanie' ||
    pathname === '/rejestracja' ||
    pathname === '/profil' ||
    pathname.startsWith('/admin') ||
    pathname === '/regulamin'

  const showAdminImport =
    !!session?.user &&
    (session.user.isAdmin === true || isAdminEmail(session.user.email ?? null))

  const linkTone = (darkTextForContrast || (scrolled && !lightTextOnScroll))
    ? 'text-gray-700 hover:text-blue-600'
    : 'text-white hover:text-blue-200 drop-shadow-lg'

  /** Jasne „nad hero” jak linki nav; po scrollu (szklany jaśniejszy pasek) ten sam kontrast co nawigacja — inaczej białe litery są niewidoczne. */
  const headerAuthLight = !(darkTextForContrast || (scrolled && !lightTextOnScroll))

  const hamburgerBarClass =
    darkTextForContrast || (scrolled && !lightTextOnScroll)
      ? 'bg-blue-950'
      : 'bg-white [filter:drop-shadow(0_1px_2px_rgba(0,0,0,0.85))]'

  /** Po scrollu: ciemna zieleń pod białe napisy / logo (gdy nav jest w trybie jasnym). */
  const headerScrolledSurface = scrolled
    ? headerAuthLight
      ? 'border-b border-white/10 bg-[rgba(26,69,80,0.94)] shadow-lg backdrop-blur-md'
      : 'bg-white/15 shadow-lg backdrop-blur-md'
    : 'bg-transparent'

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 50)
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  const recomputeNavOverflow = useCallback(() => {
    if (typeof window === 'undefined') return
    if (!window.matchMedia('(min-width: 768px)').matches) {
      setNavOverflows(false)
      return
    }
    const center = centerCellRef.current
    const measure = measureNavRef.current
    if (!center || !measure) return
    const available = center.clientWidth
    if (available <= 0) return
    const needed = measure.scrollWidth
    const slack = 8
    setNavOverflows(needed > available - slack)
  }, [])

  useLayoutEffect(() => {
    const mq = window.matchMedia('(min-width: 768px)')
    const onChange = () => {
      setIsMinMd(mq.matches)
      queueMicrotask(recomputeNavOverflow)
    }
    onChange()
    mq.addEventListener('change', onChange)
    return () => mq.removeEventListener('change', onChange)
  }, [recomputeNavOverflow])

  useLayoutEffect(() => {
    if (!isMinMd) {
      setNavOverflows(false)
      return
    }
    const nav = navRef.current
    const center = centerCellRef.current
    if (typeof ResizeObserver === 'undefined' || !nav) return
    const ro = new ResizeObserver(() => recomputeNavOverflow())
    ro.observe(nav)
    if (center) ro.observe(center)
    recomputeNavOverflow()
    return () => ro.disconnect()
  }, [isMinMd, recomputeNavOverflow, session, status])

  useLayoutEffect(() => {
    recomputeNavOverflow()
  }, [recomputeNavOverflow, session, status])

  const useCompactLayout = !isMinMd || navOverflows

  useLayoutEffect(() => {
    if (!useCompactLayout) setMobileMenuOpen(false)
  }, [useCompactLayout])

  function openAuthModal() {
    setMobileMenuOpen(false)
    setAuthModalOpen(true)
  }

  const logoLinkFocus =
    headerAuthLight
      ? 'focus-visible:ring-white/90 focus-visible:ring-offset-transparent'
      : 'focus-visible:ring-[color:var(--logo-color-dark)] focus-visible:ring-offset-white'

  const logoVariant = darkTextForContrast || (scrolled && !lightTextOnScroll) ? 'dark' : 'light'

  return (
    <>
      <motion.header
        className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${headerScrolledSurface}`}
        initial={{ y: 0 }}
        animate={{ y: 0 }}
        transition={{ duration: 0.6 }}
      >
        <div className="relative w-full max-w-[100vw]">
        <nav
          ref={navRef}
          className="relative mx-auto grid w-full grid-cols-[auto_1fr_auto] items-center gap-x-2 py-4 pl-3 pr-2 sm:gap-x-3 sm:pl-4 sm:pr-3 lg:pl-5 lg:pr-4"
        >
          <div className="flex min-w-0 items-center justify-self-start">
            <Link
              href="/"
              className={`${logoLinkFocus} -ml-0.5 shrink-0 outline-none hover:opacity-[0.92] focus-visible:ring-2 focus-visible:ring-offset-2 sm:-ml-1`}
              aria-label="Strona główna — giełda łodzi"
            >
              <Logo variant={logoVariant} />
            </Link>
          </div>

          <div ref={centerCellRef} className="relative flex min-w-0 justify-center justify-self-stretch">
            <ul
              ref={measureNavRef}
              className={`invisible absolute left-1/2 top-1/2 z-0 flex w-max -translate-x-1/2 -translate-y-1/2 flex-nowrap items-center ${navMenuGap} pb-0.5 pointer-events-none`}
              aria-hidden
              tabIndex={-1}
            >
              {navLinks.map((link) => (
                <li key={`m-${link.href}`} className="shrink-0">
                  <span className={navHeroMenuLinkClass}>{link.label}</span>
                </li>
              ))}
            </ul>
            <ul
              className={`pointer-events-auto z-[1] min-w-0 max-w-full shrink flex-nowrap items-center justify-center overflow-x-auto overflow-y-visible [scrollbar-width:none] ${navMenuGap} pb-0.5 [&::-webkit-scrollbar]:h-0 [&::-webkit-scrollbar]:w-0 ${
                isMinMd && !navOverflows ? 'flex' : 'hidden'
              }`}
            >
              {navLinks.map((link) => (
                <li key={link.href} className="shrink-0">
                  <Link href={link.href} className={`${navHeroMenuLinkClass} ${linkTone}`}>
                    {link.label}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          <div className="flex min-w-0 items-center justify-end justify-self-end gap-2 sm:gap-3">
            <div className={`min-w-0 ${isMinMd && !navOverflows ? 'block' : 'hidden'}`}>
              <HomeAuthBooksyRow
                light={headerAuthLight}
                session={session}
                status={status}
                onOpenAuthModal={openAuthModal}
                authModalOpen={authModalOpen}
                showAdminImport={showAdminImport}
              />
            </div>
            <div
              className={`min-w-0 items-center justify-end gap-1 sm:gap-1.5 ${useCompactLayout ? 'flex' : 'hidden'}`}
            >
              <div className="shrink-0 min-w-0 py-1">
                <HomeAuthBooksyRow
                  light={headerAuthLight}
                  session={session}
                  status={status}
                  variant="mobileHeader"
                  onOpenAuthModal={openAuthModal}
                  authModalOpen={authModalOpen}
                  showAdminImport={showAdminImport}
                />
              </div>
              <button
                className="shrink-0 p-1.5 sm:p-2"
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                aria-label="Toggle menu"
              >
                <div className="flex h-5 w-6 flex-col justify-between">
                  <span className={`block h-0.5 w-full transition-all ${hamburgerBarClass}`} />
                  <span className={`block h-0.5 w-full transition-all ${hamburgerBarClass}`} />
                  <span className={`block h-0.5 w-full transition-all ${hamburgerBarClass}`} />
                </div>
              </button>
            </div>
          </div>
        </nav>

        <MobileMenu
          isOpen={useCompactLayout && mobileMenuOpen}
          onClose={() => setMobileMenuOpen(false)}
          links={[
            ...navLinks,
            ...(session ? [...authLinksLoggedIn, ...(showAdminImport ? authLinksAdmin : [])] : []),
          ]}
        />
        </div>
      </motion.header>
      <AuthEntryModal open={authModalOpen} onClose={() => setAuthModalOpen(false)} />
    </>
  )
}
