"use client"

import { useEffect, useState } from "react"
import { cn } from "@/lib/utils"
import { motion } from "framer-motion"

interface NavItem {
  id: string
  label: string
}

const navItems: NavItem[] = [
  { id: "overview", label: "Overview" },
  { id: "specs", label: "Specs" },
  { id: "tools", label: "Tools" },
  { id: "mileage", label: "Mileage" },
  { id: "mot", label: "MOT" },
]

export function StickyNav() {
  const [activeSection, setActiveSection] = useState("overview")

  useEffect(() => {
    // Create an IntersectionObserver for each section
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // When a section becomes visible
          if (entry.isIntersecting) {
            setActiveSection(entry.target.id)
          }
        })
      },
      {
        // Adjust threshold and rootMargin for better accuracy
        threshold: 0.3,
        rootMargin: "-100px 0px -100px 0px"
      }
    )

    // Observe all sections
    navItems.forEach((item) => {
      const element = document.getElementById(item.id)
      if (element) observer.observe(element)
    })

    return () => observer.disconnect()
  }, [])

  const scrollToSection = (id: string) => {
    const element = document.getElementById(id)
    if (element) {
      const navHeight = 64 // Height of sticky nav
      const elementPosition = element.getBoundingClientRect().top
      const offsetPosition = elementPosition + window.pageYOffset - navHeight

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth"
      })
    }
  }

  return (
    <nav className="sticky top-0 z-50 w-full bg-background/95 backdrop-blur-md border-b">
      <div className="container max-w-7xl mx-auto">
        <div className="flex overflow-x-auto no-scrollbar">
          {navItems.map((item) => (
            <button
              key={item.id}
              onClick={() => scrollToSection(item.id)}
              className={cn(
                "px-6 py-6 text-sm font-medium relative whitespace-nowrap transition-colors",
                activeSection === item.id
                  ? "text-primary"
                  : "text-muted-foreground hover:text-primary"
              )}
            >
              {item.label}
              {activeSection === item.id && (
                <motion.div
                  layoutId="activeSection"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.2 }}
                />
              )}
            </button>
          ))}
        </div>
      </div>
    </nav>
  )
}

