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

// Firebase context (db) is provided by assets/js/firebase-config.js


// Safe Icon Component
const Icon = ({ name, className }) => {
    const formattedName = name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();

    // Use a key that changes when the icon or its style changes to force a fresh render
    const iconKey = `${formattedName}-${className}`;

    const getIconMarkup = () => {
        if (window.lucide && window.lucide.icons && window.lucide.icons[formattedName]) {
            return window.lucide.icons[formattedName].toSvg({
                class: className || 'w-5 h-5',
                'stroke-width': 2,
                stroke: 'currentColor',
                fill: 'none'
            });
        }
        // Fallback to the <i> tag which will be picked up by lucide.createIcons()
        return `<i data-lucide="${formattedName}" class="${className || 'w-5 h-5'}"></i>`;
    };

    useEffect(() => {
        if (window.lucide) {
            window.lucide.createIcons();
        }
    }, [iconKey]);

    return (
        <span
            key={iconKey}
            className="inline-flex items-center justify-center transition-all duration-300"
            dangerouslySetInnerHTML={{ __html: getIconMarkup() }}
        />
    );
};

const menuItems = [
    { name: 'Store', icon: 'ShoppingBag' },
    { name: 'Mac', icon: 'Monitor' },
    { name: 'iPad', icon: 'Tablet' },
    { name: 'iPhone', icon: 'Smartphone' },
    { name: 'Watch', icon: 'Watch' },
    { name: 'Vision', icon: 'Glasses' },
    { name: 'AirPods', icon: 'Headphones' },
    { name: 'TV & Home', icon: 'Tv' },
    { name: 'Entertainment', icon: 'Play' },
    { name: 'Accessories', icon: 'MousePointer' },
    { name: 'Support', icon: 'LifeBuoy' }
];

const dashboardTabs = [
    { name: 'Overview', icon: 'LayoutDashboard' },
    { name: 'Bug Tracker', icon: 'Bug' },
    { name: 'Test Case', icon: 'FileText' },
    { name: 'UAT Docs', icon: 'ClipboardList' },
    { name: 'Test Plan', icon: 'ScrollText' }
];

