const { useState, useEffect, useRef, Component } = React;

// Safe React Error Boundary to prevent blank screens
class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        console.error("React Error Boundary caught an error:", error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            return (
                <div style={{ padding: '2.5rem', color: '#f87171', textAlign: 'center', fontFamily: 'sans-serif' }}>
                    <h2 style={{ fontSize: '1.25rem', fontWeight: 600 }}>Something went wrong in the interface.</h2>
                    <p style={{ marginTop: '0.5rem', color: '#94a3b8', fontSize: '0.9rem' }}>{this.state.error?.toString()}</p>
                    <button
                        onClick={() => window.location.reload()}
                        style={{ marginTop: '1.25rem', padding: '0.6rem 1.25rem', background: '#2563eb', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600 }}
                    >
                        Reload Page
                    </button>
                </div>
            );
        }
        return this.props.children;
    }
}

// Native React SVG Icon Component (Prevents DOM-mutation crashes)
function Icon({ name, size = 18, className = "", style = {} }) {
    const props = {
        xmlns: "http://www.w3.org/2000/svg",
        width: size,
        height: size,
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: "currentColor",
        strokeWidth: "2",
        strokeLinecap: "round",
        strokeLinejoin: "round",
        className: className,
        style: style
    };

    switch (name) {
        case 'zap':
            return <svg {...props}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>;
        case 'check':
            return <svg {...props}><polyline points="20 6 9 17 4 12"></polyline></svg>;
        case 'link-2':
            return <svg {...props}><path d="M9 17H7A5 5 0 0 1 7 7h2"></path><path d="M15 7h2a5 5 0 1 1 0 10h-2"></path><line x1="8" y1="12" x2="16" y2="12"></line></svg>;
        case 'x':
            return <svg {...props}><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>;
        case 'clipboard':
            return <svg {...props}><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path></svg>;
        case 'arrow-right':
            return <svg {...props}><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>;
        case 'alert-circle':
            return <svg {...props}><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>;
        case 'user':
            return <svg {...props}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>;
        case 'video':
            return <svg {...props}><polygon points="23 7 16 12 23 17 23 7"></polygon><rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect></svg>;
        case 'music':
            return <svg {...props}><path d="M9 18V5l12-2v13"></path><circle cx="6" cy="18" r="3"></circle><circle cx="18" cy="16" r="3"></circle></svg>;
        case 'download-cloud':
            return <svg {...props}><polyline points="8 17 12 21 16 17"></polyline><line x1="12" y1="12" x2="12" y2="21"></line><path d="M20.88 18.09A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.29"></path></svg>;
        case 'loader-2':
            return <svg {...props} className={`spinner ${className}`}><line x1="12" y1="2" x2="12" y2="6"></line><line x1="12" y1="18" x2="12" y2="22"></line><line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line><line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line><line x1="2" y1="12" x2="6" y2="12"></line><line x1="18" y1="12" x2="22" y2="12"></line><line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line><line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line></svg>;
        case 'check-circle-2':
            return <svg {...props}><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>;
        case 'history':
            return <svg {...props}><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path><polyline points="3 3 3 8 8 8"></polyline><polyline points="12 7 12 12 15 15"></polyline></svg>;
        case 'trash-2':
            return <svg {...props}><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>;
        case 'download':
            return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>;
        case 'film':
            return <svg {...props}><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"></rect><line x1="7" y1="2" x2="7" y2="22"></line><line x1="17" y1="2" x2="17" y2="22"></line><line x1="2" y1="12" x2="22" y2="12"></line><line x1="2" y1="7" x2="7" y2="7"></line><line x1="2" y1="17" x2="7" y2="17"></line><line x1="17" y1="17" x2="22" y2="17"></line><line x1="17" y1="7" x2="22" y2="7"></line></svg>;
        case 'key':
            return <svg {...props}><circle cx="7.5" cy="15.5" r="5.5"></circle><path d="m21 2-9.6 9.6"></path><path d="m15.5 7.5 3 3L22 7l-3-3"></path></svg>;
        case 'shield-check':
            return <svg {...props}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><path d="m9 12 2 2 4-4"></path></svg>;
        default:
            return null;
    }
}

