package com.example.oscellamobile

import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.ViewModel

class YouTube(): ViewModel() {
    fun extractVideoId(videoUrl: String): String? {
        val regex = Regex("(?:https?://)?(?:www\\.)?(?:youtube\\.com/watch\\?v=|youtu\\.be/)([a-zA-Z0-9_-]{11})")
        return regex.find(videoUrl)?.groups?.get(1)?.value
    }

    @Composable
    fun VideoPlayerFromUrl(videoUrl: String) {
        val videoId = extractVideoId(videoUrl)

        if (videoId != null) {
            VideoPlayer(videoId)
        } else {
            Text("Неверная ссылка на видео")
        }
    }

    @Composable
    fun VideoPlayer(videoId: String) {
        AndroidView(
            factory = { context ->
                WebView(context).apply {
                    webViewClient = WebViewClient()
                    settings.javaScriptEnabled = true // Включаем JavaScript
                }
            },
            update = { webView ->
                val html = """
  <html>
    <body style="margin:0;padding:0;">
        <div style="padding: 0 5px;">
            <iframe 
                width="100%" 
                height="200" 
                src="https://www.youtube.com/embed/$videoId" 
                frameborder="0" 
                allowfullscreen 
                style="border-radius: 15px; overflow: hidden;">
            </iframe>
        </div>
    </body>
</html>
            """.trimIndent()
                webView.loadData(html, "text/html", "UTF-8")
            },
            modifier = Modifier.fillMaxWidth()
                .height(200.dp)
        )
    }

}