import { useEffect, useRef, useState, type ReactNode } from "react"
import { Link, useLocation } from "react-router-dom"
import { ArrowRight, BarChart3, Headphones, Mail, ShieldCheck, Zap } from "lucide-react"
import SiteHeader from "./SiteHeader"
import BrandLogo from "./BrandLogo"

const PUBLIC_NAV_LINKS = [
  { href: "/", label: "首页" },
  { href: "/activities", label: "最新活动" },
  { href: "/store", label: "产品服务" },
  { href: "/solutions", label: "解决方案" },
  { href: "/cooperation", label: "生态合作" },
  { href: "/#faq", label: "支持与服务" },
  { href: "/#about", label: "了解我们" },
]

interface PublicSiteLayoutProps {
  children: ReactNode
}

export default function PublicSiteLayout({ children }: PublicSiteLayoutProps) {
  const location = useLocation()
  const pageRef = useRef<HTMLDivElement>(null)
  const [scrollProgress, setScrollProgress] = useState(0)

  useEffect(() => {
    let raf = 0
    const update = () => {
      raf = 0
      setScrollProgress(Math.min(1, Math.max(0, window.scrollY / 80)))
    }
    const onScroll = () => {
      if (raf) return
      raf = window.requestAnimationFrame(update)
    }
    update()
    window.addEventListener("scroll", onScroll, { passive: true })
    return () => {
      if (raf) window.cancelAnimationFrame(raf)
      window.removeEventListener("scroll", onScroll)
    }
  }, [])

  useEffect(() => {
    if (location.hash) return
    window.scrollTo({ top: 0, behavior: "auto" })
  }, [location.pathname, location.hash])

  useEffect(() => {
    const root = pageRef.current
    if (!root) return
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      const revealAll = () => root.querySelectorAll<HTMLElement>("[data-public-reveal]").forEach((target) => target.classList.add("is-visible"))
      revealAll()
      const mutations = new MutationObserver(revealAll)
      mutations.observe(root, { childList: true, subtree: true })
      return () => mutations.disconnect()
    }

    root.classList.add("public-motion-ready")
    const observed = new WeakSet<Element>()
    const observeTarget = (target: HTMLElement) => {
      if (observed.has(target)) return
      observed.add(target)
      observer.observe(target)
    }
    const observeWithin = (node: ParentNode) => {
      if (node instanceof HTMLElement && node.matches("[data-public-reveal]")) observeTarget(node)
      node.querySelectorAll<HTMLElement>("[data-public-reveal]").forEach(observeTarget)
    }
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return
          entry.target.classList.add("is-visible")
          observer.unobserve(entry.target)
        })
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" },
    )
    observeWithin(root)
    const mutations = new MutationObserver((records) => {
      records.forEach((record) => record.addedNodes.forEach((node) => {
        if (node instanceof HTMLElement) observeWithin(node)
      }))
    })
    mutations.observe(root, { childList: true, subtree: true })
    return () => {
      mutations.disconnect()
      observer.disconnect()
    }
  }, [location.pathname])

  return (
    <div ref={pageRef} className="min-h-screen bg-white text-slate-900">
      <SiteHeader variant="home" scrollProgress={scrollProgress} anchorLinks={PUBLIC_NAV_LINKS} />
      {children}
      <PublicFooter />
    </div>
  )
}

interface PublicBannerProps {
  title: string
  description: string
  background: string
  action?: { label: string; href: string }
  align?: "left" | "center"
}

export function PublicBanner({ title, description, background, action, align = "left" }: PublicBannerProps) {
  return (
    <section
      className="www-public-banner relative overflow-hidden bg-cover bg-center"
      style={{ backgroundImage: `url('${background}')`, paddingTop: "var(--home-header-height, 112px)" }}
    >
      <div className="www-public-banner-mask absolute inset-0" />
      <div className={`www-public-container relative flex h-full items-center ${align === "center" ? "justify-center text-center" : "justify-start"}`}>
        <div className="public-banner-copy max-w-[680px]">
          <h1 className="www-public-banner-title text-slate-950">{title}</h1>
          <p className="www-public-banner-description text-slate-700">{description}</p>
          {action && (
            <Link to={action.href} className="www-public-banner-button inline-flex items-center gap-2 bg-[#0056ff] text-sm font-semibold text-white">
              {action.label}
              <ArrowRight className="h-4 w-4" />
            </Link>
          )}
        </div>
      </div>
    </section>
  )
}

export function PublicSectionTitle({ title, description }: { title: string; description?: string }) {
  return (
    <div data-public-reveal className="www-public-section-title">
      <h2>{title}</h2>
      {description && <p>{description}</p>}
    </div>
  )
}

