"use client"

import { useEffect, useRef } from "react"
import { useSearchParams } from "next/navigation"
import { cn } from "@/lib/utils"

/**
 * Wrap a table row with this to flash it when ?highlight=<id> matches.
 * Usage: <HighlightRow id={item.id} className="...your tr classes...">
 */
export function HighlightRow({
  id,
  children,
  className,
}: {
  id: string
  children: React.ReactNode
  className?: string
}) {
  const params = useSearchParams()
  const highlight = params.get("highlight")
  const isHighlighted = highlight === id
  const ref = useRef<HTMLTableRowElement>(null)

  useEffect(() => {
    if (isHighlighted && ref.current) {
      ref.current.scrollIntoView({ behavior: "smooth", block: "center" })
    }
  }, [isHighlighted])

  return (
    <tr
      ref={ref}
      className={cn(
        className,
        isHighlighted && "animate-highlight"
      )}
    >
      {children}
    </tr>
  )
}
