'use client'
import React, {useEffect, useState} from 'react';
import Image from "next/image";

function TopNav() {
  const arr = [
    {
      name: "公司简介",
      id: "section-0",
      img:"/assets/about/10.png",
      activeImg:"/assets/about/11.png",
    },
    {
      name: "发展历程",
      id: "section-1",
      img:"/assets/about/2.png",
      activeImg:"/assets/about/3.png",
    },
    {
      name: "荣誉资质",
      id: "section-2",
      img:"/assets/about/4.png",
      activeImg:"/assets/about/5.png",
    },
    {
      name: "公司招聘",
      id: "section-3",
      img:"/assets/about/6.png",
      activeImg:"/assets/about/7.png",
    },
    {
      name: "联系我们",
      id: "section-4",
      img:"/assets/about/8.png",
      activeImg:"/assets/about/9.png",
    },
  ]

  const [activeId, setActiveId] = useState(arr[0]?.id || "")
  const [hoverId, setHoverId] = useState<string | null>(null)
  // 监听滚动，设置当前 active
  useEffect(() => {
    const handleScroll = () => {
      let current = ""
      for (const item of arr) {
        const section = document.getElementById(item.id)
        if (section) {
          const rect = section.getBoundingClientRect()
          if (rect.top <= 100 && rect.bottom > 100) {
            current = item.id
            break
          }
        }
      }
      if (current) setActiveId(current)
    }

    window.addEventListener("scroll", handleScroll)
    handleScroll() // 初始运行一次
    return () => window.removeEventListener("scroll", handleScroll)
  }, [arr])
  return (
    <>
      <div className="flex justify-center space-x-10 border-b py-4 bg-white sticky top-0 z-50">
        {arr.map((item, idx) => {
          const isActive = activeId === item.id
          const isHover = hoverId === item.id
          return (
            <a
              key={idx}
              href="#"
              onClick={(e) => {
                e.preventDefault()
                document.getElementById(item.id)?.scrollIntoView({
                  behavior: "smooth",
                  block: "start",
                })
                setActiveId(item.id) // 点击时立即更新状态
              }}
              onMouseEnter={() => setHoverId(item.id)}
              onMouseLeave={() => setHoverId(null)}
              className={`font-medium flex items-center transition-colors ${
                isActive || isHover ? "text-blue-600 border-b-2 pb-1" : "text-gray-700"
              }`}
            >
              <Image
                src={isActive || isHover ? item.activeImg : item.img}
                alt={item.name}
                width={26}
                height={26}
                className="inline-block mr-1"
              />
              {item.name}
            </a>
          )
        })}
      </div>
    </>
  );
}

export default TopNav;