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

export interface RecapTrigger {
  shouldShow: boolean
  previousEpisodes: BaseItemDto[]
  daysSinceLastWatch: number | null
}

/**
 * Decide whether to show a "Previously on..." recap card before playback.
 *
 * Trigger conditions (all must hold):
 * - The current item is an Episode and not the very first episode (S1E1)
 * - We have at least one preceding episode in the list
 * - The user's most recent watch in the series happened more than
 *   `gapDays` ago (so a binge through the same season won't trigger it)
 *
 * `seasonEpisodes` should be the ordered episode list including the
 * current one. For first-of-season cases the previous-episode list ends
 * up empty, so the card stays hidden even if the gap fires.
 */
export function computeRecapTrigger(
  item: BaseItemDto | null | undefined,
  seasonEpisodes: BaseItemDto[],
  gapDays: number,
): RecapTrigger {
  const empty: RecapTrigger = { shouldShow: false, previousEpisodes: [], daysSinceLastWatch: null }
  if (!item || item.Type !== 'Episode') return empty
  // Treat S1E1 as no recap regardless of gap.
  const season = item.ParentIndexNumber ?? 0
  const episode = item.IndexNumber ?? 0
  if (season <= 1 && episode <= 1) return empty

  const idx = seasonEpisodes.findIndex(e => e.Id === item.Id)
  if (idx <= 0) return empty // first in list (or unknown) - no prior episodes
  const previousEpisodes = seasonEpisodes
    .slice(Math.max(0, idx - 2), idx)
    .filter(e => (e.UserData?.PlayedPercentage ?? 0) > 5 || e.UserData?.Played)

  if (previousEpisodes.length === 0) return empty

  // Find the most recent watch across the visible episode list (excluding
  // the current one). LastPlayedDate is an ISO string when present.
  let mostRecentMs: number | null = null
  for (const e of seasonEpisodes) {
    if (e.Id === item.Id) continue
    const raw = e.UserData?.LastPlayedDate as string | undefined
    if (!raw) continue
    const t = Date.parse(raw)
    if (!Number.isFinite(t)) continue
    if (mostRecentMs == null || t > mostRecentMs) mostRecentMs = t
  }
  if (mostRecentMs == null) return empty

  const daysSinceLastWatch = (Date.now() - mostRecentMs) / 86_400_000
  if (daysSinceLastWatch < gapDays) {
    return { shouldShow: false, previousEpisodes, daysSinceLastWatch }
  }
  return { shouldShow: true, previousEpisodes, daysSinceLastWatch }
}
