"use client";

import { useState } from "react";
import { Search, Download, AlertCircle, Loader2, Music, Video, PlaySquare } from "lucide-react";
import Image from "next/image";

interface VideoFormat {
  format_id: string;
  ext: string;
  resolution: string;
  fps: number | null;
  filesize: number | null;
  filesize_approx?: number | null;
  vcodec: string | null;
  acodec: string | null;
  type: string;
  url: string;
}

interface VideoInfo {
  id: string;
  title: string;
  thumbnail: string;
  duration: string;
  channel: string;
  formats: VideoFormat[];
}

export default function VideoDownloaderPage() {
  const [url, setUrl] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [videoInfo, setVideoInfo] = useState<VideoInfo | null>(null);
  const [isServerMerging, setIsServerMerging] = useState(false);

  const startDownloadPolling = () => {
    setIsServerMerging(true);
    // Clear old cookie just in case
    document.cookie = "download_status=; max-age=0; path=/";
    
    const interval = setInterval(() => {
      if (document.cookie.includes('download_status=done')) {
        setIsServerMerging(false);
        clearInterval(interval);
        // Clean it up
        document.cookie = "download_status=; max-age=0; path=/";
      }
    }, 1000);
  };

  const handleAnalyze = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!url.includes("youtube.com") && !url.includes("youtu.be")) {
      setError("Please enter a valid YouTube URL");
      return;
    }
    
    setError(null);
    setVideoInfo(null);
    setIsLoading(true);
    
    try {
      const res = await fetch("/api/analyze", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url }),
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.error || "Failed to analyze video");
      }
      
      setVideoInfo(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const formatSize = (bytes: number | null) => {
    if (!bytes) return "Unknown size";
    const mb = bytes / (1024 * 1024);
    return `${mb.toFixed(1)} MB`;
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@graph": [
              {
                "@type": "WebApplication",
                "name": "YTToolkits YouTube Video Downloader",
                "url": "https://yttoolkits.site/video-downloader",
                "applicationCategory": "MultimediaApplication",
                "operatingSystem": "All",
                "offers": {
                  "@type": "Offer",
                  "price": "0",
                  "priceCurrency": "USD"
                }
              },
              {
                "@type": "FAQPage",
                "mainEntity": [
                  {
                    "@type": "Question",
                    "name": "How to download YouTube videos for free?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "To download YouTube videos for free, simply copy the video URL from YouTube, paste it into the search box on YTToolkits, click 'Analyze Video', select your desired format and quality, and click the download button."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "Is YTToolkits YouTube downloader safe?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Yes, our YouTube downloader is completely safe. We do not require any software installation, there are no hidden fees, and we do not serve malicious ads or popups."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "Can I download YouTube videos in 1080p?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Absolutely! YTToolkits supports downloading YouTube videos in high-definition qualities including 720p, 1080p, 1440p, and even 4K resolution when available on the original video."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "How to convert YouTube to MP3?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Converting YouTube to MP3 is easy. Paste the video link, analyze it, and under the download options, look for the 'Audio Only' section. Click the download button next to the MP3 or M4A format."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "Does this work without software?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Yes, YTToolkits is a 100% online, web-based tool. You do not need to download or install any third-party software or browser extensions to use our service."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "Can I download YouTube Shorts?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Yes, our tool supports downloading YouTube Shorts. Just copy the link to the Short and paste it into our downloader the same way you would a regular YouTube video."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "What is the best YouTube video downloader?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "YTToolkits is considered one of the best YouTube video downloaders because it is free, fast, ad-free, and supports downloading videos in up to 4K resolution along with high-quality MP3 audio."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "How to download YouTube videos on iPhone/Android?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Our website is fully mobile-responsive. Open Safari or Chrome on your phone, go to YTToolkits, paste the YouTube video link, and download the file directly to your device's local storage."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "Is downloading YouTube videos legal?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Downloading YouTube videos is generally considered acceptable for personal, offline viewing or educational purposes under fair use. However, you should not distribute or monetize copyrighted content without permission from the creator."
                    }
                  },
                  {
                    "@type": "Question",
                    "name": "What video quality options are available?",
                    "acceptedAnswer": {
                      "@type": "Answer",
                      "text": "Depending on the original video, we offer downloads in 360p, 480p, 720p, 1080p, 1440p (2K), and 2160p (4K) resolutions in MP4 or WebM formats."
                    }
                  }
                ]
              },
              {
                "@type": "BreadcrumbList",
                "itemListElement": [
                  {
                    "@type": "ListItem",
                    "position": 1,
                    "name": "Home",
                    "item": "https://yttoolkits.site/"
                  },
                  {
                    "@type": "ListItem",
                    "position": 2,
                    "name": "Video Downloader",
                    "item": "https://yttoolkits.site/video-downloader"
                  }
                ]
              }
            ]
          }),
        }}
      />
      <div className="min-h-[calc(100vh-16rem)] px-4 py-12 relative">
        {/* Processing Overlay */}
        {isServerMerging && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-zinc-950/90 backdrop-blur-sm p-4">
            <div className="bg-zinc-900 border border-zinc-800 rounded-3xl p-8 md:p-12 max-w-md w-full shadow-2xl text-center flex flex-col items-center">
              <Loader2 className="w-12 h-12 animate-spin text-red-500 mb-6" />
              <h3 className="text-2xl font-bold text-white mb-2">Processing Video...</h3>
              <p className="text-zinc-400 mb-6">Our server is merging the highest quality video and audio streams for you. This usually takes 10 to 30 seconds.</p>
              <div className="w-full bg-zinc-800 rounded-full h-1.5 overflow-hidden">
                <div className="h-full bg-red-500 w-full animate-pulse rounded-full" />
              </div>
            </div>
          </div>
        )}

        <div className="max-w-4xl mx-auto">
          <div className="text-center mb-12">
            <h1 className="text-3xl md:text-5xl font-extrabold tracking-tight mb-4 text-white">
              YouTube Video <span className="text-red-500">Downloader</span>
            </h1>
            <p className="text-zinc-400 text-lg max-w-2xl mx-auto">
              Download YouTube videos in 1080p, 4K, and MP3 format for free. The fastest, safest, and highest quality YouTube to MP4 converter online. No signup required.
            </p>
          </div>

          {/* Downloader Card */}
          <div className="bg-zinc-900/50 border border-zinc-800 rounded-3xl p-6 md:p-10 shadow-2xl backdrop-blur-sm mb-16">
            <form onSubmit={handleAnalyze} className="relative mb-6">
              <div className="flex flex-col md:flex-row gap-4">
                <div className="relative flex-1">
                  <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
                    <Search className="h-5 w-5 text-zinc-500" />
                  </div>
                  <input 
                    type="url" 
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    placeholder="Paste YouTube link here (e.g., https://youtube.com/watch?v=...)" 
                    className="w-full bg-zinc-950 border border-zinc-800 focus:border-red-500/50 focus:ring-2 focus:ring-red-500/20 rounded-2xl py-4 pl-12 pr-4 text-white placeholder:text-zinc-600 transition-all outline-none text-base md:text-lg"
                    required
                  />
                </div>
                <button 
                  type="submit" 
                  disabled={isLoading}
                  className="bg-red-600 hover:bg-red-700 text-white font-semibold py-4 px-8 rounded-2xl transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
                >
                  {isLoading ? (
                    <Loader2 className="w-5 h-5 animate-spin" />
                  ) : (
                    <Download className="w-5 h-5" />
                  )}
                  <span>Analyze Video</span>
                </button>
              </div>
              
              {error && (
                <div className="mt-4 flex items-center gap-2 text-red-400 text-sm bg-red-500/10 p-3 rounded-xl border border-red-500/20">
                  <AlertCircle className="w-4 h-4" />
                  {error}
                </div>
              )}
            </form>

            {/* Results Section */}
            {videoInfo && (
              <div className="mt-8 animate-in fade-in slide-in-from-bottom-4 duration-500 border-t border-zinc-800/50 pt-8">
                <div className="flex flex-col md:flex-row gap-6 mb-8">
                  {/* Thumbnail */}
                  <div className="w-full md:w-1/3 aspect-video relative rounded-xl overflow-hidden border border-zinc-800 bg-zinc-950">
                    <img 
                      src={videoInfo.thumbnail} 
                      alt={videoInfo.title}
                      className="object-cover w-full h-full"
                    />
                    <div className="absolute bottom-2 right-2 bg-black/80 text-white text-xs px-2 py-1 rounded-md font-medium">
                      {videoInfo.duration}
                    </div>
                  </div>
                  
                  {/* Video Meta */}
                  <div className="flex-1 flex flex-col justify-center">
                    <h2 className="text-xl font-bold text-zinc-100 line-clamp-2 mb-2">
                      {videoInfo.title}
                    </h2>
                    <p className="text-zinc-400 flex items-center gap-2">
                      <PlaySquare className="w-4 h-4" />
                      {videoInfo.channel}
                    </p>
                  </div>
                </div>

                {/* Download Options */}
                <div className="space-y-8">
                  
                  {/* 1. Video + Audio (Server Merged) */}
                  <div className="bg-green-500/5 border border-green-500/20 rounded-2xl p-4 md:p-6">
                    <h3 className="text-base font-bold text-green-500 mb-1 flex items-center gap-2">
                      <Video className="w-5 h-5" /> VIDEO WITH SOUND (PROCESSED)
                    </h3>
                    <p className="text-zinc-400 text-sm mb-4">Includes audio. Processed on our servers for highest quality (Download takes 10-30 seconds to start).</p>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {['1080', '720', '480', '360'].map((res, idx) => {
                        const vFormat = videoInfo.formats.find(f => f.resolution === res + 'p' && (f.type === 'video-only' || f.type === 'video+audio'));
                        const aFormat = videoInfo.formats.find(f => f.type === 'audio-only');
                        const vSize = vFormat ? (vFormat.filesize || vFormat.filesize_approx || 0) : 0;
                        const aSize = aFormat ? (aFormat.filesize || aFormat.filesize_approx || 0) : 0;
                        const totalSize = (vSize && aSize) ? formatSize(vSize + aSize) : (vSize ? formatSize(vSize) : '~ Auto Size');

                        const isTooLarge = (vSize + aSize) > 1073741824; // 1 GB limit

                        return (
                          <a 
                            key={idx} 
                            href={isTooLarge ? '#' : `/api/download?url=${encodeURIComponent(url)}&title=${encodeURIComponent(videoInfo.title)}&res=${res}`} 
                            onClick={(e) => {
                              if (isTooLarge) {
                                e.preventDefault();
                                alert("This video is too large (over 1GB) to process on our free servers. Please select a lower quality or shorter video.");
                              } else {
                                startDownloadPolling();
                              }
                            }}
                            className={`flex items-center justify-between p-4 rounded-xl border transition-all group shadow-lg shadow-black/50 ${isTooLarge ? 'bg-zinc-900 border-zinc-800 opacity-50 cursor-not-allowed' : 'bg-zinc-950 border-green-500/30 hover:border-green-500 hover:bg-zinc-900'}`}
                          >
                            <div className="flex items-center gap-3">
                              <div className={`font-bold text-lg ${isTooLarge ? 'text-zinc-500' : 'text-zinc-100 group-hover:text-white'}`}>{res}p</div>
                              <div className="flex flex-col">
                                <span className={`text-xs font-semibold uppercase ${isTooLarge ? 'text-zinc-600' : 'text-zinc-500'}`}>MKV</span>
                                <span className={`text-xs ${isTooLarge ? 'text-red-500 font-bold' : 'text-zinc-500'}`}>{isTooLarge ? 'Too Large (>1GB)' : totalSize}</span>
                              </div>
                            </div>
                            <div className={`${isTooLarge ? 'bg-zinc-800 text-zinc-600' : 'bg-green-600 text-white hover:bg-green-500'} p-2 rounded-lg transition-all shadow-md`}><Download className="w-5 h-5" /></div>
                          </a>
                        );
                      })}
                    </div>
                  </div>

                  {/* 2. Video Only (High Quality) */}
                  {videoInfo.formats.filter(f => f.type === 'video-only').length > 0 && (
                    <div className="bg-orange-500/5 border border-orange-500/20 rounded-2xl p-4 md:p-6">
                      <h3 className="text-base font-bold text-orange-500 mb-1 flex items-center gap-2">
                        <Video className="w-5 h-5" /> HIGH QUALITY VIDEO (NO SOUND)
                      </h3>
                      <p className="text-zinc-400 text-sm mb-4">Muted video streams. Used by video editors who want 4K/1080p footage without the audio track.</p>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {videoInfo.formats.filter(f => f.type === 'video-only').map((format, idx) => {
                          const size = format.filesize || format.filesize_approx || 0;
                          const isTooLarge = size > 1073741824;

                          return (
                            <a 
                              key={idx} 
                              href={isTooLarge ? '#' : `/api/proxy?url=${encodeURIComponent(format.url)}&title=${encodeURIComponent(videoInfo.title)}&ext=${format.ext}`} 
                              onClick={(e) => {
                                if (isTooLarge) {
                                  e.preventDefault();
                                  alert("This video is too large (over 1GB) to download. Please select a lower quality.");
                                }
                              }}
                              className={`flex items-center justify-between p-4 rounded-xl border transition-all group shadow-lg shadow-black/50 ${isTooLarge ? 'bg-zinc-900 border-zinc-800 opacity-50 cursor-not-allowed' : 'bg-zinc-950 border-orange-500/30 hover:border-orange-500 hover:bg-zinc-900'}`}
                            >
                              <div className="flex items-center gap-3">
                                <div className={`font-bold text-lg ${isTooLarge ? 'text-zinc-500' : 'text-zinc-100 group-hover:text-white'}`}>{format.resolution}</div>
                                <div className="flex flex-col">
                                  <span className={`text-xs font-semibold uppercase ${isTooLarge ? 'text-zinc-600' : 'text-zinc-500'}`}>{format.ext}</span>
                                  <span className={`text-xs ${isTooLarge ? 'text-red-500 font-bold' : 'text-zinc-500'}`}>{isTooLarge ? 'Too Large (>1GB)' : formatSize(size)}</span>
                                </div>
                              </div>
                              <div className={`${isTooLarge ? 'bg-zinc-800 text-zinc-600' : 'bg-orange-600/20 text-orange-500 group-hover:text-white group-hover:bg-orange-600'} p-2 rounded-lg transition-all`}><Download className="w-5 h-5" /></div>
                            </a>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* 3. Audio Only */}
                  {videoInfo.formats.filter(f => f.type === 'audio-only').length > 0 && (
                    <div className="bg-blue-500/5 border border-blue-500/20 rounded-2xl p-4 md:p-6">
                      <h3 className="text-base font-bold text-blue-500 mb-1 flex items-center gap-2">
                        <Music className="w-5 h-5" /> AUDIO ONLY
                      </h3>
                      <p className="text-zinc-400 text-sm mb-4">High quality MP3/M4A audio extraction.</p>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {videoInfo.formats.filter(f => f.type === 'audio-only').map((format, idx) => (
                          <a key={idx} href={`/api/proxy?url=${encodeURIComponent(format.url)}&title=${encodeURIComponent(videoInfo.title)}&ext=${format.ext}`} className="flex items-center justify-between p-4 rounded-xl bg-zinc-950 border border-blue-500/30 hover:border-blue-500 hover:bg-zinc-900 transition-all group shadow-lg shadow-black/50">
                            <div className="flex items-center gap-3">
                              <div className="font-bold text-zinc-100 group-hover:text-white text-lg">Audio</div>
                              <div className="flex flex-col">
                                <span className="text-zinc-500 text-xs font-semibold uppercase">{format.ext}</span>
                                <span className="text-xs text-zinc-500">{formatSize(format.filesize)}</span>
                              </div>
                            </div>
                            <div className="bg-blue-600/20 text-blue-500 group-hover:text-white p-2 rounded-lg group-hover:bg-blue-600 transition-all"><Download className="w-5 h-5" /></div>
                          </a>
                        ))}
                      </div>
                    </div>
                  )}

                </div>
              </div>
            )}

            {/* Guidelines / Disclaimers (Crucial for AdSense) */}
            <div className="bg-zinc-950/50 rounded-2xl p-6 border border-zinc-800/50 mt-12">
              <h3 className="text-zinc-300 font-semibold mb-3 text-sm uppercase tracking-wider">How to use</h3>
              <ul className="space-y-2 text-zinc-500 text-sm">
                <li className="flex items-start gap-2">
                  <span className="text-red-500 mt-0.5">•</span>
                  Paste the URL of the YouTube video you want to analyze.
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-red-500 mt-0.5">•</span>
                  Click the Analyze button to fetch available formats and qualities.
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-red-500 mt-0.5">•</span>
                  Select your preferred quality (360p to 1080p) and download.
                </li>
                <li className="flex items-start gap-2 mt-4 pt-4 border-t border-zinc-800/50 italic">
                  <AlertCircle className="w-4 h-4 text-zinc-600 shrink-0 mt-0.5" />
                  By using our service, you confirm that you have permission to download the content or that it falls under fair use. Please respect creators' copyrights.
                </li>
              </ul>
            </div>
          </div>

          {/* SEO Content Section */}
          <article className="mt-16 text-zinc-300 space-y-12">
            
            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">How to Download YouTube Videos</h2>
              <p className="mb-4 leading-relaxed">
                Downloading your favorite YouTube videos to your device is incredibly easy with our YouTube video downloader. Whether you are using a PC, Mac, or mobile device, our platform guarantees a smooth experience. Follow these simple steps to save videos for offline viewing:
              </p>
              <ol className="list-decimal list-inside space-y-3 bg-zinc-900/40 p-6 rounded-2xl border border-zinc-800/50">
                <li><strong className="text-zinc-100">Copy the URL:</strong> Go to YouTube, find the video you want, and copy its link from the address bar or the share button.</li>
                <li><strong className="text-zinc-100">Paste the Link:</strong> Come back to YTToolkits and paste the copied URL into our search box above.</li>
                <li><strong className="text-zinc-100">Click Analyze:</strong> Hit the "Analyze Video" button to let our system fetch all available formats.</li>
                <li><strong className="text-zinc-100">Choose Your Quality:</strong> Review the list of available resolutions (such as 1080p, 720p, or MP3) and formats.</li>
                <li><strong className="text-zinc-100">Download:</strong> Click the download button next to your preferred option, and the file will immediately start downloading to your device.</li>
              </ol>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Supported YouTube Video Formats</h2>
              <p className="mb-4 leading-relaxed">
                Our advanced online YouTube downloader provides a wide variety of formats and video qualities. We make sure that you get exactly what you need, whether that is a high-resolution video for a large screen or a compact audio file for your mobile device.
              </p>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-zinc-800/50">
                      <th className="p-4 border-b border-zinc-700 font-semibold text-white">Format</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-white">Type</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-white">Quality Available</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-white">Best For</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4">MP4</td>
                      <td className="p-4">Video + Audio</td>
                      <td className="p-4">360p, 480p, 720p, 1080p</td>
                      <td className="p-4">Universal playback on all devices</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4">WebM</td>
                      <td className="p-4">Video Only</td>
                      <td className="p-4">1080p, 1440p (2K), 2160p (4K)</td>
                      <td className="p-4">High-end displays and video editing</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4">MP3</td>
                      <td className="p-4">Audio Only</td>
                      <td className="p-4">128kbps, 256kbps, 320kbps</td>
                      <td className="p-4">Music players, podcasts, car audio</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4">M4A</td>
                      <td className="p-4">Audio Only</td>
                      <td className="p-4">Standard Audio</td>
                      <td className="p-4">Apple devices, iTunes, iOS</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Download YouTube Videos in All Qualities</h2>
              <p className="mb-4 leading-relaxed">
                Not all videos require the same resolution. Sometimes you need a massive 4K file for your home theater, and other times a small 360p file is perfect for saving mobile data. Our free YouTube downloader online gives you complete control over what you save.
              </p>
              <p className="mb-4 leading-relaxed">
                <strong>For Mobile & Quick Viewing (360p & 480p):</strong> Ideal for smaller screens or when you are on a limited cellular data plan. These files download in seconds and take up very little storage space on your smartphone.
              </p>
              <p className="mb-4 leading-relaxed">
                <strong>High Definition (720p & 1080p):</strong> The standard for crisp, clear viewing on laptops, tablets, and desktop monitors. 1080p is the most popular choice as it offers an excellent balance between pristine video quality and manageable file sizes. 
              </p>
              <p className="mb-4 leading-relaxed">
                <strong>Ultra High Definition (1440p 2K & 2160p 4K):</strong> For the ultimate viewing experience on large smart TVs and high-resolution monitors. If the original creator uploaded the video in 4K, our tool will capture it flawlessly, providing cinematic quality.
              </p>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">YouTube to MP3 Converter</h2>
              <p className="mb-4 leading-relaxed">
                Sometimes you don't need the video at all. Whether it's a music track, a fascinating podcast, an audiobook, or a motivational speech, you can use our built-in YouTube to MP3 converter feature to extract the audio effortlessly.
              </p>
              <p className="mb-4 leading-relaxed">
                By selecting the "Audio Only" tab after analyzing a video, our platform strips away the video data and provides you with a clean, high-quality MP3 or M4A file. This is perfect for building your offline music library, saving battery on your phone by just listening to audio, or transferring files to a dedicated MP3 player. Our YouTube to MP3 conversion is extremely fast and retains the maximum audio bitrate available from the source.
              </p>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Why Use YTToolkits YouTube Downloader?</h2>
              <p className="mb-4 leading-relaxed">
                With hundreds of downloaders out there, what makes YTToolkits the best YouTube video downloader in 2026? We built our platform with the user in mind, focusing on reliability, speed, and safety.
              </p>
              <ul className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">100% Free Forever</strong>
                  We don't charge a dime. No premium tiers, no hidden costs. All resolutions and formats are available for free.
                </li>
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">No Registration Required</strong>
                  You never have to create an account, log in, or hand over your email address. Just paste the link and download.
                </li>
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">Lightning Fast Speeds</strong>
                  Our backend servers are optimized to analyze and deliver your download links almost instantly, saving you time.
                </li>
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">Safe and Secure</strong>
                  Unlike shady downloaders, we don't use popup ads, malware, or intrusive tracking. Your device stays completely safe.
                </li>
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">Unmatched High Quality</strong>
                  We give you access to genuine 1080p, 2K, and 4K downloads when available, without artificially compressing the files.
                </li>
                <li className="bg-zinc-900/40 p-4 rounded-xl border border-zinc-800/50">
                  <strong className="text-white block mb-1">Cloud-Based Processing</strong>
                  All the heavy lifting is done on our servers. Your browser won't lag, and you don't need a powerful computer.
                </li>
              </ul>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">YouTube Video Downloader for Mobile</h2>
              <p className="mb-4 leading-relaxed">
                You don't need a desktop computer to download videos. Our platform is perfectly optimized for all mobile devices, serving as a powerful YouTube video downloader for Android and iPhone (iOS). 
              </p>
              <p className="mb-4 leading-relaxed">
                If you are on an Android device, simply use Chrome or any standard browser, navigate to YTToolkits, paste your link, and the file will save directly to your Downloads folder. For iPhone and iPad users, we recommend using Safari on iOS 13 or later, as Safari now includes a native download manager that easily saves MP4 and MP3 files to your iCloud Drive or local storage. You can then access them through the "Files" app and even move them to your camera roll.
              </p>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Is It Legal to Download YouTube Videos?</h2>
              <p className="mb-4 leading-relaxed">
                The legality of downloading YouTube videos depends largely on how you use the content. According to YouTube's Terms of Service, you are generally supposed to view videos through their platform. However, downloading videos is widely considered acceptable for personal, offline viewing.
              </p>
              <p className="mb-4 leading-relaxed">
                If you are downloading copyright-free material, creative commons videos, or your own uploaded content, you have full rights to do so. Furthermore, downloading videos for educational purposes, criticism, commentary, or news reporting often falls under "Fair Use" doctrine. We strongly advise all our users to respect the intellectual property rights of content creators. You should never distribute, sell, or use downloaded copyrighted materials for commercial purposes without explicit permission from the original owner.
              </p>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Compare YouTube Downloaders</h2>
              <p className="mb-4 leading-relaxed">
                Wondering how YTToolkits stacks up against the competition? Here is a quick comparison showing why we are the preferred choice for downloading YouTube videos in 2026.
              </p>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-zinc-800/50">
                      <th className="p-4 border-b border-zinc-700 font-semibold text-white">Feature</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-green-400">YTToolkits</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-zinc-400">SSYouTube</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-zinc-400">Y2Mate</th>
                      <th className="p-4 border-b border-zinc-700 font-semibold text-zinc-400">SaveFrom</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4 font-medium text-white">1080p/4K Support</td>
                      <td className="p-4 text-green-400">Yes</td>
                      <td className="p-4 text-zinc-400">Limited</td>
                      <td className="p-4 text-zinc-400">Limited</td>
                      <td className="p-4 text-zinc-400">Limited</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4 font-medium text-white">Ad-Free Experience</td>
                      <td className="p-4 text-green-400">Yes</td>
                      <td className="p-4 text-red-400">No (Popups)</td>
                      <td className="p-4 text-red-400">No (Redirects)</td>
                      <td className="p-4 text-red-400">No</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4 font-medium text-white">Software Required</td>
                      <td className="p-4 text-green-400">None</td>
                      <td className="p-4 text-zinc-400">None</td>
                      <td className="p-4 text-zinc-400">None</td>
                      <td className="p-4 text-red-400">Sometimes</td>
                    </tr>
                    <tr className="border-b border-zinc-800/50 hover:bg-zinc-900/30">
                      <td className="p-4 font-medium text-white">Download Speed</td>
                      <td className="p-4 text-green-400">Very Fast</td>
                      <td className="p-4 text-zinc-400">Average</td>
                      <td className="p-4 text-zinc-400">Average</td>
                      <td className="p-4 text-zinc-400">Slow</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Frequently Asked Questions</h2>
              <div className="space-y-4">
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">How to download YouTube videos for free?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">To download YouTube videos for free, simply copy the video URL from YouTube, paste it into the search box on YTToolkits, click 'Analyze Video', select your desired format and quality, and click the download button.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">Is YTToolkits YouTube downloader safe?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Yes, our YouTube downloader is completely safe. We do not require any software installation, there are no hidden fees, and we do not serve malicious ads or popups.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">Can I download YouTube videos in 1080p?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Absolutely! YTToolkits supports downloading YouTube videos in high-definition qualities including 720p, 1080p, 1440p, and even 4K resolution when available on the original video.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">How to convert YouTube to MP3?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Converting YouTube to MP3 is easy. Paste the video link, analyze it, and under the download options, look for the 'Audio Only' section. Click the download button next to the MP3 or M4A format.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">Does this work without software?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Yes, YTToolkits is a 100% online, web-based tool. You do not need to download or install any third-party software or browser extensions to use our service.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">Can I download YouTube Shorts?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Yes, our tool supports downloading YouTube Shorts. Just copy the link to the Short and paste it into our downloader the same way you would a regular YouTube video.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">What is the best YouTube video downloader?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">YTToolkits is considered one of the best YouTube video downloaders because it is free, fast, ad-free, and supports downloading videos in up to 4K resolution along with high-quality MP3 audio.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">How to download YouTube videos on iPhone/Android?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Our website is fully mobile-responsive. Open Safari or Chrome on your phone, go to YTToolkits, paste the YouTube video link, and download the file directly to your device's local storage.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">Is downloading YouTube videos legal?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Downloading YouTube videos is generally considered acceptable for personal, offline viewing or educational purposes under fair use. However, you should not distribute or monetize copyrighted content without permission from the creator.</p>
                </details>
                <details className="bg-zinc-900/40 border border-zinc-800/50 rounded-xl p-4 cursor-pointer group">
                  <summary className="font-semibold text-lg text-white outline-none">What video quality options are available?</summary>
                  <p className="mt-3 text-zinc-400 leading-relaxed">Depending on the original video, we offer downloads in 360p, 480p, 720p, 1080p, 1440p (2K), and 2160p (4K) resolutions in MP4 or WebM formats.</p>
                </details>
              </div>
            </section>

            <section>
              <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">Related YouTube Tools</h2>
              <p className="mb-4 leading-relaxed">
                Beyond downloading videos, we offer a comprehensive suite of tools to help YouTube creators and viewers. Enhance your workflow with these helpful utilities:
              </p>
              <ul className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <li>
                  <a href="/thumbnail-downloader" className="flex flex-col bg-zinc-900/40 p-5 rounded-xl border border-zinc-800/50 hover:border-red-500/50 transition-colors">
                    <strong className="text-white text-lg">YouTube Thumbnail Downloader</strong>
                    <span className="text-zinc-400 mt-1">Extract and download high-quality HD and 4K thumbnails from any YouTube video in seconds.</span>
                  </a>
                </li>
                <li>
                  <a href="/tag-extractor" className="flex flex-col bg-zinc-900/40 p-5 rounded-xl border border-zinc-800/50 hover:border-red-500/50 transition-colors">
                    <strong className="text-white text-lg">YouTube Tag Extractor</strong>
                    <span className="text-zinc-400 mt-1">Discover the secret SEO tags used by top creators to help optimize your own video rankings.</span>
                  </a>
                </li>
                <li>
                  <a href="/channel-analytics" className="flex flex-col bg-zinc-900/40 p-5 rounded-xl border border-zinc-800/50 hover:border-red-500/50 transition-colors">
                    <strong className="text-white text-lg">Channel Analytics Tracker</strong>
                    <span className="text-zinc-400 mt-1">Check the estimated earnings, subscriber growth, and total views of any YouTube channel.</span>
                  </a>
                </li>
                <li>
                  <a href="/title-generator" className="flex flex-col bg-zinc-900/40 p-5 rounded-xl border border-zinc-800/50 hover:border-red-500/50 transition-colors">
                    <strong className="text-white text-lg">Video Title Generator</strong>
                    <span className="text-zinc-400 mt-1">Generate catchy, click-worthy titles for your YouTube videos using AI to increase your CTR.</span>
                  </a>
                </li>
              </ul>
            </section>

          </article>
        </div>
      </div>
    </>
  );
}
