package com.demoscene.tv
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
class PlayerActivity : FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val youtubeUrl = intent.getStringExtra("DEMO_YOUTUBE_URL") ?: ""
        if (youtubeUrl.isEmpty()) {
            finish()
            return
        }
        val videoId = extractYouTubeVideoId(youtubeUrl)
        if (videoId.isEmpty()) {
            finish()
            return
        }
        val videoUri = Uri.parse("https://www.youtube.com/watch?v=" + videoId)
        val packages = listOf(
            "com.google.android.youtube.tv",
            "com.google.android.youtube",
            "com.google.android.apps.youtube.tv"
        )
        for (pkg in packages) {
            try {
                val intent = Intent(Intent.ACTION_VIEW, videoUri)
                intent.setPackage(pkg)
                startActivity(intent)
                finish()
                return
            } catch (e: Exception) {
                // try next
            }
        }
        // Final fallback - no package specified
        try {
            startActivity(Intent(Intent.ACTION_VIEW, videoUri))
        } catch (e: Exception) {
            Toast.makeText(this, "YouTube not installed", Toast.LENGTH_SHORT).show()
        }
        finish()
    }
    private fun extractYouTubeVideoId(url: String): String {
        for (pattern in listOf("(?<=watch\\?v=)[^&]+", "(?<=youtu.be/)[^?]+")) {
            Regex(pattern).find(url)?.let { return it.value }
        }
        return ""
    }
}