function App() {
    const [isLoading, setIsLoading] = useState(true);
    const [data, setData] = useState([]);
    const [stats, setStats] = useState({
        total: 0,
        critical: 0,
        resolutionRate: 0,
        avgResolutionTime: 0
    });
    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState('Overview');
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    const [isDarkMode, setIsDarkMode] = useState(false);
    const [selectedBug, setSelectedBug] = useState(null);
    const [bugToDelete, setBugToDelete] = useState(null);
    const [testCases, setTestCases] = useState([]);
    const [tcSearch, setTcSearch] = useState('');
    const [tcModuleFilter, setTcModuleFilter] = useState('All');
    const [tcCurrentPage, setTcCurrentPage] = useState(1);
    const [selectedTC, setSelectedTC] = useState(null);
    const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [newBug, setNewBug] = useState({
        title: '',
        priority: 'Medium',
        status: 'Open',
        assignee: '',
        description: ''
    });
    const [showAllTestCases, setShowAllTestCases] = useState(false);
    const [tcItemsPerPage, setTcItemsPerPage] = useState(10);
    const [tcStats, setTcStats] = useState({ total: 0, passed: 0, failed: 0, blocked: 0 });

    useEffect(() => {
        const criticalCount = data.filter(i => (i.priority || '').toLowerCase().includes('critical')).length;
        const resolvedCount = data.filter(i => (i.status || '').toLowerCase().match(/resolved|done|closed/)).length;

        setStats({
            total: data.length,
            critical: criticalCount,
            resolutionRate: data.length > 0 ? Math.round((resolvedCount / data.length) * 100) : 0,
            avgResolutionTime: 2.4,
            testCasesTotal: testCases.length
        });

        const passed = testCases.filter(tc => (tc.status || '').toLowerCase() === 'pass').length;
        const failed = testCases.filter(tc => (tc.status || '').toLowerCase() === 'fail').length;
        const blocked = testCases.filter(tc => (tc.status || '').toLowerCase() === 'blocked').length;

        setTcStats({
            total: testCases.length,
            passed,
            failed,
            blocked
        });
    }, [data, testCases]);

    useEffect(() => {
        setCurrentPage(1);
    }, [searchQuery]);

    useEffect(() => {
        setTcCurrentPage(1);
    }, [tcSearch, tcModuleFilter]);

    const [isScrolled, setIsScrolled] = useState(false);
    useEffect(() => {
        const handleScroll = () => setIsScrolled(window.scrollY > 10);
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    const statusChartRef = useRef(null);

    const calculateStats = (mapped) => {
        const resolvedStatuses = ['resolved', 'closed', 'done', 'assignment task done', 'completed', 'finished'];
        setStats({
            total: mapped.length,
            critical: mapped.filter(i => ['critical', 'high', 'urgent'].includes(i.priority?.toLowerCase())).length,
            resolutionRate: Math.round((mapped.filter(i => resolvedStatuses.includes(i.status?.toLowerCase())).length / mapped.length) * 100) || 0,
            avgResolutionTime: 2.3
        });
    };

    useEffect(() => {
        if (data.length > 0) {
            calculateStats(data);
            setTimeout(() => initChart(data), 100);
        }
    }, [data]);

    useEffect(() => {
        // Load Bugs from Firebase
        const bugsRef = db.ref('bugs');
        bugsRef.on('value', (snapshot) => {
            const val = snapshot.val();
            console.log("Firebase Bugs Update:", val);
            if (val && Array.isArray(val)) {
                const authorizedData = val.filter(item =>
                    item.createdBy === 'Dimas .' ||
                    item.createdBy === 'Dimas Nurindra'
                );
                setData(authorizedData);
            } else if (!val) {
                // Initialize with dummy if empty
                console.log("Initializing dummy bugs...");
                const dummyData = [
                    { id: 'BUG-247', title: 'Login API timeout on mobile network', priority: 'Critical', status: 'Open', assignee: 'Alex Chen', createdBy: 'Dimas Nurindra', created: '2h ago', description: 'User experiencing timeout during login process.' },
                    { id: 'BUG-246', title: 'Profile image upload fails > 5MB', priority: 'Medium', status: 'In Progress', assignee: 'Sarah Jenkins', createdBy: 'Sarah Jenkins', created: '5h ago', description: 'Images larger than 5MB are rejected without error message.' },
                    { id: 'BUG-245', title: 'Typo in checkout success message', priority: 'Low', status: 'Resolved', assignee: 'Mike Ross', createdBy: 'Dimas Nurindra', created: '1d ago', description: 'Success message says "Thank you for your purcase".' },
                ];
                bugsRef.set(dummyData).catch(err => console.error("Firebase Set Error (Bugs):", err));
            }
            setIsLoading(false);
        }, (error) => {
            console.error("Firebase Read Error (Bugs):", error);
            setIsLoading(false);
            alert("Firebase Error: Please check your Database Rules!");
        });

        // Load Test Cases from Firebase
        const tcRef = db.ref('testCases');
        tcRef.on('value', (snapshot) => {
            const val = snapshot.val();
            if (val && Array.isArray(val)) {
                setTestCases(val);
            } else if (!val) {
                const dummyTestCases = [
                    { id: 'TC_PMP_001', title: 'Klik icon "?" pada header', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'User berada di halaman pembayaran', steps: '1. Cari ikon "?" di header\n2. Klik ikon tersebut', expected: 'Pop up informasi bantuan muncul', actual: 'Pop up informasi bantuan muncul', testData: '-', attachment: 'https://drive.google.com/file/d/1' },
                    { id: 'TC_PMP_002', title: 'Interaksi Dropdown di pop up Informasi', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'Pop up informasi terbuka', steps: '1. Klik dropdown "Registrasi"\n2. Klik kembali untuk collapse', expected: 'Konten dropdown tampil dan sembunyi sesuai aksi', actual: 'Konten dropdown tampil dan sembunyi sesuai aksi', testData: 'Data Registrasi A, B', attachment: 'https://drive.google.com/file/d/2' },
                    { id: 'TC_PMP_003', title: 'Klik "Selengkapnya" pada Info E-Wallet', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'User memilih metode E-Wallet', steps: '1. Klik teks "Selengkapnya"', expected: 'Halaman detail E-Wallet terbuka', actual: 'Halaman detail E-Wallet terbuka', testData: '-', attachment: 'https://drive.google.com/file/d/3' },
                    { id: 'TC_PMP_004', title: 'Pilih Sumber Dana "E-Wallet"', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'Saldo E-Wallet tersedia', steps: '1. Pilih opsi E-Wallet', expected: 'Opsi E-Wallet terpilih dengan highlight', actual: 'Opsi E-Wallet terpilih dengan highlight', testData: 'Akun OVO/Dana', attachment: 'https://drive.google.com/file/d/4' },
                    { id: 'TC_PMP_005', title: 'Pilih Sumber Dana "Bank"', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'User memiliki akun bank terdaftar', steps: '1. Pilih opsi Transfer Bank', expected: 'List bank muncul', actual: 'List bank muncul', testData: 'Bank BCA, Mandiri', attachment: 'https://drive.google.com/file/d/5' },
                    { id: 'TC_PMP_006', title: 'Tombol "Lanjutkan" Aktif Jika Sumber Dana Dipilih', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: 'Today', type: 'Positif', prerequisites: 'User telah memilih salah satu sumber dana', steps: '1. Klik salah satu sumber dana\n2. Perhatikan status tombol "Lanjutkan"', expected: 'Tombol "Lanjutkan" aktif dan dapat diklik', actual: 'Tombol "Lanjutkan" aktif dan dapat diklik', testData: 'Bank', attachment: 'https://drive.google.com/file/d/6' },
                    { id: 'TC_PMP_007', title: 'Validasi nomor telepon E-Wallet', category: 'Pilih Mode Pembayaran', priority: 'P2', status: 'Pass', lastRun: '1h ago', type: 'Positif', prerequisites: 'User di halaman input nomor', steps: '1. Masukkan nomor valid', expected: 'Nomor diterima tanpa error', actual: 'Nomor diterima tanpa error', testData: '08123456789', attachment: '' },
                    { id: 'TC_PMP_008', title: 'Munculkan pesan error jika saldo tidak cukup', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Fail', lastRun: '1h ago', type: 'Negatif', prerequisites: 'Saldo akun < 10.000', steps: '1. Pilih pembayaran > 10.000', expected: 'Pesan error "Saldo tidak cukup" muncul', actual: 'Pesan error tidak muncul, sistem hang', testData: 'Item Rp 50.000', attachment: '' },
                    { id: 'TC_PMP_009', title: 'Pilih metode pembayaran kartu kredit', category: 'Pilih Mode Pembayaran', priority: 'P2', status: 'Pass', lastRun: '2h ago', type: 'Positif', prerequisites: 'Kartu kredit sudah diverifikasi', steps: '1. Klik opsi Kartu Kredit', expected: 'Form input CVV muncul', actual: 'Form input CVV muncul', testData: 'Visa/Mastercard', attachment: '' },
                    { id: 'TC_PMP_010', title: 'Cek ringkasan pembayaran sebelum checkout', category: 'Pilih Mode Pembayaran', priority: 'P1', status: 'Pass', lastRun: '3h ago', type: 'Positif', prerequisites: 'User sudah memilih item', steps: '1. Klik tombol Bayar', expected: 'Rincian biaya (Admin fee, Total) muncul', actual: 'Rincian biaya muncul', testData: 'Admin fee Rp 2.500', attachment: '' },
                    { id: 'TC_PMP_011', title: 'Gunakan promo code valid', category: 'Promo', priority: 'P2', status: 'Pass', lastRun: 'Yesterday', type: 'Positif', prerequisites: 'Promo code tersedia', steps: '1. Input kode "PROMOQA"', expected: 'Diskon diaplikasikan ke total harga', actual: 'Total harga berkurang Rp 5.000', testData: 'PROMOQA', attachment: '' },
                    { id: 'TC_PMP_012', title: 'Gunakan promo code expired', category: 'Promo', priority: 'P3', status: 'Pass', lastRun: 'Yesterday', type: 'Negatif', prerequisites: 'Masa berlaku kode sudah habis', steps: '1. Input kode "EXPIRED"', expected: 'Pesan "Kode sudah tidak berlaku" muncul', actual: 'Pesan error muncul dengan benar', testData: 'EXPIRED', attachment: '' },
                ];
                tcRef.set(dummyTestCases).catch(err => console.error("Firebase Set Error (TC):", err));
            }
        });

        setTimeout(() => {
            if (window.lucide) window.lucide.createIcons();
        }, 500);
    }, []);

    useEffect(() => {
        if (activeTab === 'Bug Tracker Dashboard') {
            const timer = setTimeout(() => initChart(data), 150);
            return () => clearTimeout(timer);
        }
    }, [data, activeTab, isDarkMode]);

    const initChart = (items = []) => {
        // FILTER: Exclude 'Product Item Done' from the chart metrics
        const filteredItems = items.filter(item => (item.status || '').toLowerCase() !== 'product item done');

        const counts = filteredItems.length > 0 ? filteredItems.reduce((acc, item) => {
            const s = item.status || 'Open';
            acc[s] = (acc[s] || 0) + 1;
            return acc;
        }, {}) : { 'Open': 45, 'In Progress': 32, 'Ready for Test': 145, 'Resolved': 25 };

        // Unique Color Mapping for each status
        const statusColors = {
            'open': '#3b82f6',              // Blue
            'new': '#60a5fa',               // Light Blue
            'to-do': '#94a3b8',             // Slate
            'ready-for-test': '#6366f1',    // Indigo
            'task-in-progress': '#06b6d4',  // Cyan
            'in-progress': '#0ea5e9',       // Sky
            'in-testing': '#f59e0b',        // Amber
            'testing': '#fbbf24',           // Yellow
            'under-review': '#8b5cf6',      // Purple
            'resolved': '#10b981',          // Emerald
            'solved': '#059669',            // Dark Emerald
            'done': '#16a34a',              // Green
            'finished': '#15803d',          // Forest Green
            'bugs': '#ef4444',              // Red
            'assignment-task-done': '#0d9488', // Teal
            'closed': '#64748b',            // Slate
            'cancelled': '#f43f5e',         // Rose
            'blocked': '#dc2626',           // Crimson
            'rejected': '#b91c1c',          // Maroon
            'product-backlog-item': '#475569' // Dark Slate
        };

        const labels = Object.keys(counts);
        const backgroundColors = labels.map(label => {
            const key = label.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-');

            if (!statusColors[key]) {
                console.warn(`Color Mapping Missing: "${label}" normalized to "${key}"`);
                if (key.includes('progress')) return statusColors['in-progress'];
                if (key.includes('test')) return statusColors['testing'];
                if (key.includes('resolved') || key.includes('done') || key.includes('finished') || key.includes('solved')) return statusColors['resolved'];
                if (key.includes('bug')) return statusColors['bugs'];
                return '#cbd5e1';
            }
            return statusColors[key];
        });

        if (statusChartRef.current) statusChartRef.current.destroy();
        const ctx = document.getElementById('statusChart')?.getContext('2d');
        if (ctx) {
            statusChartRef.current = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: Object.values(counts),
                        backgroundColor: backgroundColors,
                        borderWidth: isDarkMode ? 4 : 8,
                        borderColor: isDarkMode ? '#0f172a' : '#ffffff',
                        hoverOffset: 15
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '82%',
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            padding: 12,
                            titleFont: { size: 14, weight: 'bold' },
                            bodyFont: { size: 13 },
                            cornerRadius: 12,
                            displayColors: false
                        }
                    }
                }
            });
        }
    };

    const formatDate = (dateStr) => {
        if (!dateStr) return 'N/A';
        try {
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) return dateStr.split('T')[0]; // Fallback to raw date part
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
        } catch (e) { return dateStr; }
    };

    const cleanText = (str) => {
        if (!str || typeof str !== 'string') return str;
        return str.replace(/""/g, '"').replace(/^"|"$/g, '');
    };

    const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (file) {
            setCurrentPage(1); // Reset pagination
            Papa.parse(file, {
                header: true,
                dynamicTyping: true,
                skipEmptyLines: true,
                complete: (results) => {
                    // Helper to find key regardless of minor naming differences or spaces
                    const findKey = (obj, search) => {
                        const keys = Object.keys(obj);
                        const found = keys.find(k => k.toLowerCase().trim() === search.toLowerCase());
                        if (found) return obj[found];
                        // Try partial match for "Created By"
                        if (search === 'created by name') {
                            const partial = keys.find(k => k.toLowerCase().includes('created by') || k.toLowerCase().includes('reporter'));
                            return partial ? obj[partial] : null;
                        }
                        return null;
                    };

                    const mapped = results.data.map(item => ({
                        id: findKey(item, 'identifier') || findKey(item, 'issue key') || 'N/A',
                        title: findKey(item, 'name') || findKey(item, 'summary') || 'Untitled',
                        priority: findKey(item, 'priority') || 'Medium',
                        status: findKey(item, 'state name') || findKey(item, 'status') || 'Open',
                        assignee: parseAssignees(findKey(item, 'assignees')) || findKey(item, 'assignee') || 'Unassigned',
                        createdBy: findKey(item, 'created by name') || 'System',
                        created: formatDate(findKey(item, 'created at') || findKey(item, 'created') || findKey(item, 'created_at')),
                        description: cleanText(findKey(item, 'description') || findKey(item, 'summary') || 'No description provided.'),
                        links: findKey(item, 'links') || '[]',
                        comments: findKey(item, 'comments') || '[]'
                    }));

                    // Only save if created by Dimas . or Dimas Nurindra
                    const authorizedOnly = mapped.filter(item =>
                        item.createdBy === 'Dimas .' ||
                        item.createdBy === 'Dimas Nurindra'
                    );

                    // Append to existing data instead of overwriting
                    const existingIds = new Set(data.map(item => item.id));
                    const uniqueOldData = data.filter(item => !existingIds.has(item.id));
                    const combinedData = [...authorizedOnly, ...uniqueOldData];

                    setData(combinedData);
                    db.ref('bugs').set(combinedData);
                }
            });
        }
    };

    const handleTcFileUpload = (event) => {
        const file = event.target.files[0];
        if (!file) return;

        const processData = (rows) => {
            let currentModule = 'General';
            let headers = [];
            const mapped = [];

            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                if (!row || !Array.isArray(row) || row.length === 0) continue;

                // Extract Module Name
                if (String(row[0]).trim().toLowerCase() === 'module name :') {
                    currentModule = row[1] || 'General';
                    continue;
                }

                // Fallback for missing Module Name label but obvious category header
                if (String(row[1]).trim().toLowerCase().includes('langkah 2')) {
                    currentModule = row[1];
                    continue;
                }

                // Identify Header Row
                if (String(row[0]).trim().toLowerCase() === 'test case id' || String(row[1]).trim().toLowerCase() === 'test case') {
                    headers = row.map(h => String(h || '').toLowerCase().trim());
                    continue;
                }

                // Parse Test Case Rows
                if (headers.length > 0) {
                    const idIndex = headers.indexOf('test case id');
                    const titleIndex = headers.findIndex(h => h === 'test case' || h === 'scenario');
                    const statusIndex = headers.indexOf('status');
                    const expectedIndex = headers.indexOf('expected results');
                    const actualIndex = headers.indexOf('actual results');
                    const attachmentIndex = headers.indexOf('attachment');
                    const typeIndex = headers.indexOf('type');
                    const stepsIndex = headers.indexOf('test steps');
                    const prerequisitesIndex = headers.indexOf('pre-requisites');
                    const testDataIndex = headers.indexOf('test data');

                    const idVal = idIndex !== -1 ? row[idIndex] : null;
                    const titleVal = titleIndex !== -1 ? row[titleIndex] : null;

                    // Valid Test Case requires at least a title
                    if (titleVal && String(titleVal).trim() !== '') {
                        let status = statusIndex !== -1 ? row[statusIndex] : 'Not Run';
                        status = String(status || 'Not Run').trim();
                        if (status.toLowerCase() === 'passed' || status.toUpperCase() === 'P') status = 'Pass';
                        else if (status.toLowerCase() === 'failed' || status.toUpperCase() === 'F') status = 'Fail';
                        else status = 'Not Run';

                        mapped.push({
                            id: (idVal && String(idVal).trim() !== '') ? String(idVal).trim() : `TC-${100 + mapped.length}`,
                            title: String(titleVal).trim(),
                            category: currentModule,
                            expected: expectedIndex !== -1 && row[expectedIndex] ? String(row[expectedIndex]).trim() : '-',
                            actual: actualIndex !== -1 && row[actualIndex] ? String(row[actualIndex]).trim() : '-',
                            attachment: attachmentIndex !== -1 && row[attachmentIndex] ? String(row[attachmentIndex]).trim() : '',
                            type: typeIndex !== -1 && row[typeIndex] ? String(row[typeIndex]).trim() : '-',
                            steps: stepsIndex !== -1 && row[stepsIndex] ? String(row[stepsIndex]).trim() : '-',
                            prerequisites: prerequisitesIndex !== -1 && row[prerequisitesIndex] ? String(row[prerequisitesIndex]).trim() : '-',
                            testData: testDataIndex !== -1 && row[testDataIndex] ? String(row[testDataIndex]).trim() : '-',
                            status: status
                        });
                    } else if (mapped.length > 0) {
                        const lastTC = mapped[mapped.length - 1];
                        const appendField = (idx, field) => {
                            if (idx !== -1 && row[idx] && String(row[idx]).trim() !== '') {
                                const str = String(row[idx]).trim();
                                if (lastTC[field] === '-' || !lastTC[field]) {
                                    lastTC[field] = str;
                                } else {
                                    lastTC[field] += `\n${str}`;
                                }
                            }
                        };
                        appendField(stepsIndex, 'steps');
                        appendField(testDataIndex, 'testData');
                        appendField(prerequisitesIndex, 'prerequisites');
                        appendField(expectedIndex, 'expected');
                        appendField(actualIndex, 'actual');
                    }
                }
            }

            const existingIds = new Set(mapped.map(item => item.id));
            const uniqueOldData = testCases.filter(item => !existingIds.has(item.id));
            const combinedData = [...mapped, ...uniqueOldData];

            setTestCases(combinedData);
            db.ref('testCases').set(combinedData);
        };

        if (file.name.endsWith('.csv')) {
            Papa.parse(file, {
                header: false, // Read as array of arrays
                dynamicTyping: false,
                skipEmptyLines: true,
                complete: (results) => processData(results.data)
            });
        } else if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' }); // Read as array of arrays
                processData(jsonData);
            };
            reader.readAsArrayBuffer(file);
        }
    };

    const parseAssignees = (val) => {
        if (!val) return 'Unassigned';
        if (typeof val === 'string' && val.startsWith('[')) {
            try { return JSON.parse(val.replace(/'/g, '"'))[0]; } catch (e) { return val; }
        }
        return val;
    };

    const priorityStats = useMemo(() => {
        const counts = { Critical: 0, High: 0, Medium: 0, Low: 0 };
        data.forEach(item => {
            const p = (item.priority || '').toLowerCase().trim();
            if (p === 'critical' || p === 'urgent') counts.Critical++;
            else if (p === 'high') counts.High++;
            else if (p === 'medium') counts.Medium++;
            else if (p === 'low') counts.Low++;
            else counts.Medium++; // Default fallback
        });
        return counts;
    }, [data]);

    const filteredData = useMemo(() => {
        return data.filter(item =>
            item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
            item.id.toLowerCase().includes(searchQuery.toLowerCase())
        );
    }, [data, searchQuery]);

    const totalPages = Math.ceil(filteredData.length / itemsPerPage);
    const paginatedData = useMemo(() => {
        const startIndex = (currentPage - 1) * itemsPerPage;
        return filteredData.slice(startIndex, startIndex + itemsPerPage);
    }, [filteredData, currentPage, itemsPerPage]);

    const confirmDelete = () => {
        if (!bugToDelete) return;
        const newData = data.filter(item => item.id !== bugToDelete.id);
        setData(newData);
        db.ref('bugs').set(newData);
        setBugToDelete(null);
    };

    const deleteBug = (bug) => {
        setBugToDelete(bug);
    };

    const exportToCSV = () => {
        if (data.length === 0) return;
        const csv = Papa.unparse(data);
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = "bug_report.csv";
        link.click();
    };

    const handleAddBug = (e) => {
        e.preventDefault();
        const bugId = `BUG-${Math.floor(100 + Math.random() * 900)}`;
        const bugToAdd = {
            ...newBug,
            id: bugId,
            createdBy: 'Dimas Nurindra',
            created: 'Just now',
            comments: '[]',
            links: '[]'
        };
        const newData = [bugToAdd, ...data];
        setData(newData);
        db.ref('bugs').set(newData);
        setIsAddModalOpen(false);
        setNewBug({ title: '', priority: 'Medium', status: 'Open', assignee: '', description: '' });
    };
    useEffect(() => {
    }, [isLoading]);
    // Fallback: hide loading after 1 s if data never arrives (prevents permanent blank screen)
    useEffect(() => {
        if (isLoading) {
            const timer = setTimeout(() => setIsLoading(false), 1000);
            return () => clearTimeout(timer);
        }
    }, [isLoading]);

    return (
        <div className="min-h-screen bg-white font-sans antialiased text-[#1d1d1f]">
            {/* Premium Loading Screen */}
            {isLoading && (
                <div className="fixed inset-0 z-[2000] flex flex-col items-center justify-center bg-[#0066cc] animate-in fade-in duration-700">
                    {/* Central Icon */}
                    <div className="flex items-center justify-center w-20 h-20 bg-white rounded-full mb-8 shadow-lg">
                        <Icon name="Bug" className="w-12 h-12 text-[#0066cc]" />
                    </div>
                    {/* Loading Text */}
                    <h2 className="hero-display text-white mb-4">Document Quality Assurance</h2>
                    {/* Progress Bar */}
                    <div className="w-48 h-1 bg-white/30 rounded-full overflow-hidden mt-4">
                        <div className="h-full bg-white w-1/3 animate-[loading_2s_infinite_ease-in-out]" />
                    </div>
                </div>
            )}

            {/* Sub Nav */}
            <nav className={`sub-nav transition-all duration-300 ${isScrolled ? 'bg-white/80 border-b-[#e0e0e0] shadow-sm' : 'bg-transparent border-b-transparent'}`}>
                <div className="max-w-[1024px] mx-auto w-full flex items-center justify-between px-4 h-full">
                    <span className="text-[17px] font-bold text-[#1d1d1f]">Documents QA</span>

                    <div className="hidden md:flex items-center gap-8">
                        {dashboardTabs.map(tab => (
                            <button
                                key={tab.name}
                                onClick={() => setActiveTab(tab.name)}
                                className={`text-[12px] font-normal transition-colors ${activeTab === tab.name ? 'text-[#1d1d1f]' : 'text-[#1d1d1f]/60 hover:text-[#0066cc]'}`}
                            >
                                {tab.name}
                            </button>
                        ))}
                    </div>
                    <div className="w-[100px] hidden md:block"></div> {/* Spacer for balance */}
                </div>
            </nav>

            {/* Main Content */}
            <main className="overflow-x-hidden">
                {activeTab === 'Overview' && (
                    <div className="animate-in fade-in duration-700">
                        {/* Hero Section */}
                        <section className="product-tile product-tile-light min-h-[80vh] justify-center">
                            <span className="text-[14px] font-semibold text-[#f56300] mb-2">Presentation Preview</span>
                            <h1 className="hero-display mb-4">Enterprise QA Portal</h1>
                            <p className="lead mb-8">A masterclass in analytical product validation.</p>
                            <div className="flex gap-4 mb-12">
                                <button className="btn-primary" onClick={() => setActiveTab('Bug Tracker')}>Explore Bugs</button>
                                <button className="text-link flex items-center gap-1 group" onClick={() => setActiveTab('Test Case')}>
                                    View Test Cases <Icon name="ChevronRight" className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
                                </button>
                            </div>
                            <div className="relative mt-8">
                                <div className="bg-[#f5f5f7] rounded-[32px] p-8 md:p-12 shadow-product max-w-[900px] mx-auto">
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-12 items-center">
                                        <div className="text-left space-y-6">
                                            <h2 className="display-lg">Analytical Dashboard</h2>
                                            <p className="body">Real-time synchronization with cloud infrastructure for seamless bug tracking and quality assurance workflows.</p>
                                        </div>
                                        <div className="grid grid-cols-2 gap-4">
                                            <div className="bg-white p-8 rounded-[24px] border border-[#f0f0f0] text-center flex flex-col items-center justify-center min-h-[140px] shadow-sm">
                                                <div className={`text-4xl font-bold mb-2 ${!data.length ? 'skeleton w-20 h-10' : ''}`}>
                                                    {stats.total}
                                                </div>
                                                <div className={`text-[11px] font-black text-[#86868b] uppercase tracking-[0.1em] ${!data.length ? 'skeleton w-24 h-4 mt-2' : ''}`}>
                                                    Total Bugs
                                                </div>
                                            </div>
                                            <div className="bg-white p-8 rounded-[24px] border border-[#f0f0f0] text-center flex flex-col items-center justify-center min-h-[140px] shadow-sm">
                                                <div className={`text-4xl font-bold mb-2 text-[#0066cc] ${!data.length ? 'skeleton w-20 h-10' : ''}`}>
                                                    {stats.testCasesTotal}
                                                </div>
                                                <div className={`text-[11px] font-black text-[#86868b] uppercase tracking-[0.1em] ${!data.length ? 'skeleton w-24 h-4 mt-2' : ''}`}>
                                                    Test Cases
                                                </div>
                                            </div>
                                            <div className="bg-white p-8 rounded-[24px] border border-[#f0f0f0] text-center flex flex-col items-center justify-center min-h-[140px] col-span-2 shadow-sm">
                                                <div className={`text-4xl font-bold mb-2 text-[#34c759] ${!data.length ? 'skeleton w-20 h-10' : ''}`}>
                                                    {stats.resolutionRate}%
                                                </div>
                                                <div className={`text-[11px] font-black text-[#86868b] uppercase tracking-[0.1em] ${!data.length ? 'skeleton w-32 h-4 mt-2' : ''}`}>
                                                    Resolution Rate
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>

                        {/* Feature Tile - Dark */}
                        <section className="product-tile product-tile-dark min-h-[70vh] justify-center text-center">
                            <h2 className="display-lg mb-4">End-to-end Testing</h2>
                            <p className="lead mb-12 opacity-80">Comprehensive validation across {stats.testCasesTotal} core scenarios.</p>
                            <div className="flex justify-center gap-4">
                                <button className="btn-primary" onClick={() => setActiveTab('Test Case')}>View Suite</button>
                            </div>
                            <div className="mt-16 grid grid-cols-1 sm:grid-cols-3 gap-8 px-4 max-w-[1024px] mx-auto w-full">
                                <div className="text-center space-y-2">
                                    <Icon name="Shield" className="w-8 h-8 mx-auto mb-4 text-[#2997ff]" />
                                    <h3 className="tagline">Security First</h3>
                                    <p className="caption opacity-60">Rigorous penetration testing for enterprise data.</p>
                                </div>
                                <div className="text-center space-y-2">
                                    <Icon name="Zap" className="w-8 h-8 mx-auto mb-4 text-[#2997ff]" />
                                    <h3 className="tagline">Speed Optimized</h3>
                                    <p className="caption opacity-60">Performance benchmarks tracked across devices.</p>
                                </div>
                                <div className="text-center space-y-2">
                                    <Icon name="CheckCircle" className="w-8 h-8 mx-auto mb-4 text-[#2997ff]" />
                                    <h3 className="tagline">High Accuracy</h3>
                                    <p className="caption opacity-60">Detailed logs and reproduction steps for every bug.</p>
                                </div>
                            </div>
                        </section>

                        {/* Parchment Tile */}
                        <section className="product-tile product-tile-parchment py-32">
                            <div className="max-w-[1024px] mx-auto px-4 grid grid-cols-1 md:grid-cols-2 gap-20 items-center">
                                <div className="space-y-6 text-left">
                                    <h2 className="display-lg">Collaborative Workflow</h2>
                                    <p className="body">Team-centric resolution cycles designed for maximum efficiency and clarity in technical communication.</p>
                                    <button className="text-link flex items-center gap-1 font-semibold" onClick={() => setActiveTab('Bug Tracker')}>
                                        Learn about our process <Icon name="ChevronRight" className="w-4 h-4" />
                                    </button>
                                </div>
                                <div className="bg-white rounded-3xl p-8 border border-[#e0e0e0] shadow-sm">
                                    <div className="space-y-6">
                                        <PriorityRow label="Critical" count={priorityStats.Critical} color="bg-[#d70015]" total={Math.max(data.length, 1)} />
                                        <PriorityRow label="High" count={priorityStats.High} color="bg-[#f56300]" total={Math.max(data.length, 1)} />
                                        <PriorityRow label="Medium" count={priorityStats.Medium} color="bg-[#ff9500]" total={Math.max(data.length, 1)} />
                                        <PriorityRow label="Low" count={priorityStats.Low} color="bg-[#34c759]" total={Math.max(data.length, 1)} />
                                    </div>
                                </div>
                            </div>
                        </section>
                    </div>
                )}

                {activeTab === 'Bug Tracker' && (
                    <div className="animate-in fade-in duration-700 bg-[#f5f5f7] min-h-screen py-16">
                        <div className="max-w-[1024px] mx-auto px-4">
                            <div className="flex flex-col md:flex-row md:items-center justify-between gap-8 mb-12">
                                <div>
                                    <h1 className="display-lg">Bug Tracker</h1>
                                    <p className="body opacity-60">Manage and track system-wide issues.</p>
                                </div>
                                <div className="flex gap-4">
                                    <div className="relative">
                                        <Icon name="Search" className="absolute left-4 top-[calc(50%-1px)] -translate-y-1/2 w-4 h-4 text-[#86868b]" />
                                        <input
                                            type="text"
                                            placeholder="Search bugs"
                                            className="search-input pl-12"
                                            value={searchQuery}
                                            onChange={(e) => setSearchQuery(e.target.value)}
                                        />
                                    </div>
                                    <label className="btn-primary bg-[#f5f5f7] !text-[#1d1d1f] border border-[#d2d2d7] flex items-center gap-2 cursor-pointer hover:bg-[#e8e8ed] hover:border-[#86868b] transition-all duration-200 shadow-sm hover:shadow-md">
                                        <Icon name="Download" className="w-4 h-4" /> Import
                                        <input type="file" className="hidden" accept=".csv" onChange={handleFileUpload} />
                                    </label>
                                </div>
                            </div>

                            <div className="bg-white rounded-[18px] border border-[#e0e0e0] overflow-hidden shadow-sm">
                                <div className="overflow-x-auto">
                                    <table className="w-full text-left">
                                        <thead>
                                            <tr className="border-b border-[#f0f0f0]">
                                                <th className="px-6 py-4 caption font-semibold text-[#86868b] uppercase tracking-wider">ID</th>
                                                <th className="px-6 py-4 caption font-semibold text-[#86868b] uppercase tracking-wider">Title</th>
                                                <th className="px-6 py-4 caption font-semibold text-[#86868b] uppercase tracking-wider">Status</th>
                                                <th className="px-6 py-4 caption font-semibold text-[#86868b] uppercase tracking-wider">Priority</th>
                                                <th className="px-6 py-4 caption font-semibold text-[#86868b] uppercase tracking-wider text-right">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-[#f0f0f0]">
                                            {paginatedData.map(bug => (
                                                <tr key={bug.id} className="hover:bg-[#f5f5f7]/50 transition-colors cursor-pointer" onClick={() => setSelectedBug(bug)}>
                                                    <td className="px-6 py-5 text-[14px] font-semibold text-[#0066cc]">{bug.id}</td>
                                                    <td className="px-6 py-5 text-[15px] font-medium max-w-[300px] truncate">{bug.title}</td>
                                                    <td className="px-6 py-5">
                                                        <Badge label={bug.status} />
                                                    </td>
                                                    <td className="px-6 py-5">
                                                        <Badge label={bug.priority} />
                                                    </td>
                                                    <td className="px-6 py-5 text-right">
                                                        <button
                                                            className="text-[#0066cc] hover:text-[#0071e3] p-2"
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                deleteBug(bug);
                                                            }}
                                                        >
                                                            <Icon name="Trash2" className="w-4 h-4" />
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                <div className="px-6 py-4 bg-[#fafafc] border-t border-[#f0f0f0] flex justify-between items-center">
                                    <span className="caption text-[#86868b]">Showing {paginatedData.length} of {filteredData.length}</span>
                                    <div className="flex gap-2">
                                        <button
                                            disabled={currentPage === 1}
                                            onClick={() => setCurrentPage(p => p - 1)}
                                            className="p-2 disabled:opacity-30"
                                        >
                                            <Icon name="ChevronLeft" className="w-5 h-5" />
                                        </button>
                                        <button
                                            disabled={currentPage === totalPages}
                                            onClick={() => setCurrentPage(p => p + 1)}
                                            className="p-2 disabled:opacity-30"
                                        >
                                            <Icon name="ChevronRight" className="w-5 h-5" />
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {activeTab === 'Test Case' && (
                    <div className="animate-in fade-in duration-700 bg-white min-h-screen py-16">
                        <div className="max-w-[1024px] mx-auto px-4">
                            <div className="flex flex-col md:flex-row md:items-center justify-between gap-8 mb-12">
                                <div>
                                    <h1 className="display-lg">Test Case</h1>
                                    <p className="body opacity-60">Requirements coverage and execution logs.</p>
                                    <div className="flex gap-6 mt-6">
                                        <div className="flex flex-col">
                                            <span className="text-[10px] font-bold text-[#86868b] uppercase tracking-wider mb-1">Total Cases</span>
                                            <span className="text-xl font-bold">{tcStats.total}</span>
                                        </div>
                                        <div className="w-[1px] h-8 bg-[#f0f0f0] self-end"></div>
                                        <div className="flex flex-col">
                                            <span className="text-[10px] font-bold text-[#34c759] uppercase tracking-wider mb-1">Passed</span>
                                            <span className="text-xl font-bold text-[#34c759]">{tcStats.passed}</span>
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="text-[10px] font-bold text-[#d70015] uppercase tracking-wider mb-1">Failed</span>
                                            <span className="text-xl font-bold text-[#d70015]">{tcStats.failed}</span>
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="text-[10px] font-bold text-[#ff9500] uppercase tracking-wider mb-1">Blocked</span>
                                            <span className="text-xl font-bold text-[#ff9500]">{tcStats.blocked}</span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex gap-4">
                                    <div className="relative">
                                        <Icon name="Search" className="absolute left-4 top-[calc(50%-1px)] -translate-y-1/2 w-4 h-4 text-[#86868b]" />
                                        <input
                                            type="text"
                                            placeholder="Search scenarios"
                                            className="search-input pl-12"
                                            value={tcSearch}
                                            onChange={(e) => setTcSearch(e.target.value)}
                                        />
                                    </div>
                                    <label className="btn-primary bg-[#f5f5f7] !text-[#1d1d1f] border border-[#e0e0e0] flex items-center gap-2 cursor-pointer hover:bg-[#e8e8ed] hover:border-[#86868b] transition-all duration-200 shadow-sm hover:shadow-md">
                                        <Icon name="Download" className="w-4 h-4" /> Import
                                        <input type="file" className="hidden" accept=".csv,.xlsx,.xls" onChange={handleTcFileUpload} />
                                    </label>
                                </div>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-12">
                                {testCases
                                    .filter(tc =>
                                        tc.title.toLowerCase().includes(tcSearch.toLowerCase()) ||
                                        tc.id.toLowerCase().includes(tcSearch.toLowerCase())
                                    )
                                    .slice((tcCurrentPage - 1) * 12, tcCurrentPage * 12)
                                    .map(tc => (
                                        <div key={tc.id} className="store-utility-card group hover:shadow-lg transition-shadow cursor-pointer" onClick={() => setSelectedTC(tc)}>
                                            <div className="flex justify-between items-start mb-4">
                                                <span className="caption font-bold text-[#0066cc]">{tc.id}</span>
                                                <Badge label={tc.status} />
                                            </div>
                                            <h3 className="body-strong line-clamp-2 mb-2">{tc.title}</h3>
                                            <p className="caption text-[#86868b] mb-4">{tc.category}</p>
                                            <button className="text-link caption font-semibold flex items-center gap-1">
                                                View Details <Icon name="ChevronRight" className="w-3 h-3" />
                                            </button>
                                        </div>
                                    ))}
                            </div>

                            {/* Pagination for Test Cases */}
                            <div className="flex justify-between items-center py-8 border-t border-[#f0f0f0]">
                                <span className="caption text-[#86868b]">
                                    Showing {Math.min(12, testCases.length - (tcCurrentPage - 1) * 12)} of {testCases.length} scenarios
                                </span>
                                <div className="flex gap-4">
                                    <button
                                        disabled={tcCurrentPage === 1}
                                        onClick={() => setTcCurrentPage(p => p - 1)}
                                        className="w-10 h-10 rounded-full bg-[#f5f5f7] flex items-center justify-center hover:bg-[#e8e8ed] disabled:opacity-30 transition-colors"
                                    >
                                        <Icon name="ChevronLeft" className="w-5 h-5" />
                                    </button>
                                    <button
                                        disabled={tcCurrentPage >= Math.ceil(testCases.length / 12)}
                                        onClick={() => setTcCurrentPage(p => p + 1)}
                                        className="w-10 h-10 rounded-full bg-[#f5f5f7] flex items-center justify-center hover:bg-[#e8e8ed] disabled:opacity-30 transition-colors"
                                    >
                                        <Icon name="ChevronRight" className="w-5 h-5" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {['UAT Docs', 'Test Plan'].includes(activeTab) && (
                    <div className="product-tile product-tile-parchment min-h-screen justify-center">
                        <div className="w-24 h-24 bg-white rounded-[24px] border border-[#e0e0e0] flex items-center justify-center mb-8 shadow-sm">
                            <Icon name={dashboardTabs.find(m => m.name === activeTab)?.icon} className="w-10 h-10 text-[#0066cc]" />
                        </div>
                        <h1 className="display-lg mb-4">{activeTab}</h1>
                        <p className="lead mb-12 opacity-60">This section is currently under development.</p>
                        <button className="btn-primary" onClick={() => setActiveTab('Overview')}>Return to Overview</button>
                    </div>
                )}
            </main>



            {/* Modals */}
            {selectedBug && (
                <BugDetailModal
                    bug={selectedBug}
                    onClose={() => setSelectedBug(null)}
                />
            )}
            <TestCaseDetailModal tc={selectedTC} onClose={() => setSelectedTC(null)} />

            {/* Log Bug Modal */}
            {isAddModalOpen && (
                <div className="fixed inset-0 z-[2000] flex items-center justify-center p-6 bg-white/80 backdrop-blur-xl animate-in fade-in duration-300">
                    <div className="w-full max-w-[600px] bg-white rounded-[32px] border border-[#e0e0e0] shadow-2xl overflow-hidden">
                        <div className="p-8 border-b border-[#f0f0f0] flex justify-between items-center">
                            <h3 className="tagline">Log New Issue</h3>
                            <button onClick={() => setIsAddModalOpen(false)} className="text-[#86868b] hover:text-[#d70015]">
                                <Icon name="X" className="w-6 h-6" />
                            </button>
                        </div>
                        <form onSubmit={handleAddBug} className="p-8 space-y-6">
                            <div className="space-y-2">
                                <label className="caption font-semibold text-[#86868b]">Title</label>
                                <input
                                    required
                                    className="search-input w-full"
                                    value={newBug.title}
                                    onChange={(e) => setNewBug({ ...newBug, title: e.target.value })}
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <label className="caption font-semibold text-[#86868b]">Priority</label>
                                    <select className="search-input w-full" value={newBug.priority} onChange={e => setNewBug({ ...newBug, priority: e.target.value })}>
                                        <option>Critical</option><option>High</option><option>Medium</option><option>Low</option>
                                    </select>
                                </div>
                                <div className="space-y-2">
                                    <label className="caption font-semibold text-[#86868b]">Status</label>
                                    <select className="search-input w-full" value={newBug.status} onChange={e => setNewBug({ ...newBug, status: e.target.value })}>
                                        <option>Open</option><option>In Progress</option><option>Ready for Test</option><option>Resolved</option>
                                    </select>
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="caption font-semibold text-[#86868b]">Assignee</label>
                                <input className="search-input w-full" value={newBug.assignee} onChange={e => setNewBug({ ...newBug, assignee: e.target.value })} />
                            </div>
                            <div className="space-y-2">
                                <label className="caption font-semibold text-[#86868b]">Description</label>
                                <textarea className="search-input w-full min-h-[120px] py-4" value={newBug.description} onChange={e => setNewBug({ ...newBug, description: e.target.value })} />
                            </div>
                            <div className="flex gap-4 pt-4">
                                <button type="button" onClick={() => setIsAddModalOpen(false)} className="flex-1 py-3 rounded-full bg-[#f5f5f7] font-medium">Cancel</button>
                                <button type="submit" className="flex-1 py-3 rounded-full bg-[#0066cc] text-white font-medium">Submit Report</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Delete Confirmation */}
            {bugToDelete && (
                <div className="fixed inset-0 z-[2000] flex items-center justify-center p-6 bg-white/60 backdrop-blur-md">
                    <div className="w-full max-w-[400px] bg-white rounded-[24px] border border-[#e0e0e0] p-8 text-center shadow-2xl">
                        <Icon name="AlertTriangle" className="w-12 h-12 text-[#d70015] mx-auto mb-6" />
                        <h3 className="tagline mb-2">Delete Bug?</h3>
                        <p className="body text-[#86868b] mb-8">This action cannot be undone. You are deleting <span className="font-semibold text-[#1d1d1f]">{bugToDelete.id}</span>.</p>
                        <div className="flex gap-4">
                            <button onClick={() => setBugToDelete(null)} className="flex-1 py-3 rounded-full bg-[#f5f5f7] font-medium">Cancel</button>
                            <button onClick={confirmDelete} className="flex-1 py-3 rounded-full bg-[#d70015] text-white font-medium">Delete</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

function TestCaseDetailModal({ tc, onClose }) {
    if (!tc) return null;

    const formatListText = (txt) => {
        if (!txt || txt === '-') return '-';
        return String(txt).replace(/ - /g, '\n- ').split('\n').map((line, idx) => (
            <span key={idx} className="block mt-1">{line}</span>
        ));
    };

    const formatNumberedList = (txt) => {
        if (!txt || txt === '-') return '-';
        const lines = String(txt).split('\n').map(l => l.trim().replace(/^[-•]\s*/, '')).filter(l => l !== '');
        return lines.map((line, idx) => (
            <div key={idx} className="flex gap-2 mt-2">
                <span className="text-[#0066cc] font-semibold min-w-[24px]">{idx + 1}.</span>
                <span className="block leading-relaxed flex-1">{line}</span>
            </div>
        ));
    };

    return (
        <div className="fixed inset-0 z-[2000] flex items-center justify-center p-4 md:p-6 bg-white/80 backdrop-blur-xl animate-in fade-in duration-300">
            <div className="w-full md:max-w-4xl max-h-[90vh] bg-white rounded-[32px] border border-[#e0e0e0] flex flex-col overflow-hidden shadow-2xl">
                {/* Header */}
                <div className="p-8 border-b border-[#f0f0f0] flex justify-between items-start shrink-0">
                    <div className="space-y-1">
                        <div className="flex items-center gap-3 mb-1">
                            <span className="caption font-bold text-[#0066cc] uppercase tracking-wider">{tc.id}</span>
                            {tc.type && tc.type !== '-' && (
                                <span className="px-3 py-0.5 rounded-full text-[10px] font-bold bg-[#e3fcf1] text-[#00b06b] uppercase tracking-wider">
                                    {tc.type}
                                </span>
                            )}
                        </div>
                        <h2 className="tagline !text-3xl !font-bold text-[#1d1d1f]">{tc.category}</h2>
                    </div>
                    <button
                        onClick={onClose}
                        className="w-10 h-10 rounded-full bg-[#f5f5f7] flex items-center justify-center hover:bg-[#e8e8ed] transition-colors"
                    >
                        <Icon name="X" className="w-5 h-5 text-[#86868b]" />
                    </button>
                </div>

                {/* Content */}
                <div className="p-8 overflow-y-auto custom-scrollbar flex-1 space-y-10">
                    {/* Status & Attachment */}
                    <div className="flex flex-wrap gap-12">
                        <div>
                            <h4 className="caption font-bold text-[#86868b] uppercase tracking-wider mb-3">Status</h4>
                            <Badge label={tc.status} />
                        </div>
                        <div className="flex-1 min-w-[200px]">
                            <h4 className="caption font-bold text-[#86868b] uppercase tracking-wider mb-3">Attachment</h4>
                            <a href={tc.attachment} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 p-3 bg-white border border-[#e0e0e0] rounded-xl hover:bg-[#f5f5f7] transition-colors group">
                                <Icon name="Link" className="w-4 h-4 text-[#86868b]" />
                                <span className="text-[13px] text-[#1d1d1f] font-medium truncate">{tc.attachment || 'No attachment'}</span>
                            </a>
                        </div>
                    </div>

                    {/* Pre-requisites */}
                    <div className="space-y-4">
                        <div className="flex items-center gap-2 text-[#86868b]">
                            <Icon name="Info" className="w-4 h-4" />
                            <h4 className="caption font-bold uppercase tracking-wider">Pre-requisites</h4>
                        </div>
                        <div className="bg-[#f5f5f7]/50 p-8 rounded-[24px] border border-[#f0f0f0]">
                            <p className="body text-[16px] text-[#1d1d1f]">{tc.prerequisites || '-'}</p>
                        </div>
                    </div>

                    {/* Scenario */}
                    <div className="space-y-4">
                        <div className="flex items-center gap-2 text-[#86868b]">
                            <h4 className="caption font-bold uppercase tracking-wider">Scenario</h4>
                        </div>
                        <div className="bg-[#f5f5f7]/50 p-8 rounded-[24px] border border-[#f0f0f0]">
                            <p className="body text-[16px] font-medium text-[#1d1d1f]">{tc.title}</p>
                        </div>
                    </div>

                    {/* Test Steps */}
                    <div className="space-y-4">
                        <div className="flex items-center gap-2 text-[#86868b]">
                            <Icon name="List" className="w-4 h-4" />
                            <h4 className="caption font-bold uppercase tracking-wider">Test Steps</h4>
                        </div>
                        <div className="bg-[#f5f5f7]/50 p-8 rounded-[24px] border border-[#f0f0f0]">
                            <div className="body text-[15px]">{formatNumberedList(tc.steps)}</div>
                        </div>
                    </div>

                    {/* Test Data */}
                    {tc.testData && tc.testData !== '-' && (
                        <div className="space-y-4">
                            <div className="flex items-center gap-2 text-[#86868b]">
                                <Icon name="Database" className="w-4 h-4" />
                                <h4 className="caption font-bold uppercase tracking-wider">Test Data</h4>
                            </div>
                            <div className="bg-[#f5f5f7]/50 p-8 rounded-[24px] border border-[#f0f0f0]">
                                <p className="body text-[15px]">{tc.testData}</p>
                            </div>
                        </div>
                    )}

                    {/* Results */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                        <div className="space-y-4">
                            <div className="flex items-center gap-2 text-[#00b06b]">
                                <Icon name="CheckCircle" className="w-4 h-4" />
                                <h4 className="text-[12px] font-bold uppercase tracking-wider">Expected Results</h4>
                            </div>
                            <div className="bg-[#f0fff4] p-8 rounded-[24px] border border-[#00b06b]/10">
                                <div className="body text-[15px] text-[#1d1d1f]">{formatListText(tc.expected)}</div>
                            </div>
                        </div>
                        <div className="space-y-4">
                            <div className="flex items-center gap-2 text-[#0066cc]">
                                <Icon name="PlayCircle" className="w-4 h-4" />
                                <h4 className="text-[12px] font-bold uppercase tracking-wider">Actual Results</h4>
                            </div>
                            <div className="bg-[#f0f7ff] p-8 rounded-[24px] border border-[#0066cc]/10">
                                <div className="body text-[15px] text-[#1d1d1f]">{formatListText(tc.actual)}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

function BugDetailModal({ bug, onClose }) {
    if (!bug) return null;

    const parseJSON = (str) => {
        try { return JSON.parse(str.replace(/'/g, '"')); } catch (e) { return []; }
    };

    const formatDescription = (text) => {
        if (!text) return null;

        // Define section markers
        const sections = [
            { key: 'ENVIRONMENT', labels: ['environment', 'env'] },
            { key: 'STEPS TO REPRODUCE', labels: ['steps to reproduce', 'steps'] },
            { key: 'EXPECTED RESULT', labels: ['expected result', 'expected'] },
            { key: 'ACTUAL RESULT', labels: ['actual result', 'actual'] },
            { key: 'ATTACHMENT', labels: ['attachment', 'attachments'] }
        ];

        let currentSection = 'DETAILED DESCRIPTION';
        const parsed = { 'DETAILED DESCRIPTION': [] };

        // Split by lines and parse
        text.split('\n').forEach(line => {
            const trimmed = line.trim();
            if (!trimmed) return;

            // Check if line is a header
            const foundSection = sections.find(s =>
                s.labels.some(label => trimmed.toLowerCase().startsWith(label.toLowerCase()))
            );

            if (foundSection) {
                currentSection = foundSection.key;
                parsed[currentSection] = [];
            } else {
                parsed[currentSection].push(trimmed);
            }
        });

        return (
            <div className="space-y-10">
                {Object.entries(parsed).map(([title, lines], idx) => {
                    if (lines.length === 0) return null;
                    return (
                        <div key={idx} className="space-y-4">
                            <h4 className="text-[12px] font-black text-[#86868b] uppercase tracking-widest">{title}</h4>
                            <div className="space-y-2">
                                {lines.map((line, lIdx) => {
                                    // Detect list items (starts with number or bullet)
                                    const isListItem = /^\d+\.|\*|-/.test(line);
                                    if (isListItem) {
                                        const cleanLine = line.replace(/^\d+\.|\*|-/, '').trim();
                                        return (
                                            <div key={lIdx} className="flex gap-4 items-start pl-2">
                                                <span className="text-[#0066cc] font-bold text-sm min-w-[20px]">{lIdx + 1}.</span>
                                                <p className="body text-[16px] text-[#1d1d1f] leading-relaxed">{cleanLine}</p>
                                            </div>
                                        );
                                    }
                                    return <p key={lIdx} className="body text-[16px] text-[#424245] leading-relaxed">{line}</p>;
                                })}
                            </div>
                            {idx < Object.entries(parsed).length - 1 && <div className="border-b border-[#f0f0f0] pt-4"></div>}
                        </div>
                    );
                })}
            </div>
        );
    };

    const links = typeof bug.links === 'string' ? parseJSON(bug.links) : bug.links;

    return (
        <div className="fixed inset-0 z-[2000] flex items-center justify-center p-6 bg-white/80 backdrop-blur-xl animate-in fade-in duration-300">
            <div className="w-full max-w-4xl max-h-[90vh] bg-white rounded-[32px] border border-[#e0e0e0] flex flex-col overflow-hidden shadow-2xl">
                <div className="p-10 border-b border-[#f0f0f0] flex justify-between items-start shrink-0">
                    <div className="space-y-2">
                        <div className="flex items-center gap-4 mb-1">
                            <span className="caption font-bold text-[#0066cc] uppercase tracking-wider">{bug.id}</span>
                            <Badge label={bug.priority} />
                        </div>
                        <h2 className="tagline !text-3xl">{bug.title}</h2>
                    </div>
                    <button
                        onClick={onClose}
                        className="w-12 h-12 rounded-full bg-[#f5f5f7] flex items-center justify-center hover:bg-[#e8e8ed] transition-colors"
                    >
                        <Icon name="X" className="w-6 h-6 text-[#86868b]" />
                    </button>
                </div>

                <div className="p-10 overflow-y-auto custom-scrollbar flex-1 space-y-12">
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
                        <div>
                            <h4 className="caption-strong uppercase">Status</h4>
                            <Badge label={bug.status} />
                        </div>
                        <div>
                            <h4 className="caption-strong uppercase">Assignee</h4>
                            <div className="body font-semibold">{bug.assignee}</div>
                        </div>
                        <div>
                            <h4 className="caption-strong uppercase">Reporter</h4>
                            <div className="body font-semibold">{bug.createdBy || 'System'}</div>
                        </div>
                        <div>
                            <h4 className="caption-strong uppercase">Date</h4>
                            <div className="body text-[#86868b]">{bug.created}</div>
                        </div>
                    </div>

                    <div className="bg-white rounded-3xl">
                        {formatDescription(bug.description)}
                    </div>

                    {links && links.length > 0 && (
                        <div>
                            <h4 className="caption-strong uppercase mb-4">Related Resources</h4>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {links.map((link, i) => (
                                    <a key={i} href={link.url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-3 p-4 bg-[#f5f5f7] rounded-xl hover:bg-[#e8e8ed] transition-colors group">
                                        <Icon name="link" className="w-4 h-4 text-[#0066cc]" />
                                        <span className="body font-medium truncate">{link.title || 'View Link'}</span>
                                    </a>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                <div className="p-8 bg-[#fafafc] border-t border-[#f0f0f0] flex justify-end">
                    <button onClick={onClose} className="btn-primary px-10">Done</button>
                </div>
            </div>
        </div>
    );
}

function MetricCard({ title, value, change, subtitle, icon, color, isDarkMode }) {
    const colors = {
        rose: 'text-rose-500 bg-rose-50',
        amber: 'text-amber-500 bg-amber-50',
        emerald: 'text-emerald-500 bg-emerald-50',
        blue: 'text-blue-500 bg-blue-50'
    };
    const darkColors = {
        rose: 'text-rose-400 bg-rose-500/10',
        amber: 'text-amber-400 bg-amber-500/10',
        emerald: 'text-emerald-400 bg-emerald-500/10',
        blue: 'text-blue-400 bg-blue-500/10'
    };

    return (
        <div className={`${isDarkMode ? 'bg-slate-900 border-slate-800' : 'bg-white border-slate-100'} p-10 rounded-[40px] border shadow-sm transition-all hover:shadow-md`}>
            <div className="flex justify-between items-start mb-6">
                <div className={`w-14 h-14 rounded-2xl flex items-center justify-center ${isDarkMode ? darkColors[color] : colors[color]} transition-colors`}>
                    <Icon name={icon} className="w-7 h-7" />
                </div>
                {change && <div className={`text-xs font-black ${change.startsWith('+') ? 'text-emerald-500' : 'text-rose-500'} ${isDarkMode ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-50'} px-3 py-1 rounded-full shadow-sm border`}>{change}</div>}
            </div>
            <div>
                <div className={`text-4xl font-[900] ${isDarkMode ? 'text-white' : 'text-slate-900'} tracking-tight mb-2 transition-colors`}>{value}</div>
                <div className="text-[11px] font-bold text-slate-400 uppercase tracking-widest">{title}</div>
                {subtitle && <div className="text-[10px] font-bold text-slate-400 mt-2 italic">{subtitle}</div>}
            </div>
        </div>
    );
}

function PriorityRow({ label, count, color, total }) {
    const percentage = Math.round((count / total) * 100);
    return (
        <div className="space-y-2">
            <div className="flex justify-between items-center">
                <span className="body-strong text-sm">{label}</span>
                <span className="caption font-semibold opacity-60">{count} issues</span>
            </div>
            <div className="h-1.5 w-full bg-[#e8e8ed] rounded-full overflow-hidden">
                <div
                    className={`h-full ${color} rounded-full transition-all duration-1000`}
                    style={{ width: `${percentage}%` }}
                ></div>
            </div>
        </div>
    );
}

function Badge({ label }) {
    if (!label) return null;

    const colors = {
        // Priorities
        critical: "text-[#d70015] border-[#d70015]/20",
        urgent: "text-[#d70015] border-[#d70015]/20",
        high: "text-[#f56300] border-[#f56300]/20",
        medium: "text-[#ff9500] border-[#ff9500]/20",
        low: "text-[#34c759] border-[#34c759]/20",

        // Statuses
        open: "text-[#0066cc] border-[#0066cc]/20",
        new: "text-[#0066cc] border-[#0066cc]/20",
        'to-do': "text-[#86868b] border-[#86868b]/20",
        'ready-for-test': "text-[#5856d6] border-[#5856d6]/20",
        'in-progress': "text-[#0071e3] border-[#0071e3]/20",
        'task-in-progress': "text-[#0071e3] border-[#0071e3]/20",
        'testing': "text-[#ff9500] border-[#ff9500]/20",
        'under-review': "text-[#af52de] border-[#af52de]/20",
        resolved: "text-[#34c759] border-[#34c759]/20",
        solved: "text-[#34c759] border-[#34c759]/20",
        done: "text-[#34c759] border-[#34c759]/20",
        finished: "text-[#34c759] border-[#34c759]/20",
        closed: "text-[#86868b] border-[#86868b]/20",
        cancelled: "text-[#d70015] border-[#d70015]/20",
        blocked: "text-[#d70015] border-[#d70015]/20",
        bugs: "text-[#d70015] border-[#d70015]/20",

        // Test Case Statuses
        'pass': "text-[#34c759] border-[#34c759]/20",
        'fail': "text-[#d70015] border-[#d70015]/20",
        'not run': "text-[#86868b] border-[#86868b]/20",
        'not-run': "text-[#86868b] border-[#86868b]/20",
    };

    const key = label.toLowerCase().trim().replace(/\s+/g, '-');

    return (
        <span className={`px-3 py-1 rounded-full text-[11px] font-semibold tracking-tight inline-block text-center border transition-all duration-300 ${colors[key] || 'text-[#86868b] border-[#f0f0f0]'}`}>
            {label}
        </span>
    );
}

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