function App() {
    const [url, setUrl] = useState('');
    const [isFetching, setIsFetching] = useState(false);
    const [videoInfo, setVideoInfo] = useState(null);
    const [activeTab, setActiveTab] = useState('video');
    const [selectedFormat, setSelectedFormat] = useState(null);
    const [selectedAudioFormat, setSelectedAudioFormat] = useState('mp3');
    const [isDownloading, setIsDownloading] = useState(false);
    const [progress, setProgress] = useState(null);
    const [completedFile, setCompletedFile] = useState(null);
    const [history, setHistory] = useState([]);
    const [errorMsg, setErrorMsg] = useState(null);
    const [showCookieModal, setShowCookieModal] = useState(false);
    const [hasCookies, setHasCookies] = useState(false);
    const [cookieInput, setCookieInput] = useState('');
    const [cookieSaving, setCookieSaving] = useState(false);
    const [cookieStatusMsg, setCookieStatusMsg] = useState('');

    const sseRef = useRef(null);

    // Load download history and cookie status on mount
    useEffect(() => {
        fetchHistory();
        fetchCookiesStatus();
    }, []);

    const fetchCookiesStatus = async () => {
        try {
            const res = await fetch('/api/cookies');
            if (res.ok) {
                const data = await res.json();
                setHasCookies(data.has_cookies);
            }
        } catch (e) {
            console.error("Failed to check cookies status:", e);
        }
    };

    const handleSaveCookies = async () => {
        if (!cookieInput.trim()) return;
        setCookieSaving(true);
        setCookieStatusMsg('');
        try {
            const res = await fetch('/api/cookies', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ cookies: cookieInput.trim() })
            });
            const data = await res.json();
            if (res.ok) {
                setHasCookies(true);
                setCookieStatusMsg('Cookies saved successfully! YouTube bot check is now authenticated.');
                setCookieInput('');
            } else {
                setCookieStatusMsg(data.detail || 'Failed to save cookies');
            }
        } catch (err) {
            setCookieStatusMsg(err.message || 'Error saving cookies');
        } finally {
            setCookieSaving(false);
        }
    };

    const handleDeleteCookies = async () => {
        try {
            await fetch('/api/cookies', { method: 'DELETE' });
            setHasCookies(false);
            setCookieStatusMsg('Cookies cleared.');
        } catch (err) {
            console.error("Failed to delete cookies:", err);
        }
    };

    const fetchHistory = async () => {
        try {
            const res = await fetch('/api/history');
            if (res.ok) {
                const data = await res.json();
                setHistory(data);
            }
        } catch (err) {
            console.error("Failed to load history:", err);
        }
    };

    const handlePaste = async () => {
        try {
            if (navigator.clipboard && navigator.clipboard.readText) {
                const text = await navigator.clipboard.readText();
                if (text) {
                    setUrl(text.trim());
                }
            }
        } catch (err) {
            console.warn("Clipboard read failed:", err);
        }
    };

    const handleFetchInfo = async (e) => {
        if (e) e.preventDefault();
        const targetUrl = url.trim();
        if (!targetUrl) return;

        setIsFetching(true);
        setErrorMsg(null);
        setVideoInfo(null);
        setCompletedFile(null);
        setProgress(null);

        try {
            const res = await fetch('/api/info', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ url: targetUrl })
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.detail || "Failed to fetch video details");
            }

            setVideoInfo(data);
            if (data.video_formats && data.video_formats.length > 0) {
                setSelectedFormat(data.video_formats[0]);
            }
        } catch (err) {
            setErrorMsg(err.message || "Network error fetching media info");
        } finally {
            setIsFetching(false);
        }
    };

    const handleStartDownload = async () => {
        if (!videoInfo) return;

        setIsDownloading(true);
        setProgress({ percent: 0, status: 'starting', downloaded_formatted: '0 B', speed_formatted: '0 B/s', eta_formatted: '--:--' });
        setErrorMsg(null);
        setCompletedFile(null);

        const payload = {
            url: videoInfo.webpage_url || url,
            type: activeTab,
            format_id: activeTab === 'video' ? (selectedFormat ? selectedFormat.format_id : 'best') : 'best',
            audio_format: selectedAudioFormat
        };

        try {
            const res = await fetch('/api/download', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.detail || "Failed to initiate download");
            }

            const taskId = data.task_id;
            listenToProgress(taskId);

        } catch (err) {
            setErrorMsg(err.message);
            setIsDownloading(false);
        }
    };

    const listenToProgress = (taskId) => {
        if (sseRef.current) {
            sseRef.current.close();
        }

        const es = new EventSource(`/api/progress/${taskId}`);
        sseRef.current = es;

        es.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                setProgress(data);

                if (data.status === 'completed') {
                    es.close();
                    setIsDownloading(false);
                    setCompletedFile(data.file_info);
                    fetchHistory();
                } else if (data.status === 'error') {
                    es.close();
                    setIsDownloading(false);
                    setErrorMsg(data.error || "An error occurred during download");
                }
            } catch (e) {
                console.error("Failed to parse SSE data", e);
            }
        };

        es.onerror = () => {
            es.close();
        };
    };

    const handleDeleteHistory = async (id) => {
        try {
            await fetch(`/api/history/${id}`, { method: 'DELETE' });
            setHistory(history.filter(item => item.id !== id));
        } catch (err) {
            console.error("Delete history item failed", err);
        }
    };

    return (
        <div className="app-container">
            {/* Header */}
            <header className="app-header">
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.75rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
                    <div className="brand-badge" style={{ marginBottom: 0 }}>
                        <Icon name="zap" size={14} /> StreamFetch Media Tool
                    </div>
                    <button
                        type="button"
                        className={`cookie-badge-btn ${hasCookies ? 'active' : ''}`}
                        onClick={() => setShowCookieModal(true)}
                        title="YouTube Cookie Authentication for Cloud/VPS"
                    >
                        <Icon name={hasCookies ? 'shield-check' : 'key'} size={13} />
                        <span>{hasCookies ? 'Cookies Active' : 'Cookie Settings'}</span>
                    </button>
                </div>
                <h1 className="hero-title">Video & Audio Downloader</h1>
                <p className="hero-subtitle">
                    Fast media extraction and conversion. Download HD video and high-bitrate audio from YouTube and major web platforms.
                </p>
                <div className="platform-pills">
                    <span className="platform-tag">YouTube 4K / HD</span>
                    <span className="platform-tag">Twitter / X</span>
                    <span className="platform-tag">TikTok</span>
                    <span className="platform-tag">Instagram</span>
                    <span className="platform-tag">Vimeo</span>
                    <span className="platform-tag">MP3 / M4A</span>
                </div>
            </header>

            {/* Main Downloader Panel */}
            <main>
                <div className="solid-card">
                    <form onSubmit={handleFetchInfo}>
                        <div className="search-wrapper">
                            <Icon name="link-2" className="search-icon" size={18} />
                            <input
                                type="text"
                                className="search-input"
                                placeholder="Paste video link here (e.g. https://www.youtube.com/watch?v=...)"
                                value={url}
                                onChange={(e) => setUrl(e.target.value)}
                            />
                            {url && (
                                <button type="button" className="clear-btn" onClick={() => setUrl('')} title="Clear input">
                                    <Icon name="x" size={16} />
                                </button>
                            )}
                            <button type="button" className="icon-btn" onClick={handlePaste} title="Paste from clipboard">
                                <Icon name="clipboard" size={16} />
                            </button>
                            <button type="submit" className="action-btn" disabled={isFetching || !url.trim()}>
                                {isFetching ? (
                                    <>
                                        <div className="spinner"></div>
                                        <span>Fetching...</span>
                                    </>
                                ) : (
                                    <>
                                        <Icon name="arrow-right" size={16} />
                                        <span>Fetch Media</span>
                                    </>
                                )}
                            </button>
                        </div>
                    </form>

                    {/* Error Banner */}
                    {errorMsg && (
                        <div className="alert-banner">
                            <div className="alert-banner-title">
                                <Icon name="alert-circle" size={18} />
                                <span>Operation Error</span>
                            </div>
                            <p className="alert-banner-message">{errorMsg}</p>
                            {(errorMsg.toLowerCase().includes('bot') || errorMsg.toLowerCase().includes('cookie') || errorMsg.toLowerCase().includes('sign in')) && (
                                <div style={{ marginTop: '0.65rem' }}>
                                    <button
                                        type="button"
                                        className="action-btn"
                                        style={{ padding: '0.45rem 0.9rem', fontSize: '0.85rem' }}
                                        onClick={() => setShowCookieModal(true)}
                                    >
                                        <Icon name="key" size={14} />
                                        <span>Open Cookie Settings</span>
                                    </button>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Video Info Section */}
                    {videoInfo && (
                        <div>
                            <div className="video-preview-grid">
                                <div className="thumbnail-container">
                                    <img src={videoInfo.thumbnail} alt={videoInfo.title} className="thumbnail-img" />
                                    {videoInfo.duration_formatted && (
                                        <span className="duration-badge">{videoInfo.duration_formatted}</span>
                                    )}
                                </div>
                                <div className="video-details">
                                    <h2 className="video-title">{videoInfo.title}</h2>
                                    <div className="uploader-row">
                                        <span className="uploader-name">
                                            <Icon name="user" size={15} /> {videoInfo.uploader}
                                        </span>
                                        {videoInfo.view_count && (
                                            <span>• {videoInfo.view_count.toLocaleString()} views</span>
                                        )}
                                    </div>
                                    {videoInfo.description && (
                                        <p className="video-desc">
                                            {videoInfo.description}
                                        </p>
                                    )}
                                </div>
                            </div>

                            {/* Format Picker Tabs */}
                            <div className="tabs-header">
                                <button
                                    type="button"
                                    className={`tab-btn ${activeTab === 'video' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('video')}
                                >
                                    <Icon name="video" size={16} /> Video + Audio
                                </button>
                                <button
                                    type="button"
                                    className={`tab-btn ${activeTab === 'audio' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('audio')}
                                >
                                    <Icon name="music" size={16} /> Audio Only
                                </button>
                            </div>

                            {/* Options Body */}
                            {activeTab === 'video' ? (
                                <div className="formats-grid">
                                    {videoInfo.video_formats && videoInfo.video_formats.length > 0 ? (
                                        videoInfo.video_formats.map((f) => {
                                            const isSelected = selectedFormat && selectedFormat.format_id === f.format_id;
                                            return (
                                                <div
                                                    key={f.format_id}
                                                    className={`format-card ${isSelected ? 'selected' : ''}`}
                                                    onClick={() => setSelectedFormat(f)}
                                                >
                                                    <div className="format-res">
                                                        <span>{f.resolution}</span>
                                                        {isSelected && <Icon name="check" size={16} />}
                                                    </div>
                                                    <div className="format-meta">
                                                        <span className="format-badge">{f.ext}</span>
                                                        <span>{f.filesize_formatted}</span>
                                                    </div>
                                                </div>
                                            );
                                        })
                                    ) : (
                                        <div className="format-card selected" onClick={() => setSelectedFormat({ format_id: 'best' })}>
                                            <div className="format-res">
                                                <span>Best Quality</span>
                                                <Icon name="check" size={16} />
                                            </div>
                                            <div className="format-meta">
                                                <span className="format-badge">MP4</span>
                                                <span>Auto Selected</span>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ) : (
                                <div className="formats-grid">
                                    {videoInfo.audio_formats.map((af) => {
                                        const isSelected = selectedAudioFormat === af.ext;
                                        return (
                                            <div
                                                key={af.format_id}
                                                className={`format-card ${isSelected ? 'selected' : ''}`}
                                                onClick={() => setSelectedAudioFormat(af.ext)}
                                            >
                                                <div className="format-res">
                                                    <span>{af.label}</span>
                                                    {isSelected && <Icon name="check" size={16} />}
                                                </div>
                                                <div className="format-meta">
                                                    <span className="format-badge">{af.ext.toUpperCase()}</span>
                                                    <span>Audio Only</span>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            )}

                            {/* Start Download Button */}
                            {!isDownloading && !completedFile && (
                                <button
                                    type="button"
                                    className="action-btn"
                                    onClick={handleStartDownload}
                                    style={{ width: '100%', marginTop: '0.5rem' }}
                                >
                                    <Icon name="download-cloud" size={18} />
                                    <span>
                                        Download {activeTab === 'video' ? (selectedFormat ? selectedFormat.resolution : 'Video') : `${selectedAudioFormat.toUpperCase()} Audio`}
                                    </span>
                                </button>
                            )}

                            {/* Download Progress Widget */}
                            {isDownloading && progress && (
                                <div className="progress-card">
                                    <div className="progress-header">
                                        <div className="progress-title">
                                            <Icon name="loader-2" size={16} />
                                            <span>
                                                {progress.status === 'processing'
                                                    ? 'Processing & Merging Media...'
                                                    : `Downloading (${progress.percent || 0}%)`}
                                            </span>
                                        </div>
                                        <div className="progress-percentage">
                                            {progress.percent || 0}%
                                        </div>
                                    </div>

                                    <div className="progress-track">
                                        <div
                                            className="progress-fill"
                                            style={{ width: `${progress.percent || 0}%` }}
                                        ></div>
                                    </div>

                                    <div className="progress-stats">
                                        <div className="stat-item">
                                            <span>Downloaded</span>
                                            {progress.downloaded_formatted || '0 B'} / {progress.total_formatted || 'calculating...'}
                                        </div>
                                        <div className="stat-item">
                                            <span>Speed</span>
                                            {progress.speed_formatted || '0 B/s'}
                                        </div>
                                        <div className="stat-item">
                                            <span>ETA Remaining</span>
                                            {progress.eta_formatted || '--:--'}
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Download Success & Preview Player */}
                            {completedFile && (
                                <div className="success-box">
                                    <div className="success-icon">
                                        <Icon name="check-circle-2" size={26} />
                                    </div>
                                    <h3 className="success-title">
                                        Download Complete
                                    </h3>
                                    <p className="success-meta">
                                        {completedFile.title} • {completedFile.filesize_formatted}
                                    </p>

                                    {/* Built-in Preview Player */}
                                    {completedFile.media_type === 'video' ? (
                                        <video controls className="media-preview-player" src={completedFile.download_url}></video>
                                    ) : (
                                        <audio controls className="media-preview-player" src={completedFile.download_url}></audio>
                                    )}

                                    <div>
                                        <a
                                            href={completedFile.download_url}
                                            download={completedFile.filename}
                                            className="save-file-btn"
                                        >
                                            <Icon name="download" size={18} /> Save File to Device
                                        </a>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>

                {/* History Section */}
                {history && history.length > 0 && (
                    <div className="solid-card">
                        <h3 className="section-title">
                            <Icon name="history" size={18} /> Recent Downloads
                        </h3>
                        <div className="history-list">
                            {history.map((item) => (
                                <div key={item.id} className="history-item">
                                    <div className="history-thumb-info">
                                        {item.thumbnail ? (
                                            <img src={item.thumbnail} alt={item.title} className="history-thumb" />
                                        ) : (
                                            <div className="history-thumb" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#64748b' }}>
                                                <Icon name="film" size={18} />
                                            </div>
                                        )}
                                        <div className="history-text-col">
                                            <div className="history-title" title={item.title}>{item.title}</div>
                                            <div className="history-meta">
                                                <span>{item.uploader}</span> • <span>{item.filesize_formatted}</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="history-actions">
                                        <a
                                            href={item.download_url}
                                            download={item.filename}
                                            className="icon-btn"
                                            title="Download file again"
                                        >
                                            <Icon name="download" size={16} />
                                        </a>
                                        <button
                                            type="button"
                                            className="icon-btn delete"
                                            onClick={() => handleDeleteHistory(item.id)}
                                            title="Delete record"
                                        >
                                            <Icon name="trash-2" size={16} />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </main>

            {/* Cookie Settings Modal */}
            {showCookieModal && (
                <div className="modal-backdrop" onClick={() => setShowCookieModal(false)}>
                    <div className="modal-card" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                                <Icon name="key" size={18} />
                                <h3 style={{ margin: 0, fontSize: '1.15rem', color: 'var(--text-primary)' }}>YouTube Cookie Authentication</h3>
                            </div>
                            <button type="button" className="clear-btn" onClick={() => setShowCookieModal(false)}>
                                <Icon name="x" size={18} />
                            </button>
                        </div>
                        
                        <div className="modal-body">
                            <div className="cookie-status-bar">
                                <span style={{ color: 'var(--text-secondary)', fontSize: '0.85rem' }}>Authentication Status:</span>
                                {hasCookies ? (
                                    <span className="status-badge success">
                                        <Icon name="shield-check" size={13} /> Cookies Active & Ready
                                    </span>
                                ) : (
                                    <span className="status-badge warning">
                                        <Icon name="alert-circle" size={13} /> No Cookies Set (Needed on Cloud/VPS)
                                    </span>
                                )}
                            </div>

                            <div className="cookie-guide-box">
                                <strong style={{ color: 'var(--text-primary)', fontSize: '0.9rem' }}>Why are cookies needed on deployed servers?</strong>
                                <p style={{ margin: '0.35rem 0 0.65rem 0', fontSize: '0.85rem', color: 'var(--text-secondary)', lineHeight: '1.5' }}>
                                    Cloud and VPS providers (Oracle Cloud, AWS, GCP, etc.) have IP addresses flagged by YouTube, resulting in <i>"Sign in to confirm you’re not a bot"</i>. Supplying your cookies authenticates your server with YouTube so downloads work smoothly.
                                </p>
                                <strong style={{ color: 'var(--text-primary)', fontSize: '0.9rem' }}>How to export in 3 quick steps:</strong>
                                <ol style={{ margin: '0.35rem 0 0 1.25rem', padding: 0, fontSize: '0.85rem', color: 'var(--text-secondary)', lineHeight: '1.6' }}>
                                    <li>Install the browser extension <b>Get cookies.txt LOCALLY</b> (Chrome / Firefox / Edge).</li>
                                    <li>Go to <a href="https://www.youtube.com" target="_blank" rel="noreferrer" style={{ color: '#38bdf8', textDecoration: 'underline' }}>youtube.com</a> while signed into any account.</li>
                                    <li>Click the extension icon, copy the exported text, and paste it into the box below.</li>
                                </ol>
                            </div>

                            <div style={{ marginTop: '1.1rem' }}>
                                <label style={{ display: 'block', marginBottom: '0.45rem', fontSize: '0.85rem', fontWeight: 600, color: 'var(--text-primary)' }}>
                                    Paste cookies.txt contents (Netscape format):
                                </label>
                                <textarea
                                    className="cookie-textarea"
                                    rows={5}
                                    placeholder="# Netscape HTTP Cookie File&#10;.youtube.com&#9;TRUE&#9;/&#9;TRUE&#9;1789494530&#9;..."
                                    value={cookieInput}
                                    onChange={(e) => setCookieInput(e.target.value)}
                                />
                            </div>

                            {cookieStatusMsg && (
                                <div style={{ marginTop: '0.75rem', fontSize: '0.85rem', color: hasCookies ? '#4ade80' : '#f87171', fontWeight: 500 }}>
                                    {cookieStatusMsg}
                                </div>
                            )}
                        </div>

                        <div className="modal-footer">
                            {hasCookies && (
                                <button
                                    type="button"
                                    className="action-btn secondary"
                                    onClick={handleDeleteCookies}
                                    style={{ marginRight: 'auto' }}
                                >
                                    <Icon name="trash-2" size={14} />
                                    <span>Delete Cookies</span>
                                </button>
                            )}
                            <button
                                type="button"
                                className="action-btn secondary"
                                onClick={() => setShowCookieModal(false)}
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                className="action-btn"
                                disabled={cookieSaving || !cookieInput.trim()}
                                onClick={handleSaveCookies}
                            >
                                {cookieSaving ? 'Saving...' : 'Save Cookies'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('root')).render(
    <ErrorBoundary>
        <App />
    </ErrorBoundary>
);
