"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
    Download, Archive, CheckCircle2, Upload, Cloud,
    Trash2, RefreshCcw, Play, ExternalLink, Eye,
    AlertCircle, Loader2, FolderOpen, Film, X,
    ChevronRight, Maximize2, Minimize2, FileVideo,
    FileArchive, Check, Copy, QrCode, ArrowRight,
    MoreVertical, ZoomIn, Clock, HardDrive, Search,
    ArrowUpDown, CheckSquare, Square, Folder, Subtitles
} from "lucide-react";
import { clsx } from "clsx";
import { useUI } from "@/context/UIContext";
import { formatBytes } from "@/lib/api";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";

// ─── Types ────────────────────────────────────────────────────────────────
interface DownloadedFile {
    name: string; path: string; size: number; sizeHuman: string;
    type: "video" | "archive" | "other"; ext: string;
    modifiedAt: string; createdAt?: string;
}
interface ExtractedFile {
    name: string; path: string; relativePath: string; size: number;
    sizeHuman: string; type: "video"; ext: string; modifiedAt: string;
}
interface CompletedFile {
    id: string; jobId: string; jobName: string; seriesName: string;
    resolution: string; fileName: string; filePath: string;
    size: number; createdAt: string; status: string;
}
interface UploadRecord {
    id: string; fileName: string; size: number; sizeHuman: string;
    resolution: string; gdriveFileId: string; gdriveFolderId: string;
    gdriveLink: string; uploadedAt: string;
}

type TabId = "downloaded" | "extracted" | "completed" | "uploading" | "uploaded";

// ─── Approval Gate Modal ──────────────────────────────────────────────────
function ApprovalModal({ open, title, message, confirmLabel, onConfirm, onCancel, type = "info" }: any) {
    if (!open) return null;
    const colors: any = {
        info: "text-accent-cyan", danger: "text-red-400", success: "text-emerald-400", warning: "text-amber-400"
    };
    return (
        <div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/80 backdrop-blur-sm">
            <div className="bg-[#0f1117] border border-white/10 rounded-2xl p-8 max-w-md w-full shadow-2xl animate-scale-up">
                <div className={`text-4xl mb-4 ${colors[type]}`}>
                    {type === "danger" ? "⚠️" : type === "success" ? "✅" : "🔐"}
                </div>
                <h2 className="text-xl font-black text-white mb-2">{title}</h2>
                <p className="text-white/50 text-sm mb-8 leading-relaxed">{message}</p>
                <div className="flex gap-3">
                    <button onClick={onCancel} className="flex-1 py-3 rounded-xl border border-white/10 text-white/50 hover:bg-white/5 font-bold transition-all">
                        Cancel
                    </button>
                    <button
                        onClick={onConfirm}
                        className={clsx(
                            "flex-1 py-3 rounded-xl font-bold transition-all",
                            type === "danger" ? "bg-red-500 hover:bg-red-400 text-white" : "bg-accent-cyan hover:bg-cyan-400 text-white"
                        )}
                    >
                        {confirmLabel || "Confirm"}
                    </button>
                </div>
            </div>
        </div>
    );
}

