import { useEffect, useState } from 'react'
import { Link, NavLink } from 'react-router-dom'
import { Moon, Sun } from 'lucide-react'
import { usePlatformAuth } from '../../auth/platform-auth'
import { MarketingLaunchStatusBanner } from '../ui/PublicLaunchStatus'
import { brandConfig } from '../../site-config'
import { footerLinks, marketingNavLinks } from '../../public-route-registry'
import { HyperTwistButton, HyperTwistButtonLink } from '../ui/HyperTwistButton'

export const publicProductRealityStrip = (
  <section className="product-reality-strip" aria-label="Current HyperTwist product reality">
    <article className="product-reality-strip__item">
      <p className="eyebrow">Main experience</p>
      <strong>Desktop app</strong>
      <p>Daily training, replay review, coaching, and the deepest puzzle families all live in the desktop app.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Website role</p>
      <strong>Account and launch hub</strong>
      <p>Create your account, compare plans, read updates, get help, and unlock desktop downloads from the website.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Ready now</p>
      <strong>Keyboard and mouse</strong>
      <p>Train and explore with keyboard and mouse today, while broader headset support stays clearly marked as still in validation.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Download path</p>
      <strong>Account-backed delivery</strong>
      <p>Start on the site, sign in once, and carry your account cleanly into the desktop build for access and first-launch pairing.</p>
    </article>
  </section>
)

export const compactProductRealityStrip = (
  <section
    className="product-reality-strip product-reality-strip--compact"
    aria-label="Current HyperTwist product reality"
  >
    <article className="product-reality-strip__item">
      <p className="eyebrow">Main experience</p>
      <strong>Desktop app</strong>
      <p>Daily training, replay review, coaching, and the deepest puzzle families all live in the desktop app.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Website role</p>
      <strong>Account and launch hub</strong>
      <p>Create your account, compare plans, read updates, get help, and unlock desktop downloads from the website.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Ready now</p>
      <strong>Keyboard and mouse</strong>
      <p>Train and explore with keyboard and mouse today, while broader headset support stays clearly marked as still in validation.</p>
    </article>
    <article className="product-reality-strip__item">
      <p className="eyebrow">Download path</p>
      <strong>Account-backed delivery</strong>
      <p>Start on the site, sign in once, and carry your account cleanly into the desktop build for access and first-launch pairing.</p>
    </article>
  </section>
)