export interface PageTab {
  id: string
  label: string
}

export function PageSectionTabs({ tabs }: { tabs: PageTab[] }) {
  const [active, setActive] = useState(tabs[0]?.id ?? "")

  useEffect(() => {
    const onScroll = () => {
      let current = tabs[0]?.id ?? ""
      for (const tab of tabs) {
        const element = document.getElementById(tab.id)
        if (element && element.getBoundingClientRect().top <= 170) current = tab.id
      }
      setActive(current)
    }
    onScroll()
    window.addEventListener("scroll", onScroll, { passive: true })
    return () => window.removeEventListener("scroll", onScroll)
  }, [tabs])

  return (
    <div className="www-public-tabs sticky top-[var(--home-header-height,72px)] z-30 bg-white">
      <div className="www-public-container overflow-x-auto">
        <nav className="flex min-w-max items-center">
          {tabs.map((tab) => (
            <a
              key={tab.id}
              href={`#${tab.id}`}
              onClick={() => setActive(tab.id)}
              className={`www-public-tab relative flex items-center transition-colors first:ml-0 ${
                active === tab.id ? "text-[#0868f5]" : "text-slate-700 hover:text-[#0868f5]"
              }`}
            >
              {tab.label}
              <span className={`absolute inset-x-0 bottom-0 h-[3px] bg-[#0056ff] transition-transform ${active === tab.id ? "scale-x-100" : "scale-x-0"}`} />
            </a>
          ))}
        </nav>
      </div>
    </div>
  )
}

function PublicFooter() {
  return (
    <footer id="about" className="border-t border-slate-200 bg-white text-slate-600">
      <div className="border-b border-slate-200">
        <div className="mx-auto grid max-w-7xl grid-cols-2 px-5 sm:px-6 lg:grid-cols-4">
          {[
            { icon: ShieldCheck, title: "稳定服务", desc: "基础安全与资源隔离" },
            { icon: Zap, title: "快速交付", desc: "自动开通云上资源" },
            { icon: BarChart3, title: "透明计费", desc: "订单与费用清晰可查" },
            { icon: Headphones, title: "技术支持", desc: "工单协助处理问题" },
          ].map(({ icon: Icon, title, desc }, index) => (
            <div key={title} className={`flex min-h-[112px] items-center gap-4 py-6 ${index > 0 ? "lg:border-l lg:border-slate-200 lg:pl-7" : ""}`}>
              <Icon className="h-7 w-7 shrink-0 text-[#0868f5]" strokeWidth={1.6} />
              <div>
                <p className="text-sm font-medium text-slate-900">{title}</p>
                <p className="mt-1 text-xs text-slate-500">{desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="mx-auto grid max-w-7xl gap-10 px-5 py-14 sm:px-6 md:grid-cols-[1.4fr_repeat(3,1fr)]">
        <div>
          <BrandLogo className="h-10 w-auto object-contain" />
          <p className="mt-5 max-w-sm text-sm leading-7 text-slate-500">为开发者和企业提供云服务器、网络、安全与存储等基础云服务。</p>
          <a href="mailto:hello@qingyun.example" className="mt-5 inline-flex items-center gap-2 text-sm hover:text-[#0868f5]">
            <Mail className="h-4 w-4 text-[#0868f5]" />联系我们
          </a>
        </div>
        {[
          { title: "解决方案", links: [{ label: "方案总览", href: "/solutions" }, { label: "网站解决方案", href: "/solutions/web" }, { label: "游戏解决方案", href: "/solutions/game" }] },
          { title: "生态合作", links: [{ label: "合作总览", href: "/cooperation" }, { label: "合作伙伴", href: "/cooperation/partner" }, { label: "推广合作", href: "/cooperation/affiliate" }] },
          { title: "快捷入口", links: [{ label: "网站首页", href: "/" }, { label: "产品中心", href: "/store" }, { label: "用户控制台", href: "/dashboard" }] },
        ].map((column) => (
          <div key={column.title}>
            <p className="text-sm font-medium text-slate-900">{column.title}</p>
            <ul className="mt-5 space-y-3">
              {column.links.map((link) => (
                <li key={link.href}><Link to={link.href} className="text-sm text-slate-500 hover:text-[#0868f5]">{link.label}</Link></li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div className="border-t border-slate-200 py-6">
        <div className="mx-auto flex max-w-7xl flex-col gap-2 px-5 text-xs text-slate-400 sm:px-6 md:flex-row md:justify-between">
          <span>© {new Date().getFullYear()} All rights reserved.</span>
          <span>云计算基础服务平台</span>
        </div>
      </div>
    </footer>
  )
}
