import '../../core/contracts/trakt/trakt_playback_entry.dart';


class TraktContinueWatchingItem {

  final int tmdbId;


  final String mediaType;

  final String title;
  final String? subtitle;


  final double progress;

  final String? backdropUrl;

  const TraktContinueWatchingItem({
    required this.tmdbId,
    required this.mediaType,
    required this.title,
    required this.subtitle,
    required this.progress,
    required this.backdropUrl,
  });


  static TraktContinueWatchingItem? fromEntry(
    TraktPlaybackEntry e, {
    String? backdropUrl,
  }) {
    final progress = (e.progress / 100.0).clamp(0.0, 1.0).toDouble();

    if (e.type == 'movie') {
      final tmdb = e.movieIds?.tmdb;
      if (tmdb == null || tmdb <= 0) return null;
      return TraktContinueWatchingItem(
        tmdbId: tmdb,
        mediaType: 'movie',
        title: e.movieTitle ?? '',
        subtitle: e.movieYear?.toString(),
        progress: progress,
        backdropUrl: backdropUrl,
      );
    }

    final tmdb = e.showIds?.tmdb;
    if (tmdb == null || tmdb <= 0) return null;
    return TraktContinueWatchingItem(
      tmdbId: tmdb,
      mediaType: 'tv',
      title: e.showTitle ?? '',
      subtitle: _episodeSubtitle(
        e.episodeSeason,
        e.episodeNumber,
        e.episodeTitle,
      ),
      progress: progress,
      backdropUrl: backdropUrl,
    );
  }

  TraktContinueWatchingItem withBackdrop(String? url) {
    return TraktContinueWatchingItem(
      tmdbId: tmdbId,
      mediaType: mediaType,
      title: title,
      subtitle: subtitle,
      progress: progress,
      backdropUrl: url,
    );
  }


  TraktContinueWatchingItem withTitle(String title) {
    return TraktContinueWatchingItem(
      tmdbId: tmdbId,
      mediaType: mediaType,
      title: title,
      subtitle: subtitle,
      progress: progress,
      backdropUrl: backdropUrl,
    );
  }

  static String? _episodeSubtitle(int? season, int? number, String? title) {
    final String base;
    if (season != null && season > 0 && number != null) {
      base = '第$season季 第$number集';
    } else if (number != null) {
      base = '第$number集';
    } else {
      base = '';
    }
    final t = title?.trim();
    if (t != null && t.isNotEmpty) {
      return base.isEmpty ? t : '$base · $t';
    }
    return base.isEmpty ? null : base;
  }
}
