"use client"

import { useEffect, useState } from "react"
import { ArrowUp } from "lucide-react"
import { cn } from "@/lib/utils"

export function ScrollToTop() {
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    // Watch the main scroll container
    const el = document.getElementById("main-scroll")
    if (!el) return
    function onScroll() { setVisible(el!.scrollTop > 300) }
    el.addEventListener("scroll", onScroll, { passive: true })
    return () => el!.removeEventListener("scroll", onScroll)
  }, [])

  function scrollUp() {
    document.getElementById("main-scroll")?.scrollTo({ top: 0, behavior: "smooth" })
  }

  return (
    <button
      onClick={scrollUp}
      aria-label="Scroll to top"
      className={cn(
        "fixed bottom-6 right-6 z-50 flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.1] bg-[#1d1d2a] shadow-lg shadow-black/40 text-white/50 transition-all duration-300 hover:border-indigo-500/40 hover:bg-indigo-600/20 hover:text-white",
        visible ? "opacity-100 translate-y-0 pointer-events-auto" : "opacity-0 translate-y-4 pointer-events-none"
      )}
    >
      <ArrowUp className="h-4 w-4" />
    </button>
  )
}
