// src/components/ui/Tabs.jsx
// Horizontal tab navigation. Two visual variants: sliding underline or filled pill.
//
// Props:
//   tabs      — Array<{ key: string, label: string, icon?: ReactNode, count?: number }>
//   active    — string — key of the active tab
//   onChange  — (key: string) => void
//   variant   — 'line' | 'pill'   (default: 'line')
//   className — extra classes on the wrapper

import { useRef, useState, useEffect, useLayoutEffect } from 'react'

export default function Tabs({
  tabs = [],
  active,
  onChange,
  variant = 'line',
  className = '',
}) {
  const tabRefs = useRef({})
  const tabsInnerRef = useRef(null)
  const [indicator, setIndicator] = useState({ left: 0, width: 0 })

  // Measure the active tab and update the sliding indicator
  const updateIndicator = () => {
    if (variant !== 'line') return
    const el = tabRefs.current[active]
    if (el) {
      setIndicator({ left: el.offsetLeft, width: el.offsetWidth })
    }
  }

  useLayoutEffect(updateIndicator, [active, variant, tabs])

  // Also re-measure on window resize
  useEffect(() => {
    if (variant !== 'line') return
    window.addEventListener('resize', updateIndicator)
    return () => window.removeEventListener('resize', updateIndicator)
  }, [active, variant])

  return (
    <div
      className={[`tabs-${variant}`, className].filter(Boolean).join(' ')}
      role="tablist"
    >
      <div
        ref={tabsInnerRef}
        className={`tabs-${variant}__inner`}
      >
        {tabs.map((tab) => (
          <button
            key={tab.key}
            ref={(el) => { tabRefs.current[tab.key] = el }}
            role="tab"
            aria-selected={tab.key === active}
            className={['tab', tab.key === active ? 'active' : ''].filter(Boolean).join(' ')}
            onClick={() => onChange?.(tab.key)}
          >
            {tab.icon && (
              <span className="tab-icon" aria-hidden="true">{tab.icon}</span>
            )}
            {tab.label}
            {tab.count != null && (
              <span className="tab-badge">{tab.count}</span>
            )}
          </button>
        ))}

        {/* Sliding underline — line variant only */}
        {variant === 'line' && (
          <span
            className="tabs-indicator"
            aria-hidden="true"
            style={{ left: indicator.left, width: indicator.width }}
          />
        )}
      </div>
    </div>
  )
}
