/**
 * Per-series accumulator for seconds saved by auto-skipping intros and
 * credits markers. Persists in localStorage so the badge survives
 * sessions. The figure is rough - we count `marker.endSec - currentTime`
 * at the moment of skip, rounded down to whole seconds.
 */

const KEY_PREFIX = 'jf_time_saved_'

export interface TimeSavedEntry {
  intro: number
  credits: number
  /** ISO timestamp of the most recent recorded skip. */
  lastAt?: string
}

export function readTimeSaved(seriesId: string): TimeSavedEntry {
  if (!seriesId) return { intro: 0, credits: 0 }
  try {
    const raw = localStorage.getItem(KEY_PREFIX + seriesId)
    if (!raw) return { intro: 0, credits: 0 }
    const parsed = JSON.parse(raw)
    return {
      intro: Number(parsed.intro) || 0,
      credits: Number(parsed.credits) || 0,
      lastAt: parsed.lastAt,
    }
  } catch {
    return { intro: 0, credits: 0 }
  }
}

export function recordSkippedSeconds(
  seriesId: string,
  type: 'intro' | 'credits',
  seconds: number,
) {
  if (!seriesId || !Number.isFinite(seconds) || seconds <= 0) return
  // Cap a single skip at 20 minutes. Marvel credits with mid- and
  // post-credit scenes can run over 10 minutes; anything past 20 is
  // almost certainly a marker glitch.
  const capped = Math.min(seconds, 1200)
  const cur = readTimeSaved(seriesId)
  const next: TimeSavedEntry = {
    ...cur,
    [type]: cur[type] + Math.round(capped),
    lastAt: new Date().toISOString(),
  }
  try {
    localStorage.setItem(KEY_PREFIX + seriesId, JSON.stringify(next))
  } catch { /* noop */ }
}

export function formatTimeSaved(totalSec: number): string {
  if (totalSec <= 0) return '0m'
  const hours = Math.floor(totalSec / 3600)
  const mins = Math.floor((totalSec % 3600) / 60)
  if (hours === 0) return `${mins}m`
  if (mins === 0) return `${hours}h`
  return `${hours}h ${mins}m`
}
