import { useState, useEffect } from 'react';
import { API } from '../api/client';
import { useToast } from './ui';
import type { DiskUsage, ScanResult, SystemInfo } from '../api/client';

export function Dashboard() {
    const [scanResults, setScanResults] = useState<ScanResult[]>([]);
    const [scanTitle, setScanTitle] = useState("");
    const [storageData, setStorageData] = useState<DiskUsage>({ usedGB: '0', totalGB: '0', freeGB: '0' });
    const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
    const [activeScanType, setActiveScanType] = useState<string>('');

    // Wizard State
    const [wizardStep, setWizardStep] = useState(0);
    const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

    // Category sizes
    const [categorySizes, setCategorySizes] = useState({
        documents: -1,
        downloads: -1,
        desktop: -1,
        music: -1,
        movies: -1,
        system: -1,
        apps: -1,
        photos: -1,
        icloud: -1,
        trash: -1
    });

    const isCategoriesScanned = categorySizes.documents !== -1;

    const [isScanning, setIsScanning] = useState(false);
    const toast = useToast();

    const refreshDiskUsage = async () => {
        const usage = await API.getDiskUsage();
        if (usage) {
            setStorageData(usage);
            // Update Tray Title
            if (window.electronAPI && window.electronAPI.updateTrayTitle) {
                window.electronAPI.updateTrayTitle(`${usage.freeGB} GB Free`)
                    .catch(e => console.error("Tray error", e));
            }

            // Update Tray Icon with Graph - REMOVED
        }
    };

    // Dynamic Tray Icon removed per user request


    const scanCategories = async () => {
        setIsScanning(true);
        try {
            const sizes = await API.getCategorySizes();
            if (sizes) {
                setCategorySizes({
                    documents: sizes.documents,
                    downloads: sizes.downloads,
                    desktop: sizes.desktop,
                    music: sizes.music,
                    movies: sizes.movies,
                    system: sizes.system,
                    trash: sizes.trash,
                    apps: sizes.apps,
                    photos: sizes.photos,
                    icloud: sizes.icloud
                });
            }
        } catch (e) {
            console.error("Failed to scan categories", e);
        } finally {
            setIsScanning(false);
        }
    };


    useEffect(() => {
        refreshDiskUsage();
        API.getSystemInfo().then(setSystemInfo);
        API.getCategorySizes().then(setCategorySizes);
        // Auto-refresh disk usage every 30 seconds
        const interval = setInterval(refreshDiskUsage, 30000);
        return () => clearInterval(interval);
    }, []);

    // Ensure Tray is updated whenever storageData changes
    useEffect(() => {
        if (storageData.totalGB !== '0') {
            if (window.electronAPI?.updateTrayTitle) {
                window.electronAPI.updateTrayTitle(`${storageData.freeGB} GB Free`);
            }
            // Icon update removed
        }
    }, [storageData]);

    // Helper to run a scan and show results
    const runScan = async (type: string, title: string) => {
        setIsScanning(true);
        setScanTitle(title);
        setActiveScanType(type);
        setScanResults([]); // Clear previous results immediately

        // Reset Wizard state
        setWizardStep(0);
        setSelectedItems(new Set());

        try {
            let results: ScanResult[] = [];
            if (type === 'heavy') {
                results = await API.deepestScan();
            } else {
                results = await API.scanCategory(type);
            }

            if (results.length === 0) {
                toast.addToast({
                    type: 'success',
                    title: 'Scan Complete',
                    message: 'No items found matching criteria.'
                });
            } else {
                setScanResults(results);
            }
        } catch (e) {
            console.error(e);
            toast.addToast({
                type: 'error',
                title: 'Scan Failed',
                message: 'An error occurred while scanning.'
            });
        } finally {
            setIsScanning(false);
        }

    };


    const handlePurge = async (itemPath: string) => {
        const confirmed = await toast.confirm(
            `Delete "${itemPath.split('/').pop()}"?`,
            'This action cannot be undone.'
        );
        if (!confirmed) return;
        if (await API.purgePath(itemPath)) {
            setScanResults(prev => prev.filter(p => p.path !== itemPath));
            refreshDiskUsage();
            toast.addToast({ type: 'success', title: 'Deleted', message: itemPath.split('/').pop() });
        }
    };

    const handlePurgeAll = async () => {
        const confirmed = await toast.confirm(
            `Delete all ${scanResults.length} items?`,
            'This will permanently remove all scanned files.'
        );
        if (!confirmed) return;
        for (const item of scanResults) await API.purgePath(item.path);
        setScanResults([]);
        refreshDiskUsage();
        toast.addToast({ type: 'success', title: 'Cleanup Complete', message: `${scanResults.length} items removed` });
    };

    const formatBytes = (bytes: number) => {
        if (bytes === 0) return "0 B";
        const k = 1024;
        const sizes = ["B", "KB", "MB", "GB", "TB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    };

    // Calculate bar width percentages
    const total = parseFloat(storageData.totalGB) || 1;
    const used = parseFloat(storageData.usedGB) || 0;
    const usedPercent = (used / total) * 100;

    return (
        <div className="h-full flex flex-col p-4 md:p-8 max-w-7xl mx-auto w-full animate-fade-in overflow-hidden">
            <div className="flex flex-col lg:flex-row gap-6 h-full min-h-0">
                {/* Left Column: Actions & Overview */}
                <div className="flex flex-col gap-6 lg:w-[450px] shrink-0 overflow-y-auto lg:overflow-visible no-scrollbar">
                    {/* Header */}
                    <div className="flex items-center justify-between shrink-0">
                        <div className="flex items-center gap-4">
                            <h1 className="text-xl md:text-[28px] font-semibold text-black tracking-tight">Storage</h1>
                            {systemInfo && (
                                <div className="hidden md:flex items-center gap-3 px-3 py-1.5 liquid-glass rounded-[var(--radius-lg)] animate-fade-in border border-white/20 shadow-sm">
                                    <span className="text-[11px] font-medium text-gray-600">{systemInfo.model}</span>
                                    <span className="w-px h-3 bg-black/10"></span>
                                    <div className="flex items-center gap-1.5">
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-gray-500">
                                            <rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18" />
                                            <line x1="7" y1="2" x2="7" y2="22" />
                                            <line x1="17" y1="2" x2="17" y2="22" />
                                            <line x1="2" y1="12" x2="22" y2="12" />
                                            <line x1="2" y1="7" x2="7" y2="7" />
                                            <line x1="2" y1="17" x2="7" y2="17" />
                                            <line x1="17" y1="17" x2="22" y2="17" />
                                            <line x1="17" y1="7" x2="22" y2="7" />
                                        </svg>
                                        <span className="text-[11px] font-medium text-gray-600">{systemInfo.chip}</span>
                                    </div>
                                    <span className="w-px h-3 bg-black/10"></span>
                                    <span className="text-[11px] font-medium text-gray-600">{systemInfo.memory}</span>
                                    <span className="w-px h-3 bg-black/10"></span>
                                    <div className="flex items-center gap-1.5">
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" className="text-gray-900">
                                            <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.3-3.14-2.53C4.25 17 2.91 12.45 4.7 9.35c.89-1.54 2.49-2.51 4.2-2.54 1.35-.03 2.61.91 3.42.91.81 0 2.38-1.12 4-1.09 1.4.03 2.64.92 3.65 1.5-3.05 1.6-2.52 6.01.6 7.37zM15.56 5.36c.72-.87 1.21-2.08 1.07-3.32-1.04.04-2.3.69-3.04 1.56-.66.79-1.24 2.05-1.08 3.25 1.16.09 2.34-.64 3.05-1.49z" />
                                        </svg>
                                        <span className="text-[11px] font-medium text-gray-900">{systemInfo.os.replace('macOS ', '')}</span>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Flash & Deep Clean Hero - Side by Side */}
                    <div className="grid grid-cols-2 gap-3 shrink-0">
                        {/* Flash Clean Card */}
                        <button
                            onClick={async () => {
                                const confirmed = await toast.confirm(
                                    'Start Flash Clean?',
                                    'This will safely remove system caches, logs, trash, and Docker data.'
                                );
                                if (confirmed) {
                                    setIsScanning(true);
                                    // Execute cleanup steps
                                    try {
                                        // Capture trash size before emptying
                                        const trashSize = categorySizes.trash > 0 ? categorySizes.trash : 0;

                                        const cacheRes = await API.clearCache();
                                        await API.emptyTrash();
                                        const dockerRes = await API.cleanDocker();

                                        refreshDiskUsage();
                                        scanCategories();

                                        // Calculate total and formatted details
                                        const totalFreed = cacheRes.cleared + trashSize + (dockerRes.cleared || 0);
                                        const details = [];
                                        if (cacheRes.cleared > 0) details.push('Cache');
                                        if (trashSize > 0) details.push('Trash');
                                        if (dockerRes.cleared > 0) details.push('Docker');

                                        const detailStr = details.length > 0 ? ` (${details.join(', ')})` : '';

                                        toast.addToast({
                                            type: 'success',
                                            title: 'Flash Clean Complete',
                                            message: `Freed ${formatBytes(totalFreed)}${detailStr}`
                                        });
                                    } catch (e) {
                                        console.error(e);
                                        toast.addToast({ type: 'error', title: 'Cleanup Failed', message: 'Check console for details' });
                                    } finally {
                                        setIsScanning(false);
                                    }
                                }
                            }}
                            disabled={isScanning}
                            className="relative group overflow-hidden rounded-[var(--radius-xl)] p-4 md:p-5 text-left transition-all duration-300 hover:scale-[1.02] active:scale-[0.98] border border-white/20 shadow-lg min-h-[160px] flex flex-col"
                        >
                            <div className="absolute inset-0 bg-gradient-to-br from-[#FFD60A] to-[#FF9F0A] opacity-90 transition-opacity group-hover:opacity-100" />
                            <div className="absolute inset-0 bg-[url('https://grainy-gradients.vercel.app/noise.svg')] opacity-20" />
                            <div className="relative z-10 flex flex-col h-full justify-between">
                                <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center backdrop-blur-sm mb-3">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-white">
                                        <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />
                                    </svg>
                                </div>
                                <div>
                                    <h3 className="text-lg font-bold text-white mb-1 leading-tight">Flash Clean</h3>
                                    <p className="text-white/80 text-[11px] font-medium leading-snug line-clamp-2">Instantly free up space.</p>
                                </div>
                            </div>
                        </button>

                        {/* Deep Clean Card */}
                        <button
                            onClick={() => runScan('heavy', 'Deep Clean Results')}
                            disabled={isScanning}
                            className="relative group overflow-hidden rounded-[var(--radius-xl)] p-4 md:p-5 text-left transition-all duration-300 hover:scale-[1.02] active:scale-[0.98] border border-white/10 shadow-lg bg-white/40 backdrop-blur-xl min-h-[160px] flex flex-col"
                        >
                            <div className="absolute inset-0 bg-gradient-to-br from-[#007AFF]/10 to-[#5856D6]/10 opacity-50 group-hover:opacity-100 transition-opacity" />
                            <div className="relative z-10 flex flex-col h-full justify-between">
                                <div className="w-10 h-10 rounded-full bg-[#007AFF]/10 flex items-center justify-center backdrop-blur-sm mb-3 group-hover:bg-[#007AFF]/20 transition-colors">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-[#007AFF]">
                                        <circle cx="11" cy="11" r="8" />
                                        <line x1="21" y1="21" x2="16.65" y2="16.65" />
                                    </svg>
                                </div>
                                <div>
                                    <h3 className="text-lg font-bold text-gray-900 mb-1 leading-tight">Deep Clean</h3>
                                    <p className="text-gray-600 text-[11px] font-medium leading-snug line-clamp-2">Review large files & folders.</p>
                                </div>
                            </div>
                        </button>
                    </div>


                    {/* Storage Bar Section - Glass Container */}
                    <div className="liquid-glass rounded-[var(--radius-lg)] p-5 md:p-6 shrink-0">
                        <div className="flex justify-between items-end mb-3">
                            <h2 className="text-[14px] font-semibold text-gray-900">Macintosh HD</h2>
                            <span className="text-[12px] md:text-[13px] text-gray-500 font-medium tabular-nums">
                                {storageData.usedGB} GB of {storageData.totalGB} GB used
                            </span>
                        </div>

                        {/* The Bar - Enhanced with inner glow */}
                        <div className="h-[28px] w-full bg-gradient-to-b from-black/5 to-black/10 rounded-[var(--radius-sm)] overflow-hidden flex shadow-inner">
                            {/* Applications Segment */}
                            <div
                                className="h-full bg-gradient-to-b from-[#FF5147] to-[#FF3B30] first:rounded-l-[var(--radius-sm)]"
                                style={{ width: `${Math.max(5, usedPercent * 0.4)}%` }}
                            />
                            {/* Photos Segment */}
                            <div
                                className="h-full bg-gradient-to-b from-[#FFB340] to-[#FF9500]"
                                style={{ width: `${Math.max(5, usedPercent * 0.2)}%` }}
                            />
                            {/* System Data Segment */}
                            <div
                                className="h-full bg-gradient-to-b from-[#A0A0A5] to-[#8E8E93]"
                                style={{ width: `${Math.max(5, usedPercent * 0.3)}%` }}
                            />
                            {/* macOS Segment */}
                            <div
                                className="h-full bg-gradient-to-b from-[#D4D4D9] to-[#C7C7CC] last:rounded-r-[var(--radius-sm)]"
                                style={{ width: `${Math.max(5, usedPercent * 0.1)}%` }}
                            />
                        </div>

                        {/* Legend */}
                        <div className="flex flex-wrap gap-x-5 gap-y-2 mt-4 text-[11px] font-medium text-gray-600">
                            <LegendItem color="bg-[#FF3B30]" label="Applications" />
                            <LegendItem color="bg-[#FFCC00]" label="Documents" />
                            <LegendItem color="bg-[#FF9500]" label="Photos" />
                            <LegendItem color="bg-[#8E8E93]" label="System Data" />
                            <LegendItem color="bg-[#C7C7CC]" label="macOS" />
                        </div>
                    </div>
                </div>

                {/* Right Column: Categories List */}
                <div className="flex-1 flex flex-col min-h-0 h-full gap-6">
                    {/* Header - Aligned with Left "Storage" */}
                    <div className="flex items-center justify-between shrink-0 h-[44px]">
                        <h2 className="text-xl md:text-[28px] font-semibold text-black tracking-tight" style={{ lineHeight: '1.2' }}>Categories</h2>
                        <button
                            onClick={scanCategories}
                            disabled={isScanning}
                            className={`flex items-center gap-2 px-4 py-2 rounded-[var(--radius-lg)] font-medium text-[13px] shadow-sm transition-all duration-200 ${isScanning
                                ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                                : 'bg-[#007AFF] text-white hover:bg-[#0062CC] active:scale-95'
                                }`}
                        >
                            {isScanning ? (
                                <>
                                    <Icons.Spinner />
                                    Scanning
                                </>
                            ) : (
                                <>
                                    <Icons.Scan />
                                    {isCategoriesScanned ? 'Rescan' : 'Scan System'}
                                </>
                            )}
                        </button>
                    </div>

                    {/* List Container - Glass Card */}
                    <div className="liquid-glass-heavy rounded-[var(--radius-lg)] overflow-hidden flex flex-col min-h-0 relative border border-white/20 dark:border-white/10 shadow-lg max-h-full">
                        <div className="overflow-y-auto flex-1 stagger-children py-3 px-3">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                                <CategoryRow
                                    icon={<Icons.Apps />}
                                    label="Applications"
                                    size={categorySizes.apps >= 0 ? formatBytes(categorySizes.apps) : "Not Scanned"}
                                    onClick={() => runScan('apps', 'Applications')}
                                    actionIcon
                                    description="Installed apps & support files"
                                />
                                <CategoryRow
                                    icon={<Icons.Documents />}
                                    label="Documents"
                                    size={categorySizes.documents >= 0 ? formatBytes(categorySizes.documents) : "Not Scanned"}
                                    onClick={() => runScan('docs', 'Documents')}
                                    actionIcon
                                    description="Personal documents folder"
                                />
                                <CategoryRow
                                    icon={<Icons.Downloads />}
                                    label="Downloads"
                                    size={categorySizes.downloads >= 0 ? formatBytes(categorySizes.downloads) : "Not Scanned"}
                                    onClick={() => runScan('downloads', 'Downloads')}
                                    actionIcon
                                    description="Downloads folder items"
                                />
                                <CategoryRow
                                    icon={<Icons.Desktop />}
                                    label="Desktop"
                                    size={categorySizes.desktop >= 0 ? formatBytes(categorySizes.desktop) : "Not Scanned"}
                                    onClick={() => runScan('desktop', 'Desktop Items')}
                                    actionIcon
                                    description="Files on your desktop"
                                />
                                <CategoryRow
                                    icon={<Icons.Music />}
                                    label="Music"
                                    size={categorySizes.music >= 0 ? formatBytes(categorySizes.music) : "Not Scanned"}
                                    onClick={() => runScan('music', 'Music Library')}
                                    actionIcon
                                    description="iTunes/Music library & files"
                                />
                                <CategoryRow
                                    icon={<Icons.Movies />}
                                    label="Movies"
                                    size={categorySizes.movies >= 0 ? formatBytes(categorySizes.movies) : "Not Scanned"}
                                    onClick={() => runScan('movies', 'Movies & Videos')}
                                    actionIcon
                                    description="Movies folder & video files"
                                />
                                <CategoryRow
                                    icon={<Icons.CloudDrive />}
                                    label="iCloud Drive"
                                    size={categorySizes.icloud >= 0 ? formatBytes(categorySizes.icloud) : "Not Scanned"}
                                    onClick={() => runScan('icloud', 'iCloud Drive')}
                                    actionIcon
                                    description="Local iCloud file copies"
                                />
                                <CategoryRow
                                    icon={<Icons.Photos />}
                                    label="Photos"
                                    size={categorySizes.photos >= 0 ? formatBytes(categorySizes.photos) : "Not Scanned"}
                                    onClick={() => runScan('photos', 'Photos')}
                                    actionIcon
                                    description="Photos library caches"
                                />
                                <CategoryRow
                                    icon={<Icons.Trash />}
                                    label="Trash"
                                    size={categorySizes.trash >= 0 ? formatBytes(categorySizes.trash) : "Not Scanned"}
                                    onClick={async () => {
                                        if (categorySizes.trash > 0) {
                                            const confirmed = await toast.confirm('Empty Trash?', 'This cannot be undone.');
                                            if (confirmed) {
                                                const success = await API.emptyTrash();
                                                if (success) {
                                                    setCategorySizes(prev => ({ ...prev, trash: 0 }));
                                                    refreshDiskUsage();
                                                    toast.addToast({ type: 'success', title: 'Trash Emptied' });
                                                }
                                            }
                                        }
                                    }}
                                    actionIcon={false}
                                    highlight={categorySizes.trash > 0}
                                    description="Deleted files in Trash"
                                />
                                <CategoryRow
                                    icon={<Icons.System />}
                                    label="System Data"
                                    size={categorySizes.system >= 0 ? formatBytes(categorySizes.system) : "Not Scanned"}
                                    onClick={() => runScan('system', 'System Data')}
                                    actionIcon
                                    description="Caches, logs, temp files"
                                />
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            {/* Native Sheet / Modal - Glass */}
            {scanResults.length > 0 && (
                <div className="absolute inset-0 z-50 flex items-center justify-center p-4 md:p-12 bg-black/20 backdrop-blur-md animate-fade-in">
                    {activeScanType === 'heavy' ? (
                        // --- WIZARD UI for Deep Clean ---
                        <div className="liquid-glass-heavy rounded-[var(--radius-xl)] w-full h-full max-w-4xl flex flex-col animate-scale-in overflow-hidden relative">
                            {/* Wizard Header */}
                            <div className="h-16 border-b border-white/10 flex items-center justify-between px-6 liquid-glass-light shrink-0">
                                <div>
                                    <h2 className="text-lg font-semibold text-gray-900">Deep Clean Wizard</h2>
                                    <p className="text-[11px] text-gray-500 font-medium">Step {wizardStep + 1} of 3: {['Overview', 'Select Items', 'Confirmation'][wizardStep]}</p>
                                </div>
                                <button
                                    onClick={() => setScanResults([])}
                                    className="p-2 hover:bg-black/5 rounded-full transition-colors"
                                >
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-gray-500">
                                        <path d="M18 6L6 18M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            {/* Wizard Content */}
                            <div className="flex-1 overflow-y-auto p-6 md:p-10 flex flex-col items-center justify-center text-center">
                                {/* Step 0: Overview */}
                                {wizardStep === 0 && (
                                    <div className="max-w-md animate-fade-in space-y-6">
                                        <div className="w-20 h-20 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-4">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-10 h-10 text-blue-500"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                                        </div>
                                        <div>
                                            <h3 className="text-2xl font-bold text-gray-900 mb-2">Scan Complete</h3>
                                            <p className="text-gray-600">
                                                We found <span className="font-semibold text-gray-900">{scanResults.length} large items</span> taking up{' '}
                                                <span className="font-semibold text-gray-900">{formatBytes(scanResults.reduce((acc, i) => acc + i.size, 0))}</span>.
                                            </p>
                                        </div>
                                        <div className="p-4 bg-yellow-50/50 border border-yellow-100 rounded-[var(--radius-lg)] text-left">
                                            <div className="flex gap-3">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5 text-yellow-600 shrink-0 mt-0.5"><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>
                                                <p className="text-[13px] text-yellow-800 leading-relaxed">
                                                    Deep Clean finds large files that might be important.
                                                    Please review each item carefully before deleting.
                                                </p>
                                            </div>
                                        </div>
                                        <button
                                            onClick={() => setWizardStep(1)}
                                            className="w-full py-3 bg-[#007AFF] text-white rounded-[var(--radius-lg)] font-semibold shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all active:scale-[0.98]"
                                        >
                                            Start Review
                                        </button>
                                    </div>
                                )}

                                {/* Step 1: Selection Checklist */}
                                {wizardStep === 1 && (
                                    <div className="w-full h-full flex flex-col animate-fade-in text-left">
                                        <div className="mb-4 flex items-center justify-between">
                                            <h3 className="text-lg font-semibold text-gray-900">Select Items to Remove</h3>
                                            <span className="text-[13px] text-gray-500">
                                                {selectedItems.size} selected ({formatBytes(scanResults.filter(i => selectedItems.has(i.path)).reduce((a, b) => a + b.size, 0))})
                                            </span>
                                        </div>
                                        <div className="flex-1 overflow-y-auto border border-black/5 rounded-[var(--radius-lg)] bg-white/40">
                                            {scanResults.map((item, i) => (
                                                <div
                                                    key={i}
                                                    onClick={() => {
                                                        const next = new Set(selectedItems);
                                                        if (next.has(item.path)) next.delete(item.path);
                                                        else next.add(item.path);
                                                        setSelectedItems(next);
                                                    }}
                                                    className={`p-4 border-b border-black/5 flex items-center gap-4 cursor-pointer transition-colors ${selectedItems.has(item.path) ? 'bg-blue-50/50' : 'hover:bg-white/60'
                                                        }`}
                                                >
                                                    <div className={`w-5 h-5 rounded border flex items-center justify-center transition-colors ${selectedItems.has(item.path) ? 'bg-blue-500 border-blue-500' : 'border-gray-300'
                                                        }`}>
                                                        {selectedItems.has(item.path) && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>}
                                                    </div>
                                                    <div className="flex-1 min-w-0">
                                                        <div className="font-medium text-gray-900 truncate">{item.path.split('/').pop()}</div>
                                                        <div className="text-[11px] text-gray-500 truncate">{item.path}</div>
                                                    </div>
                                                    <div className="text-[13px] font-medium text-gray-700 tabular-nums">
                                                        {formatBytes(item.size)}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                        <div className="mt-4 flex gap-3">
                                            <button
                                                onClick={() => setWizardStep(0)}
                                                className="px-6 py-2.5 text-gray-600 font-medium hover:bg-black/5 rounded-[var(--radius-lg)] transition-colors"
                                            >
                                                Back
                                            </button>
                                            <button
                                                onClick={() => setWizardStep(2)}
                                                disabled={selectedItems.size === 0}
                                                className="flex-1 py-2.5 bg-[#007AFF] text-white rounded-[var(--radius-lg)] font-semibold shadow-md disabled:opacity-50 disabled:shadow-none transition-all"
                                            >
                                                Review Selection
                                            </button>
                                        </div>
                                    </div>
                                )}

                                {/* Step 2: Confirmation */}
                                {wizardStep === 2 && (
                                    <div className="max-w-md animate-fade-in space-y-6">
                                        <div className="w-20 h-20 bg-red-50 rounded-full flex items-center justify-center mx-auto mb-4">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-10 h-10 text-red-500"><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>
                                        </div>
                                        <div>
                                            <h3 className="text-2xl font-bold text-gray-900 mb-2">Are you sure?</h3>
                                            <p className="text-gray-600">
                                                You are about to permanently delete <span className="font-bold text-gray-900">{selectedItems.size} items</span>.
                                            </p>
                                            <p className="text-[13px] text-red-600 mt-2 font-medium bg-red-50 py-1 px-3 rounded-full inline-block">
                                                This action cannot be undone.
                                            </p>
                                        </div>

                                        <div className="p-4 bg-gray-50 rounded-[var(--radius-lg)] text-left border border-black/5 max-h-48 overflow-y-auto">
                                            <ul className="space-y-2">
                                                {Array.from(selectedItems).map(path => (
                                                    <li key={path} className="text-[12px] text-gray-600 flex justify-between truncate">
                                                        <span className="truncate flex-1 mr-4">{path.split('/').pop()}</span>
                                                        <span className="font-medium text-gray-900">{formatBytes(scanResults.find(i => i.path === path)?.size || 0)}</span>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>

                                        <div className="flex gap-3 w-full">
                                            <button
                                                onClick={() => setWizardStep(1)}
                                                className="flex-1 py-3 bg-gray-100 text-gray-700 rounded-[var(--radius-lg)] font-semibold hover:bg-gray-200 transition-colors"
                                            >
                                                Back
                                            </button>
                                            <button
                                                disabled={isScanning}
                                                onClick={async () => {
                                                    setIsScanning(true);
                                                    let deletedCount = 0;
                                                    let deletedSize = 0;

                                                    // Process deletions
                                                    for (const path of selectedItems) {
                                                        const item = scanResults.find(i => i.path === path);
                                                        // Optimistic UI update could happen here, but easier to just wait
                                                        try {
                                                            const success = await API.purgePath(path);
                                                            if (success && item) {
                                                                deletedCount++;
                                                                deletedSize += item.size;
                                                            }
                                                        } catch (e) {
                                                            console.error('Failed to delete', path, e);
                                                        }
                                                    }

                                                    setIsScanning(false);
                                                    setScanResults([]); // Close modal
                                                    refreshDiskUsage();
                                                    scanCategories(); // Refresh categories too

                                                    toast.addToast({
                                                        type: 'success',
                                                        title: 'Deep Clean Complete',
                                                        message: `Removed ${deletedCount} items (${formatBytes(deletedSize)})`
                                                    });
                                                }}
                                                className="flex-1 py-3 bg-red-500 text-white rounded-[var(--radius-lg)] font-semibold shadow-lg hover:shadow-red-500/30 hover:bg-red-600 transition-all active:scale-[0.98]"
                                            >
                                                {isScanning ? 'Cleaning...' : 'Confirm Delete'}
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    ) : (
                        // --- STANDARD TABLE UI (for Categories) ---
                        <div className="liquid-glass-heavy rounded-[var(--radius-xl)] w-full h-full max-w-4xl flex flex-col animate-scale-in overflow-hidden">
                            {/* Toolbar */}
                            <div className="h-14 md:h-12 border-b border-white/10 flex items-center justify-between px-5 liquid-glass-light rounded-t-[var(--radius-xl)] shrink-0">
                                <span className="font-semibold text-[14px] truncate mr-3">{scanTitle}</span>
                                <div className="flex gap-2">
                                    <button
                                        className="px-4 py-1.5 bg-gradient-to-b from-[#FF5147] to-[#FF3B30] text-white rounded-[var(--radius-sm)] text-[13px] font-medium shadow-lg glass-press"
                                        onClick={handlePurgeAll}
                                    >
                                        Purge All
                                    </button>
                                    <button
                                        className="px-4 py-1.5 bg-gradient-to-b from-[#1E90FF] to-[#007AFF] text-white rounded-[var(--radius-sm)] text-[13px] font-medium shadow-lg glass-press"
                                        onClick={() => setScanResults([])}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                            {/* Table - Responsive */}
                            <div className="flex-1 overflow-auto">
                                {/* Desktop: Table View */}
                                <table className="w-full text-left border-collapse hidden md:table">
                                    <thead className="liquid-glass-light sticky top-0 z-10 border-b border-white/10">
                                        <tr>
                                            <th className="py-3 px-5 text-[12px] font-semibold text-gray-600 uppercase tracking-wide">Name</th>
                                            <th className="py-3 px-5 text-[12px] font-semibold text-gray-600 uppercase tracking-wide w-24">Kind</th>
                                            <th className="py-3 px-5 text-[12px] font-semibold text-gray-600 uppercase tracking-wide w-28 text-right">Size</th>
                                            <th className="py-3 px-5 w-20"></th>
                                        </tr>
                                    </thead>
                                    <tbody className="stagger-children">
                                        {scanResults.map((item, i) => (
                                            <tr key={i} className="group hover:bg-[#007AFF]/90 hover:text-white border-b border-black/5 last:border-0 text-[13px] transition-colors">
                                                <td className="py-3 px-5">
                                                    <div className="font-medium truncate max-w-sm">{item.path.split('/').pop()}</div>
                                                    <div className="text-[11px] text-gray-400 group-hover:text-blue-100 truncate max-w-sm">{item.path}</div>
                                                </td>
                                                <td className="py-3 px-5 text-gray-500 group-hover:text-white/80">{item.isDirectory ? 'Folder' : 'File'}</td>
                                                <td className="py-3 px-5 text-right tabular-nums font-medium">{formatBytes(item.size)}</td>
                                                <td className="py-3 px-5 text-right">
                                                    <button
                                                        onClick={(e) => { e.stopPropagation(); handlePurge(item.path); }}
                                                        className="opacity-0 group-hover:opacity-100 text-white font-medium text-[11px] bg-red-500/80 hover:bg-red-500 px-3 py-1 rounded-[var(--radius-xs)] transition-all glass-press"
                                                    >
                                                        Delete
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>

                                {/* Mobile: Card View */}
                                <div className="md:hidden divide-y divide-black/5 stagger-children">
                                    {scanResults.map((item, i) => (
                                        <div key={i} className="p-4 flex items-center gap-3 active:bg-white/40 transition-colors">
                                            <div className="flex-1 min-w-0">
                                                <div className="flex items-center gap-2 mb-1">
                                                    <span className="text-[10px] uppercase tracking-wide text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded">
                                                        {item.isDirectory ? 'Folder' : 'File'}
                                                    </span>
                                                    <span className="text-[13px] font-semibold text-gray-900 tabular-nums">{formatBytes(item.size)}</span>
                                                </div>
                                                <div className="font-medium text-[14px] text-gray-900 truncate">{item.path.split('/').pop()}</div>
                                                <div className="text-[12px] text-gray-500 truncate">{item.path}</div>
                                            </div>
                                            <button
                                                onClick={(e) => { e.stopPropagation(); handlePurge(item.path); }}
                                                className="shrink-0 p-2 text-red-500 bg-red-50 rounded-full"
                                            >
                                                <Icons.Trash />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

function LegendItem({ color, label }: { color: string, label: string }) {
    return (
        <div className="flex items-center gap-2">
            <div className={`w-3 h-3 rounded-full ${color} shadow-sm`} />
            <span className="text-[11px]">{label}</span>
        </div>
    );
}


function CategoryRow({ icon, label, size, onClick, actionIcon, highlight, description }: any) {
    return (
        <div
            onClick={onClick}
            className={`flex items-center justify-between px-3 py-2 md:px-4 md:py-2.5 border border-black/5 dark:border-white/5 rounded-[var(--radius-md)] bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10 active:bg-white/80 dark:active:bg-white/15 group transition-all duration-200 cursor-pointer shadow-sm`}
        >
            <div className="flex items-center gap-3 min-w-0 flex-1 mr-4">
                {/* Icon container - fixed size for alignment */}
                <div className="w-9 h-9 flex items-center justify-center shrink-0">
                    {icon}
                </div>
                <div className="flex flex-col justify-center min-w-0">
                    <span className="text-[13px] font-semibold text-gray-900 dark:text-gray-100 leading-tight truncate">{label}</span>
                    <span className="text-[11px] text-gray-500 dark:text-gray-400 mt-0.5 truncate pr-2" title={description}>
                        {highlight ? "Scan for large files" : description}
                    </span>
                </div>
            </div>
            <div className="flex items-center gap-2 shrink-0">
                <span className={`text-[12px] tabular-nums font-medium ${size === '—' ? 'text-gray-400 dark:text-gray-600' : 'text-gray-600 dark:text-gray-300'}`}>
                    {size === '—' ? 'Scan' : size}
                </span>
                {actionIcon && (
                    <div className="w-5 h-5 flex items-center justify-center text-gray-300 dark:text-gray-600 group-hover:text-gray-500 dark:group-hover:text-gray-400 transition-colors">
                        <Icons.Info />
                    </div>
                )}
            </div>
        </div>
    );
}

// Liquid Glass Icons - Modern macOS 26 Tahoe Style
const Icons = {
    BackArrow: () => (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="m15 18-6-6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    ),

    Apps: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="apps-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#FF6B6B" />
                    <stop offset="100%" stopColor="#FF3B30" />
                </linearGradient>
                <filter id="apps-glow" x="-20%" y="-20%" width="140%" height="140%">
                    <feGaussianBlur stdDeviation="2" result="blur" />
                    <feComposite in="SourceGraphic" in2="blur" operator="over" />
                </filter>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#apps-bg)" filter="url(#apps-glow)" />
            <g transform="translate(10, 10)">
                <rect x="2" y="2" width="8" height="8" rx="2" fill="white" fillOpacity="0.9" />
                <rect x="14" y="2" width="8" height="8" rx="2" fill="white" fillOpacity="0.7" />
                <rect x="2" y="14" width="8" height="8" rx="2" fill="white" fillOpacity="0.7" />
                <rect x="14" y="14" width="8" height="8" rx="2" fill="white" fillOpacity="0.5" />
            </g>
        </svg>
    ),

    Documents: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="docs-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#FFE066" />
                    <stop offset="100%" stopColor="#FFCC00" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#docs-bg)" />
            <g transform="translate(10, 8)">
                <path d="M4 4h14l6 6v16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" fill="white" fillOpacity="0.95" />
                <path d="M18 4v6h6" fill="white" fillOpacity="0.6" />
                <path d="M6 16h12M6 20h8" stroke="#FFCC00" strokeWidth="2" strokeLinecap="round" />
            </g>
        </svg>
    ),

    CloudDrive: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="cloud-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#6DD5FA" />
                    <stop offset="100%" stopColor="#2980B9" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#cloud-bg)" />
            <g transform="translate(8, 12)">
                <path d="M24 16H6a4 4 0 0 1 0-8 4.5 4.5 0 0 1 .3-1.5 6 6 0 0 1 11.4 0A4.5 4.5 0 0 1 22 11a4 4 0 0 1 2 5z" fill="white" fillOpacity="0.95" />
            </g>
        </svg>
    ),

    Photos: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="photos-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#FF9500" />
                    <stop offset="50%" stopColor="#FF3B30" />
                    <stop offset="100%" stopColor="#AF52DE" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#photos-bg)" />
            <g transform="translate(8, 8)">
                <circle cx="14" cy="14" r="10" fill="white" fillOpacity="0.95" />
                <circle cx="14" cy="14" r="6" fill="none" stroke="url(#photos-bg)" strokeWidth="3" />
                <circle cx="14" cy="14" r="2" fill="#FF3B30" />
            </g>
        </svg>
    ),

    Trash: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="trash-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#B0B0B0" />
                    <stop offset="100%" stopColor="#8E8E93" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#trash-bg)" />
            <g transform="translate(10, 8)">
                <path d="M3 8h18M19 8v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8" stroke="white" strokeWidth="2" strokeLinecap="round" />
                <path d="M8 8V6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" stroke="white" strokeWidth="2" strokeLinecap="round" />
                <path d="M9 12v8M12 12v8M15 12v8" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeOpacity="0.7" />
            </g>
        </svg>
    ),

    System: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="system-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#636366" />
                    <stop offset="100%" stopColor="#48484A" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#system-bg)" />
            <g transform="translate(10, 10)">
                <circle cx="12" cy="12" r="10" fill="none" stroke="white" strokeWidth="2" strokeOpacity="0.9" />
                <path d="M12 2v4M12 18v4M2 12h4M18 12h4" stroke="white" strokeWidth="2" strokeLinecap="round" strokeOpacity="0.7" />
                <circle cx="12" cy="12" r="4" fill="white" fillOpacity="0.9" />
            </g>
        </svg>
    ),

    Downloads: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="down-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#5AC8FA" />
                    <stop offset="100%" stopColor="#007AFF" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#down-bg)" />
            <g transform="translate(10, 10)">
                <circle cx="12" cy="12" r="10" fill="black" fillOpacity="0.1" />
                <path d="M12 4v10M12 14l-4-4M12 14l4-4" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M6 18h12" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeOpacity="0.6" />
            </g>
        </svg>
    ),

    Desktop: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="desk-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#AF52DE" />
                    <stop offset="100%" stopColor="#5856D6" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#desk-bg)" />
            <g transform="translate(9, 10)">
                <rect x="2" y="2" width="22" height="15" rx="2" stroke="white" strokeWidth="2" fill="white" fillOpacity="0.1" />
                <path d="M13 17v3M9 20h8" stroke="white" strokeWidth="2" strokeLinecap="round" />
            </g>
        </svg>
    ),

    Music: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="music-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#FF2D55" />
                    <stop offset="100%" stopColor="#FF375F" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#music-bg)" />
            <g transform="translate(10, 10)">
                <path d="M9 18V5l12-3v13" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <circle cx="6" cy="18" r="4" fill="white" />
                <circle cx="18" cy="16" r="4" fill="white" />
            </g>
        </svg>
    ),

    Movies: () => (
        <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
            <defs>
                <linearGradient id="movies-bg" x1="0" y1="0" x2="44" y2="44">
                    <stop offset="0%" stopColor="#5856D6" />
                    <stop offset="100%" stopColor="#3634A3" />
                </linearGradient>
            </defs>
            <rect width="44" height="44" rx="12" fill="url(#movies-bg)" />
            <g transform="translate(10, 10)">
                <rect x="2" y="2" width="20" height="20" rx="3" stroke="white" strokeWidth="2" />
                <path d="M7 2v20M17 2v20M2 7h20M2 17h20" stroke="white" strokeWidth="2" strokeOpacity="0.5" />
                <path d="M10 10h4v4h-4z" fill="white" />
            </g>
        </svg>
    ),

    Info: () => (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" strokeOpacity="0.4" />
            <path d="M12 16v-4M12 8h.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeOpacity="0.6" />
        </svg>
    ),

    Scan: () => (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <circle cx="11" cy="11" r="8" stroke="currentColor" strokeWidth="2" />
            <path d="m21 21-4.35-4.35" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </svg>
    ),

    Spinner: () => (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className="animate-spin">
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" strokeOpacity="0.25" />
            <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </svg>
    ),
};