// ─── Extractor Modal ───────────────────────────────────────────────────────
function ExtractorModal({ operationId, archiveName, onClose, onComplete }: any) {
    const [minimized, setMinimized] = useState(false);
    const [progress, setProgress] = useState(0);
    const [currentFile, setCurrentFile] = useState("");
    const [files, setFiles] = useState<string[]>([]);
    const [status, setStatus] = useState<"running" | "complete" | "error">("running");
    const [error, setError] = useState<string | null>(null);
    const [totalFiles, setTotalFiles] = useState(0);
    const logsRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (!operationId) return;
        const evtSource = new EventSource(`${API}/api/events`);
        evtSource.addEventListener(`extract_${operationId}`, (e: any) => {
            const data = JSON.parse(e.data);
            if (data.type === "progress") {
                setProgress(data.percent || 0);
                if (data.currentFile) setCurrentFile(data.currentFile);
            } else if (data.type === "total") {
                setTotalFiles(data.totalFiles);
            } else if (data.type === "file") {
                setFiles(prev => [...prev, data.name]);
                if (logsRef.current) logsRef.current.scrollTop = logsRef.current.scrollHeight;
            } else if (data.type === "complete") {
                setStatus("complete");
                setProgress(100);
                setCurrentFile("Extraction complete!");
                setFiles(data.videoFiles?.map((f: any) => f.name) || []);
                onComplete?.(data.videoFiles || []);
                evtSource.close();
            } else if (data.type === "error") {
                setStatus("error");
                setError(data.message);
                evtSource.close();
            }
        });
        return () => evtSource.close();
    }, [operationId]);

    if (minimized) {
        return (
            <div className="fixed bottom-6 left-6 z-[150] flex items-center gap-4 bg-[#0f1117] border border-white/10 rounded-2xl px-5 py-3 shadow-2xl cursor-pointer hover:border-accent-cyan/40 transition-all" onClick={() => setMinimized(false)}>
                <div className="w-2 h-2 bg-accent-cyan rounded-full animate-pulse" />
                <span className="text-sm font-bold text-white">Extracting: {archiveName}</span>
                <span className="text-accent-cyan font-black">{progress}%</span>
                <Maximize2 className="w-4 h-4 text-white/40" />
            </div>
        );
    }

    return (
        <div className="fixed inset-0 z-[150] flex items-center justify-center bg-black/80 backdrop-blur-sm">
            <div className="bg-[#0d0f14] border border-white/10 rounded-2xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[85vh]">
                {/* Header */}
                <div className="flex items-center justify-between p-6 border-b border-white/5">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center">
                            <Archive className="w-5 h-5 text-amber-400" />
                        </div>
                        <div>
                            <h3 className="font-black text-lg text-white">Extractor</h3>
                            <p className="text-white/40 text-xs truncate max-w-[300px]">{archiveName}</p>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <button onClick={() => setMinimized(true)} className="p-2 rounded-lg bg-white/5 text-white/40 hover:text-white transition-all" title="Minimize (extraction continues)">
                            <Minimize2 className="w-4 h-4" />
                        </button>
                        <button onClick={onClose} className="p-2 rounded-lg bg-white/5 text-white/40 hover:text-red-400 transition-all" title="Close (extraction continues in background)">
                            <X className="w-4 h-4" />
                        </button>
                    </div>
                </div>

                {/* Progress */}
                <div className="p-6 border-b border-white/5">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs font-black uppercase tracking-widest text-white/40">
                            {status === "running" ? "Extracting..." : status === "complete" ? "✅ Complete!" : "❌ Error"}
                        </span>
                        <span className="text-2xl font-black text-white">{progress}%</span>
                    </div>
                    <div className="w-full bg-white/5 h-3 rounded-full overflow-hidden mb-3">
                        <div
                            className={clsx("h-full rounded-full transition-all duration-500", status === "complete" ? "bg-emerald-500" : status === "error" ? "bg-red-500" : "bg-gradient-to-r from-amber-500 to-orange-400")}
                            style={{ width: `${progress}%` }}
                        />
                    </div>
                    {currentFile && (
                        <p className="text-xs text-white/50 truncate">
                            <span className="text-amber-400 font-bold">▶ </span>{currentFile}
                        </p>
                    )}
                    {error && <p className="text-xs text-red-400 mt-2">{error}</p>}
                </div>

                {/* File List */}
                <div className="flex-1 overflow-y-auto p-4 custom-scrollbar" ref={logsRef}>
                    <p className="text-[10px] uppercase font-black tracking-widest text-white/30 mb-3">
                        Extracted Files ({files.length}{totalFiles > 0 ? ` / ${totalFiles}` : ""})
                    </p>
                    {files.length === 0 && status === "running" && (
                        <div className="flex items-center gap-2 text-white/30 text-sm">
                            <Loader2 className="w-4 h-4 animate-spin" /> Starting extraction...
                        </div>
                    )}
                    {files.map((f, i) => (
                        <div key={i} className="flex items-center gap-2 py-1.5 border-b border-white/5 text-sm">
                            <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
                            <span className="text-white/70 truncate font-mono text-xs">{f}</span>
                        </div>
                    ))}
                </div>

                {/* Footer */}
                {status === "complete" && (
                    <div className="p-4 border-t border-white/5 flex justify-end">
                        <button onClick={onClose} className="btn-primary px-8 py-3 rounded-xl">
                            <Check className="w-4 h-4" /> Done — Go to Extracted
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
}

// ─── Video Player Modal ───────────────────────────────────────────────────
function VideoPlayerModal({ filePath, fileName, onClose, onApprove }: any) {
    const videoUrl = filePath ? `${API}/previews/${encodeURIComponent(filePath.split("/output/")[1] || filePath.split("\\output\\")[1] || "")}` : null;
    const vlcUrl = filePath ? `vlc://${filePath}` : null;

    return (
        <div className="fixed inset-0 z-[150] flex items-center justify-center bg-black/95 backdrop-blur-sm">
            <div className="w-full max-w-5xl flex flex-col gap-4">
                {/* Controls */}
                <div className="flex items-center justify-between px-4">
                    <div className="flex items-center gap-3">
                        <Film className="w-5 h-5 text-accent-cyan" />
                        <span className="text-white font-bold truncate max-w-md text-sm">{fileName}</span>
                    </div>
                    <div className="flex items-center gap-2">
                        {vlcUrl && (
                            <a href={vlcUrl} className="flex items-center gap-2 px-4 py-2 bg-orange-500/20 border border-orange-500/30 text-orange-400 rounded-xl text-xs font-bold hover:bg-orange-500/30 transition-all">
                                <ExternalLink className="w-3.5 h-3.5" /> Open in VLC
                            </a>
                        )}
                        {onApprove && (
                            <button onClick={onApprove} className="flex items-center gap-2 px-4 py-2 bg-emerald-500/20 border border-emerald-500/30 text-emerald-400 rounded-xl text-xs font-bold hover:bg-emerald-500/30 transition-all">
                                <CheckCircle2 className="w-3.5 h-3.5" /> Approve for Upload
                            </button>
                        )}
                        <button onClick={onClose} className="p-2 rounded-xl bg-white/5 text-white/40 hover:text-white transition-all">
                            <X className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                {/* Video */}
                <div className="bg-black rounded-2xl overflow-hidden aspect-video">
                    {videoUrl ? (
                        <video src={videoUrl} controls autoPlay className="w-full h-full" />
                    ) : (
                        <div className="w-full h-full flex items-center justify-center text-white/20">
                            <div className="text-center">
                                <Film className="w-16 h-16 mx-auto mb-4" />
                                <p>Cannot stream this file directly.</p>
                                <p className="text-xs mt-2">Use "Open in VLC" for full playback.</p>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

// ─── Main Files Pipeline Page ─────────────────────────────────────────────
export default function FilePipelinePage() {
    const { confirm, alert } = useUI();
    const [activeTab, setActiveTab] = useState<TabId>("downloaded");
    const [loading, setLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");
    const [sortBy, setSortBy] = useState<string>("newest");

    // Data
    const [downloaded, setDownloaded] = useState<DownloadedFile[]>([]);
    const [extracted, setExtracted] = useState<ExtractedFile[]>([]);
    const [completed, setCompleted] = useState<CompletedFile[]>([]);
    const [uploaded, setUploaded] = useState<UploadRecord[]>([]);
    const [dlSummary, setDlSummary] = useState<any>(null);
    const [exSummary, setExSummary] = useState<any>(null);

    // Selection
    const [selected, setSelected] = useState<Set<string>>(new Set());

    // Modals
    const [extractorModal, setExtractorModal] = useState<any>(null);
    const [playerModal, setPlayerModal] = useState<any>(null);
    const [approvalModal, setApprovalModal] = useState<any>(null);

    // Upload progress (minimizable)
    const [uploadProgress, setUploadProgress] = useState<any[]>([]);
    const [uploadMinimized, setUploadMinimized] = useState(false);

    // Stats
    const [stats, setStats] = useState<any>(null);

    // Helpers
    function timeAgo(date: string) {
        const s = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
        if (s < 60) return `${s}s ago`;
        if (s < 3600) return `${Math.floor(s / 60)}m ago`;
        if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
        return `${Math.floor(s / 86400)}d ago`;
    }
    function toggleSelect(path: string) {
        setSelected(prev => { const n = new Set(prev); n.has(path) ? n.delete(path) : n.add(path); return n; });
    }
    function selectAll(items: any[]) {
        const paths = items.map(f => f.path);
        const allSelected = paths.every(p => selected.has(p));
        setSelected(prev => {
            const n = new Set(prev);
            paths.forEach(p => allSelected ? n.delete(p) : n.add(p));
            return n;
        });
    }

    const authHeaders = () => {
        const token = typeof window !== "undefined" ? localStorage.getItem("mhb_token") : "";
        return { "Content-Type": "application/json", Authorization: `Bearer ${token}` };
    };

    // ─── Load data ──────────────────────────────────────────────
    const loadAll = useCallback(async () => {
        setLoading(true);
        try {
            const [dlRes, exRes, cmpRes, statsRes] = await Promise.all([
                fetch(`${API}/api/downloads`, { headers: authHeaders() }),
                fetch(`${API}/api/downloads/extracted`, { headers: authHeaders() }),
                fetch(`${API}/api/files`, { headers: authHeaders() }),
                fetch(`${API}/api/stats`, { headers: authHeaders() }),
            ]);
            if (dlRes.ok) { const d = await dlRes.json(); setDownloaded(d.files || []); setDlSummary(d.summary || null); }
            if (exRes.ok) { const d = await exRes.json(); setExtracted(d.files || []); setExSummary(d.summary || null); }
            if (cmpRes.ok) setCompleted((await cmpRes.json()).files || []);
            if (statsRes.ok) setStats(await statsRes.json());
        } catch (e) { console.error("Load failed", e); }
        finally { setLoading(false); setSelected(new Set()); }
    }, []);

    useEffect(() => { loadAll(); }, [loadAll]);

    // ─── Tab config ─────────────────────────────────────────────
    const tabs = [
        { id: "downloaded" as TabId, label: "Downloaded", icon: Download, count: downloaded.length, color: "text-blue-400" },
        { id: "extracted" as TabId, label: "Extracted", icon: Archive, count: extracted.length, color: "text-amber-400" },
        { id: "completed" as TabId, label: "Completed", icon: CheckCircle2, count: completed.length, color: "text-emerald-400" },
        { id: "uploading" as TabId, label: "Uploading", icon: Upload, count: uploadProgress.length, color: "text-violet-400" },
        { id: "uploaded" as TabId, label: "Uploaded", icon: Cloud, count: uploaded.length, color: "text-cyan-400" },
    ];

    // ─── Handlers ───────────────────────────────────────────────
    function askPermission({ title, message, confirmLabel, type = "info", onConfirm }: any) {
        setApprovalModal({ open: true, title, message, confirmLabel, type, onConfirm });
    }

    function handleVideoClick(file: DownloadedFile | ExtractedFile) {
        askPermission({
            title: "Send to File Downloader?",
            message: `"${file.name}" will be opened in File Downloader for analysis and processing. Live track info, subtitle preview, and encode options will be available.`,
            confirmLabel: "Open in File Downloader",
            type: "info",
            onConfirm: () => {
                setApprovalModal(null);
                // Store in sessionStorage so analyzer page picks it up
                sessionStorage.setItem("pipeline_file", JSON.stringify({ filePath: file.path, fileName: file.name }));
                window.location.href = "/analyzer";
            }
        });
    }

    function handleArchiveClick(file: DownloadedFile) {
        askPermission({
            title: "Extract This Archive?",
            message: `"${file.name}" (${file.sizeHuman}) will be extracted. Depending on file size this may take a moment. You can minimize the extractor and continue working.`,
            confirmLabel: "Extract Now",
            type: "info",
            onConfirm: async () => {
                setApprovalModal(null);
                const opId = `extract_${Date.now()}`;
                // Start extraction
                await fetch(`${API}/api/downloads/extract`, {
                    method: "POST",
                    headers: authHeaders(),
                    body: JSON.stringify({ filePath: file.path, operationId: opId }),
                });
                setExtractorModal({ operationId: opId, archiveName: file.name });
            }
        });
    }

    async function handleDelete(filePath: string, name: string, section: "downloaded" | "extracted") {
        const ok = await confirm({
            title: "Delete File?",
            message: `"${name}" will be permanently deleted from the server. This cannot be undone.`,
            type: "danger",
            confirmLabel: "Delete",
        });
        if (!ok) return;
        try {
            const endpoint = section === "downloaded"
                ? `${API}/api/downloads/${encodeURIComponent(name)}`
                : `${API}/api/downloads/extracted/${encodeURIComponent(name)}`;
            const res = await fetch(endpoint, { method: "DELETE", headers: authHeaders() });
            if (!res.ok) throw new Error((await res.json()).error);
            loadAll();
        } catch (err: any) {
            alert({ title: "Delete Failed", message: err.message, type: "error" });
        }
    }

    function handlePlayCompleted(file: CompletedFile) {
        setPlayerModal({ filePath: file.filePath, fileName: file.fileName });
    }

    function copyToClipboard(text: string) {
        navigator.clipboard?.writeText(text);
    }

    // ─── Render sections ─────────────────────────────────────────

    // Bulk delete handler
    async function handleBulkDelete() {
        if (selected.size === 0) return;
        const ok = await confirm({ title: `Delete ${selected.size} Files?`, message: `${selected.size} file(s) will be permanently deleted. This cannot be undone.`, type: "danger", confirmLabel: "Delete All" });
        if (!ok) return;
        try {
            await fetch(`${API}/api/downloads/bulk-delete`, { method: "POST", headers: authHeaders(), body: JSON.stringify({ files: Array.from(selected) }) });
            loadAll();
        } catch (err: any) { alert({ title: "Bulk Delete Failed", message: err.message, type: "error" }); }
    }

    // Filter + sort helper
    function filterAndSort<T extends { name: string; size?: number; modifiedAt?: string }>(items: T[]): T[] {
        let result = items;
        if (searchQuery) { const q = searchQuery.toLowerCase(); result = result.filter(f => f.name.toLowerCase().includes(q)); }
        if (sortBy === "size_desc") result = [...result].sort((a, b) => (b.size || 0) - (a.size || 0));
        else if (sortBy === "size_asc") result = [...result].sort((a, b) => (a.size || 0) - (b.size || 0));
        else if (sortBy === "name") result = [...result].sort((a, b) => a.name.localeCompare(b.name));
        return result;
    }

    function renderDownloaded() {
        const files = filterAndSort(downloaded);
        if (downloaded.length === 0) return <EmptyState icon={Download} title="No downloaded files" subtitle="Download a URL from File Downloader to see files here." />;

        const typeIcon = (t: string) => t === "video" ? <FileVideo className="w-5 h-5 text-blue-400" /> : t === "archive" ? <FileArchive className="w-5 h-5 text-amber-400" /> : t === "folder" ? <Folder className="w-5 h-5 text-violet-400" /> : <Subtitles className="w-5 h-5 text-green-400" />;
        const typeBg = (t: string) => t === "video" ? "bg-blue-500/10" : t === "archive" ? "bg-amber-500/10" : t === "folder" ? "bg-violet-500/10" : "bg-green-500/10";

        return (
            <div className="space-y-2">
                {/* Summary bar */}
                {dlSummary && (
                    <div className="flex items-center gap-4 p-3 bg-white/[0.02] border border-white/5 rounded-xl text-xs mb-3">
                        <span className="text-white/30 font-bold">{dlSummary.totalFiles} files</span>
                        <span className="text-white/10">|</span>
                        <span className="text-blue-400 font-bold">{dlSummary.videoCount} videos</span>
                        <span className="text-white/10">|</span>
                        <span className="text-amber-400 font-bold">{dlSummary.archiveCount} archives</span>
                        <span className="text-white/10">|</span>
                        <span className="text-white/50 font-bold">{dlSummary.totalSizeHuman}</span>
                        <div className="flex-1" />
                        {selected.size > 0 && (
                            <button onClick={handleBulkDelete} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 font-bold hover:bg-red-500/20 transition-all">
                                <Trash2 className="w-3 h-3" /> Delete {selected.size}
                            </button>
                        )}
                        <button onClick={() => selectAll(files)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white/5 text-white/40 font-bold hover:bg-white/10 transition-all">
                            {files.every(f => selected.has(f.path)) ? <CheckSquare className="w-3 h-3" /> : <Square className="w-3 h-3" />} All
                        </button>
                    </div>
                )}
                {files.map(file => (
                    <div key={file.path} className={clsx("flex items-center gap-4 p-4 border rounded-xl hover:border-white/10 transition-all group", selected.has(file.path) ? "bg-accent-cyan/5 border-accent-cyan/20" : "bg-white/[0.03] border-white/5")}>
                        <button onClick={() => toggleSelect(file.path)} className="shrink-0">
                            {selected.has(file.path) ? <CheckSquare className="w-4 h-4 text-accent-cyan" /> : <Square className="w-4 h-4 text-white/15 group-hover:text-white/30" />}
                        </button>
                        <div className={clsx("w-10 h-10 rounded-xl flex items-center justify-center shrink-0", typeBg(file.type))}>
                            {typeIcon(file.type)}
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-bold text-white truncate">{file.name}</p>
                            <div className="flex items-center gap-3 text-xs text-white/30 mt-0.5">
                                <span className="font-mono">{file.sizeHuman}</span>
                                <span className={clsx("uppercase font-black px-1.5 py-0.5 rounded text-[9px]",
                                    file.type === "video" ? "bg-blue-500/10 text-blue-400" : file.type === "archive" ? "bg-amber-500/10 text-amber-400" : "bg-white/5 text-white/40"
                                )}>{file.type}</span>
                                <span className="text-white/20">{timeAgo(file.modifiedAt)}</span>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-all">
                            {file.type === "video" && (
                                <button onClick={() => handleVideoClick(file)} className="px-4 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20 text-blue-400 text-xs font-bold hover:bg-blue-500/20 transition-all flex items-center gap-1.5">
                                    <ArrowRight className="w-3.5 h-3.5" /> Analyze
                                </button>
                            )}
                            {file.type === "archive" && (
                                <button onClick={() => handleArchiveClick(file)} className="px-4 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs font-bold hover:bg-amber-500/20 transition-all flex items-center gap-1.5">
                                    <Archive className="w-3.5 h-3.5" /> Extract
                                </button>
                            )}
                            <button onClick={() => handleDelete(file.path, file.name, "downloaded")} className="p-2 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-all">
                                <Trash2 className="w-3.5 h-3.5" />
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        );
    }

    function renderExtracted() {
        const files = filterAndSort(extracted);
        if (extracted.length === 0) return <EmptyState icon={Archive} title="No extracted files" subtitle="Extract an archive from the Downloaded tab to see files here." />;
        return (
            <div className="space-y-2">
                {exSummary && (
                    <div className="flex items-center gap-4 p-3 bg-white/[0.02] border border-white/5 rounded-xl text-xs mb-3">
                        <span className="text-amber-400 font-bold">{exSummary.totalFiles} video files</span>
                        <span className="text-white/10">|</span>
                        <span className="text-white/50 font-bold">{exSummary.totalSizeHuman}</span>
                        <div className="flex-1" />
                        {selected.size > 0 && (
                            <button onClick={handleBulkDelete} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 font-bold hover:bg-red-500/20 transition-all">
                                <Trash2 className="w-3 h-3" /> Delete {selected.size}
                            </button>
                        )}
                    </div>
                )}
                {files.map(file => (
                    <div key={file.path} className={clsx("flex items-center gap-4 p-4 border rounded-xl hover:border-white/10 transition-all group", selected.has(file.path) ? "bg-accent-cyan/5 border-accent-cyan/20" : "bg-white/[0.03] border-white/5")}>
                        <button onClick={() => toggleSelect(file.path)} className="shrink-0">
                            {selected.has(file.path) ? <CheckSquare className="w-4 h-4 text-accent-cyan" /> : <Square className="w-4 h-4 text-white/15 group-hover:text-white/30" />}
                        </button>
                        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center shrink-0">
                            <FileVideo className="w-5 h-5 text-amber-400" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-bold text-white truncate">{file.name}</p>
                            <div className="flex items-center gap-2 text-xs text-white/30 mt-0.5">
                                <span className="text-white/20 truncate max-w-[200px]">{file.relativePath}</span>
                                <span className="font-mono text-white/40">{file.sizeHuman}</span>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-all">
                            <button onClick={() => handleVideoClick(file)} className="px-4 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20 text-blue-400 text-xs font-bold hover:bg-blue-500/20 transition-all flex items-center gap-1.5">
                                <ArrowRight className="w-3.5 h-3.5" /> Analyze
                            </button>
                            <button onClick={() => handleDelete(file.path, file.name, "extracted")} className="p-2 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-all">
                                <Trash2 className="w-3.5 h-3.5" />
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        );
    }

    function renderCompleted() {
        if (completed.length === 0) return <EmptyState icon={CheckCircle2} title="No completed files" subtitle="Encode or remux a file to see results here." />;
        return (
            <div className="space-y-2">
                {completed.map(file => (
                    <div key={file.id} className="flex items-center gap-4 p-4 bg-white/[0.03] border border-white/5 rounded-xl hover:border-white/10 transition-all group">
                        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 flex items-center justify-center shrink-0">
                            <Film className="w-5 h-5 text-emerald-400" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-bold text-white truncate">{file.fileName}</p>
                            <div className="flex items-center gap-2 mt-0.5">
                                <span className="text-[10px] font-black uppercase px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-400">{file.resolution}</span>
                                <span className="text-xs text-white/30">{formatBytes ? formatBytes(file.size) : `${(file.size / 1024 / 1024).toFixed(1)} MB`}</span>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-all">
                            <button
                                onClick={() => handlePlayCompleted(file)}
                                className="px-3 py-2 rounded-lg bg-white/5 text-white/60 text-xs font-bold hover:bg-white/10 transition-all flex items-center gap-1.5"
                                title="Play to Verify"
                            >
                                <Play className="w-3.5 h-3.5" /> Play
                            </button>
                        </div>
                    </div>
                ))}
            </div>
        );
    }

    function renderUploading() {
        if (uploadProgress.length === 0) return <EmptyState icon={Upload} title="No active uploads" subtitle="Start an upload from the Completed tab to track it here." />;
        return (
            <div className="space-y-4">
                {uploadProgress.map(op => (
                    <div key={op.id} className="p-5 bg-white/[0.03] border border-white/5 rounded-xl">
                        <div className="flex items-center justify-between mb-3">
                            <span className="text-sm font-bold text-white truncate max-w-xs">{op.fileName}</span>
                            <span className="text-lg font-black text-white">{op.percent}%</span>
                        </div>
                        <div className="w-full bg-white/5 h-2 rounded-full overflow-hidden mb-3">
                            <div className="h-full bg-gradient-to-r from-violet-500 to-accent-cyan rounded-full transition-all" style={{ width: `${op.percent}%` }} />
                        </div>
                        <div className="grid grid-cols-3 gap-3 text-center">
                            <div className="bg-white/5 rounded-lg p-2">
                                <p className="text-[9px] font-black uppercase tracking-widest text-white/30 mb-1">Speed</p>
                                <p className="text-sm font-bold text-accent-cyan">{op.speed || "—"}</p>
                            </div>
                            <div className="bg-white/5 rounded-lg p-2">
                                <p className="text-[9px] font-black uppercase tracking-widest text-white/30 mb-1">Uploaded</p>
                                <p className="text-sm font-bold text-white">{op.uploaded || "—"} / {op.total || "—"}</p>
                            </div>
                            <div className="bg-white/5 rounded-lg p-2">
                                <p className="text-[9px] font-black uppercase tracking-widest text-white/30 mb-1">ETA</p>
                                <p className="text-sm font-bold text-white">{op.eta || "—"}</p>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        );
    }

    function renderUploaded() {
        if (uploaded.length === 0) return <EmptyState icon={Cloud} title="No uploaded files" subtitle="Files will appear here after successful uploads to Google Drive." />;
        return (
            <div className="space-y-2">
                {uploaded.map(file => (
                    <div key={file.id} className="flex items-center gap-4 p-4 bg-white/[0.03] border border-white/5 rounded-xl group">
                        <div className="w-10 h-10 rounded-xl bg-cyan-500/10 flex items-center justify-center shrink-0">
                            <Cloud className="w-5 h-5 text-accent-cyan" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-bold text-white truncate">{file.fileName}</p>
                            <p className="text-xs text-white/30 mt-0.5">{file.sizeHuman} · Uploaded {new Date(file.uploadedAt).toLocaleDateString()}</p>
                        </div>
                        <div className="flex items-center gap-2">
                            {file.gdriveLink && (
                                <a href={file.gdriveLink} target="_blank" rel="noreferrer"
                                    className="p-2 rounded-lg bg-cyan-500/10 text-accent-cyan hover:bg-cyan-500/20 transition-all"
                                    title="Open in Google Drive"
                                >
                                    <ExternalLink className="w-3.5 h-3.5" />
                                </a>
                            )}
                            {file.gdriveLink && (
                                <button onClick={() => copyToClipboard(file.gdriveLink)}
                                    className="p-2 rounded-lg bg-white/5 text-white/40 hover:text-white transition-all"
                                    title="Copy Link"
                                >
                                    <Copy className="w-3.5 h-3.5" />
                                </button>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        );
    }

    return (
        <div className="space-y-6 max-w-[1400px] mx-auto pb-20 px-4 md:px-0">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-extrabold tracking-tight">File <span className="text-white">Pipeline</span></h1>
                    <p className="text-white/40 text-sm mt-1">Full control over every stage — Downloaded → Extracted → Completed → Uploaded</p>
                </div>
                <div className="flex items-center gap-3">
                    {/* Search */}
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-white/20" />
                        <input
                            type="text" placeholder="Search files..."
                            value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
                            className="bg-white/5 border border-white/5 rounded-xl pl-9 pr-4 h-10 text-white text-xs placeholder:text-white/20 focus:outline-none focus:border-accent-cyan/30 w-48 transition-all"
                        />
                    </div>
                    {/* Sort */}
                    <select value={sortBy} onChange={e => setSortBy(e.target.value)}
                        className="bg-white/5 border border-white/5 rounded-xl px-3 h-10 text-white/60 text-xs focus:outline-none focus:border-accent-cyan/30 appearance-none cursor-pointer"
                    >
                        <option value="newest">Newest</option>
                        <option value="name">Name A-Z</option>
                        <option value="size_desc">Size ↓</option>
                        <option value="size_asc">Size ↑</option>
                    </select>
                    <button onClick={loadAll} disabled={loading} className="btn-ghost py-2 px-4 flex items-center gap-2">
                        <RefreshCcw className={clsx("w-4 h-4", loading && "animate-spin")} />
                        Refresh
                    </button>
                </div>
            </div>

            {/* Stats Bar */}
            {stats && (
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    {[
                        { label: "Downloads", value: stats.storage?.downloads?.sizeHuman, icon: Download, color: "text-blue-400" },
                        { label: "Output", value: stats.storage?.output?.sizeHuman, icon: Film, color: "text-emerald-400" },
                        { label: "Disk Free", value: stats.disk?.availHuman, icon: HardDrive, color: stats.disk?.usedPercent > 85 ? "text-red-400" : "text-white" },
                        { label: "Processed", value: stats.storage?.processed?.sizeHuman, icon: CheckCircle2, color: "text-accent-cyan" },
                    ].map(s => (
                        <div key={s.label} className="card p-4 flex items-center gap-3 bg-black/40 border-white/5">
                            <s.icon className={clsx("w-5 h-5 shrink-0", s.color)} />
                            <div>
                                <p className="text-[10px] uppercase font-black tracking-widest text-white/30">{s.label}</p>
                                <p className={clsx("text-sm font-bold", s.color)}>{s.value || "—"}</p>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Tabs */}
            <div className="flex items-center gap-1 bg-white/5 p-1.5 rounded-2xl border border-white/5 overflow-x-auto no-scrollbar">
                {tabs.map(tab => (
                    <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        className={clsx(
                            "flex items-center gap-2 px-5 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap transition-all",
                            activeTab === tab.id
                                ? "bg-white/10 text-white shadow-lg"
                                : "text-white/30 hover:text-white/60 hover:bg-white/5"
                        )}
                    >
                        <tab.icon className={clsx("w-3.5 h-3.5", activeTab === tab.id ? tab.color : "")} />
                        {tab.label}
                        {tab.count > 0 && (
                            <span className={clsx("px-2 py-0.5 rounded-full text-[9px] font-black", activeTab === tab.id ? "bg-white/20" : "bg-white/10 text-white/40")}>
                                {tab.count}
                            </span>
                        )}
                    </button>
                ))}
            </div>

            {/* Content */}
            <div className="min-h-[400px]">
                {loading && (
                    <div className="flex items-center justify-center py-20">
                        <Loader2 className="w-8 h-8 animate-spin text-accent-cyan" />
                    </div>
                )}
                {!loading && activeTab === "downloaded" && renderDownloaded()}
                {!loading && activeTab === "extracted" && renderExtracted()}
                {!loading && activeTab === "completed" && renderCompleted()}
                {!loading && activeTab === "uploading" && renderUploading()}
                {!loading && activeTab === "uploaded" && renderUploaded()}
            </div>

            {/* Extractor Modal */}
            {extractorModal && (
                <ExtractorModal
                    operationId={extractorModal.operationId}
                    archiveName={extractorModal.archiveName}
                    onClose={() => setExtractorModal(null)}
                    onComplete={(files: any[]) => {
                        setTimeout(() => loadAll(), 1000);
                        setActiveTab("extracted");
                    }}
                />
            )}

            {/* Video Player Modal */}
            {playerModal && (
                <VideoPlayerModal
                    filePath={playerModal.filePath}
                    fileName={playerModal.fileName}
                    onClose={() => setPlayerModal(null)}
                    onApprove={() => {
                        setPlayerModal(null);
                    }}
                />
            )}

            {/* Approval Gate Modal */}
            {approvalModal && (
                <ApprovalModal
                    open={approvalModal.open}
                    title={approvalModal.title}
                    message={approvalModal.message}
                    confirmLabel={approvalModal.confirmLabel}
                    type={approvalModal.type}
                    onConfirm={approvalModal.onConfirm}
                    onCancel={() => setApprovalModal(null)}
                />
            )}
        </div>
    );
}

// ─── Empty State Component ─────────────────────────────────────────────
function EmptyState({ icon: Icon, title, subtitle }: any) {
    return (
        <div className="flex flex-col items-center justify-center py-24 text-center">
            <div className="w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4">
                <Icon className="w-8 h-8 text-white/20" />
            </div>
            <p className="text-lg font-bold text-white/30">{title}</p>
            <p className="text-sm text-white/20 mt-1 max-w-xs">{subtitle}</p>
        </div>
    );
}
