import { useEffect, useState } from 'react'
import { readTimeSaved, formatTimeSaved } from '../../lib/time-saved'

interface Props {
  seriesId: string
}

/**
 * Small chip surfacing the time auto-skip has saved on this series.
 * Renders nothing when the total is below 60 seconds so we don't badge
 * shows where the user has only seen one episode.
 */
export default function TimeSavedBadge({ seriesId }: Props) {
  const [entry, setEntry] = useState(() => readTimeSaved(seriesId))

  useEffect(() => {
    setEntry(readTimeSaved(seriesId))
    // Re-check when the user comes back to the tab; auto-skip happens in
    // a different page, so we want the badge to update on focus.
    const onFocus = () => setEntry(readTimeSaved(seriesId))
    window.addEventListener('focus', onFocus)
    return () => window.removeEventListener('focus', onFocus)
  }, [seriesId])

  const total = entry.intro + entry.credits
  if (total < 60) return null

  const introLabel = entry.intro > 0 ? formatTimeSaved(entry.intro) : null
  const creditsLabel = entry.credits > 0 ? formatTimeSaved(entry.credits) : null

  return (
    <span
      className="inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md bg-accent/8 ring-1 ring-accent/20 text-[11.5px] text-accent font-medium tracking-tight"
      title={[
        introLabel ? `Intros: ${introLabel}` : null,
        creditsLabel ? `Credits: ${creditsLabel}` : null,
      ].filter(Boolean).join(' · ')}
    >
      <svg className="w-3 h-3" viewBox="0 0 20 20" fill="currentColor">
        <path d="M10 2a8 8 0 100 16 8 8 0 000-16zm.75 4.25a.75.75 0 00-1.5 0v4c0 .2.08.39.22.53l2.5 2.5a.75.75 0 101.06-1.06l-2.28-2.28V6.25z" />
      </svg>
      Auto-skip saved {formatTimeSaved(total)}
    </span>
  )
}
