function Customers({ notify }) {
    const { customers, formatLKR, getUpcomingBirthdays, transactions } = window.MockData;
    const [localCustomers, setLocalCustomers] = React.useState(customers);
    const [searchTerm, setSearchTerm] = React.useState('');
    
    // UI State
    const [showAddModal, setShowAddModal] = React.useState(false);
    const [showHistoryModal, setShowHistoryModal] = React.useState(false);
    const [selectedHistory, setSelectedHistory] = React.useState(null);
    const [contactModal, setContactModal] = React.useState(null);
    const [customerForm, setCustomerForm] = React.useState({
        name: '', email: '', phone: '', birthday: ''
    });

    const upcomingBirthdays = getUpcomingBirthdays(localCustomers);

    const filteredCustomers = localCustomers.filter(c => 
        c.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
        c.phone.includes(searchTerm) || 
        c.email.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const handleAddCustomer = async (e) => {
        e.preventDefault();
        
        const customerData = {
            name: customerForm.name,
            email: customerForm.email,
            phone: customerForm.phone,
            birthday: customerForm.birthday,
            address: '', 
            city: '', 
            postal_code: ''
        };

        if (window.POSApiService) {
            try {
                const res = await window.POSApiService.createCustomer(customerData);
                if (!res.success) throw new Error(res.error || 'Failed to create customer');
                
                const newCustomer = {
                    id: res.id,
                    ...customerData,
                    points: 0,
                    totalSpent: 0,
                    lastVisit: 'N/A'
                };
                
                const updated = [...localCustomers, newCustomer];
                setLocalCustomers(updated);
                window.MockData.customers = updated;
                
                setShowAddModal(false);
                setCustomerForm({ name: '', email: '', phone: '', birthday: '' });
                notify('Success', 'Customer profile created successfully', 'success');
            } catch (err) {
                console.error(err);
                if (window.AppDialog) {
                    window.AppDialog.alert('Error', err.message || 'Failed to create customer profile', 'error');
                } else {
                    notify('Error', err.message || 'Failed to create customer profile', 'error');
                }
            }
        } else {
            notify('Error', 'Backend service not available', 'error');
        }
    };

    const handleViewHistory = (customer) => {
        const history = transactions.filter(t => t.customerId === customer.id);
        setSelectedHistory({ customer, transactions: history });
        setShowHistoryModal(true);
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-2xl font-bold text-gray-900">Customer Database</h2>
                <button onClick={() => setShowAddModal(true)} className="btn btn-primary">
                    <span className="icon-user-plus mr-2"></span> Add Customer
                </button>
            </div>

            {/* Upcoming Birthdays Widget */}
            {upcomingBirthdays.length > 0 && (
                <div className="bg-gradient-to-r from-pink-500 to-rose-500 rounded-xl p-4 text-white shadow-lg flex items-center gap-4 animate-fade-in">
                    <div className="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center text-2xl backdrop-blur-sm">
                        <span className="icon-cake"></span>
                    </div>
                    <div className="flex-1">
                        <h3 className="font-bold text-lg">Upcoming Birthdays (Next 3 Days)</h3>
                        <div className="flex flex-wrap gap-2 mt-2">
                            {upcomingBirthdays.map(c => {
                                const bday = new Date(c.birthday);
                                const today = new Date();
                                const isToday = bday.getDate() === today.getDate() && bday.getMonth() === today.getMonth();
                                return (
                                    <div key={c.id} className="bg-white/20 px-3 py-1 rounded-full text-xs font-medium flex items-center gap-2 backdrop-blur-sm">
                                        <span>{c.name}</span>
                                        <span className="opacity-75">({bday.getDate()}/{bday.getMonth() + 1})</span>
                                        {isToday && <span className="bg-yellow-400 text-pink-700 text-[10px] px-1.5 rounded font-bold uppercase">Today!</span>}
                                        <button className="hover:text-yellow-200" title="View Contact" onClick={() => setContactModal(c)}>
                                            <span className="icon-eye w-3 h-3"></span>
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}

            <div className="card">
                <div className="flex gap-4 mb-6">
                    <div className="flex-1 relative">
                        <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                        <input 
                            type="text" 
                            placeholder="Search by name, phone or email..." 
                            className="input-field pl-10"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </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 rounded-tl-lg">Name</th>
                                <th className="px-4 py-3">Contact</th>
                                <th className="px-4 py-3">Birthday</th>
                                <th className="px-4 py-3">Loyalty Points</th>
                                <th className="px-4 py-3">Total Spent</th>
                                <th className="px-4 py-3">Last Visit</th>
                                <th className="px-4 py-3 rounded-tr-lg text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                            {filteredCustomers.map(customer => (
                                <tr key={customer.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 font-medium text-gray-900">{customer.name}</td>
                                    <td className="px-4 py-3 text-gray-600">
                                        <div className="flex flex-col">
                                            <span>{customer.email}</span>
                                            <span className="text-xs text-gray-400 font-mono">{customer.phone}</span>
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-gray-600">
                                        {customer.birthday || '-'}
                                    </td>
                                    <td className="px-4 py-3">
                                        <span className="badge bg-yellow-100 text-yellow-800 border border-yellow-200">
                                            {customer.points} pts
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 font-medium">{formatLKR(customer.totalSpent)}</td>
                                    <td className="px-4 py-3 text-gray-500">{customer.lastVisit}</td>
                                    <td className="px-4 py-3 text-center">
                                        <button 
                                            onClick={() => handleViewHistory(customer)}
                                            className="text-[var(--primary)] hover:underline text-xs font-medium"
                                        >
                                            History
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Add Customer Modal */}
            <Modal isOpen={showAddModal} onClose={() => setShowAddModal(false)} title="Register New Customer">
                <form onSubmit={handleAddCustomer} className="p-5 space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                        <input required type="text" className="input-field" value={customerForm.name} onChange={(e) => setCustomerForm({...customerForm, name: e.target.value})} />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Mobile Phone</label>
                        <input required type="text" className="input-field" value={customerForm.phone} onChange={(e) => setCustomerForm({...customerForm, phone: e.target.value})} />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                        <input type="email" className="input-field" value={customerForm.email} onChange={(e) => setCustomerForm({...customerForm, email: e.target.value})} />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Birthday</label>
                        <input type="date" className="input-field" value={customerForm.birthday} onChange={(e) => setCustomerForm({...customerForm, birthday: e.target.value})} />
                    </div>
                    <button type="submit" className="btn btn-primary w-full">Create Profile</button>
                </form>
            </Modal>

            {/* History Modal */}
            <Modal isOpen={showHistoryModal} onClose={() => setShowHistoryModal(false)} title="Purchase History" size="lg">
                <div className="p-5">
                    {selectedHistory && (
                        <>
                            <div className="flex justify-between items-center mb-4 bg-gray-50 p-3 rounded-lg">
                                <div>
                                    <h4 className="font-bold text-gray-900">{selectedHistory.customer.name}</h4>
                                    <p className="text-xs text-gray-500">Member since 2026</p>
                                </div>
                                <div className="text-right">
                                    <p className="text-xs text-gray-500">Total Spent</p>
                                    <p className="font-bold text-[var(--primary)]">{formatLKR(selectedHistory.customer.totalSpent)}</p>
                                </div>
                            </div>

                            <div className="overflow-x-auto">
                                <table className="w-full text-left text-xs">
                                    <thead>
                                        <tr className="bg-gray-100 text-gray-600">
                                            <th className="p-2">Invoice</th>
                                            <th className="p-2">Date</th>
                                            <th className="p-2">Items</th>
                                            <th className="p-2 text-right">Amount</th>
                                            <th className="p-2 text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {selectedHistory.transactions.map(t => (
                                            <tr key={t.id}>
                                                <td className="p-2 font-mono">{t.id}</td>
                                                <td className="p-2">{t.date}</td>
                                                <td className="p-2">{t.items}</td>
                                                <td className="p-2 text-right font-medium">{formatLKR(t.total)}</td>
                                                <td className="p-2 text-center">
                                                    <span className={`px-1.5 py-0.5 rounded ${t.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                                        {t.status}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                        {selectedHistory.transactions.length === 0 && (
                                            <tr><td colSpan="5" className="p-4 text-center text-gray-400">No transaction history found</td></tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </>
                    )}
                </div>
            </Modal>
            {/* Contact Details Modal */}
            {contactModal && (
                <div className="fixed inset-0 z-[9998] bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in" onClick={() => setContactModal(null)}>
                    <div className="bg-white rounded-2xl shadow-2xl max-w-xs w-full overflow-hidden animate-scale-in" onClick={e => e.stopPropagation()}>
                        <div className="bg-gradient-to-br from-[var(--primary)] to-emerald-700 p-6 text-center text-white">
                            <div className="w-16 h-16 rounded-full bg-white/20 flex items-center justify-center text-2xl font-bold mx-auto mb-3 backdrop-blur-sm">
                                {contactModal.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                            </div>
                            <h3 className="font-bold text-xl">{contactModal.name}</h3>
                            <p className="text-white/70 text-xs mt-1">Customer Profile</p>
                        </div>
                        <div className="p-5 space-y-3">
                            <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                                <div className="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 flex-shrink-0">
                                    <span className="icon-phone text-sm"></span>
                                </div>
                                <div>
                                    <p className="text-[10px] text-gray-400 uppercase tracking-wider font-semibold">Phone</p>
                                    <p className="text-sm font-bold text-gray-800 font-mono">{contactModal.phone}</p>
                                </div>
                            </div>
                            <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                                <div className="w-9 h-9 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 flex-shrink-0">
                                    <span className="icon-mail text-sm"></span>
                                </div>
                                <div>
                                    <p className="text-[10px] text-gray-400 uppercase tracking-wider font-semibold">Email</p>
                                    <p className="text-sm font-bold text-gray-800">{contactModal.email || 'Not provided'}</p>
                                </div>
                            </div>
                            {contactModal.birthday && (
                                <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                                    <div className="w-9 h-9 rounded-full bg-pink-100 flex items-center justify-center text-pink-600 flex-shrink-0">
                                        <span className="icon-cake text-sm"></span>
                                    </div>
                                    <div>
                                        <p className="text-[10px] text-gray-400 uppercase tracking-wider font-semibold">Birthday</p>
                                        <p className="text-sm font-bold text-gray-800">{contactModal.birthday}</p>
                                    </div>
                                </div>
                            )}
                        </div>
                        <div className="px-5 pb-5">
                            <button onClick={() => setContactModal(null)} className="w-full py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-semibold text-gray-700 transition-colors text-sm">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}