'use client'

import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cn } from '../primitives/utils'

export interface SubNavItem {
  id: string
  label: string
  href?: string
  icon?: ReactNode
  active?: boolean
}

export interface SubNavProps extends Omit<HTMLAttributes<HTMLElement>, 'onSelect'> {
  items: SubNavItem[]
  onSelect?: (id: string) => void
}

const SubNav = forwardRef<HTMLElement, SubNavProps>(
  ({ items, onSelect, className, ...props }, ref) => (
    <nav
      ref={ref}
      className={cn('flex gap-1 overflow-x-auto pb-1', className)}
      aria-label="Section navigation"
      role="tablist"
      {...props}
    >
      {items.map(item => {
        const itemClassName = cn(
          'inline-flex shrink-0 items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors',
          item.active
            ? 'border-primary/25 bg-primary/15 text-[hsl(var(--primary))]'
            : 'border-transparent text-foreground-tertiary hover:bg-foreground/[0.05] hover:text-foreground-secondary'
        )
        const content = (
          <>
            {item.icon}
            {item.label}
          </>
        )
        if (item.href) {
          return (
            <a
              key={item.id}
              href={item.href}
              role="tab"
              aria-selected={item.active}
              onClick={() => onSelect?.(item.id)}
              className={itemClassName}
            >
              {content}
            </a>
          )
        }
        return (
          <button
            key={item.id}
            type="button"
            role="tab"
            aria-selected={item.active}
            onClick={() => onSelect?.(item.id)}
            className={itemClassName}
          >
            {content}
          </button>
        )
      })}
    </nav>
  )
)
SubNav.displayName = 'SubNav'
export { SubNav }
