function Reports() {
    const { formatLKR, exportToExcel, transactions, expenses, supplierPayments, creditNotes, products, isDateInRange, logs } = window.MockData;
    const [dateRange, setDateRange] = React.useState({
        start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0], // First day of current month
        end: new Date().toISOString().split('T')[0]
    });
    const [reportType, setReportType] = React.useState('financial'); // financial, returns, profit, audit, cashier

    // Profit Report State
    const allCategories = ['All', ...new Set(products.map(p => p.category))];
    const [selectedCategories, setSelectedCategories] = React.useState(['All']);
    const [showCategoryDropdown, setShowCategoryDropdown] = React.useState(false);

    // Charts Refs
    const paymentChartRef = React.useRef(null);
    const paymentChartInstance = React.useRef(null);
    const expenseChartRef = React.useRef(null);
    const expenseChartInstance = React.useRef(null);

    // --- Data Processing Based on Date Range ---
    const filteredTransactions = transactions.filter(t => isDateInRange(t.date, dateRange.start, dateRange.end) && t.status === 'Completed');
    const filteredExpenses = expenses.filter(e => isDateInRange(e.date, dateRange.start, dateRange.end));
    const filteredSupplierPayments = supplierPayments.filter(s => isDateInRange(s.date, dateRange.start, dateRange.end));
    // Filter returns: Look for Credit Notes created in range OR Transactions with status 'Returned'
    const filteredReturns = creditNotes.filter(cn => isDateInRange(cn.createdDate, dateRange.start, dateRange.end));

    // Stats
    const totalSales = filteredTransactions.reduce((acc, t) => acc + t.total, 0);
    const totalExpenses = filteredExpenses.reduce((acc, e) => acc + e.amount, 0);
    const totalSupplierPaid = filteredSupplierPayments.reduce((acc, s) => acc + (s.paidAmount || s.amount), 0);
    const totalSupplierDueInPeriod = filteredSupplierPayments.reduce((acc, s) => acc + (s.dueAmount || 0), 0);
    const totalReturnsValue = filteredReturns.reduce((acc, r) => acc + Math.abs(r.amount), 0);
    const netCashFlow = totalSales - totalExpenses - totalSupplierPaid;

    // --- Profit Analysis Logic ---
    const profitData = React.useMemo(() => {
        const productStats = {};

        // Iterate all completed transactions
        filteredTransactions.forEach(trx => {
            // MockData transactions don't strictly have items in the list object, 
            // but we need to simulate items based on products for the aggregation to work well 
            // if we rely solely on MockData.transactions structure which is simplified.
            // However, `getMockInvoiceDetails` generates random items. 
            // For this report to be consistent with the "Sales Profit" request, we need to iterate actual sold items.
            // Since MOCK_TRANSACTIONS in `utils/mockData.js` is simple (just totals), 
            // we will simulate the "sold items" by inferring or generating consistent mock items 
            // OR we can improve the mock data. 
            // For now, let's assume we can map transaction total to some products for demonstration,
            // OR better: let's use the `products` list to simulate "sales" based on the transaction volume,
            // to ensure the report looks populated.
            
            // *Correction*: In a real app, `trx.items` would be an array of objects. 
            // The current MockData `transactions` only has `items: count`. 
            // To make this report functional for the prototype, let's generate deterministic "sold items" 
            // for each transaction based on its ID hash to simulate consistent data.

            // Deterministic pseudo-random items generator for report
            const seed = trx.id.split('').reduce((a,b)=>a+b.charCodeAt(0),0);
            const numItems = trx.items;
            
            for(let i=0; i<numItems; i++) {
                // Pick product based on seed
                const prodIndex = (seed + i) % products.length;
                const product = products[prodIndex];
                
                if (!productStats[product.id]) {
                    productStats[product.id] = {
                        id: product.id,
                        name: product.name,
                        category: product.category,
                        qty: 0,
                        revenue: 0,
                        cost: 0
                    };
                }
                
                // Estimate price share (approximate since we only have total)
                // In real app: use item.price and item.cost
                const estimatedPrice = product.price; 
                const cost = product.cost;

                productStats[product.id].qty += 1;
                productStats[product.id].revenue += estimatedPrice;
                productStats[product.id].cost += cost;
            }
        });

        // Convert to array and calculate profit
        let report = Object.values(productStats).map(p => ({
            ...p,
            profit: p.revenue - p.cost,
            margin: p.revenue ? ((p.revenue - p.cost) / p.revenue) * 100 : 0
        }));

        // Filter by Category
        if (!selectedCategories.includes('All')) {
            report = report.filter(p => selectedCategories.includes(p.category));
        }

        return report.sort((a, b) => b.profit - a.profit);
    }, [filteredTransactions, products, selectedCategories]);

    const totalProfit = profitData.reduce((acc, p) => acc + p.profit, 0);

    // --- Charts Effects ---
    React.useEffect(() => {
        if (reportType !== 'financial') return;

        const ChartJS = window.ChartJS;

        // 1. Payment Methods Chart
        if (paymentChartRef.current) {
            if (paymentChartInstance.current) paymentChartInstance.current.destroy();
            const ctx = paymentChartRef.current.getContext('2d');
            
            const methods = {};
            filteredTransactions.forEach(t => {
                methods[t.payment] = (methods[t.payment] || 0) + t.total;
            });

            paymentChartInstance.current = new ChartJS(ctx, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(methods),
                    datasets: [{
                        data: Object.values(methods),
                        backgroundColor: ['#3b82f6', '#10b981', '#a855f7', '#f59e0b'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { position: 'bottom' } }
                }
            });
        }

        // 2. Expense Breakdown Chart
        if (expenseChartRef.current) {
            if (expenseChartInstance.current) expenseChartInstance.current.destroy();
            const ctx = expenseChartRef.current.getContext('2d');
            
            const cats = {};
            filteredExpenses.forEach(e => {
                cats[e.category] = (cats[e.category] || 0) + e.amount;
            });

            expenseChartInstance.current = new ChartJS(ctx, {
                type: 'bar',
                data: {
                    labels: Object.keys(cats),
                    datasets: [{
                        label: 'Expense Amount',
                        data: Object.values(cats),
                        backgroundColor: '#64748b',
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true } }
                }
            });
        }

        return () => {
            if (paymentChartInstance.current) paymentChartInstance.current.destroy();
            if (expenseChartInstance.current) expenseChartInstance.current.destroy();
        };
    }, [dateRange, filteredTransactions, filteredExpenses, reportType]);


    // --- Actions ---

    const handleCategoryToggle = (cat) => {
        if (cat === 'All') {
            setSelectedCategories(['All']);
        } else {
            let newCats = selectedCategories.includes('All') ? [] : [...selectedCategories];
            
            if (newCats.includes(cat)) {
                newCats = newCats.filter(c => c !== cat);
            } else {
                newCats.push(cat);
            }

            if (newCats.length === 0) newCats = ['All'];
            setSelectedCategories(newCats);
        }
    };

    const handleExportProfitReport = () => {
        const data = profitData.map(p => ({
            Category: p.category,
            Product: p.name,
            SoldQty: p.qty,
            Revenue: p.revenue,
            COGS: p.cost,
            Profit: p.profit,
            Margin: p.margin.toFixed(2) + '%'
        }));
        exportToExcel(data, `Sales_Profit_Analysis_${dateRange.start}_${dateRange.end}.csv`);
    };

    const handlePrintReturnReport = () => {
        const printArea = document.getElementById('receipt-print-area');
        const labelArea = document.getElementById('print-area');
        
        if (labelArea) labelArea.innerHTML = ''; // Clear label area
        
        const now = new Date();
        
        // Ensure receipt print class is active
        document.body.classList.remove('printing-labels');
        document.body.classList.add('printing-receipt');
        
        let rowsHtml = filteredReturns.map(r => `
            <tr>
                <td class="desc" style="padding: 5px 0; border-bottom: 1px dashed #ddd;">
                    CN: <b>${r.creditId}</b><br/>
                    <span style="font-size: 9px; color: #666;">Orig: ${r.originalInvoiceId} | ${r.reason}</span>
                </td>
                <td class="price" style="vertical-align: middle; border-bottom: 1px dashed #ddd;">
                    ${formatLKR(Math.abs(r.amount))}
                </td>
            </tr>
        `).join('');

        printArea.innerHTML = `
            <div class="receipt-container">
                <div class="receipt-header">
                    <div class="receipt-logo">RETURNS REPORT</div>
                    <div class="receipt-meta">Period: ${dateRange.start} to ${dateRange.end}</div>
                    <div class="receipt-meta">Printed: ${now.toLocaleString()}</div>
                </div>
                <table class="receipt-items" style="margin-top: 10px;">
                    <thead><tr><th class="desc">Details</th><th class="price">Value</th></tr></thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
                <div class="receipt-totals" style="margin-top: 10px;">
                    <div class="receipt-row grand-total"><span>TOTAL RETURNS</span><span>${formatLKR(totalReturnsValue)}</span></div>
                    <div class="receipt-row"><span>Count</span><span>${filteredReturns.length}</span></div>
                </div>
                <div class="receipt-footer"><p>-- END OF REPORT --</p></div>
            </div>
        `;
        if (window.setupPrintConfig) window.setupPrintConfig('receipt');
        window.print();
    };

    const handleExportReturns = () => {
        const data = filteredReturns.map(r => ({
            CreditID: r.creditId,
            OriginalInvoice: r.originalInvoiceId,
            Date: r.createdDate,
            Reason: r.reason,
            Amount: Math.abs(r.amount),
            IsRedeemed: r.isUsed ? 'Yes' : 'No'
        }));
        exportToExcel(data, `Returns_Report_${dateRange.start}_${dateRange.end}.csv`);
    };

    const handleExportFinancials = () => {
        // Prepare summary data
        const summary = [
            { Category: "Total Sales Revenue", Amount: totalSales },
            { Category: "Total Expenses", Amount: totalExpenses },
            { Category: "Supplier Paid Amount", Amount: totalSupplierPaid },
            { Category: "Supplier Due (Period)", Amount: totalSupplierDueInPeriod },
            { Category: "Total Returns Value", Amount: totalReturnsValue },
            { Category: "Net Cash Flow", Amount: netCashFlow }
        ];
        exportToExcel(summary, `Financial_Summary_${dateRange.start}_${dateRange.end}.csv`);
    };

    return (
        <div className="space-y-6 pb-10">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <h2 className="text-2xl font-bold text-gray-900">Reports & Analytics</h2>
                
                <div className="flex flex-wrap items-center gap-3 bg-white p-2 rounded-lg border border-gray-200 shadow-sm">
                    <div className="flex items-center gap-2">
                        <span className="text-xs font-bold text-gray-500 uppercase px-2">Date Range:</span>
                        <input 
                            type="date" 
                            className="input-field py-1 text-sm w-auto border-gray-200"
                            value={dateRange.start}
                            onChange={(e) => setDateRange({...dateRange, start: e.target.value})}
                        />
                        <span className="text-gray-400">-</span>
                        <input 
                            type="date" 
                            className="input-field py-1 text-sm w-auto border-gray-200"
                            value={dateRange.end}
                            onChange={(e) => setDateRange({...dateRange, end: e.target.value})}
                        />
                    </div>
                </div>
            </div>

            {/* Report Type Tabs */}
            <div className="flex gap-2 border-b border-gray-200 overflow-x-auto">
                <button 
                    onClick={() => setReportType('financial')}
                    className={`px-4 py-2 font-medium text-sm transition-colors relative top-[1px] whitespace-nowrap ${reportType === 'financial' ? 'text-[var(--primary)] border-b-2 border-[var(--primary)]' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    Financial Overview
                </button>
                <button 
                    onClick={() => setReportType('profit')}
                    className={`px-4 py-2 font-medium text-sm transition-colors relative top-[1px] whitespace-nowrap ${reportType === 'profit' ? 'text-[var(--primary)] border-b-2 border-[var(--primary)]' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    Sales Profit Analysis
                </button>
                <button 
                    onClick={() => setReportType('returns')}
                    className={`px-4 py-2 font-medium text-sm transition-colors relative top-[1px] whitespace-nowrap ${reportType === 'returns' ? 'text-[var(--primary)] border-b-2 border-[var(--primary)]' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    Returns Report
                </button>
                <button 
                    onClick={() => setReportType('audit')}
                    className={`px-4 py-2 font-medium text-sm transition-colors relative top-[1px] whitespace-nowrap ${reportType === 'audit' ? 'text-[var(--primary)] border-b-2 border-[var(--primary)]' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    System Logs (Audit)
                </button>
                <button 
                    onClick={() => setReportType('cashier')}
                    className={`px-4 py-2 font-medium text-sm transition-colors relative top-[1px] whitespace-nowrap ${reportType === 'cashier' ? 'text-[var(--primary)] border-b-2 border-[var(--primary)]' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    Cashier Reports
                </button>
            </div>

            {reportType === 'financial' && (
                <div className="space-y-6 animate-fade-in">
                    <div className="flex justify-end">
                        <button onClick={handleExportFinancials} className="btn btn-secondary text-sm">
                            <span className="icon-file-spreadsheet mr-2"></span> Export Summary
                        </button>
                    </div>

                    {/* Summary Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        <div className="card border-l-4 border-l-emerald-500">
                            <h3 className="text-gray-500 text-xs font-bold uppercase mb-1">Total Sales</h3>
                            <p className="text-2xl font-bold text-gray-900">{formatLKR(totalSales)}</p>
                        </div>
                        <div className="card border-l-4 border-l-red-500">
                            <h3 className="text-gray-500 text-xs font-bold uppercase mb-1">Op. Expenses</h3>
                            <p className="text-2xl font-bold text-gray-900">{formatLKR(totalExpenses)}</p>
                        </div>
                        <div className="card border-l-4 border-l-orange-500 relative">
                            <h3 className="text-gray-500 text-xs font-bold uppercase mb-1">Supplier Payments</h3>
                            <p className="text-2xl font-bold text-gray-900">{formatLKR(totalSupplierPaid)}</p>
                            {totalSupplierDueInPeriod > 0 && (
                                <p className="absolute bottom-2 right-2 text-xs font-bold text-red-500 bg-red-50 px-2 py-0.5 rounded-full">
                                    Due: {formatLKR(totalSupplierDueInPeriod)}
                                </p>
                            )}
                        </div>
                        <div className="card border-l-4 border-l-blue-500 bg-slate-50">
                            <h3 className="text-gray-500 text-xs font-bold uppercase mb-1">Net Cash Flow</h3>
                            <p className={`text-2xl font-bold ${netCashFlow >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                                {formatLKR(netCashFlow)}
                            </p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {/* Payment Chart */}
                        <div className="card">
                            <h3 className="font-bold text-gray-800 mb-4">Income by Payment Method</h3>
                            <div className="h-64 relative">
                                <canvas ref={paymentChartRef}></canvas>
                            </div>
                        </div>

                        {/* Expense Chart */}
                        <div className="card">
                            <h3 className="font-bold text-gray-800 mb-4">Expense Breakdown</h3>
                            <div className="h-64 relative">
                                <canvas ref={expenseChartRef}></canvas>
                            </div>
                        </div>
                    </div>

                    {/* Supplier Payments Table Preview */}
                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-4">Recent Supplier Payments in Period</h3>
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-50 text-gray-600 font-semibold border-b border-gray-200">
                                    <tr>
                                        <th className="px-4 py-2">Date</th>
                                        <th className="px-4 py-2">Reference</th>
                                        <th className="px-4 py-2 text-right">Bill</th>
                                        <th className="px-4 py-2 text-right">Paid</th>
                                        <th className="px-4 py-2 text-right">Due</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {filteredSupplierPayments.length > 0 ? filteredSupplierPayments.map(p => {
                                        const due = p.dueAmount || 0;
                                        return (
                                            <tr key={p.id}>
                                                <td className="px-4 py-2">{p.date}</td>
                                                <td className="px-4 py-2">{p.invoiceRef}</td>
                                                <td className="px-4 py-2 text-right">{formatLKR(p.totalBill || p.amount)}</td>
                                                <td className="px-4 py-2 text-right text-green-600 font-medium">{formatLKR(p.paidAmount || p.amount)}</td>
                                                <td className="px-4 py-2 text-right text-red-500 font-medium">{due > 0 ? formatLKR(due) : '-'}</td>
                                            </tr>
                                        );
                                    }) : (
                                        <tr><td colSpan="5" className="px-4 py-4 text-center text-gray-400">No records found</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            )}

            {reportType === 'profit' && (
                <div className="space-y-6 animate-fade-in">
                    {/* Controls & Toolbar */}
                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-4 rounded-xl border border-gray-200 shadow-sm">
                        <div className="relative z-10">
                            <button 
                                onClick={() => setShowCategoryDropdown(!showCategoryDropdown)}
                                className="flex items-center gap-2 px-4 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm font-medium hover:bg-gray-100"
                            >
                                <span className="icon-list-filter text-gray-500"></span>
                                Categories: {selectedCategories.includes('All') ? 'All Selected' : `${selectedCategories.length} Selected`}
                                <span className="icon-chevron-down text-gray-400 text-xs ml-1"></span>
                            </button>
                            
                            {showCategoryDropdown && (
                                <>
                                    <div className="fixed inset-0 z-0" onClick={() => setShowCategoryDropdown(false)}></div>
                                    <div className="absolute top-full left-0 mt-2 w-56 bg-white rounded-lg shadow-xl border border-gray-100 z-20 max-h-60 overflow-y-auto">
                                        <div className="p-2 space-y-1">
                                            {allCategories.map(cat => (
                                                <label key={cat} className="flex items-center gap-2 p-2 hover:bg-gray-50 rounded cursor-pointer">
                                                    <input 
                                                        type="checkbox" 
                                                        className="rounded text-[var(--primary)] focus:ring-[var(--primary)]"
                                                        checked={selectedCategories.includes(cat)}
                                                        onChange={() => handleCategoryToggle(cat)}
                                                    />
                                                    <span className="text-sm text-gray-700">{cat}</span>
                                                </label>
                                            ))}
                                        </div>
                                    </div>
                                </>
                            )}
                        </div>

                        <div className="flex items-center gap-4">
                            <div className="text-right">
                                <p className="text-xs text-gray-500 uppercase font-bold">Total Profit</p>
                                <p className="text-xl font-bold text-[var(--primary)]">{formatLKR(totalProfit)}</p>
                            </div>
                            <button onClick={handleExportProfitReport} className="btn btn-primary text-sm shadow-lg shadow-emerald-500/20">
                                <span className="icon-file-spreadsheet mr-2"></span> Export Excel
                            </button>
                        </div>
                    </div>

                    <div className="card">
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-900 text-white font-medium rounded-t-lg">
                                    <tr>
                                        <th className="px-4 py-3 rounded-tl-lg">Product</th>
                                        <th className="px-4 py-3">Category</th>
                                        <th className="px-4 py-3 text-center">Qty Sold</th>
                                        <th className="px-4 py-3 text-right">Revenue</th>
                                        <th className="px-4 py-3 text-right">Cost (COGS)</th>
                                        <th className="px-4 py-3 text-right">Profit</th>
                                        <th className="px-4 py-3 text-right rounded-tr-lg">Margin</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {profitData.length > 0 ? profitData.map(p => (
                                        <tr key={p.id} className="hover:bg-gray-50 transition-colors">
                                            <td className="px-4 py-3 font-medium text-gray-900">{p.name}</td>
                                            <td className="px-4 py-3 text-gray-500">{p.category}</td>
                                            <td className="px-4 py-3 text-center font-mono bg-gray-50">{p.qty}</td>
                                            <td className="px-4 py-3 text-right">{formatLKR(p.revenue)}</td>
                                            <td className="px-4 py-3 text-right text-gray-500">{formatLKR(p.cost)}</td>
                                            <td className="px-4 py-3 text-right font-bold text-[var(--primary)]">{formatLKR(p.profit)}</td>
                                            <td className="px-4 py-3 text-right">
                                                <span className={`text-xs font-bold px-2 py-1 rounded ${p.margin > 20 ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>
                                                    {p.margin.toFixed(1)}%
                                                </span>
                                            </td>
                                        </tr>
                                    )) : (
                                        <tr>
                                            <td colSpan="7" className="px-4 py-12 text-center text-gray-400">
                                                <div className="flex flex-col items-center">
                                                    <span className="icon-chart-bar text-4xl mb-2 opacity-30"></span>
                                                    <p>No sales data found for the selected criteria</p>
                                                </div>
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                                <tfoot className="bg-gray-50 font-bold border-t border-gray-200">
                                    <tr>
                                        <td colSpan="3" className="px-4 py-3 text-right uppercase text-xs text-gray-500">Totals</td>
                                        <td className="px-4 py-3 text-right">{formatLKR(profitData.reduce((a,b)=>a+b.revenue,0))}</td>
                                        <td className="px-4 py-3 text-right">{formatLKR(profitData.reduce((a,b)=>a+b.cost,0))}</td>
                                        <td className="px-4 py-3 text-right text-[var(--primary)]">{formatLKR(totalProfit)}</td>
                                        <td className="px-4 py-3"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            )}

            {reportType === 'returns' && (
                <div className="space-y-6 animate-fade-in">
                    <div className="flex justify-end gap-3">
                        <button onClick={handlePrintReturnReport} className="btn btn-secondary text-sm">
                            <span className="icon-printer mr-2"></span> Print Receipt Report
                        </button>
                        <button onClick={handleExportReturns} className="btn btn-primary text-sm">
                            <span className="icon-file-spreadsheet mr-2"></span> Export Excel
                        </button>
                    </div>

                    <div className="card">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="font-bold text-gray-800">Returns Log</h3>
                            <span className="badge bg-red-100 text-red-700 font-bold">Total: {formatLKR(totalReturnsValue)}</span>
                        </div>
                        
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-50 text-gray-600 font-semibold border-b border-gray-200">
                                    <tr>
                                        <th className="px-4 py-3">Date</th>
                                        <th className="px-4 py-3">Credit ID</th>
                                        <th className="px-4 py-3">Original Inv.</th>
                                        <th className="px-4 py-3">Reason</th>
                                        <th className="px-4 py-3 text-right">Value</th>
                                        <th className="px-4 py-3 text-center">Redeemed?</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {filteredReturns.length > 0 ? filteredReturns.map(r => (
                                        <tr key={r.creditId} className="hover:bg-gray-50">
                                            <td className="px-4 py-3 text-gray-600">{r.createdDate}</td>
                                            <td className="px-4 py-3 font-mono font-medium">{r.creditId}</td>
                                            <td className="px-4 py-3 text-gray-500">{r.originalInvoiceId}</td>
                                            <td className="px-4 py-3"><span className="badge bg-slate-100 text-slate-700">{r.reason}</span></td>
                                            <td className="px-4 py-3 text-right font-bold text-red-600">{formatLKR(Math.abs(r.amount))}</td>
                                            <td className="px-4 py-3 text-center">
                                                {r.isUsed ? (
                                                    <span className="icon-check text-green-500" title={`Used on ${r.usedDate}`}></span>
                                                ) : (
                                                    <span className="text-gray-300">-</span>
                                                )}
                                            </td>
                                        </tr>
                                    )) : (
                                        <tr><td colSpan="6" className="px-4 py-8 text-center text-gray-400">No return records found in selected period.</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            )}

            {reportType === 'audit' && (
                <div className="space-y-6 animate-fade-in">
                    <div className="flex justify-end gap-3">
                        <button onClick={() => {
                             if (window.setupPrintConfig) window.setupPrintConfig('a4');
                             window.print();
                        }} className="btn btn-primary text-sm shadow-lg shadow-gray-500/20">
                            <span className="icon-printer mr-2"></span> Print / Save as PDF
                        </button>
                    </div>

                    <div className="card">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="font-bold text-gray-800 flex items-center gap-2">
                                <span className="icon-shield-check text-emerald-600"></span> System Activity Log
                            </h3>
                            <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded border border-gray-200">Last {logs.length} Records</span>
                        </div>
                        
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-900 text-white font-medium border-b border-gray-200">
                                    <tr>
                                        <th className="px-4 py-3 rounded-tl-lg">Timestamp</th>
                                        <th className="px-4 py-3">User</th>
                                        <th className="px-4 py-3">Action</th>
                                        <th className="px-4 py-3 rounded-tr-lg">Details</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {logs.length > 0 ? logs.map(log => (
                                        <tr key={log.id} className="hover:bg-gray-50">
                                            <td className="px-4 py-3 text-gray-600 whitespace-nowrap font-mono text-xs">{log.timestamp}</td>
                                            <td className="px-4 py-3 font-medium text-gray-900">{log.user}</td>
                                            <td className="px-4 py-3">
                                                <span className={`badge ${
                                                    log.action.includes('Delete') || log.action.includes('Removed') ? 'bg-red-100 text-red-700' :
                                                    log.action.includes('New') || log.action.includes('Added') ? 'bg-blue-100 text-blue-700' :
                                                    log.action.includes('Update') || log.action.includes('Change') ? 'bg-yellow-100 text-yellow-800' :
                                                    'bg-gray-100 text-gray-700'
                                                }`}>
                                                    {log.action}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 text-gray-600">{log.details}</td>
                                        </tr>
                                    )) : (
                                        <tr><td colSpan="4" className="px-4 py-8 text-center text-gray-400">No logs available.</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div className="bg-yellow-50 border border-yellow-100 rounded-lg p-4 flex gap-3 text-sm text-yellow-800">
                        <span className="icon-info mt-0.5"></span>
                        <p>This log maintains the last 100 system actions for security auditing. Actions such as Price Changes, Stock Adjustments, and Approved Returns are automatically recorded here with timestamps.</p>
                    </div>
                </div>
            )}

            {reportType === 'cashier' && (
                <div className="space-y-6 animate-fade-in">
                    <div className="flex justify-end">
                        <button 
                            onClick={() => {
                                const data = [];
                                // Re-calculate for export
                                const cashierGroups = {};
                                filteredTransactions.forEach(trx => {
                                    const cid = trx.cashierId;
                                    if (!cashierGroups[cid]) {
                                        const cashierName = window.MockData.users.find(u => u.id === cid)?.name || cid || 'Unknown';
                                        cashierGroups[cid] = { name: cashierName, count: 0, total: 0 };
                                    }
                                    cashierGroups[cid].count++;
                                    cashierGroups[cid].total += trx.total;
                                });
                                Object.values(cashierGroups).forEach(c => {
                                    data.push({
                                        Cashier: c.name,
                                        TotalBills: c.count,
                                        TotalRevenue: c.total,
                                        AvgBillValue: c.count ? (c.total / c.count).toFixed(2) : 0
                                    });
                                });
                                exportToExcel(data, `Cashier_Sales_Report_${dateRange.start}_${dateRange.end}.csv`);
                            }} 
                            className="btn btn-primary text-sm shadow-lg shadow-emerald-500/20"
                        >
                            <span className="icon-file-spreadsheet mr-2"></span> Export Sales Data
                        </button>
                    </div>

                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-6 flex items-center gap-2">
                            <span className="icon-users text-[var(--primary)]"></span> Cashier Performance Summary (Includes Admin)
                        </h3>
                        
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-900 text-white font-medium">
                                    <tr>
                                        <th className="px-4 py-3 rounded-tl-lg">Cashier Name</th>
                                        <th className="px-4 py-3 text-center">Total Bills</th>
                                        <th className="px-4 py-3 text-right">Total Revenue</th>
                                        <th className="px-4 py-3 text-right rounded-tr-lg">Avg. Bill Value</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {(() => {
                                        // Group by Cashier using transactions in date range
                                        const cashierGroups = {};
                                        filteredTransactions.forEach(trx => {
                                            const cid = trx.cashierId;
                                            if (!cashierGroups[cid]) {
                                                // Find cashier name
                                                const cashierName = window.MockData.users.find(u => u.id === cid)?.name || cid || 'Unknown';
                                                cashierGroups[cid] = { name: cashierName, count: 0, total: 0 };
                                            }
                                            cashierGroups[cid].count++;
                                            cashierGroups[cid].total += trx.total;
                                        });

                                        const rows = Object.values(cashierGroups);

                                        if (rows.length === 0) {
                                            return <tr><td colSpan="4" className="px-4 py-8 text-center text-gray-400">No transactions found in selected period.</td></tr>;
                                        }

                                        return rows.map((c, idx) => (
                                            <tr key={idx} className="hover:bg-gray-50">
                                                <td className="px-4 py-3 font-bold text-gray-900">{c.name}</td>
                                                <td className="px-4 py-3 text-center">{c.count}</td>
                                                <td className="px-4 py-3 text-right font-bold text-[var(--primary)]">{formatLKR(c.total)}</td>
                                                <td className="px-4 py-3 text-right text-gray-600">{formatLKR(c.count ? c.total / c.count : 0)}</td>
                                            </tr>
                                        ));
                                    })()}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-4">Detailed Transaction Log</h3>
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-50 text-gray-600 font-semibold border-b border-gray-200">
                                    <tr>
                                        <th className="px-4 py-3">Date</th>
                                        <th className="px-4 py-3">Invoice</th>
                                        <th className="px-4 py-3">Cashier</th>
                                        <th className="px-4 py-3 text-right">Amount</th>
                                        <th className="px-4 py-3 text-center">Payment</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {filteredTransactions.map(trx => {
                                        const cashierName = window.MockData.users.find(u => u.id === trx.cashierId)?.name || trx.cashierId;
                                        return (
                                            <tr key={trx.id} className="hover:bg-gray-50">
                                                <td className="px-4 py-3 text-gray-600">{trx.date}</td>
                                                <td className="px-4 py-3 font-mono">{trx.id}</td>
                                                <td className="px-4 py-3 font-medium">{cashierName}</td>
                                                <td className="px-4 py-3 text-right font-bold text-gray-900">{formatLKR(trx.total)}</td>
                                                <td className="px-4 py-3 text-center text-xs">
                                                    <span className="px-2 py-1 bg-gray-100 rounded border border-gray-200">{trx.payment}</span>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}