function Settings() {
    const { users, paymentMethods } = window.MockData;
    const [localUsers, setLocalUsers] = React.useState(users);
    const [localPaymentMethods, setLocalPaymentMethods] = React.useState(paymentMethods);
    const [taxRate, setTaxRate] = React.useState(0);
    const [newPaymentMethod, setNewPaymentMethod] = React.useState('');

    // --- Add User Modal State ---
    const [showAddModal, setShowAddModal] = React.useState(false);
    const [newUser, setNewUser] = React.useState({ name: '', pin: '', role: 'cashier', email: '', phone: '' });

    // --- Edit User Modal State ---
    const [editUser, setEditUser] = React.useState(null); // the full user object being edited
    const [editForm, setEditForm] = React.useState({ name: '', email: '', phone: '', role: '', pin: '', newPin: '' });
    const [savingEdit, setSavingEdit] = React.useState(false);

    const openEditModal = (user) => {
        setEditUser(user);
        setEditForm({ name: user.name || '', email: user.email || '', phone: user.phone || '', role: user.role || 'cashier', newPin: '' });
    };

    const closeEditModal = () => { setEditUser(null); };

    const handleAddUser = async (e) => {
        e.preventDefault();
        const id = `user-${Date.now()}`;
        const userToAdd = { id, ...newUser };

        try {
            const res = await window.POSApiService.post('auth.php?action=create', userToAdd);
            if (!res.success) throw new Error(res.error || 'Failed to create');
            const updatedUsers = [...localUsers, userToAdd];
            setLocalUsers(updatedUsers);
            window.MockData.users = updatedUsers;
            setShowAddModal(false);
            setNewUser({ name: '', pin: '', role: 'cashier', email: '', phone: '' });
        } catch(e) {
            window.AppDialog.alert('Error', e.message || 'Failed to create user', 'error');
        }
    };

    const handleSaveEdit = async (e) => {
        e.preventDefault();
        if (!editUser) return;
        setSavingEdit(true);

        try {
            // 1. Save profile (name, email, phone, role)
            const profilePayload = {
                id: editUser.id,
                name: editForm.name,
                email: editForm.email,
                phone: editForm.phone,
                role: editForm.role
            };
            const profileRes = await window.POSApiService.post('auth.php?action=update_profile', profilePayload);
            if (!profileRes.success) throw new Error(profileRes.error || 'Failed to update profile');

            // 2. Optionally update PIN if a new one was entered
            if (editForm.newPin && editForm.newPin.length === 4) {
                const pinRes = await window.POSApiService.post('auth.php?action=update_pin', { id: editUser.id, pin: editForm.newPin });
                if (!pinRes.success) throw new Error(pinRes.error || 'Failed to update PIN');
            }

            // 3. Update local state
            const updatedUsers = localUsers.map(u =>
                u.id === editUser.id ? { ...u, ...profilePayload } : u
            );
            setLocalUsers(updatedUsers);
            window.MockData.users = updatedUsers;

            closeEditModal();
        } catch(err) {
            window.AppDialog.alert('Error', err.message, 'error');
        } finally {
            setSavingEdit(false);
        }
    };

    const handleDeleteUser = async (userId) => {
        const ok = await window.AppDialog.confirm('Remove User', 'Are you sure? This cannot be undone.', 'Remove User');
        if (!ok) return;
        try {
            const res = await window.POSApiService.post('auth.php?action=delete', { id: userId });
            if (!res.success) throw new Error(res.error || 'Failed to delete');
            const updatedUsers = localUsers.filter(u => u.id !== userId);
            setLocalUsers(updatedUsers);
            window.MockData.users = updatedUsers;
        } catch(e) {
            window.AppDialog.alert('Error', e.message, 'error');
        }
    };

    const handleAddPaymentMethod = (e) => {
        e.preventDefault();
        if (!newPaymentMethod.trim()) return;
        const method = { id: newPaymentMethod.toLowerCase().replace(/\s+/g, '-'), name: newPaymentMethod, icon: 'icon-credit-card' };
        const updatedMethods = [...localPaymentMethods, method];
        setLocalPaymentMethods(updatedMethods);
        window.MockData.paymentMethods = updatedMethods;
        setNewPaymentMethod('');
    };

    const handleRemovePaymentMethod = async (id) => {
        if (id === 'cash' || id === 'card') {
            await window.AppDialog.alert('Cannot Remove', 'Default payment methods cannot be removed.', 'warning');
            return;
        }
        const ok = await window.AppDialog.confirm('Remove Payment Method', 'Remove this payment method?', 'Remove');
        if (ok) {
            const updatedMethods = localPaymentMethods.filter(m => m.id !== id);
            setLocalPaymentMethods(updatedMethods);
            window.MockData.paymentMethods = updatedMethods;
        }
    };

    const roleBadgeClass = (role) => {
        if (role === 'admin') return 'bg-purple-100 text-purple-700';
        if (role === 'manager') return 'bg-yellow-100 text-yellow-800';
        return 'bg-blue-100 text-blue-700';
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-2xl font-bold text-gray-900">System Settings</h2>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Left column */}
                <div className="lg:col-span-1 space-y-6">
                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
                            <span className="icon-store text-[var(--primary)]"></span> Store Details
                        </h3>
                        <div className="space-y-4">
                            <div>
                                <label className="block text-xs font-medium text-gray-500 mb-1">Store Name</label>
                                <input type="text" value="NOAHVELLE" className="input-field bg-gray-50" readOnly />
                            </div>
                            <div>
                                <label className="block text-xs font-medium text-gray-500 mb-1">Currency</label>
                                <input type="text" value="LKR (Rs)" className="input-field bg-gray-50" readOnly />
                            </div>
                            <div>
                                <label className="block text-xs font-medium text-gray-500 mb-1">Tax Rate (%)</label>
                                <input type="number" value={taxRate} onChange={(e) => setTaxRate(e.target.value)} className="input-field" min="0" max="100" />
                            </div>
                            <button className="btn btn-primary w-full text-sm">Save Changes</button>
                        </div>
                    </div>

                    <div className="card">
                        <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
                            <span className="icon-wallet-minimal text-[var(--primary)]"></span> Payment Methods
                        </h3>
                        <div className="space-y-4">
                            <form onSubmit={handleAddPaymentMethod} className="flex gap-2">
                                <input type="text" placeholder="Add method (e.g. Bank Transfer)" className="input-field text-sm" value={newPaymentMethod} onChange={(e) => setNewPaymentMethod(e.target.value)} />
                                <button type="submit" className="btn btn-secondary px-3"><span className="icon-plus"></span></button>
                            </form>
                            <div className="space-y-2">
                                {localPaymentMethods.map(method => (
                                    <div key={method.id} className="flex items-center justify-between p-2 bg-gray-50 rounded border border-gray-100">
                                        <div className="flex items-center gap-2">
                                            <span className={`${method.icon} text-gray-400`}></span>
                                            <span className="text-sm font-medium text-gray-700">{method.name}</span>
                                        </div>
                                        {(method.id !== 'cash' && method.id !== 'card') && (
                                            <button onClick={() => handleRemovePaymentMethod(method.id)} className="text-red-400 hover:text-red-600">
                                                <span className="icon-trash w-4 h-4"></span>
                                            </button>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Right column — User Management */}
                <div className="lg:col-span-2">
                    <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-users-round text-[var(--primary)]"></span> User Management
                            </h3>
                            <button onClick={() => setShowAddModal(true)} className="btn btn-primary text-sm py-1.5">
                                <span className="icon-plus mr-1"></span> Add User
                            </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">User</th>
                                        <th className="px-4 py-3">Role</th>
                                        <th className="px-4 py-3">Email</th>
                                        <th className="px-4 py-3">Phone</th>
                                        <th className="px-4 py-3 text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {localUsers.map(user => (
                                        <tr key={user.id} className="group hover:bg-gray-50">
                                            <td className="px-4 py-3">
                                                <div className="flex items-center gap-3">
                                                    <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs ${user.role === 'admin' ? 'bg-purple-100 text-purple-700' : 'bg-slate-200 text-slate-500'}`}>
                                                        {user.name.split(' ').map(n => n[0]).join('').substring(0,2)}
                                                    </div>
                                                    <div>
                                                        <p className="font-medium text-gray-900">{user.name}</p>
                                                        <p className="text-[10px] text-gray-400 font-mono">{user.id}</p>
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-4 py-3">
                                                <span className={`badge ${roleBadgeClass(user.role)} capitalize`}>{user.role}</span>
                                            </td>
                                            <td className="px-4 py-3 text-sm text-gray-600">
                                                {user.email
                                                    ? <a href={`mailto:${user.email}`} className="hover:text-[var(--primary)] hover:underline">{user.email}</a>
                                                    : <span className="text-gray-300">—</span>}
                                            </td>
                                            <td className="px-4 py-3 text-sm text-gray-600">
                                                {user.phone
                                                    ? <a href={`tel:${user.phone}`} className="hover:text-[var(--primary)] hover:underline">{user.phone}</a>
                                                    : <span className="text-gray-300">—</span>}
                                            </td>
                                            <td className="px-4 py-3 text-right">
                                                <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                    <button
                                                        onClick={() => openEditModal(user)}
                                                        className="text-blue-400 hover:text-blue-600 p-1"
                                                        title="Edit User"
                                                    >
                                                        <span className="icon-pencil"></span>
                                                    </button>
                                                    {user.id !== 'admin' && (
                                                        <button
                                                            onClick={() => handleDeleteUser(user.id)}
                                                            className="text-red-400 hover:text-red-600 p-1"
                                                            title="Remove User"
                                                        >
                                                            <span className="icon-trash"></span>
                                                        </button>
                                                    )}
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            {/* ── ADD USER MODAL ── */}
            {showAddModal && (
                <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-sm 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 User</h3>
                            <button onClick={() => setShowAddModal(false)}><span className="icon-x text-gray-400"></span></button>
                        </div>
                        <form onSubmit={handleAddUser} 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={newUser.name} onChange={(e) => setNewUser({...newUser, name: e.target.value})} />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                                <select className="input-field" value={newUser.role} onChange={(e) => setNewUser({...newUser, role: e.target.value})}>
                                    <option value="cashier">Cashier</option>
                                    <option value="manager">Manager</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Access PIN (4 Digits)</label>
                                <input required type="text" pattern="\d{4}" maxLength="4" className="input-field" value={newUser.pin} onChange={(e) => setNewUser({...newUser, pin: 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={newUser.email} onChange={(e) => setNewUser({...newUser, email: e.target.value})} />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                                <input type="text" className="input-field" value={newUser.phone} onChange={(e) => setNewUser({...newUser, phone: e.target.value})} />
                            </div>
                            <div className="pt-2">
                                <button type="submit" className="w-full btn btn-primary">Create Account</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* ── EDIT USER MODAL ── */}
            {editUser && (
                <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-sm overflow-hidden">
                        <div className="p-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                            <div>
                                <h3 className="font-bold text-gray-900">Edit User</h3>
                                <p className="text-xs text-gray-400 font-mono mt-0.5">ID: {editUser.id}</p>
                            </div>
                            <button onClick={closeEditModal}><span className="icon-x text-gray-400"></span></button>
                        </div>
                        <form onSubmit={handleSaveEdit} 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={editForm.name} onChange={(e) => setEditForm({...editForm, name: e.target.value})} />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                                <select className="input-field" value={editForm.role} onChange={(e) => setEditForm({...editForm, role: e.target.value})}>
                                    <option value="cashier">Cashier</option>
                                    <option value="manager">Manager</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                <input type="email" className="input-field" value={editForm.email} onChange={(e) => setEditForm({...editForm, email: e.target.value})} />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                                <input type="text" className="input-field" value={editForm.phone} onChange={(e) => setEditForm({...editForm, phone: e.target.value})} />
                            </div>
                            <div className="bg-amber-50 border border-amber-100 rounded-lg p-3">
                                <label className="block text-sm font-medium text-amber-800 mb-1">New PIN (leave blank to keep current)</label>
                                <input
                                    type="text"
                                    pattern="\d{4}"
                                    maxLength="4"
                                    placeholder="Enter 4-digit PIN to change..."
                                    className="input-field border-amber-200 focus:ring-amber-400 font-mono tracking-widest"
                                    value={editForm.newPin}
                                    onChange={(e) => setEditForm({...editForm, newPin: e.target.value})}
                                />
                            </div>
                            <div className="pt-2 flex gap-3">
                                <button type="button" onClick={closeEditModal} className="flex-1 btn btn-secondary">Cancel</button>
                                <button type="submit" disabled={savingEdit} className="flex-[2] btn btn-primary">
                                    {savingEdit ? <><span className="icon-loader-circle animate-spin mr-2"></span>Saving...</> : 'Save Changes'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}