const AccessManagementView = ({ currentUser, selectedProperty, isActiveView }) => {
    const { useState, useEffect, useRef, useMemo } = React;
    const [users, setUsers] = useState([]);
    const [propertyOptions, setPropertyOptions] = useState([]);
    const [roleOptions, setRoleOptions] = useState([]);
    const [roleObjectsMap, setRoleObjectsMap] = useState({}); // NEW: Map of display_name -> full role object
    const [isLoading, setIsLoading] = useState(true);
    const [loadError, setLoadError] = useState('');
    const [selectedUser, setSelectedUser] = useState(null);
    const [showUserForm, setShowUserForm] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [statusFilter, setStatusFilter] = useState('Active');
    const [includeOTOContacts, setIncludeOTOContacts] = useState(false); // NEW: Toggle for OTO contacts (default OFF)

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [phone, setPhone] = useState('');
    const [role, setRole] = useState('Front Desk');
    const [roleCanViewAllProperties, setRoleCanViewAllProperties] = useState(false);
    const [properties, setProperties] = useState([]);
    const [propertySearch, setPropertySearch] = useState('');
    const [preferredContactMethods, setPreferredContactMethods] = useState(['email']);
    const [tempPassword, setTempPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [editingUsername, setEditingUsername] = useState(null);

    const currentUsername = (currentUser?.Username || localStorage.getItem('oto_username') || '').trim();
    const selectedPropertyCode = (selectedProperty?.property_code || '').trim();
    // View disabled users: requires explicit can_view_disabled_users permission
    const canViewDisabledUsers = !!currentUser?.can_view_disabled_users;
    const myPropertyCodes = new Set((currentUser?.properties || []).map(p => p.property_code).filter(Boolean));
    const canManageProperty = (code) => myPropertyCodes.has(code);

    const normalizeRole = (r) => String(r || '').toLowerCase().replace(/[^a-z0-9]+/g, '');

    // Role hierarchy map: role display_name -> sort_order (from database)
    const [roleSortOrderMap, setRoleSortOrderMap] = useState({});

    const getRoleLevel = (roleName) => {
        // Try to get sort_order from the map first (from database)
        if (roleName && roleSortOrderMap[roleName] !== undefined) {
            return roleSortOrderMap[roleName] || 0;
        }
        // Fallback to 0 if role not found
        return 0;
    };

    const currentUserRoleLevel = getRoleLevel(currentUser?.Role || '');

    // Permissions: require can_manage_users (not just can_view_directory)
    const canManageUsers = !!(currentUser?.can_manage_users);
    const canCreateUsers = canManageUsers;
    const canSeeUsersWithoutPropertyAccess = canManageUsers; // derived from Manage Users (no separate UI permission)
    const canEditUsers = canManageUsers;
    const canResetPasswords = canManageUsers;
    const canToggleStatus = canManageUsers;

    // Can manage users: require can_manage_users permission AND target role must be strictly lower rank.
    // Users can only modify users of a lower role and cannot assign roles higher than their own.
    const canManageRole = (targetRole) => {
        if (!canManageUsers) {
            return false;
        }
        const targetLevel = getRoleLevel(targetRole);
        return currentUserRoleLevel > targetLevel;
    };

    const isCorporateRole = ['corporateit', 'corporate', 'administrator', 'administrators'].includes(normalizeRole(role));
    const isSystemRole = normalizeRole(role) === 'system';


    const formatPhoneForDisplay = (digits) => {
        if (!digits) return '';
        const cleaned = String(digits).replace(/\D/g, '');
        if (cleaned.length !== 10) return String(digits);
        return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6, 10)}`;
    };

    const normalizeStatus = (row) => {
        if (row.normalized_status) return row.normalized_status;
        if (row.status) return row.status;
        if (row.is_active === false) return 'Disabled';
        return 'Active';
    };

    const mapStaffToUser = (staffRow, idx) => ({
        UserID: staffRow.id ?? staffRow.user_id ?? (idx + 1),
        FirstName: staffRow.first_name ?? '',
        LastName: staffRow.last_name ?? '',
        Username: staffRow.username ?? '',
        Email: staffRow.email ?? '',
        Phone: formatPhoneForDisplay(staffRow.phone ?? ''),
        // Use role_display_name or role_name from backend so we can reliably look up role permissions.
        Role: staffRow.role_display_name ?? staffRow.role_name ?? staffRow.role ?? staffRow.department ?? 'Front Desk',
        Status: normalizeStatus(staffRow),
        Created: staffRow.created_at ?? staffRow.created ?? staffRow.created_on ?? '',
        LastLogin: staffRow.last_login ?? staffRow.last_login_at ?? '',
        PropertyCodes: staffRow.property_codes || [],
        PreferredContactMethods: staffRow.preferred_contact_methods ?? staffRow.preferredContactMethods ?? ['email'],
        // From backend: role's can_be_global_directory_contact (for OTO contacts toggle)
        can_be_global_directory_contact: !!staffRow.can_be_global_directory_contact,
    });

    const baseRoleOptions = (roleOptions && roleOptions.length)
        ? roleOptions
        : ['Administrator', 'Corporate IT', 'Corporate', 'Property Management', 'Front Desk', 'Food & Beverage', 'Sales', 'Engineering'];
    const roleOptionsWithCurrent = baseRoleOptions.includes(role)
        ? baseRoleOptions
        : [role, ...baseRoleOptions];

    const loadData = async () => {
        try {
            setIsLoading(true);
            setLoadError('');

            const staffParams = new URLSearchParams();
            // When filtering by \"Unassigned\", ignore selectedPropertyCode so we can see global no-property users.
            if (selectedPropertyCode && statusFilter !== 'Unassigned') {
                staffParams.set('property_code', selectedPropertyCode);
            }
            if (currentUsername) staffParams.set('exclude_username', currentUsername);
            // Request disabled/all users when user has permission and selected that filter
            if (canViewDisabledUsers && statusFilter === 'Disabled') {
                staffParams.set('status', 'Disabled');
            } else if (canViewDisabledUsers && statusFilter === 'All Users') {
                // no status = backend returns both Active and Disabled
            } else {
                staffParams.set('status', 'Active');
            }
            const staffUrl = staffParams.toString() ? `/api/staff?${staffParams.toString()}` : '/api/staff';

            const [staffRes, propsRes] = await Promise.all([
                fetch(staffUrl, { headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : undefined }),
                fetch('/api/properties', { headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : undefined })
            ]);

            // Roles/statuses (best-effort; endpoint may be absent in older backends)
            try {
                const rolesRes = await fetch('/api/roles', { headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : undefined });
                if (rolesRes.ok) {
                    const rolesData = await rolesRes.json();
                    if (Array.isArray(rolesData.roles)) {
                        // Build sort_order map: display_name -> sort_order
                        const sortOrderMap = {};
                        rolesData.roles.forEach(r => {
                            const displayName = r.display_name || r.name;
                            sortOrderMap[displayName] = r.sort_order !== undefined ? r.sort_order : 0;
                        });
                        setRoleSortOrderMap(sortOrderMap);

                        // Check if current user is admin (using sort_order >= 90 as threshold, or fallback to role name)
                        const currentUserRoleName = currentUser?.Role || '';
                        const currentUserSortOrder = sortOrderMap[currentUserRoleName] || 0;
                        const isCurrentUserAdmin = currentUserSortOrder >= 90 || ['administrator', 'administrators', 'system'].includes(normalizeRole(currentUserRoleName));
                        
                        const filteredRoles = rolesData.roles.filter(r => {
                            if (r.name === 'system') return false;
                            if (r.name === 'administrator') return isCurrentUserAdmin;
                            return true;
                        });

                        // Create array of display names for dropdown
                        const roleNames = filteredRoles.map(r => r.display_name || r.name);
                        setRoleOptions(roleNames);

                        // Create map of display_name -> full role object for permission lookups
                        const rolesMap = {};
                        filteredRoles.forEach(r => {
                            const displayName = r.display_name || r.name;
                            rolesMap[displayName] = r;
                        });
                        setRoleObjectsMap(rolesMap);
                    }
                }
            } catch (e) {
                setRoleOptions([]);
                setRoleObjectsMap({});
                setRoleSortOrderMap({});
            }

            const staffData = await staffRes.json();
            const propsData = await propsRes.json();

            const staffRows = (staffData.users || []).map(mapStaffToUser);
            // OTO troubleshooting: log every user's OTO-relevant fields (so we can see can_be_global_directory_contact + PropertyCodes)
            try {
                const otoRelevant = staffRows.map(u => ({
                    Username: u.Username,
                    Role: u.Role,
                    PropertyCodes: u.PropertyCodes,
                    can_be_global_directory_contact: u.can_be_global_directory_contact,
                }));
                console.log('[OTO DEBUG] Directory loadData – staff with OTO fields', {
                    totalStaff: staffRows.length,
                    requestedPropertyCode: selectedPropertyCode,
                    users: otoRelevant,
                });
            } catch (e) {
                console.warn('[OTO DEBUG] loadData log failed', e);
            }
            setUsers(staffRows);
            // Selection is synced to first *filtered* user in an effect below (so it matches the visible list)

            // propsData is already an array, not wrapped in {properties: [...]}
            const propsArray = Array.isArray(propsData) ? propsData : (propsData.properties || []);
            const props = propsArray
                .map(p => ({
                    code: p.property_code || p.code,
                    name: p.display_name || p.name || p.property_name || p.full_name || p.code,
                    address: p.address,
                    city: p.city,
                    state: p.state,
                    zip: p.zip,
                    his: p.his
                }))
                .filter(p => !!p.code)
                // Sort alphabetically by property name for easier scanning
                .sort((a, b) => a.name.localeCompare(b.name));
            setPropertyOptions(props);
        } catch (e) {
            console.error('Failed to load staff/properties', e);
            setLoadError('Failed to load staff users. Please refresh the page.');
            setUsers([]);
            setPropertyOptions([]);
            setSelectedUser(null);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        loadData();
    }, [selectedPropertyCode, currentUsername, statusFilter]);

    // Refetch when this view becomes active (e.g. user clicked Directory) so data is always fresh
    const loadDataRef = useRef(loadData);
    loadDataRef.current = loadData;
    const hasModalOpen = showUserForm || showPassword;
    const hasModalOpenRef = useRef(hasModalOpen);
    hasModalOpenRef.current = hasModalOpen;

    useEffect(() => {
        if (!isActiveView || hasModalOpenRef.current) return;
        if (typeof loadDataRef.current === 'function') loadDataRef.current();
    }, [isActiveView]);

    // Poll while view is visible so updates from other tabs/sessions appear without a click (skip when a popup is open)
    useEffect(() => {
        if (!isActiveView) return;
        const interval = setInterval(() => {
            if (hasModalOpenRef.current) return;
            if (typeof loadDataRef.current === 'function') loadDataRef.current();
        }, 45000);
        return () => clearInterval(interval);
    }, [isActiveView]);

    // Live update: when roles change in Administration, refetch roles and staff (skip when a popup is open)
    useEffect(() => {
        if (!window.otoEvents) return;
        const unsub = window.otoEvents.on('roles-updated', () => {
            if (hasModalOpenRef.current) return;
            if (typeof loadDataRef.current === 'function') loadDataRef.current();
        });
        return () => { if (typeof unsub === 'function') unsub(); };
    }, []);

    useEffect(() => {
        if (roleOptions.length > 0) {
            // Only set role if current role is not in the options
            const roleIsValid = roleOptions.some(opt =>
                typeof opt === 'string' && typeof role === 'string' && opt.toLowerCase() === role.toLowerCase()
            );
            if (!roleIsValid) {
                setRole(roleOptions[0]);
            }
        }
    }, [roleOptions]);

    // Update roleCanViewAllProperties whenever role changes
    useEffect(() => {
        if (role && roleObjectsMap[role]) {
            setRoleCanViewAllProperties(!!roleObjectsMap[role].can_view_all_properties);
        } else {
            setRoleCanViewAllProperties(false);
        }
    }, [role, roleObjectsMap]);

    // Roles with can_view_all_properties automatically have access to ALL properties.
    useEffect(() => {
        if (roleCanViewAllProperties && propertyOptions.length) {
            const all = propertyOptions.map(p => p.code).filter(Boolean);
            setProperties(all);
        }
    }, [roleCanViewAllProperties, propertyOptions.length]);

    // Role changes should only clear property selections when the user changes the role dropdown.
    const handleRoleChange = (e) => {
        const newRole = e.target.value;
        const currentNorm = normalizeRole(role);
        const newNorm = normalizeRole(newRole);

        // If role didn't actually change, do nothing
        if (newNorm === currentNorm) return;

        setRole(newRole);

        // Look up the role object from our map to get its permissions
        const selectedRoleObj = roleObjectsMap[newRole];
        if (selectedRoleObj) {
            setRoleCanViewAllProperties(!!selectedRoleObj.can_view_all_properties);
        } else {
            // Fallback for roles not in map (shouldn't happen, but be safe)
            setRoleCanViewAllProperties(false);
        }

        const newRoleObj = roleObjectsMap[newRole];
        const newCanViewAll = !!(newRoleObj && newRoleObj.can_view_all_properties);

        // Switching into a role without can_view_all_properties should clear selected properties
        // (roles with can_view_all_properties will auto-get all properties via the effect above)
        if (!newCanViewAll) {
            setProperties([]);
        }
    };

    const toggleProperty = (propertyCode) => {
        if (roleCanViewAllProperties) return;
        if (!canManageProperty(propertyCode)) return;
        setProperties(prev =>
            prev.includes(propertyCode)
                ? prev.filter(code => code !== propertyCode)
                : [...prev, propertyCode]
        );
    };

    // When user cannot view disabled users, only "Active" is allowed; keep filter in sync
    useEffect(() => {
        if (!canViewDisabledUsers && statusFilter !== 'Active') setStatusFilter('Active');
    }, [canViewDisabledUsers, statusFilter]);

    // Keep selection in sync with the visible (filtered) list: when property/filters change, select first visible user if current selection is not in the list
    useEffect(() => {
        if (showUserForm) return;
        if (filteredUsers.length === 0) {
            setSelectedUser(null);
            return;
        }
        const selectedInList = selectedUser && filteredUsers.some(u => (u.Username || u.UserID) === (selectedUser.Username || selectedUser.UserID));
        if (!selectedInList) {
            setSelectedUser(filteredUsers[0]);
        }
    }, [filteredUsers, selectedPropertyCode, showUserForm]);

    const formatPhoneNumber = (value) => {
        const digits = value.replace(/\D/g, '');
        if (digits.length === 0) return '';
        if (digits.length <= 3) return `(${digits}`;
        if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
        return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
    };

    const generateTempPassword = () => {
        const date = new Date();
        const dayName = date.toLocaleDateString('en-US', { weekday: 'long' }).toUpperCase();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const year = String(date.getFullYear()).slice(-2);
        const random = Math.floor(Math.random() * 90) + 10;
        return `${dayName}${month}${day}${year}!${random}`;
    };

    useEffect(() => {
        if (showUserForm && !tempPassword) {
            setTempPassword(generateTempPassword());
        }
    }, [showUserForm]);

    const handlePhoneChange = (e) => {
        const formatted = formatPhoneNumber(e.target.value);
        setPhone(formatted);
    };

    const resetUserForm = () => {
        setFirstName('');
        setLastName('');
        setUsername('');
        setEmail('');
        setPhone('');
        setRole((roleOptions && roleOptions.length) ? roleOptions[0] : 'Front Desk');
        setProperties([]);
        setPropertySearch('');
        setPreferredContactMethods(['email']);
        setTempPassword('');
        setShowPassword(false);
        setEditingUsername(null);
    };

    const handleCreateUser = async () => {
        if (!firstName || !lastName || !username || !email) {
            window.otoNotify?.toast('Please fill in all required fields', 'error');
            return;
        }
        if (!roleCanViewAllProperties && properties.length === 0) {
            window.otoNotify?.toast('Please select at least one property', 'error');
            return;
        }
        if (preferredContactMethods.length === 0) {
            window.otoNotify?.toast('Please select at least one contact preference', 'error');
            return;
        }

        const phoneDigits = phone ? phone.replace(/\D/g, '') : '';
        const nextPropertyCodes = roleCanViewAllProperties ? propertyOptions.map(p => p.code).filter(Boolean) : properties;
        const payload = {
            username: editingUsername || username,
            first_name: firstName,
            last_name: lastName,
            email,
            phone: phoneDigits,
            role,
            status: editingUsername ? undefined : 'Active',
            property_codes: nextPropertyCodes,
            preferred_contact_methods: preferredContactMethods
        };

        // When editing, skip API call if nothing changed
        if (editingUsername && selectedUser) {
            const currentPhone = (selectedUser.Phone || '').replace(/\D/g, '');
            const currentProps = [...(selectedUser.PropertyCodes || [])].sort();
            const nextProps = [...nextPropertyCodes].sort();
            const same =
                (selectedUser.FirstName || '') === (firstName || '') &&
                (selectedUser.LastName || '') === (lastName || '') &&
                (selectedUser.Email || '') === (email || '') &&
                currentPhone === phoneDigits &&
                (selectedUser.Role || '') === (role || '') &&
                currentProps.length === nextProps.length &&
                currentProps.every((c, i) => c === nextProps[i]) &&
                (selectedUser.PreferredContactMethods || []).length === preferredContactMethods.length &&
                [...(selectedUser.PreferredContactMethods || [])].sort().join(',') === [...preferredContactMethods].sort().join(',');
            if (same) {
                setShowUserForm(false);
                resetUserForm();
                window.otoNotify?.toast('No changes to save', 'info');
                return;
            }
        }

        try {
            const url = editingUsername ? `/api/staff/${encodeURIComponent(editingUsername)}` : '/api/staff';
            const method = editingUsername ? 'PUT' : 'POST';
            const res = await fetch(url, {
                method,
                headers: { 'Content-Type': 'application/json', ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : {}) },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            if (!res.ok) {
                throw new Error(data.detail || 'Failed to save user');
            }
            const savedUser = mapStaffToUser(data.user, 0);

            // Refresh list for accuracy (status/created/last_login etc)
            await loadData();
            setSelectedUser(savedUser);
            window.otoEvents?.emit('staff-updated');
            if ((savedUser?.Username || editingUsername || username) === currentUsername) {
                window.otoEvents?.emit('current-user-updated');
            }

            if (!editingUsername) {
                // Only show temp password for domain-attached roles (not Corporate IT/Corporate/Administrator)
                const createdRoleToken = normalizeRole(role);
                const isDomainRole = !['corporateit', 'corporate', 'administrator', 'administrators'].includes(createdRoleToken);

                if (isDomainRole) {
                    setShowPassword(true);
                } else {
                    // For Corporate IT/Corporate/Admin, just close form and show the created user
                    setShowUserForm(false);
                    resetUserForm();
                }
            } else {
                setShowUserForm(false);
                resetUserForm();
            }
        } catch (e) {
            window.otoNotify?.toast(e.message || 'Failed to save user', 'error');
        }
    };

    const handleResetPassword = async () => {
        if (!selectedUser) return;
        try {
            const res = await fetch(`/api/staff/${encodeURIComponent(selectedUser.Username)}/send-login`, { method: 'POST', headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : undefined });
            const data = await res.json();
            if (!res.ok) throw new Error(data.detail || 'Failed to send login link');
            window.otoNotify?.toast('Login link and verification code sent to the user\'s email.', 'success');
        } catch (e) {
            window.otoNotify?.toast(e.message || 'Failed to send login link', 'error');
        }
    };

    const handleToggleStatus = async () => {
        if (!selectedUser) return;
        try {
            const res = await fetch(`/api/staff/${encodeURIComponent(selectedUser.Username)}/toggle`, { method: 'POST', headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : undefined });
            const data = await res.json();
            if (!res.ok) throw new Error(data.detail || 'Failed to toggle status');
            const updated = mapStaffToUser(data.user, 0);
            setUsers(prev => prev.map(u => (u.Username === updated.Username ? updated : u)));
            setSelectedUser(updated);
            window.otoEvents?.emit('staff-updated');
            if (selectedUser?.Username === currentUsername) {
                window.otoEvents?.emit('current-user-updated');
            }
        } catch (e) {
            window.otoNotify?.toast(e.message || 'Failed to toggle status', 'error');
        }
    };

    const handleEditUser = () => {
        if (!selectedUser) return;

        setEditingUsername(selectedUser.Username);
        setFirstName(selectedUser.FirstName || '');
        setLastName(selectedUser.LastName || '');
        setUsername(selectedUser.Username || '');
        setEmail(selectedUser.Email || '');
        setPhone(selectedUser.Phone || '');
        setRole(
            selectedUser.Role ||
            ((roleOptions && roleOptions.length) ? roleOptions[0] : 'Front Desk')
        );
        setProperties(selectedUser.PropertyCodes || []);
        setPropertySearch('');
        setPreferredContactMethods(selectedUser.PreferredContactMethods || ['email']);
        setTempPassword('');
        setShowPassword(false);
        setShowUserForm(true);
    };
    const closePasswordDisplay = () => {
        setShowPassword(false);
        setShowUserForm(false);
        resetUserForm();
    };

    // Helper: is this user a global directory contact based at OTO?
    // Prefer backend flag (can_be_global_directory_contact) when present; fallback to roleObjectsMap by Role name.
    const isGlobalDirectoryContact = (user) => {
        const hasFlag = user && (
            user.can_be_global_directory_contact === true ||
            !!(roleObjectsMap[user.Role || ''] && roleObjectsMap[user.Role || ''].can_be_global_directory_contact)
        );
        const codes = Array.isArray(user.PropertyCodes) ? user.PropertyCodes : [];
        const hasOTO = codes.includes('OTO');
        return !!hasFlag && hasOTO;
    };

    const filteredUsers = useMemo(() => users.filter(user => {
        const uLower = (user.Username || '').toLowerCase();
        if (uLower === 'system') return false;
        if (currentUsername && uLower === currentUsername.toLowerCase()) return false;

        // Status filter (special case: "Unassigned" for no property access)
        const userStatus = user.Status;
        const hasAnyProperty = Array.isArray(user.PropertyCodes) && user.PropertyCodes.length > 0;
        let matchesStatus = true;
        if (statusFilter === 'Unassigned') {
            // Only Active users with NO property assignments
            matchesStatus = userStatus === 'Active' && !hasAnyProperty;
        } else if (statusFilter === 'All Users') {
            matchesStatus = true;
        } else {
            matchesStatus = userStatus === statusFilter;
        }

        // Search filter
        const matchesSearch = searchText === '' ||
            user.FirstName.toLowerCase().includes(searchText.toLowerCase()) ||
            user.LastName.toLowerCase().includes(searchText.toLowerCase()) ||
            user.Email.toLowerCase().includes(searchText.toLowerCase()) ||
            user.Username.toLowerCase().includes(searchText.toLowerCase());

        // Property filter - Use selected property from sidebar (ignored when filtering by "Unassigned")
        let matchesProperty = true;
        if (selectedPropertyCode && statusFilter !== 'Unassigned') {
            const userPropertyCodes = Array.isArray(user.PropertyCodes) ? user.PropertyCodes : [];
            const isOtoContact = isGlobalDirectoryContact(user);
            const roleLower = normalizeRole(user.Role || '');
            const isCorporateUser = ['administrator', 'corporateit', 'corporate'].includes(roleLower);

            if (selectedPropertyCode === 'OTO') {
                // Viewing OTO "property":
                // - Show any user explicitly assigned to OTO.
                // - Also show global OTO directory contacts (Corporate IT/Admin with the flag).
                matchesProperty = userPropertyCodes.includes('OTO') || isOtoContact;
            } else if (isCorporateUser) {
                // Viewing a hotel property:
                // - Corporate users should NEVER appear as "hotel staff".
                // - They only appear when they are global OTO contacts AND the toggle is ON.
                matchesProperty = includeOTOContacts && isOtoContact;
            } else {
                // Hotel roles:
                // - Always include users assigned to this hotel.
                // - Global OTO contacts do NOT affect hotel roles; they remain in the hotel list only if assigned.
                matchesProperty = userPropertyCodes.includes(selectedPropertyCode);
            }
        }

        return matchesStatus && matchesSearch && matchesProperty;
    }), [users, statusFilter, searchText, includeOTOContacts, selectedPropertyCode, currentUsername, roleObjectsMap]);

    // Users with no property access (PropertyCodes empty). Surface to admins/user managers so they can assign or disable.
    const usersWithNoPropertyAccess = useMemo(
        () => users.filter(u =>
            // Only care about Active users for this alert/report
            u.Status === 'Active' &&
            (!Array.isArray(u.PropertyCodes) || u.PropertyCodes.length === 0)
        ),
        [users]
    );

    const getStatusBadgeColor = (status) => {
        switch (status) {
            case 'Active': return 'bg-primary/10 text-primary border border-primary/20';
            case 'Disabled': return 'bg-primary/10 text-primary/80 border border-primary/20';
            case 'Locked': return 'bg-red-100 text-red-800 border border-red-200';
            default: return 'bg-primary/10 text-primary border border-primary/20';
        }
    };





    // Contact preference icons (Email / Cell / Text)
    // - "card" variant: fixed-width vertical stack aligned on the dot (great for list cards)
    // - "center" variant: centered vertical stack (great for selected/detail view)
    const ContactPrefIcons = ({ methods, variant = 'card' }) => {
        const prefs = Array.isArray(methods) ? methods : [];
        const isOn = (key) => prefs.includes(key);

        const containerClass =
            variant === 'center'
                ? 'flex flex-col items-center gap-2'
                : 'flex flex-col items-start gap-1.5 w-24';

        const Item = ({ enabled, label, svg }) => (
            <div
                className={variant === 'center'
                    ? 'flex items-center justify-center gap-2'
                    : 'grid grid-cols-[10px_16px_1fr] items-center gap-x-2 w-full'}
                title={label}
            >
                <span className={`w-2 h-2 rounded-full ${enabled ? 'bg-primary' : 'bg-gray-300'}`} />
                <svg className={`w-4 h-4 ${enabled ? 'text-gray-800' : 'text-gray-400'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    {svg}
                </svg>
                <span className={`${variant === 'center' ? 'text-sm' : 'text-xs'} ${enabled ? 'text-gray-800' : 'text-gray-400'}`}>{label}</span>
            </div>
        );

        return (
            <div className={containerClass}>
                <Item
                    enabled={isOn('email')}
                    label="Email"
                    svg={<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 6h14a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2z" />}
                />
                <Item
                    enabled={isOn('call')}
                    label="Cell"
                    svg={<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2 5.5A2.5 2.5 0 014.5 3h2.2a2 2 0 011.8 1.1l1.1 2.2a2 2 0 01-.5 2.3l-1 1c1.2 2.4 3.2 4.4 5.6 5.6l1-1a2 2 0 012.3-.5l2.2 1.1A2 2 0 0121 18.4v2.1A2.5 2.5 0 0118.5 23C9.4 23 2 15.6 2 6.5V5.5z" />}
                />
                <Item
                    enabled={isOn('text')}
                    label="Text"
                    svg={<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h8m-8 4h6m-6 6l-4-4H4a2 2 0 01-2-2V6a2 2 0 012-2h16a2 2 0 012 2v8a2 2 0 01-2 2h-6l-4 4z" />}
                />
            </div>
        );
    };


    return (
        <div className="flex h-full">
            <div className="w-[500px] border-r border-slate-200 bg-white flex flex-col">
                <div className="p-6 border-b border-gray-200">
                    <div className="flex items-center justify-between mb-4">
                        <h2 className="text-xl font-bold text-gray-800">Directory</h2>
                        {canCreateUsers && (
                            <button
                                onClick={() => { resetUserForm(); setShowUserForm(true); }}
                                className="bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded-lg font-semibold transition-colors text-sm"
                            >
                                + Create User
                            </button>
                        )}
                    </div>

                    <div className="space-y-3">
                        {/* Show OTO toggle only when viewing a hotel property */}
                        {selectedPropertyCode && selectedPropertyCode !== 'OTO' && (
                            <div className="bg-primary/5 border-2 border-primary/20 rounded-xl p-4 shadow-sm">
                                <div className="flex items-center justify-between gap-4">
                                    <div className="flex items-center gap-3">
                                        <div className="bg-primary/15 rounded-lg p-2">
                                            <svg className="w-5 h-5 text-primary" fill="currentColor" viewBox="0 0 20 20">
                                                <path fillRule="evenodd" d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a1 1 0 110 2h-3a1 1 0 01-1-1v-2a1 1 0 00-1-1H9a1 1 0 00-1 1v2a1 1 0 01-1 1H4a1 1 0 110-2V4zm3 1h2v2H7V5zm2 4H7v2h2V9zm2-4h2v2h-2V5zm2 4h-2v2h2V9z" clipRule="evenodd" />
                                            </svg>
                                        </div>
                                        <div>
                                            <div className="text-base font-bold text-gray-900">OTO Development</div>
                                            <div className="text-sm text-gray-600 mt-0.5">Would you like to include OTO contacts?</div>
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => setIncludeOTOContacts(!includeOTOContacts)}
                                        className={`
                                                    relative inline-flex h-8 w-16 items-center rounded-full transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2
                                                    ${includeOTOContacts ? 'bg-primary' : 'bg-gray-300'}
                                                `}
                                    >
                                        <span
                                            className={`
                                                        inline-block h-6 w-6 transform rounded-full bg-white shadow-lg transition-transform duration-200 ease-in-out
                                                        ${includeOTOContacts ? 'translate-x-9' : 'translate-x-1'}
                                                    `}
                                        />
                                    </button>
                                </div>
                                <div className={`mt-3 text-sm font-semibold transition-colors flex items-center gap-1.5 ${includeOTOContacts ? 'text-primary' : 'text-gray-500'}`}>
                                    <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                        {includeOTOContacts ? (
                                            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                        ) : (
                                            <path fillRule="evenodd" clipRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm2.83-10.83a1 1 0 00-1.41 0L10 8.59 8.59 7.17a1 1 0 10-1.41 1.41L8.59 10l-1.41 1.41a1 1 0 101.41 1.41L10 11.41l1.41 1.41a1 1 0 001.41-1.41L11.41 10l1.42-1.42a1 1 0 000-1.41z" />
                                        )}
                                    </svg>
                                    {includeOTOContacts ? 'Showing Hotel + OTO Contacts' : 'Showing Hotel Contacts Only'}
                                </div>
                            </div>
                        )}

                        <select
                            value={canViewDisabledUsers ? statusFilter : 'Active'}
                            onChange={(e) => setStatusFilter(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                        >
                            <option value="Active">Active</option>
                            {canViewDisabledUsers && (
                                <>
                                    <option value="All Users">All Users</option>
                                    <option value="Disabled">Disabled</option>
                                </>
                            )}
                            {canSeeUsersWithoutPropertyAccess && (
                                <option value="Unassigned">
                                    No Property Access
                                    {usersWithNoPropertyAccess.length
                                        ? ` (${usersWithNoPropertyAccess.length})`
                                        : ''}
                                </option>
                            )}
                        </select>

                        <input
                            type="text"
                            placeholder="Search (name, email, username)"
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                        />
                    </div>
                </div>

                {canSeeUsersWithoutPropertyAccess && usersWithNoPropertyAccess.length > 0 && statusFilter !== 'Unassigned' && (
                    <div className="mx-4 mt-3 px-4 py-2.5 bg-amber-50 border border-amber-200 rounded-lg flex items-center justify-between">
                        <div className="flex items-center gap-2 text-sm text-amber-800">
                            <svg className="w-4 h-4 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" /></svg>
                            <span><strong>{usersWithNoPropertyAccess.length}</strong> active user{usersWithNoPropertyAccess.length !== 1 ? 's have' : ' has'} no property access.</span>
                        </div>
                        <button
                            type="button"
                            onClick={() => setStatusFilter('Unassigned')}
                            className="text-sm font-semibold text-amber-700 hover:text-amber-900 underline underline-offset-2 flex-shrink-0"
                        >
                            View
                        </button>
                    </div>
                )}

                <div className="flex-1 overflow-y-auto p-4 space-y-3 scrollbar-thin">
                    {isLoading ? (
                        <div className="text-sm text-gray-500 p-4">Loading users…</div>
                    ) : loadError ? (
                        <div className="text-sm text-red-600 p-4">{loadError}</div>
                    ) : filteredUsers.length === 0 ? (
                        <div className="text-sm text-gray-500 p-4">No users found.</div>
                    ) : (() => {
                        const isHotelContext = !!(selectedPropertyCode && selectedPropertyCode !== 'OTO');
                        const isSplit = !!(includeOTOContacts && isHotelContext);

                        const isCorp = (u) => {
                            // "OTO Contacts" should be global directory contacts based at OTO.
                            return isGlobalDirectoryContact(u);
                        };

                        const corporateUsers = isSplit ? filteredUsers.filter(isCorp) : [];
                        const hotelUsers = isSplit ? filteredUsers.filter(u => !isCorp(u)) : filteredUsers;

                        const renderUserCard = (user) => (
                            <div
                                key={user.Username || user.UserID}
                                onClick={() => { setSelectedUser(user); setShowUserForm(false); }}
                                className={`relative p-4 rounded-xl border-2 cursor-pointer transition-all ${selectedUser?.Username === user.Username
                                        ? 'border-primary bg-primary/5'
                                        : 'border-gray-200 bg-white hover:border-gray-300'
                                    } ${user.Status === 'Locked' ? 'opacity-60' : ''}`}
                            >
                                <div className="flex items-start justify-between gap-4">
                                    <div className="min-w-0 flex-1">
                                        <div className="flex items-center gap-2">
                                            <div className="font-semibold text-gray-900 mb-1 truncate">
                                                {user.FirstName} {user.LastName}
                                            </div>
                                        </div>
                                        <div className="text-xs text-gray-600 flex items-center gap-1.5">
                                            <span className="truncate">{user.Username} — {user.Role}</span>
                                        </div>
                                        <div className="text-xs text-gray-500 mt-1 truncate">{user.Email}</div>
                                    </div>

                                    <div className="flex flex-col items-end gap-2 flex-shrink-0">
                                        <span className={`text-xs px-2 py-1 rounded-full font-medium ${getStatusBadgeColor(user.Status)}`}>
                                            {user.Status}
                                        </span>
                                        {statusFilter === 'Unassigned' && (
                                            <span className="text-xs px-2 py-0.5 rounded-full font-medium bg-amber-100 text-amber-700">
                                                No Properties
                                            </span>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );

                        if (!isSplit) {
                            return hotelUsers.map(u => renderUserCard(u));
                        }

                        return (
                            <div className="space-y-3">
                                {corporateUsers.length > 0 && (
                                    <div className="px-3 py-2 rounded-lg border border-primary/20 bg-gradient-to-r from-primary/10 to-primary/5">
                                        <div className="flex items-center justify-between">
                                            <div className="text-sm font-semibold text-gray-900">OTO Contacts</div>
                                            <div className="text-xs text-gray-600">{corporateUsers.length}</div>
                                        </div>
                                        <div className="text-xs text-gray-600 mt-0.5">Corporate IT & Administrators (quick access)</div>
                                    </div>
                                )}

                                {corporateUsers.map(u => renderUserCard(u))}

                                {hotelUsers.length > 0 && corporateUsers.length > 0 && (
                                    <div className="pt-1">
                                        <div className="px-3 py-2 rounded-lg border border-slate-200 bg-slate-50">
                                            <div className="flex items-center justify-between">
                                                <div className="text-sm font-semibold text-gray-900">Hotel Users</div>
                                                <div className="text-xs text-gray-600">{hotelUsers.length}</div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {hotelUsers.map(u => renderUserCard(u))}
                            </div>
                        );
                    })()}
                </div>
            </div>

            <div className="flex-1 bg-surface overflow-y-auto scrollbar-thin">
                {showUserForm ? (
                    <div className="p-8">
                        {/* UPDATED VERSION - Contact Preferences Added */}
                        <div className="max-w-3xl mx-auto bg-white rounded-xl border border-slate-200 p-8">
                            <div className="flex items-center justify-between mb-6">
                                <h2 className="text-2xl font-bold text-gray-800">
                                    {editingUsername ? 'Edit User' : 'Create User'}
                                </h2>
                                <button
                                    onClick={() => { resetUserForm(); setShowUserForm(false); }}
                                    className="text-gray-500 hover:text-gray-700"
                                >
                                    Back
                                </button>
                            </div>

                            <div className="space-y-6">
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            First Name <span className="text-red-500">*</span>
                                        </label>
                                        <input
                                            type="text"
                                            value={firstName}
                                            onChange={(e) => setFirstName(e.target.value)}
                                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            Last Name <span className="text-red-500">*</span>
                                        </label>
                                        <input
                                            type="text"
                                            value={lastName}
                                            onChange={(e) => setLastName(e.target.value)}
                                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                        />
                                    </div>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        Username {!editingUsername && (<span className="text-red-500">*</span>)}
                                    </label>
                                    <input
                                        type="text"
                                        value={username}
                                        onChange={(e) => setUsername(e.target.value)}
                                        disabled={!!editingUsername}
                                        className={`w-full border border-gray-300 rounded-lg px-4 py-2 ${editingUsername ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : ''
                                            }`}
                                    />
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        Email Address {!editingUsername && (<span className="text-red-500">*</span>)}
                                    </label>
                                    <input
                                        type="email"
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                        disabled={!!editingUsername}
                                        className={`w-full border border-gray-300 rounded-lg px-4 py-2 ${editingUsername ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : ''}`}
                                    />
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        Phone Number
                                    </label>
                                    <input
                                        type="tel"
                                        value={phone}
                                        onChange={handlePhoneChange}
                                        className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                    />
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-3">
                                        Contact Preferences
                                    </label>
                                    <div className="space-y-3">
                                        {/* Email Checkbox */}
                                        <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-lg hover:border-primary/30 cursor-pointer transition-all group">
                                            <input
                                                type="checkbox"
                                                checked={preferredContactMethods.includes('email')}
                                                onChange={(e) => {
                                                    if (e.target.checked) {
                                                        setPreferredContactMethods([...preferredContactMethods, 'email']);
                                                    } else {
                                                        setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'email'));
                                                    }
                                                }}
                                                style={{ accentColor: "#172C56" }}
                                                className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20"
                                            />
                                            <div className="flex items-center gap-2 flex-1">
                                                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                </svg>
                                                <span className="font-medium text-gray-900">Email</span>
                                            </div>
                                        </label>

                                        {/* Phone Call Checkbox */}
                                        <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-lg hover:border-primary/30 cursor-pointer transition-all group">
                                            <input
                                                type="checkbox"
                                                checked={preferredContactMethods.includes('call')}
                                                onChange={(e) => {
                                                    if (e.target.checked) {
                                                        setPreferredContactMethods([...preferredContactMethods, 'call']);
                                                    } else {
                                                        setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'call'));
                                                    }
                                                }}
                                                style={{ accentColor: "#172C56" }}
                                                className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20"
                                            />
                                            <div className="flex items-center gap-2 flex-1">
                                                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                </svg>
                                                <span className="font-medium text-gray-900">Phone Call</span>
                                            </div>
                                        </label>

                                        {/* Text Message Checkbox */}
                                        <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-lg hover:border-primary/30 cursor-pointer transition-all group">
                                            <input
                                                type="checkbox"
                                                checked={preferredContactMethods.includes('text')}
                                                onChange={(e) => {
                                                    if (e.target.checked) {
                                                        setPreferredContactMethods([...preferredContactMethods, 'text']);
                                                    } else {
                                                        setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'text'));
                                                    }
                                                }}
                                                style={{ accentColor: "#172C56" }}
                                                className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20"
                                            />
                                            <div className="flex items-center gap-2 flex-1">
                                                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                                                </svg>
                                                <span className="font-medium text-gray-900">Text Message</span>
                                            </div>
                                        </label>
                                    </div>
                                    {preferredContactMethods.length === 0 && (
                                        <p className="text-sm text-amber-600 mt-2 flex items-center gap-1">
                                            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                                            </svg>
                                            Select at least one contact method
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        Role <span className="text-red-500">*</span>
                                    </label>
                                    <select
                                        value={role}
                                        onChange={handleRoleChange}
                                        className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                    >
                                        {roleOptionsWithCurrent
                                            .filter(opt => normalizeRole(opt) !== 'system')
                                            .filter(opt => canManageRole(opt))
                                            .map(opt => (
                                                <option key={opt} value={opt}>{opt}</option>
                                            ))
                                        }
                                    </select>
                                </div>

                                {!roleCanViewAllProperties && (
                                    <div>
                                        <label className="block text-sm font-semibold text-gray-700 mb-3">
                                            Properties <span className="text-red-500">*</span>
                                        </label>

                                        <input
                                            type="text"
                                            value={propertySearch}
                                            onChange={(e) => setPropertySearch(e.target.value)}
                                            placeholder="Search properties..."
                                            className="w-full border-2 border-gray-200 rounded-lg px-4 py-2 mb-3 text-sm focus:outline-none focus:border-primary"
                                        />
                                        <div className="max-h-64 overflow-y-auto border-2 border-slate-200 rounded-lg p-3 bg-slate-50 scrollbar-thin">
                                            <div className="grid grid-cols-2 gap-3">
                                                {propertyOptions
                                                    .filter(property => {
                                                        const matches = property.code.toLowerCase().includes(propertySearch.toLowerCase()) ||
                                                            property.name.toLowerCase().includes(propertySearch.toLowerCase());
                                                        if (!matches) return false;
                                                        // Hotel roles: show manageable + already assigned (read-only)
                                                        return canManageProperty(property.code) || properties.includes(property.code);
                                                    })
                                                    .map(property => (
                                                        <button
                                                            key={property.code}
                                                            type="button"
                                                            onClick={() => toggleProperty(property.code)}
                                                            disabled={!canManageProperty(property.code)}
                                                            className={`p-3 rounded-lg border-2 text-left transition-all ${!canManageProperty(property.code) ? 'opacity-60 cursor-not-allowed' : 'hover:shadow-sm'} ${properties.includes(property.code)
                                                                ? 'border-primary bg-primary/5 shadow-sm'
                                                                : 'border-gray-200 hover:border-primary/30'
                                                                }`}
                                                        >
                                                            <div className="flex items-start justify-between gap-2">
                                                                <div className="flex-1 min-w-0">
                                                                    <div className="font-bold text-sm text-gray-900 truncate">{property.code}</div>
                                                                    <div className="text-xs text-gray-600 mt-0.5 line-clamp-2">{property.name}</div>
                                                                </div>
                                                                <div className={`flex-shrink-0 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${properties.includes(property.code) ? 'border-primary bg-primary' : 'border-gray-300'}`}>
                                                                    {properties.includes(property.code) ? (
                                                                        <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                                                                        </svg>
                                                                    ) : (!canManageProperty(property.code) && (
                                                                        <svg className="w-3 h-3 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 11c1.105 0 2 .895 2 2v3H10v-3c0-1.105.895-2 2-2zm6 2v5a2 2 0 01-2 2H8a2 2 0 01-2-2v-5a2 2 0 012-2h1V9a3 3 0 016 0v2h1a2 2 0 012 2z" />
                                                                        </svg>
                                                                    ))}
                                                                </div>
                                                            </div>
                                                        </button>
                                                    ))}
                                            </div>
                                        </div>
                                        {properties.length === 0 && (
                                            <p className="text-sm text-gray-500 mt-2">Select at least one property</p>
                                        )}
                                    </div>
                                )}

                                {showPassword && tempPassword && (
                                    <div className="bg-primary/5 border-2 border-primary/20 rounded-lg p-4">
                                        <div className="flex items-start gap-3">
                                            <div className="flex-shrink-0 text-primary text-2xl">🔑</div>
                                            <div className="flex-1">
                                                <h4 className="font-semibold text-primary mb-2">User Created Successfully!</h4>
                                                <p className="text-sm text-primary mb-3">
                                                    First-Time Login Password (user must change on first login):
                                                </p>
                                                <div className="bg-white border border-primary/20 rounded px-4 py-3 font-mono text-lg font-semibold text-gray-900 mb-3">
                                                    {tempPassword}
                                                </div>
                                                <p className="text-xs text-primary">
                                                    This password will only be shown once. Please save it securely.
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                <div className="flex gap-3 justify-end">
                                    <button
                                        onClick={() => { resetUserForm(); setShowUserForm(false); }}
                                        className="px-6 py-2 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
                                    >
                                        {showPassword ? 'Close' : 'Cancel'}
                                    </button>
                                    {!showPassword && (
                                        <button
                                            onClick={handleCreateUser}
                                            className="px-6 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors"
                                        >
                                            {editingUsername ? 'Save Changes' : 'Create User'}
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                ) : selectedUser ? (
                    <div className="p-8">
                        <div className="max-w-2xl mx-auto space-y-6">
                            <div className="bg-white rounded-xl border border-gray-200 p-8 text-center">
                                <div className="w-24 h-24 bg-primary rounded-full flex items-center justify-center text-white text-3xl font-bold mx-auto mb-4">
                                    {(selectedUser.FirstName?.[0] || '?')}{(selectedUser.LastName?.[0] || '?')}
                                </div>
                                <h2 className="text-2xl font-bold text-gray-800">
                                    {selectedUser.FirstName} {selectedUser.LastName}
                                </h2>
                                <p className="text-gray-600 text-sm mt-1">@{selectedUser.Username}</p>


                                <div className="mt-4 flex flex-col items-center text-center">
                                    <span className={`inline-block px-2 py-1 rounded text-xs font-semibold ${getStatusBadgeColor(selectedUser.Status)}`}>
                                        {selectedUser.Status}
                                    </span>

                                    <div className="mt-3 text-xs font-semibold text-gray-500">
                                        Preferred Contact Method(s):
                                    </div>

                                    <div className="mt-2">
                                        <ContactPrefIcons methods={selectedUser.PreferredContactMethods} variant="center" />
                                    </div>
                                </div>
                            </div>

                            <div className="bg-white rounded-xl border border-gray-200 p-6">
                                <h3 className="font-semibold text-gray-800 mb-4">Account Information</h3>
                                <div className="space-y-3 text-sm">
                                    <div className="flex"><span className="text-gray-600 w-32">Email:</span><span className="text-gray-800">{selectedUser.Email}</span></div>
                                    <div className="flex"><span className="text-gray-600 w-32">Phone:</span><span className="text-gray-800">{selectedUser.Phone}</span></div>
                                    <div className="flex"><span className="text-gray-600 w-32">Role:</span><span className="text-gray-800">{selectedUser.Role}</span></div>
                                    <div className="flex"><span className="text-gray-600 w-32">Created:</span><span className="text-gray-800">{formatDate(selectedUser.Created)}</span></div>
                                    <div className="flex"><span className="text-gray-600 w-32">Last Login:</span><span className="text-gray-800">{selectedUser.LastLogin ? formatDate(selectedUser.LastLogin) : 'Never'}</span></div>
                                </div>
                            </div>

                            {selectedUser.Status !== 'Locked' && canEditUsers && canManageRole(selectedUser.Role) && (
                                <div className="bg-white rounded-xl border border-gray-200 p-6">
                                    <h3 className="font-semibold text-gray-800 mb-4">Account Actions</h3>
                                    <div className="space-y-3">
                                        {canResetPasswords && (() => {
                                            const tok = normalizeRole(selectedUser.Role);
                                            if (tok === 'corporateit' || tok === 'corporate' || tok === 'administrator' || tok === 'administrators' || tok === 'system') return null;
                                            return (
                                                <button
                                                    onClick={handleResetPassword}
                                                    className="w-full px-6 py-3 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
                                                >
                                                    Reset Password
                                                </button>
                                            );
                                        })()}
                                        {canToggleStatus && (
                                            <button
                                                onClick={handleToggleStatus}
                                                className="w-full px-6 py-3 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
                                            >
                                                {selectedUser.Status === 'Active' ? 'Disable Account' : 'Enable Account'}
                                            </button>
                                        )}
                                        <button
                                            onClick={handleEditUser}
                                            className="w-full px-6 py-3 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
                                        >
                                            Edit User Details
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                ) : null}
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.AccessManagementView = AccessManagementView;