function Expenses() {
    const { expenses, expenseCategories, formatLKR, exportToExcel, isDateInRange } = window.MockData;
    const [localExpenses, setLocalExpenses] = React.useState(expenses);
    const [showModal, setShowModal] = React.useState(false);
    
    // Filters
    const [dateRange, setDateRange] = React.useState({ start: '', end: '' });

    // Filtered Expenses
    const filteredExpenses = localExpenses.filter(exp => isDateInRange(exp.date, dateRange.start, dateRange.end));

    const handleExport = () => {
        const data = filteredExpenses.map(exp => ({
            Date: exp.date,
            Category: exp.category,
            Description: exp.description,
            "Paid By": exp.payedBy,
            Amount: exp.amount
        }));
        exportToExcel(data, `Expenses_Report_${dateRange.start || 'All'}_to_${dateRange.end || 'All'}`);
    };
    
    // Form
    const [form, setForm] = React.useState({
        category: expenseCategories[0],
        amount: '',
        date: new Date().toISOString().split('T')[0],
        description: ''
    });

    const handleAddExpense = async (e) => {
        e.preventDefault();
        const newExpense = {
            category: form.category,
            amount: parseFloat(form.amount),
            payed_by: 'admin',
            description: form.description,
            expense_date: form.date
        };
        
        try {
            if (window.POSApiService) {
                await window.POSApiService.createExpense(newExpense);
            }
            
            // Add locally to update UI instantly without reloading
            const id = `EXP-${Date.now()}`;
            const localVersion = { ...newExpense, id, date: form.date, payedBy: 'admin' };
            const updated = [...localExpenses, localVersion];
            setLocalExpenses(updated);
            window.MockData.expenses = updated;
            
            setShowModal(false);
            setForm({ category: expenseCategories[0], amount: '', date: new Date().toISOString().split('T')[0], description: '' });
        } catch (err) {
            console.error("Failed to save expense to DB", err);
            alert("Failed to save expense exactly to DB: " + err.message);
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                    <span className="icon-receipt-text text-[var(--primary)]"></span> Expenses Tracking
                </h2>
                <button onClick={() => setShowModal(true)} className="btn btn-primary">
                    <span className="icon-plus mr-2"></span> Add Expense
                </button>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="lg:col-span-2 card">
                    <div className="flex flex-col md:flex-row justify-between md:items-center mb-6 gap-4">
                        <h3 className="font-bold text-gray-800">Recent Expenses</h3>
                        <div className="flex gap-2 items-center">
                            <input type="date" className="input-field text-xs py-1.5" value={dateRange.start} onChange={(e) => setDateRange({...dateRange, start: e.target.value})} title="Start Date"/>
                            <span className="text-gray-400">-</span>
                            <input type="date" className="input-field text-xs py-1.5" value={dateRange.end} onChange={(e) => setDateRange({...dateRange, end: e.target.value})} title="End Date"/>
                            <button onClick={handleExport} className="btn btn-secondary text-xs py-1.5 whitespace-nowrap bg-green-50 text-green-700 border-green-200 hover:bg-green-100">
                                <span className="icon-file-spreadsheet mr-1"></span> Excel
                            </button>
                        </div>
                    </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">Category</th>
                                    <th className="px-4 py-3">Description</th>
                                    <th className="px-4 py-3">Payed By</th>
                                    <th className="px-4 py-3 text-right">Amount</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {filteredExpenses.map(exp => (
                                    <tr key={exp.id} className="hover:bg-gray-50">
                                        <td className="px-4 py-3 text-gray-600">{exp.date}</td>
                                        <td className="px-4 py-3">
                                            <span className="badge bg-slate-100 text-slate-700">{exp.category}</span>
                                        </td>
                                        <td className="px-4 py-3 text-gray-800">{exp.description}</td>
                                        <td className="px-4 py-3 text-xs text-gray-500 uppercase">{exp.payedBy}</td>
                                        <td className="px-4 py-3 text-right font-bold text-gray-900">{formatLKR(exp.amount)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>

                <div className="lg:col-span-1 space-y-6">
                    <div className="card bg-slate-900 text-white border-none">
                        <h3 className="text-slate-400 text-sm font-medium mb-1">Total Expenses</h3>
                        <p className="text-3xl font-bold">{formatLKR(filteredExpenses.reduce((acc, curr) => acc + curr.amount, 0))}</p>
                    </div>

                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-4">Breakdown by Category</h3>
                        <div className="space-y-3">
                            {expenseCategories.slice(0, 5).map(cat => {
                                const total = filteredExpenses.filter(e => e.category === cat).reduce((acc, e) => acc + e.amount, 0);
                                if (total === 0) return null;
                                const grandTotal = filteredExpenses.reduce((acc, e) => acc + e.amount, 0);
                                const pct = (total / grandTotal) * 100;
                                
                                return (
                                    <div key={cat}>
                                        <div className="flex justify-between text-sm mb-1">
                                            <span className="text-gray-600">{cat}</span>
                                            <span className="font-medium">{formatLKR(total)}</span>
                                        </div>
                                        <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                            <div className="h-full bg-slate-600" style={{ width: `${pct}%` }}></div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            </div>

            {/* Add Expense Modal */}
            {showModal && (
                <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden">
                        <div className="p-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                            <h3 className="font-bold text-gray-900">Add New Expense</h3>
                            <button onClick={() => setShowModal(false)}><span className="icon-x text-gray-400"></span></button>
                        </div>
                        <form onSubmit={handleAddExpense} className="p-5 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Category</label>
                                <select required className="input-field" value={form.category} onChange={(e) => setForm({...form, category: e.target.value})}>
                                    {expenseCategories.map(c => <option key={c} value={c}>{c}</option>)}
                                </select>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Amount (LKR)</label>
                                    <input required type="number" step="0.01" className="input-field font-bold" value={form.amount} onChange={(e) => setForm({...form, amount: e.target.value})} />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
                                    <input required type="date" className="input-field" value={form.date} onChange={(e) => setForm({...form, date: e.target.value})} />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                                <textarea required className="input-field h-24 resize-none" value={form.description} onChange={(e) => setForm({...form, description: e.target.value})}></textarea>
                            </div>
                            <button type="submit" className="btn btn-primary w-full">Record Expense</button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}