function Suppliers({ notify }) {
    const { suppliers, supplierPayments, formatLKR, isDateInRange, exportToExcel } = window.MockData;
    const [localSuppliers, setLocalSuppliers] = React.useState(suppliers);
    const [localPayments, setLocalPayments] = React.useState(supplierPayments);
    const [activeTab, setActiveTab] = React.useState('list'); // list, payments
    
    // UI State
    const [showModal, setShowModal] = React.useState(false);
    const [showPaymentModal, setShowPaymentModal] = React.useState(false);
    
    // Directory Search
    const [directorySearch, setDirectorySearch] = React.useState('');

    // Payment Log Filters
    const [paymentLogDateRange, setPaymentLogDateRange] = React.useState({
        start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0],
        end: new Date().toISOString().split('T')[0]
    });
    
    // Supplier Form
    const [supplierForm, setSupplierForm] = React.useState({
        id: '', name: '', contactPerson: '', phone: '', email: '', address: ''
    });

    // Transaction Types: 'BILL' (New Bill) or 'PAYMENT' (Settle Due)
    const [transactionType, setTransactionType] = React.useState('BILL');

    // Payment Form
    const [paymentForm, setPaymentForm] = React.useState({
        supplierId: '', 
        totalBill: '', 
        paidAmount: '', 
        date: new Date().toISOString().split('T')[0], 
        method: 'Bank Transfer', 
        reference: '', 
        invoiceRef: ''
    });
    
    // Invoice Attachment Simulation
    const [attachedFile, setAttachedFile] = React.useState(null);

    // Calculate outstanding due for selected supplier (Helper)
    const getSupplierDue = (sId) => {
        if (!sId) return 0;
        const supplierHistory = localPayments.filter(p => p.supplierId === sId);
        const totalBilled = supplierHistory.reduce((acc, p) => acc + (p.totalBill || 0), 0);
        const totalPaid = supplierHistory.reduce((acc, p) => acc + (p.paidAmount || 0), 0);
        return Math.max(0, totalBilled - totalPaid);
    };

    // Current Form Due
    const currentSupplierDue = React.useMemo(() => {
        if (!paymentForm.supplierId) return 0;
        return getSupplierDue(parseInt(paymentForm.supplierId));
    }, [paymentForm.supplierId, localPayments]);

    // Calculated Due Amount for current transaction form (New Bill)
    const dueAmount = React.useMemo(() => {
        if (transactionType === 'PAYMENT') return 0; // Paying off due, no new due created
        const total = parseFloat(paymentForm.totalBill) || 0;
        const paid = parseFloat(paymentForm.paidAmount) || 0;
        return Math.max(0, total - paid);
    }, [paymentForm.totalBill, paymentForm.paidAmount, transactionType]);

    // Filter Suppliers for Directory
    const filteredSuppliers = localSuppliers.filter(s => 
        s.name.toLowerCase().includes(directorySearch.toLowerCase()) || 
        s.contactPerson.toLowerCase().includes(directorySearch.toLowerCase()) ||
        s.phone.includes(directorySearch)
    );

    // Filter Payment Logs
    const filteredPayments = localPayments.filter(p => 
        isDateInRange(p.date, paymentLogDateRange.start, paymentLogDateRange.end)
    );

    // Suppliers with Outstanding Debt (For Settle Outstanding Dropdown)
    const outstandingSuppliers = localSuppliers.filter(s => getSupplierDue(s.id) > 0);

    const handleAddSupplier = async (e) => {
        e.preventDefault();
        
        const payload = {
            name: supplierForm.name,
            contact_person: supplierForm.contactPerson,
            phone: supplierForm.phone,
            email: supplierForm.email,
            address: supplierForm.address,
            city: '',
            postal_code: ''
        };

        if (window.POSApiService) {
            try {
                const res = await window.POSApiService.createSupplier(payload);
                if (!res.success) throw new Error(res.error || 'Failed to register supplier');

                const newSupplier = { ...supplierForm, id: res.id || Date.now() };
                const updated = [...localSuppliers, newSupplier];
                
                setLocalSuppliers(updated);
                window.MockData.suppliers = updated;
                
                setShowModal(false);
                setSupplierForm({ id: '', name: '', contactPerson: '', phone: '', email: '', address: '' });
                notify('Success', 'New supplier registered successfully', 'success');
            } catch (err) {
                console.error(err);
                notify('Error', err.message || 'Failed to register supplier', 'error');
            }
        } else {
            notify('Error', 'Backend not available', 'error');
        }
    };

    const handleAddPayment = async (e) => {
        e.preventDefault();
        
        if (!paymentForm.supplierId) {
            notify('Validation Error', 'Please select a supplier', 'error');
            return;
        }

        let payload = {};

        if (transactionType === 'BILL') {
            payload = {
                supplier_id: parseInt(paymentForm.supplierId),
                total_bill: parseFloat(paymentForm.totalBill),
                paid_amount: parseFloat(paymentForm.paidAmount),
                payment_date: paymentForm.date + ' 00:00:00',
                payment_method: paymentForm.method.toLowerCase().replace(' ', '_'),
                reference: paymentForm.reference,
                invoice_ref: paymentForm.invoiceRef,
                notes: 'Bill Entry'
            };
        } else {
            if (parseFloat(paymentForm.paidAmount) > currentSupplierDue) {
                 notify('Error', 'Payment amount cannot exceed outstanding due', 'error');
                 return;
            }
            payload = {
                supplier_id: parseInt(paymentForm.supplierId),
                total_bill: 0,
                paid_amount: parseFloat(paymentForm.paidAmount),
                payment_date: paymentForm.date + ' 00:00:00',
                payment_method: paymentForm.method.toLowerCase().replace(' ', '_'),
                reference: paymentForm.reference,
                invoice_ref: paymentForm.invoiceRef || 'DEBT-SETTLE',
                notes: 'Debt Settlement'
            };
        }

        if (window.POSApiService) {
            try {
                const res = await window.POSApiService.createSupplierPayment(payload);
                if (!res.success) throw new Error(res.error || 'Failed to record transaction');

                // Update UI state
                const newPayment = {
                    id: res.payment_id || `SP-${Date.now()}`,
                    ...paymentForm,
                    supplierId: parseInt(paymentForm.supplierId),
                    totalBill: payload.total_bill,
                    paidAmount: payload.paid_amount,
                    dueAmount: transactionType === 'BILL' ? Math.max(0, payload.total_bill - payload.paid_amount) : 0,
                    hasAttachment: !!attachedFile,
                    type: transactionType,
                    invoiceRef: payload.invoice_ref
                };

                const updated = [...localPayments, newPayment];
                setLocalPayments(updated);
                window.MockData.supplierPayments = updated;

                setShowPaymentModal(false);
                setPaymentForm({ supplierId: '', totalBill: '', paidAmount: '', date: new Date().toISOString().split('T')[0], method: 'Bank Transfer', reference: '', invoiceRef: '' });
                setAttachedFile(null);
                setTransactionType('BILL');
                notify('Success', 'Payment transaction recorded successfully', 'success');
            } catch (err) {
                console.error(err);
                notify('Error', err.message || 'Failed to record transaction', 'error');
            }
        } else {
            notify('Error', 'Backend not available', 'error');
        }
    };

    const handleEditSupplier = (supplier) => {
        setSupplierForm(supplier);
        notify('Info', 'Edit mode simulation: Form pre-filled.', 'info');
        setShowModal(true);
    };

    const handleExport = () => {
        const data = filteredPayments.map(p => {
            const supplier = localSuppliers.find(s => s.id === p.supplierId);
            return {
                Date: p.date,
                TransactionID: p.id,
                Type: p.type,
                Supplier: supplier ? supplier.name : 'Unknown',
                InvoiceRef: p.invoiceRef || '-',
                Method: p.method,
                TotalBill: p.totalBill || 0,
                PaidAmount: p.paidAmount || 0,
                DueAmount: p.dueAmount || 0
            };
        });
        exportToExcel(data, `Supplier_Payments_${paymentLogDateRange.start}_${paymentLogDateRange.end}`);
    };

    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-truck text-[var(--primary)]"></span> Supplier Management
                </h2>
                <div className="flex gap-2">
                    <button 
                        onClick={() => setActiveTab('list')}
                        className={`btn ${activeTab === 'list' ? 'btn-primary' : 'btn-secondary'}`}
                    >
                        <span className="icon-list mr-2"></span> Directory
                    </button>
                    <button 
                        onClick={() => setActiveTab('payments')}
                        className={`btn ${activeTab === 'payments' ? 'btn-primary' : 'btn-secondary'}`}
                    >
                        <span className="icon-credit-card mr-2"></span> Payments
                    </button>
                </div>
            </div>

            {activeTab === 'list' && (
                <div className="card">
                    <div className="flex justify-between items-center mb-6">
                        <div className="flex-1 max-w-sm relative">
                            <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                            <input 
                                type="text" 
                                placeholder="Search suppliers..." 
                                className="input-field pl-10"
                                value={directorySearch}
                                onChange={(e) => setDirectorySearch(e.target.value)}
                            />
                        </div>
                        <button onClick={() => setShowModal(true)} className="btn btn-primary text-sm ml-4">
                            <span className="icon-plus mr-2"></span> Register New
                        </button>
                    </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">Supplier Name</th>
                                    <th className="px-4 py-3">Contact Person</th>
                                    <th className="px-4 py-3">Contact Info</th>
                                    <th className="px-4 py-3">Address</th>
                                    <th className="px-4 py-3 text-right">Outstanding</th>
                                    <th className="px-4 py-3 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {filteredSuppliers.map(s => {
                                    const due = getSupplierDue(s.id);
                                    return (
                                    <tr key={s.id} className="hover:bg-gray-50">
                                        <td className="px-4 py-3 font-medium text-gray-900">{s.name}</td>
                                        <td className="px-4 py-3 text-gray-600">{s.contactPerson}</td>
                                        <td className="px-4 py-3 text-gray-600">
                                            <div>{s.phone}</div>
                                            <div className="text-xs text-blue-500">{s.email}</div>
                                        </td>
                                        <td className="px-4 py-3 text-gray-600 max-w-xs truncate">{s.address}</td>
                                        <td className="px-4 py-3 text-right">
                                            {due > 0 ? (
                                                <span className="badge bg-red-100 text-red-700 font-bold">{formatLKR(due)}</span>
                                            ) : (
                                                <span className="badge bg-green-100 text-green-700">Settled</span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <button 
                                                onClick={() => handleEditSupplier(s)} 
                                                className="text-gray-400 hover:text-[var(--primary)] mr-2"
                                            >
                                                <span className="icon-pencil"></span>
                                            </button>
                                        </td>
                                    </tr>
                                )})}
                                {filteredSuppliers.length === 0 && (
                                    <tr><td colSpan="6" className="text-center py-8 text-gray-400">No suppliers found matching "{directorySearch}"</td></tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {activeTab === 'payments' && (
                <div className="card">
                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
                        <div>
                            <h3 className="font-bold text-gray-800">Supplier Payments Log</h3>
                            <p className="text-xs text-gray-500 mt-1">Track bills and debt settlements</p>
                        </div>
                        
                        <div className="flex flex-wrap items-center gap-3">
                            <div className="flex items-center gap-2 bg-gray-50 p-1.5 rounded-lg border border-gray-200">
                                <span className="text-xs font-bold text-gray-500 uppercase px-2">Period:</span>
                                <input 
                                    type="date" 
                                    className="bg-white border border-gray-200 rounded px-2 py-1 text-xs outline-none focus:border-blue-500"
                                    value={paymentLogDateRange.start}
                                    onChange={(e) => setPaymentLogDateRange({...paymentLogDateRange, start: e.target.value})}
                                />
                                <span className="text-gray-400">-</span>
                                <input 
                                    type="date" 
                                    className="bg-white border border-gray-200 rounded px-2 py-1 text-xs outline-none focus:border-blue-500"
                                    value={paymentLogDateRange.end}
                                    onChange={(e) => setPaymentLogDateRange({...paymentLogDateRange, end: e.target.value})}
                                />
                            </div>

                            <button onClick={handleExport} className="btn btn-secondary text-sm bg-green-50 text-green-700 border-green-200 hover:bg-green-100">
                                <span className="icon-file-spreadsheet mr-2"></span> Export Excel
                            </button>

                            <button onClick={() => setShowPaymentModal(true)} className="btn btn-primary text-sm">
                                <span className="icon-plus mr-2"></span> Record Transaction
                            </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">Type</th>
                                    <th className="px-4 py-3">Supplier</th>
                                    <th className="px-4 py-3">Details</th>
                                    <th className="px-4 py-3 text-right">Bill Amt</th>
                                    <th className="px-4 py-3 text-right">Paid Amt</th>
                                    <th className="px-4 py-3 text-right">Due Amt</th>
                                    <th className="px-4 py-3 text-center">Attach.</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {filteredPayments.length > 0 ? filteredPayments.map(p => {
                                    const supplier = localSuppliers.find(s => s.id === p.supplierId);
                                    const total = p.totalBill || 0;
                                    const paid = p.paidAmount || 0;
                                    const due = p.dueAmount || 0;
                                    const isPayment = p.type === 'PAYMENT';

                                    return (
                                        <tr key={p.id} className="hover:bg-gray-50">
                                            <td className="px-4 py-3 text-gray-600">{p.date}</td>
                                            <td className="px-4 py-3">
                                                <span className={`badge ${isPayment ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'}`}>
                                                    {isPayment ? 'SETTLEMENT' : 'BILL'}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 font-medium text-gray-900">
                                                {supplier ? supplier.name : 'Unknown'}
                                            </td>
                                            <td className="px-4 py-3 text-gray-600 font-mono text-xs">
                                                <div className="flex gap-2">
                                                    <span className="text-gray-800">{p.invoiceRef}</span>
                                                    <span className="text-gray-400">| {p.method}</span>
                                                </div>
                                            </td>
                                            <td className="px-4 py-3 text-right text-gray-600">{!isPayment ? formatLKR(total) : '-'}</td>
                                            <td className="px-4 py-3 text-right font-bold text-green-600">{formatLKR(paid)}</td>
                                            <td className="px-4 py-3 text-right font-bold text-red-600">{due > 0 ? formatLKR(due) : '-'}</td>
                                            <td className="px-4 py-3 text-center">
                                                {p.hasAttachment ? (
                                                    <span className="icon-paperclip text-blue-500 cursor-pointer" title="View Attachment" onClick={() => notify('Info', 'Opening attachment viewer...', 'info')}></span>
                                                ) : <span className="text-gray-300">-</span>}
                                            </td>
                                        </tr>
                                    );
                                }) : (
                                    <tr><td colSpan="8" className="text-center py-8 text-gray-400">No payment records found in selected period</td></tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Modal: Register Supplier */}
            <Modal isOpen={showModal} onClose={() => setShowModal(false)} title="Register New Supplier">
                <form onSubmit={handleAddSupplier} className="p-5 space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Company Name</label>
                        <input required type="text" className="input-field" value={supplierForm.name} onChange={(e) => setSupplierForm({...supplierForm, name: e.target.value})} />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Contact Person</label>
                            <input required type="text" className="input-field" value={supplierForm.contactPerson} onChange={(e) => setSupplierForm({...supplierForm, contactPerson: e.target.value})} />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Phone</label>
                            <input required type="text" className="input-field" value={supplierForm.phone} onChange={(e) => setSupplierForm({...supplierForm, phone: e.target.value})} />
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                        <input type="email" className="input-field" value={supplierForm.email} onChange={(e) => setSupplierForm({...supplierForm, email: e.target.value})} />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Address</label>
                        <textarea className="input-field h-20 resize-none" value={supplierForm.address} onChange={(e) => setSupplierForm({...supplierForm, address: e.target.value})}></textarea>
                    </div>
                    <button type="submit" className="btn btn-primary w-full">Register Supplier</button>
                </form>
            </Modal>

            {/* Modal: Record Payment */}
            <Modal isOpen={showPaymentModal} onClose={() => setShowPaymentModal(false)} title="Record Transaction">
                <form onSubmit={handleAddPayment} className="p-5 space-y-4">
                    {/* Transaction Type Selection */}
                    <div className="flex p-1 bg-gray-100 rounded-lg">
                        <button 
                            type="button"
                            onClick={() => { setTransactionType('BILL'); setPaymentForm({...paymentForm, supplierId: ''}); }}
                            className={`flex-1 py-2 text-sm font-medium rounded-md transition-all ${transactionType === 'BILL' ? 'bg-white text-[var(--primary)] shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
                        >
                            New Invoice (Bill)
                        </button>
                        <button 
                            type="button"
                            onClick={() => { setTransactionType('PAYMENT'); setPaymentForm({...paymentForm, supplierId: ''}); }}
                            className={`flex-1 py-2 text-sm font-medium rounded-md transition-all ${transactionType === 'PAYMENT' ? 'bg-white text-[var(--primary)] shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
                        >
                            Settle Outstanding
                        </button>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Select Supplier</label>
                        <select required className="input-field" value={paymentForm.supplierId} onChange={(e) => setPaymentForm({...paymentForm, supplierId: e.target.value})}>
                            <option value="">-- Select --</option>
                            {/* Filter suppliers based on type */}
                            {(transactionType === 'PAYMENT' ? outstandingSuppliers : localSuppliers).map(s => (
                                <option key={s.id} value={s.id}>
                                    {s.name} {transactionType === 'PAYMENT' && `(Due: ${formatLKR(getSupplierDue(s.id))})`}
                                </option>
                            ))}
                        </select>
                        {transactionType === 'PAYMENT' && outstandingSuppliers.length === 0 && (
                            <p className="text-xs text-green-600 mt-1">No suppliers with outstanding dues!</p>
                        )}
                    </div>

                    {transactionType === 'BILL' ? (
                        <>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Total Bill (LKR)</label>
                                    <input required type="number" step="0.01" className="input-field font-bold" value={paymentForm.totalBill} onChange={(e) => setPaymentForm({...paymentForm, totalBill: e.target.value})} />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Paid Now (LKR)</label>
                                    <input required type="number" step="0.01" className="input-field font-bold text-green-600" value={paymentForm.paidAmount} onChange={(e) => setPaymentForm({...paymentForm, paidAmount: e.target.value})} />
                                </div>
                            </div>
                            <div className={`p-3 rounded-lg flex justify-between items-center border ${dueAmount > 0 ? 'bg-red-50 border-red-100' : 'bg-green-50 border-green-100'}`}>
                                <span className="text-sm font-medium text-gray-700">Balance Due:</span>
                                <span className={`font-bold text-lg ${dueAmount > 0 ? 'text-red-600' : 'text-green-600'}`}>{formatLKR(dueAmount)}</span>
                            </div>
                        </>
                    ) : (
                        <>
                            {paymentForm.supplierId && (
                                <div className="p-3 bg-orange-50 border border-orange-100 rounded-lg">
                                    <div className="text-sm text-orange-800 font-medium">Current Outstanding Due</div>
                                    <div className="text-2xl font-bold text-orange-700">{formatLKR(currentSupplierDue)}</div>
                                </div>
                            )}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Payment Amount (LKR)</label>
                                <input required type="number" step="0.01" max={currentSupplierDue} className="input-field font-bold text-green-600" value={paymentForm.paidAmount} onChange={(e) => setPaymentForm({...paymentForm, paidAmount: e.target.value})} />
                            </div>
                        </>
                    )}

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
                            <input required type="date" className="input-field" value={paymentForm.date} onChange={(e) => setPaymentForm({...paymentForm, date: e.target.value})} />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Method</label>
                            <select className="input-field" value={paymentForm.method} onChange={(e) => setPaymentForm({...paymentForm, method: e.target.value})}>
                                <option>Bank Transfer</option>
                                <option>Cheque</option>
                                <option>Cash</option>
                            </select>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Ref No.</label>
                            <input type="text" className="input-field" placeholder="Cheque/Ref No" value={paymentForm.reference} onChange={(e) => setPaymentForm({...paymentForm, reference: e.target.value})} />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">Supplier Invoice No.</label>
                            <input type="text" className="input-field" placeholder={transactionType === 'BILL' ? "e.g. INV-12345" : "Optional"} value={paymentForm.invoiceRef} onChange={(e) => setPaymentForm({...paymentForm, invoiceRef: e.target.value})} />
                        </div>
                    </div>
                    
                    {/* File Attachment Simulation */}
                    <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center cursor-pointer hover:bg-gray-50 transition-colors relative">
                        <input type="file" className="absolute inset-0 opacity-0 cursor-pointer" onChange={(e) => setAttachedFile(e.target.files[0])} />
                        <div className="pointer-events-none">
                            <span className="icon-cloud-upload text-gray-400 text-2xl mb-1 block"></span>
                            <span className="text-sm text-gray-600 font-medium">
                                {attachedFile ? attachedFile.name : 'Attach Invoice / Receipt (Optional)'}
                            </span>
                        </div>
                    </div>

                    <button type="submit" className="btn btn-primary w-full">Record Transaction</button>
                </form>
            </Modal>
        </div>
    );
}