import 'package:just_audio/just_audio.dart';
import 'package:flutter/material.dart';
import 'dart:async';

class PlayerService {
  static final PlayerService _instance = PlayerService._internal();
  factory PlayerService() => _instance;
  PlayerService._internal();

  final AudioPlayer player = AudioPlayer();

  // Track state that other screens can listen to
  ValueNotifier<Map<String, dynamic>?> currentTrack = ValueNotifier(null);

  // Subscription to handle the 30-second snip-lock
  StreamSubscription? _tierSubscription;

  void play(Map<String, dynamic> track, int userTier) async {
    try {
      // 1. Clean up previous track and listeners
      await player.stop();
      await _tierSubscription?.cancel();

      currentTrack.value = track;

      // 2. Load and Play
      await player.setUrl(track['audioUrl']);
      player.play();

      // 3. Set up the Snip-Lock for the NEW track
      _tierSubscription = player.positionStream.listen((position) {
        if (userTier < 2 && position.inSeconds >= 30 && player.playing) {
          player.pause();
          player.seek(Duration.zero);
        }
      });
    } catch (e) {
      print("PLAYER_SYSTEM_ERROR: $e");
    }
  }

  void toggle() {
    if (player.playing) {
      player.pause();
    } else {
      player.play();
    }
  }
}