import { useMemo } from 'react'
import type { BaseItemDto } from '../../api/types'

interface Props {
  episodes: BaseItemDto[] | null | undefined
  /** Hide the sparkline if no episodes have any progress at all (avoids
   *  visual noise on freshly-added seasons). */
  hideWhenEmpty?: boolean
}

/**
 * One thin bar per episode. Bar height encodes watched percentage:
 * - 0%   - tiny stub at the baseline (so the column is countable)
 * - <100 - partial accent fill from the bottom
 * - 100  - full accent
 *
 * Renders inline next to the season tab. Cheap (pure DOM, no SVG) and
 * tooltips report a "X of N watched - P%" summary.
 */
export default function SeasonProgressSparkline({ episodes, hideWhenEmpty = true }: Props) {
  const stats = useMemo(() => {
    if (!episodes?.length) return null
    let watched = 0
    let totalPct = 0
    const bars: number[] = []
    for (const ep of episodes) {
      const ud = ep.UserData
      const pct = ud?.PlayedPercentage ?? (ud?.Played ? 100 : 0)
      bars.push(pct)
      if (ud?.Played) watched++
      totalPct += pct
    }
    const avg = totalPct / episodes.length
    return { bars, watched, total: episodes.length, avg }
  }, [episodes])

  if (!stats) return null
  if (hideWhenEmpty && stats.bars.every(b => b === 0)) return null

  const tooltip = `${stats.watched} of ${stats.total} watched - ${Math.round(stats.avg)}%`

  return (
    <span
      className="inline-flex items-end gap-[1px] h-3.5 ml-1.5 align-middle"
      title={tooltip}
      aria-label={tooltip}
    >
      {stats.bars.map((pct, i) => {
        const filled = pct >= 99
        const partial = pct > 0 && pct < 99
        return (
          <span
            key={i}
            className="w-[2px] rounded-[1px] transition-colors"
            style={{
              height: pct === 0 ? '2px' : `${Math.max(3, (pct / 100) * 14)}px`,
              backgroundColor: filled
                ? 'var(--accent, #F5B642)'
                : partial
                  ? 'rgba(245, 182, 66, 0.5)'
                  : 'var(--border, rgba(255,255,255,0.12))',
            }}
          />
        )
      })}
    </span>
  )
}
