namespace ConstructorAppUI.Helpers
{
    public static class YouTubeHelper
    {
        public static string? ExtractVideoId(string url)
        {
            if (string.IsNullOrEmpty(url))
                return null;

            try
            {
                // 1. URL parametreleri ile  
                if (url.Contains("youtube.com/watch"))
                {
                    var uri = new Uri(url);
                    var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
                    return query["v"];
                }
                // 2. kısa link olan youtu.be  
                if (url.Contains("youtu.be/"))
                {
                    var parts = url.Split(new[] { "youtu.be/" }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 1)
                    {
                        var idPart = parts[1];
                        var ampIndex = idPart.IndexOf('&');
                        if (ampIndex >= 0)
                            idPart = idPart.Substring(0, ampIndex);
                        return idPart;
                    }
                }
                // 3. embed url  
                if (url.Contains("youtube.com/embed/"))
                {
                    var parts = url.Split(new[] { "youtube.com/embed/" }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 1)
                    {
                        var idPart = parts[1];
                        var slashIndex = idPart.IndexOfAny(new[] { '/', '?' });
                        if (slashIndex >= 0)
                            idPart = idPart.Substring(0, slashIndex);
                        return idPart;
                    }
                }
                // 4. Eğer sadece ID ise, uzunluk 11 ise  
                if (url.Length == 11 && !url.Contains("youtube"))
                    return url;
            }
            catch { }
            return null;
        }
}
}