function useHideHeaderOnScroll() {
  const [hidden, setHidden] = useState(() => (typeof window !== 'undefined' ? window.scrollY > 220 : false))

  useEffect(() => {
    let previousScrollY = window.scrollY
    let ticking = false

    function updateHeaderVisibility() {
      const nextScrollY = window.scrollY
      const delta = nextScrollY - previousScrollY
      const isScrollingDown = delta > 12
      const isNearTop = nextScrollY < 172

      if (isNearTop) {
        setHidden(false)
      } else if (isScrollingDown && nextScrollY > 220) {
        setHidden(true)
      }

      previousScrollY = Math.max(nextScrollY, 0)
      ticking = false
    }

    function handleScroll() {
      if (!ticking) {
        window.requestAnimationFrame(updateHeaderVisibility)
        ticking = true
      }
    }

    window.addEventListener('scroll', handleScroll, { passive: true })
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  return hidden
}

export function MarketingShell({
  title,
  eyebrow,
  lede,
  children,
}: {
  title: string
  eyebrow: string
  lede: string
  children: React.ReactNode
}) {
  const { colorMode, isAuthenticated, toggleColorMode } = usePlatformAuth()
  const isHeaderHidden = useHideHeaderOnScroll()
  const footerLookup = new Map(footerLinks.map((link) => [link.to, link]))
  const footerGroups = [
    {
      title: 'Product',
      routes: ['/', '/browser', '/features', '/about', '/resources', '/help', '/docs'],
    },
    {
      title: 'Access',
      routes: ['/pricing', '/download', '/getting-started', '/launch-status', '/support', '/contact', '/changelog'],
    },
    {
      title: 'Policy',
      routes: ['/open-source-notices', '/privacy', '/terms', '/shipping-payment'],
    },
  ] as const

  return (
    <div className="site-shell">
      <header className={`site-header${isHeaderHidden ? ' site-header--hidden' : ''}`}>
        <Link to="/" className="brand-mark">
          <img
            src="/branding/hypertwist-3d-symbol.png"
            alt="HyperTwist"
            className="brand-mark__image"
          />
          <span className="brand-mark__copy">
            <strong>{brandConfig.brandName}</strong>
            <small>{brandConfig.tagline}</small>
          </span>
        </Link>
        <nav className="site-nav" aria-label="Primary">
          {marketingNavLinks.map((link) => (
            <NavLink
              key={link.to}
              to={link.to}
              className={({ isActive }) => `site-nav__link${isActive ? ' is-active' : ''}`}
            >
              {link.label}
            </NavLink>
          ))}
        </nav>
        <div className="site-header__actions">
          <HyperTwistButton
            tone="ghost"
            type="button"
            aria-label={`Switch to ${colorMode === 'dark' ? 'light' : 'dark'} mode`}
            onClick={toggleColorMode}
            className="theme-toggle"
          >
            <span className="theme-toggle__content">
              <span className="theme-toggle__icon">
                {colorMode === 'dark' ? <Sun size={17} /> : <Moon size={17} />}
              </span>
              <span className="theme-toggle__label">{colorMode === 'dark' ? 'Light' : 'Dark'}</span>
            </span>
          </HyperTwistButton>
          {!isAuthenticated ? (
            <HyperTwistButtonLink tone="secondary" to="/register?next=%2Fapp">
              Create account
            </HyperTwistButtonLink>
          ) : null}
          <HyperTwistButtonLink tone="ghost" to={isAuthenticated ? '/app' : '/login'}>
            {isAuthenticated ? 'Open dashboard' : 'Log in'}
          </HyperTwistButtonLink>
          <HyperTwistButtonLink to={isAuthenticated ? '/app/downloads?platform=windows' : '/register?next=%2Fapp%2Fdownloads%3Fplatform%3Dwindows'}>
            Get the desktop app
          </HyperTwistButtonLink>
        </div>
      </header>

      <main className="page-main">
        <section className="page-hero">
          <p className="eyebrow">{eyebrow}</p>
          <h1>{title}</h1>
          <p className="page-hero__lede">{lede}</p>
        </section>
        <MarketingLaunchStatusBanner />
        {publicProductRealityStrip}
        {children}
      </main>

      <footer className="site-footer">
        <div className="site-footer__brand">
          <strong>{brandConfig.brandName}</strong>
          <p>{brandConfig.tagline}</p>
          <p className="site-footer__contact">
            Contact: <a href={brandConfig.contact.emailHref}>{brandConfig.contact.email}</a>
          </p>
          <div className="button-row top-gap">
            <HyperTwistButtonLink to={isAuthenticated ? '/app/downloads?platform=windows' : '/register?next=%2Fapp%2Fdownloads%3Fplatform%3Dwindows'}>
              Get the desktop app
            </HyperTwistButtonLink>
            <HyperTwistButtonLink tone="ghost" to={isAuthenticated ? '/app' : '/login'}>
              {isAuthenticated ? 'Account overview' : 'Account sign-in'}
            </HyperTwistButtonLink>
            {!isAuthenticated ? (
              <HyperTwistButtonLink tone="ghost" to="/register?next=%2Fapp">
                Start free account
              </HyperTwistButtonLink>
            ) : null}
          </div>
        </div>
        <div className="site-footer__grid">
          {footerGroups.map((group) => (
            <div key={group.title} className="site-footer__group">
              <p className="eyebrow">{group.title}</p>
              <div className="site-footer__links">
                {group.routes
                  .map((route) => footerLookup.get(route))
                  .filter((link): link is { to: string; label: string } => Boolean(link))
                  .map((link) => (
                    <Link key={link.to} to={link.to}>
                      {link.label}
                    </Link>
                  ))}
              </div>
            </div>
          ))}
        </div>
        <p className="site-footer__note">
          Downloadable releases include open-source notices and corresponding-source links whenever the shipped build requires them.
        </p>
      </footer>
    </div>
  )
}
