const PropertiesManagementModal = ({ isOpen, onClose, currentUser, selectedPropertyContext, onPropertyChange, onDataChange }) => {
    const { useState, useEffect, useRef } = React;
    const TagsInput = window.TagsInput;
    // ═══════════════════════════════════════════════════════════════════════════
    // STATE MANAGEMENT
    // ═══════════════════════════════════════════════════════════════════════════

    const [properties, setProperties] = useState([]);
    const [selectedProperty, setSelectedProperty] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [loadError, setLoadError] = useState('');
    const [searchText, setSearchText] = useState('');

    // Active Tab: 'details', 'vendors', 'venues', or 'statistics' (for OTO)
    const [activeTab, setActiveTab] = useState('details');

    // OTO Statistics State
    const [otoStats, setOtoStats] = useState(null);
    const [loadingOtoStats, setLoadingOtoStats] = useState(false);
    const [overviewPropertiesDetail, setOverviewPropertiesDetail] = useState(null); // 'active' | 'owned' | 'managed' — which properties list to show in modal

    // Property Details State
    const [isEditingDetails, setIsEditingDetails] = useState(false);
    const [isSavingDetails, setIsSavingDetails] = useState(false);
    const [saveMessage, setSaveMessage] = useState({ type: '', text: '' });
    const [editPhone, setEditPhone] = useState('');
    const [editGMUsername, setEditGMUsername] = useState('');
    const [editAbbreviation, setEditAbbreviation] = useState('');
    const [editIsOwned, setEditIsOwned] = useState(false);
    const [editIsManagedByOto, setEditIsManagedByOto] = useState(false);
    const [editAmenities, setEditAmenities] = useState([]);
    const [editAmenitiesVenue, setEditAmenitiesVenue] = useState([]);
    const [isEditingAmenities, setIsEditingAmenities] = useState(false);
    const [savingAmenities, setSavingAmenities] = useState(false);
    const [eligibleManagers, setEligibleManagers] = useState([]);
    const [loadingManagers, setLoadingManagers] = useState(false);

    // Vendors State
    const [vendors, setVendors] = useState([]);
    const [loadingVendors, setLoadingVendors] = useState(false);

    // Vendor catalog (system-wide vendors + vendor services)
    const [allVendors, setAllVendors] = useState([]);
    const [vendorServices, setVendorServices] = useState([]);
    const [loadingVendorCatalog, setLoadingVendorCatalog] = useState(false);

    // Editing state:
    // mode: 'add' (assign to property), 'edit' (change assignment), 'details' (edit vendor service details)
    const [editingVendor, setEditingVendor] = useState(null); // { mode, pvs_id, vendor_service_id, vendor_id, service, phone, email, url, notes, new_vendor_name, new_service_name, service_select_id }
    const [isSavingVendor, setIsSavingVendor] = useState(false);
    const [vendorSaveMessage, setVendorSaveMessage] = useState({ type: '', text: '' });

    // Dining Venues State
    const [venues, setVenues] = useState([]);
    const [venuesLoading, setVenuesLoading] = useState(false);
    const [restaurants, setRestaurants] = useState([]);
    const [restaurantsLoading, setRestaurantsLoading] = useState(false);
    const [selectedConceptId, setSelectedConceptId] = useState('');
    const [conceptSearch, setConceptSearch] = useState('');

    const [editingVenue, setEditingVenue] = useState(null);
    const [savingVenue, setSavingVenue] = useState(false);

    const [addingConcept, setAddingConcept] = useState(false);
    const [newConceptName, setNewConceptName] = useState('');
    const [newConceptDescription, setNewConceptDescription] = useState('');
    const [savingConcept, setSavingConcept] = useState(false);
    const [deletingConceptId, setDeletingConceptId] = useState(null);
    const [conceptNameSuggestions, setConceptNameSuggestions] = useState([]);
    const newConceptNameInputRef = useRef(null);

    // Add Property
    const [showAddProperty, setShowAddProperty] = useState(false);
    const [newPropertyCode, setNewPropertyCode] = useState('');
    const [newPropertyName, setNewPropertyName] = useState('');
    const [newPropertyAddress, setNewPropertyAddress] = useState('');
    const [newPropertyCity, setNewPropertyCity] = useState('');
    const [newPropertyState, setNewPropertyState] = useState('');
    const [newPropertyZip, setNewPropertyZip] = useState('');
    const [savingNewProperty, setSavingNewProperty] = useState(false);
    const [addPropertyError, setAddPropertyError] = useState('');

    const currentUsername = currentUser?.Username || currentUser?.username || '';

    // Permission checks from actual permission flags
    const isPrivileged = !!currentUser?.can_manage_properties;
    const canEditDetails = !!currentUser?.can_edit_property_details;
    const canManageVendors = !!currentUser?.can_manage_vendors;
    const canManageDiningVenues = !!currentUser?.can_manage_venues || !!currentUser?.can_edit_dining_concepts;
    const canSeeAllProperties = isPrivileged || !!currentUser?.can_view_all_properties;
    const canAddProperties = window.canAddProperties ? window.canAddProperties(currentUser) : !!(currentUser?.can_manage_properties && currentUser?.can_add_properties);

    const displayedVenues = selectedConceptId
        ? (venues || []).filter(v => String(v?.restaurant_id || '') === String(selectedConceptId))
        : (venues || []);


    // Predefined amenity options (selection box, not free-text)
    const AMENITY_OPTIONS = [
        'Pool', 'Fitness Center', 'Beach Access', 'Free WiFi', 'Restaurant', 'Bar', 'Spa',
        'Parking', 'Business Center', 'Pet Friendly', 'Room Service', 'Concierge', 'Laundry'
    ];

    // Vendor Categories
    const VENDOR_CATEGORIES = [
        { value: 'hsia', label: 'HSIA (Guest Internet)' },
        { value: 'back_office_internet', label: 'Back Office Internet' },
        { value: 'guest_internet', label: 'Guest Internet Provider' },
        { value: 'pos', label: 'Point of Sale' },
        { value: 'av', label: 'Audio/Visual' },
        { value: 'phone', label: 'Phone System' },
        { value: 'tv', label: 'TV/Entertainment' },
        { value: 'music', label: 'Hotel Music' },
        { value: 'key_system', label: 'Key Management System' },
        { value: 'pms', label: 'Property Management System' },
        { value: 'hvac', label: 'HVAC Controls' },
        { value: 'fire_safety', label: 'Fire & Life Safety' }
    ];

    // ═══════════════════════════════════════════════════════════════════════════
    // UTILITIES
    // ═══════════════════════════════════════════════════════════════════════════

    const formatPhone = (value) => {
        if (!value) return '';
        const digits = String(value).replace(/\D/g, '');
        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 formatPhoneForDisplay = (phone) => {
        if (!phone) return '';
        const cleaned = String(phone).replace(/\D/g, '');
        if (cleaned.length !== 10) return String(phone);
        return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6, 10)}`;
    };

    const handlePhoneChange = (e) => {
        const digits = e.target.value.replace(/\D/g, '').slice(0, 10);
        setEditPhone(formatPhone(digits));
    };

    const getCategoryLabel = (category) => {
        const cat = VENDOR_CATEGORIES.find(c => c.value === category);
        return cat ? cat.label : category;
    };

    // ═══════════════════════════════════════════════════════════════════════════
    // DATA LOADING
    // ═══════════════════════════════════════════════════════════════════════════

    const loadOtoStatistics = async () => {
        try {
            setLoadingOtoStats(true);
            const response = await fetch('/api/statistics/oto', {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (response.ok) {
                const data = await response.json();
                setOtoStats(data);
            }
        } catch (err) {
            console.error('Error loading OTO statistics:', err);
        } finally {
            setLoadingOtoStats(false);
        }
    };

    // Load OTO stats when statistics tab is active
    useEffect(() => {
        if (activeTab === 'statistics' && selectedProperty?.code === 'OTO' && !otoStats) {
            loadOtoStatistics();
        }
    }, [activeTab, selectedProperty]);

    const loadProperties = async () => {
        try {
            setIsLoading(true);
            setLoadError('');
            const response = await fetch('/api/properties/management', {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.detail || 'Failed to load properties');
            }
            const data = await response.json();
            setProperties(data.properties || []);

            // Initialize with selectedPropertyContext if available, otherwise first property
            if (selectedPropertyContext && data.properties?.some(p => p.code === selectedPropertyContext.property_code)) {
                const contextProperty = data.properties.find(p => p.code === selectedPropertyContext.property_code);
                setSelectedProperty(contextProperty);
            } else if (data.properties?.length > 0 && !selectedProperty) {
                setSelectedProperty(data.properties[0]);
            }
        } catch (err) {
            setLoadError(err.message || 'Failed to load properties');
        } finally {
            setIsLoading(false);
        }
    };

    const loadSingleProperty = async () => {
        try {
            setIsLoading(true);
            setLoadError('');
            const code = selectedPropertyContext?.property_code || currentUser?.properties?.[0]?.property_code;
            if (!code) {
                setProperties([]);
                setSelectedProperty(null);
                setLoadError('No property is associated with this account.');
                return;
            }

            const response = await fetch(`/api/properties/${code}/details`, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.detail || 'Failed to load property');
            const prop = data.property;
            setProperties([prop]);
            setSelectedProperty(prop);
        } catch (err) {
            setLoadError(err.message || 'Failed to load property');
        } finally {
            setIsLoading(false);
        }
    };

    const loadEligibleManagers = async (propertyCode) => {
        try {
            setLoadingManagers(true);
            const response = await fetch(`/api/properties/${propertyCode}/eligible-managers`, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to load eligible managers');
            const data = await response.json();
            // Debug: log raw response so we can see what's coming back from the API
            console.log('[OTO DEBUG] Eligible managers response', { propertyCode, data });
            setEligibleManagers(data.managers || []);
        } catch (err) {
            console.error('[OTO DEBUG] Error loading eligible managers', { propertyCode, error: err });
            setEligibleManagers([]);
        } finally {
            setLoadingManagers(false);
        }
    };

    const loadVendors = async (propertyCode) => {
        if (!propertyCode) return;
        try {
            setLoadingVendors(true);
            const response = await fetch(`/api/properties/${propertyCode}/vendor-services`, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to load vendor services');
            const data = await response.json();
            setVendors(data.vendor_services || []);
        } catch (err) {
            console.error('Error loading vendor services:', err);
            setVendors([]);
        } finally {
            setLoadingVendors(false);
        }
    };
    const loadAllVendors = async () => {
        try {
            setLoadingVendorCatalog(true);
            const response = await fetch('/api/vendors', {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to load vendors');
            const data = await response.json();
            setAllVendors(data.vendors || []);
        } catch (err) {
            console.error('Error loading vendors:', err);
            setAllVendors([]);
        } finally {
            setLoadingVendorCatalog(false);
        }
    };

    const loadServicesForVendor = async (vendorId) => {
        if (!vendorId) { setVendorServices([]); return; }
        try {
            setLoadingVendorCatalog(true);
            const response = await fetch(`/api/vendors/${vendorId}/services`, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to load vendor services');
            const data = await response.json();
            setVendorServices(data.services || []);
        } catch (err) {
            console.error('Error loading vendor services:', err);
            setVendorServices([]);
        } finally {
            setLoadingVendorCatalog(false);
        }
    };

    const loadVenues = async (propertyCode) => {
        if (!propertyCode) return;
        try {
            setVenuesLoading(true);

            const response = await fetch(`/api/properties/${propertyCode}/venues`, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });

            // Surface any backend error text in console (helps when the API returns non-JSON errors)
            if (!response.ok) {
                let detail = '';
                try {
                    const errJson = await response.json();
                    detail = errJson?.detail ? `: ${errJson.detail}` : '';
                } catch (_) {
                    try { detail = `: ${await response.text()}`; } catch (_) { }
                }
                throw new Error(`Failed to load venues${detail}`);
            }

            const data = await response.json();

            // Be tolerant to different response shapes:
            // - { venues: [...] }
            // - { items: [...] }
            // - [...] (array)
            // - { data: [...] }
            let venuesList = [];
            if (Array.isArray(data)) {
                venuesList = data;
            } else if (Array.isArray(data?.venues)) {
                venuesList = data.venues;
            } else if (Array.isArray(data?.items)) {
                venuesList = data.items;
            } else if (Array.isArray(data?.data)) {
                venuesList = data.data;
            } else if (Array.isArray(data?.results)) {
                venuesList = data.results;
            }

            // If the backend returns venues across multiple properties, filter client-side.
            const filtered = (venuesList || []).filter(v => {
                const pc = v?.property_code || v?.propertyCode || v?.property || v?.property_id || v?.propertyId;
                // If there's no property field at all, keep it (assume API already filtered).
                if (pc == null) return true;
                return String(pc).toUpperCase() === String(propertyCode).toUpperCase();
            });

            // Normalize restaurant name if backend returns restaurant_id instead of restaurant_name
            const normalized = filtered.map(v => {
                const restaurantId = v?.restaurant_id ?? v?.restaurantId ?? v?.restaurant;
                const restaurantName =
                    v?.restaurant_name ??
                    v?.restaurantName ??
                    (restaurantId != null ? (restaurants.find(r => String(r.id) === String(restaurantId))?.name || '') : '');

                return {
                    ...v,
                    restaurant_id: restaurantId ?? v?.restaurant_id,
                    restaurant_name: restaurantName
                };
            });

            setVenues(normalized);
        } catch (err) {
            console.error('Error loading venues:', err);
            setVenues([]);
        } finally {
            setVenuesLoading(false);
        }
    };

    const loadRestaurants = async (propertyCode = null) => {
        try {
            setRestaurantsLoading(true);
            const url = propertyCode ? `/api/restaurants?property_code=${encodeURIComponent(propertyCode)}` : '/api/restaurants';
            const response = await fetch(url, {
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to load restaurants');
            const data = await response.json();
            setRestaurants(data.restaurants || []);
        } catch (err) {
            console.error('🔴 Error loading restaurants:', err);
            setRestaurants([]);
        } finally {
            setRestaurantsLoading(false);
        }
    };

    const handleSaveVenue = async () => {
        if (!selectedProperty || !editingVenue) return;
        try {
            setSavingVenue(true);
            const method = editingVenue.mode === 'add' ? 'POST' : 'PUT';
            const url = editingVenue.mode === 'add'
                ? `/api/properties/${selectedProperty.code}/venues`
                : `/api/venues/${editingVenue.id}`;

            const featuresFlat = {};
            const predefinedIds = ['self_pour_system'];
            Object.entries(editingVenue.features || {}).forEach(([k, f]) => {
                if (predefinedIds.includes(k) && typeof f === 'string') {
                    if (f.trim()) featuresFlat[k] = f.trim();
                } else if (f && typeof f === 'object' && (f.key || f.value)) {
                    const key = String(f.key || '').trim();
                    if (key) featuresFlat[key] = String(f.value || '');
                }
            });
            const payload = {
                restaurant_id: editingVenue.restaurant_id ? parseInt(editingVenue.restaurant_id, 10) : null,
                name: editingVenue.name,
                type: editingVenue.type,
                links: editingVenue.links || {},
                features: featuresFlat,
                vendor_ids: Array.isArray(editingVenue.vendor_ids) ? editingVenue.vendor_ids : (editingVenue.vendors || []).map(v => v.id)
            };

            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUsername
                },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Failed to save venue');
            }

            setEditingVenue(null);
            await loadVenues(selectedProperty.code);
            if (onDataChange) onDataChange('venues');
        } catch (err) {
            console.error('Error saving venue:', err);
            alert('Error: ' + err.message);
        } finally {
            setSavingVenue(false);
        }
    };

    const handleDeleteVenue = async (venueId) => {
        if (!confirm('Delete this venue? This cannot be undone.')) return;
        try {
            const response = await fetch(`/api/venues/${venueId}`, {
                method: 'DELETE',
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) throw new Error('Failed to delete venue');
            await loadVenues(selectedProperty.code);
            if (onDataChange) onDataChange('venues');
        } catch (err) {
            console.error('Error deleting venue:', err);
            alert('Error: ' + err.message);
        }
    };

    const handleSaveConcept = async () => {
        if (!selectedProperty || !newConceptName.trim()) return;
        const propCode = selectedProperty.property_code || selectedProperty.code;
        if (propCode === 'OTO') return;
        const nameTrimmed = newConceptName.trim();
        const hasPropField = (restaurants || []).some(x => x && (x.property_code !== undefined && x.property_code !== null));
        const conceptsForProperty = hasPropField ? (restaurants || []).filter(x => String(x?.property_code || '') === String(propCode)) : (restaurants || []);
        const alreadyExists = conceptsForProperty.some(c => (c.name || '').trim().toLowerCase() === nameTrimmed.toLowerCase());
        if (alreadyExists) {
            window.otoNotify?.toast?.('This concept already exists at this property. Use a different name or add locations to the existing one.', 'error') || alert('This concept already exists at this property. Use a different name or add locations to the existing one.');
            return;
        }
        try {
            setSavingConcept(true);
            const response = await fetch('/api/restaurants', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUsername
                },
                body: JSON.stringify({
                    property_code: propCode,
                    name: nameTrimmed,
                    description: (newConceptDescription || '').trim()
                })
            });
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.detail || 'Failed to add concept');
            }
            setAddingConcept(false);
            setNewConceptName('');
            setNewConceptDescription('');
            await loadRestaurants(propCode);
        } catch (err) {
            alert('Error: ' + (err.message || 'Failed to add concept'));
        } finally {
            setSavingConcept(false);
        }
    };

    const handleDeleteConcept = async (conceptId, conceptName) => {
        if (!confirm(`Remove the restaurant concept "${conceptName}"? Any venues under it will need to be removed or reassigned first.`)) return;
        try {
            setDeletingConceptId(conceptId);
            const response = await fetch(`/api/restaurants/${conceptId}`, {
                method: 'DELETE',
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.detail || 'Failed to remove concept');
            }
            const propCode = selectedProperty?.property_code || selectedProperty?.code;
            if (propCode) {
                await loadRestaurants(propCode);
                await loadVenues(propCode);
            }
        } catch (err) {
            alert('Error: ' + (err.message || 'Failed to remove concept'));
        } finally {
            setDeletingConceptId(null);
        }
    };

    const startAddVendor = async () => {
        if (!selectedProperty) return;
        setVendorSaveMessage({ type: '', text: '' });
        setEditingVendor({
            mode: 'add',
            pvs_id: null,
            vendor_service_id: null,
            vendor_id: '',
            service: '',
            phone: '',
            email: '',
            url: '',
            notes: '',
            new_vendor_name: '',
            new_service_name: '',
            service_select_id: ''
        });
        await loadAllVendors();
        setVendorServices([]);
    };

    const startEditVendorAssignment = async (pvs) => {
        if (!pvs) return;
        setVendorSaveMessage({ type: '', text: '' });
        setEditingVendor({
            mode: 'edit',
            pvs_id: pvs.id,
            vendor_service_id: pvs.vendor_service_id,
            vendor_id: String(pvs.vendor_id || ''),
            service: pvs.service || '',
            phone: pvs.phone || '',
            email: pvs.email || '',
            url: pvs.url || '',
            notes: pvs.notes || '',
            new_vendor_name: '',
            new_service_name: '',
            service_select_id: String(pvs.vendor_service_id || '')
        });
        await loadAllVendors();
        await loadServicesForVendor(pvs.vendor_id);
    };


    const handleCancelVendor = () => {
        setEditingVendor(null);
        setVendorServices([]);
        setVendorSaveMessage({ type: '', text: '' });
    };

    const ensureVendorAndService = async () => {
        // Returns vendor_service_id to assign
        // If vendor_id is '__new__' or blank, create vendor using new_vendor_name
        // If service_select_id is '__new__' or blank, create vendor service using new_service_name + contact fields
        let vendorId = editingVendor.vendor_id;
        if (!vendorId || vendorId === '__new__') {
            const vendorName = (editingVendor.new_vendor_name || '').trim();
            if (!vendorName) throw new Error('Please enter a vendor name');
            const resp = await fetch('/api/vendors', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(currentUsername ? { 'X-OTO-User': currentUsername } : {})
                },
                body: JSON.stringify({ name: vendorName })
            });
            if (!resp.ok) {
                const data = await resp.json().catch(() => ({}));
                throw new Error(data.detail || 'Failed to create vendor');
            }
            const data = await resp.json();
            vendorId = String(data.vendor?.id || data.vendor_id || '');
        }

        // Existing service picked
        if (editingVendor.service_select_id && editingVendor.service_select_id !== '__new__') {
            return Number(editingVendor.service_select_id);
        }

        // Create new service
        const serviceName = (editingVendor.new_service_name || editingVendor.service || '').trim();
        if (!serviceName) throw new Error('Please enter a service name');

        const resp2 = await fetch('/api/vendor-services', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...(currentUsername ? { 'X-OTO-User': currentUsername } : {})
            },
            body: JSON.stringify({
                vendor_id: Number(vendorId),
                service: serviceName,
                phone: editingVendor.phone || null,
                email: editingVendor.email || null,
                url: editingVendor.url || null,
                notes: editingVendor.notes || null
            })
        });
        if (!resp2.ok) {
            const data = await resp2.json().catch(() => ({}));
            throw new Error(data.detail || 'Failed to create vendor service');
        }
        const data2 = await resp2.json();
        return Number(data2.vendor_service?.id || data2.vendor_service_id || data2.id);
    };

    const handleSaveVendor = async () => {
        if (!selectedProperty || !editingVendor) return;
        if (!canManageVendors) return;

        try {
            setIsSavingVendor(true);
            setVendorSaveMessage({ type: '', text: '' });

            if (editingVendor.mode === 'edit') {
                // Update the vendor service details (phone/email/url/notes/service name),
                // then update the property's assignment (vendor_service_id).
                const vendorId = editingVendor.vendor_id ? Number(editingVendor.vendor_id) : null;
                if (!vendorId) throw new Error('Please select a vendor');

                const vendorServiceId = editingVendor.service_select_id ? Number(editingVendor.service_select_id) : null;

                if (!vendorServiceId) throw new Error('Please select a service');

                const serviceName = (editingVendor.service || '').trim();
                if (!serviceName) throw new Error('Please enter a service name');

                // 1) Update vendor service details (global for this vendor service)
                const respDetails = await fetch(`/api/vendor-services/${vendorServiceId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        ...(currentUsername ? { 'X-OTO-User': currentUsername } : {})
                    },
                    body: JSON.stringify({
                        vendor_id: vendorId,
                        service: serviceName,
                        phone: editingVendor.phone || null,
                        email: editingVendor.email || null,
                        url: editingVendor.url || null,
                        notes: editingVendor.notes || null
                    })
                });
                if (!respDetails.ok) {
                    const data = await respDetails.json().catch(() => ({}));
                    throw new Error(data.detail || 'Failed to update vendor service details');
                }

                // 2) Update the property assignment (even if unchanged, this keeps updated_at/updated_by accurate)
                const respAssign = await fetch(`/api/properties/${selectedProperty.code}/vendor-services/${editingVendor.pvs_id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        ...(currentUsername ? { 'X-OTO-User': currentUsername } : {})
                    },
                    body: JSON.stringify({ vendor_service_id: vendorServiceId })
                });
                if (!respAssign.ok) {
                    const data = await respAssign.json().catch(() => ({}));
                    throw new Error(data.detail || 'Failed to update vendor assignment');
                }
            } else {
                // add
                const vendorServiceId = await ensureVendorAndService();
                const resp = await fetch(`/api/properties/${selectedProperty.code}/vendor-services`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        ...(currentUsername ? { 'X-OTO-User': currentUsername } : {})
                    },
                    body: JSON.stringify({ vendor_service_id: vendorServiceId })
                });
                if (!resp.ok) {
                    const data = await resp.json().catch(() => ({}));
                    throw new Error(data.detail || 'Failed to assign vendor service');
                }
            }

            setVendorSaveMessage({ type: 'success', text: 'Vendor information saved.' });
            setEditingVendor(null);
            setVendorServices([]);
            await loadVendors(selectedProperty.code);
        } catch (err) {
            console.error(err);
            setVendorSaveMessage({ type: 'error', text: err.message || 'Failed to save vendor information.' });
        } finally {
            setIsSavingVendor(false);
        }
    };

    const handleRemoveVendor = async (pvs) => {
        if (!selectedProperty || !pvs) return;
        if (!canManageVendors) return;
        if (!window.confirm('Remove this vendor from the property?')) return;

        try {
            setIsSavingVendor(true);
            const resp = await fetch(`/api/properties/${selectedProperty.code}/vendor-services/${pvs.id}`, {
                method: 'DELETE',
                headers: currentUsername ? { 'X-OTO-User': currentUsername } : {}
            });
            if (!resp.ok) {
                const data = await resp.json().catch(() => ({}));
                throw new Error(data.detail || 'Failed to remove vendor');
            }
            setVendorSaveMessage({ type: 'success', text: 'Vendor removed from property.' });
            await loadVendors(selectedProperty.code);
        } catch (err) {
            setVendorSaveMessage({ type: 'error', text: err.message || 'Failed to remove vendor.' });
        } finally {
            setIsSavingVendor(false);
        }
    };

    // ═══════════════════════════════════════════════════════════════════════════
    // EFFECTS
    // ═══════════════════════════════════════════════════════════════════════════

    useEffect(() => {
        if (!isOpen) return;  // Don't load if modal is closed
        if (canSeeAllProperties) {
            loadProperties();
        } else {
            loadSingleProperty();
        }
    }, [isOpen, currentUsername, canSeeAllProperties, selectedPropertyContext?.property_code]);

    useEffect(() => {
        if (selectedProperty && activeTab === 'vendors') {
            loadVendors(selectedProperty.code);
            // Vendors tab also shows the "Venues at This Property" panel, so load venues + restaurants here too.
            loadVenues(selectedProperty.code);
            loadRestaurants(selectedProperty.code);
        } else if (selectedProperty && activeTab === 'venues') {
            loadVenues(selectedProperty.code);
            loadRestaurants(selectedProperty.code);
            loadAllVendors();
        }
    }, [selectedProperty, activeTab]);

    // Auto-dismiss vendor save message after 3 seconds
    useEffect(() => {
        if (vendorSaveMessage.text) {
            const timer = setTimeout(() => {
                setVendorSaveMessage({ type: '', text: '' });
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [vendorSaveMessage.text]);

    // Suggest existing concept names as they type (debounced)
    useEffect(() => {
        if (!addingConcept) {
            setConceptNameSuggestions([]);
            return;
        }
        const q = newConceptName.trim();
        if (!q) {
            setConceptNameSuggestions([]);
            return;
        }
        let cancelled = false;
        const t = setTimeout(() => {
            fetch(`/api/restaurants/concept-names?q=${encodeURIComponent(q)}&limit=10`, { headers: currentUsername ? { 'X-OTO-User': currentUsername } : {} })
                .then(res => res.ok ? res.json() : { concept_names: [] })
                .then(data => { if (!cancelled) setConceptNameSuggestions(data.concept_names || []); })
                .catch(() => { if (!cancelled) setConceptNameSuggestions([]); });
        }, 250);
        return () => { cancelled = true; clearTimeout(t); };
    }, [addingConcept, newConceptName, currentUsername]);

    // ═══════════════════════════════════════════════════════════════════════════
    // PROPERTY DETAILS HANDLERS
    // ═══════════════════════════════════════════════════════════════════════════

    const handleEditDetails = () => {
        if (!selectedProperty) return;
        setEditPhone(formatPhone(selectedProperty.phone_number || ''));
        setEditGMUsername(selectedProperty.general_manager_username || '');
        setEditAbbreviation(selectedProperty.abbreviation || '');
        // Initialize ownership/management toggles from current property values
        setEditIsOwned(!!selectedProperty.is_owned);
        const managedBy = selectedProperty.managed_by || '';
        setEditIsManagedByOto(/oto/i.test(managedBy));
        if (canEditDetails) {
            loadEligibleManagers(selectedProperty.code);
        }
        setIsEditingDetails(true);
        setSaveMessage({ type: '', text: '' });
    };

    const handleCancelDetails = () => {
        setIsEditingDetails(false);
        setEditPhone('');
        setEditGMUsername('');
        setEditAbbreviation('');
        setEditIsOwned(false);
        setEditIsManagedByOto(false);
        setSaveMessage({ type: '', text: '' });
    };

    const handleSaveDetails = async () => {
        if (!selectedProperty) return;
        try {
            setIsSavingDetails(true);
            setSaveMessage({ type: '', text: '' });
            const phoneDigits = editPhone.replace(/\D/g, '');
            const body = {
                phone_number: phoneDigits || null,
                general_manager_username: editGMUsername || null,
                abbreviation: (editAbbreviation && editAbbreviation.trim()) || null,
                 // Owned by OTO? Uses is_owned boolean.
                 is_owned: !!editIsOwned,
                 // Managed by OTO? When true, set a consistent label; when false, clear it.
                 managed_by: editIsManagedByOto ? 'OTO Development' : null,
                amenities: Array.isArray(selectedProperty.amenities) ? selectedProperty.amenities : []
            };
            const response = await fetch(`/api/properties/${selectedProperty.code}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUsername
                },
                body: JSON.stringify(body)
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.detail || 'Failed to save');

            const savedAmenities = data.property?.amenities ?? selectedProperty.amenities ?? [];
            setSelectedProperty(prev => ({
                ...prev,
                phone_number: phoneDigits || null,
                general_manager_username: editGMUsername || null,
                general_manager_name: data.property?.general_manager_name ?? prev?.general_manager_name ?? null,
                general_manager_email: data.property?.general_manager_email ?? prev?.general_manager_email ?? null,
                is_owned: body.is_owned,
                managed_by: body.managed_by,
                abbreviation: (editAbbreviation && editAbbreviation.trim()) || null,
                amenities: savedAmenities
            }));

            const updatedAbbrev = (editAbbreviation && editAbbreviation.trim()) || null;
            setProperties(prev => prev.map(p =>
                p.code === selectedProperty.code
                    ? { ...p, ...data.property, abbreviation: data.property?.abbreviation ?? updatedAbbrev, amenities: savedAmenities }
                    : p
            ));

            setIsEditingDetails(false);
            setSaveMessage({ type: 'success', text: 'Property details saved successfully' });
            setTimeout(() => setSaveMessage({ type: '', text: '' }), 3000);
        } catch (err) {
            setSaveMessage({ type: 'error', text: err.message || 'Failed to save property details' });
        } finally {
            setIsSavingDetails(false);
        }
    };

    // ═══════════════════════════════════════════════════════════════════════════
    // VENDOR HANDLERS
    // ═══════════════════════════════════════════════════════════════════════════

    // ═══════════════════════════════════════════════════════════════════════════
    // VENDOR HANDLERS - TO BE IMPLEMENTED FOR NEW SYSTEM
    // ═══════════════════════════════════════════════════════════════════════════

    // TODO: Implement handlers for new 3-table vendor system
    // - Add vendor service to property
    // - Edit property-specific vendor details
    // - Remove vendor service from property

    // ═══════════════════════════════════════════════════════════════════════════
    // FILTERED PROPERTIES
    // ═══════════════════════════════════════════════════════════════════════════

    const filteredProperties = properties.filter(prop => {
        if (!searchText) return true;
        const search = searchText.toLowerCase();
        return (
            prop.code?.toLowerCase().includes(search) ||
            prop.name?.toLowerCase().includes(search) ||
            prop.abbreviation?.toLowerCase().includes(search) ||
            prop.city?.toLowerCase().includes(search) ||
            prop.state?.toLowerCase().includes(search)
        );
    });

    const handleOpenAddProperty = () => {
        setNewPropertyCode('');
        setNewPropertyName('');
        setNewPropertyAddress('');
        setNewPropertyCity('');
        setNewPropertyState('');
        setNewPropertyZip('');
        setAddPropertyError('');
        setShowAddProperty(true);
    };

    const handleCloseAddProperty = () => {
        setShowAddProperty(false);
        setAddPropertyError('');
    };

    const handleCreateProperty = async (e) => {
        e.preventDefault();
        const code = (newPropertyCode || '').trim().toUpperCase();
        const name = (newPropertyName || '').trim();
        if (!code) {
            setAddPropertyError('Property code is required.');
            return;
        }
        if (!name) {
            setAddPropertyError('Property name is required.');
            return;
        }
        setSavingNewProperty(true);
        setAddPropertyError('');
        try {
            const response = await fetch('/api/properties', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUsername
                },
                body: JSON.stringify({
                    code,
                    name,
                    address: (newPropertyAddress || '').trim() || undefined,
                    city: (newPropertyCity || '').trim() || undefined,
                    state: (newPropertyState || '').trim() || undefined,
                    zip: (newPropertyZip || '').trim() || undefined,
                })
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.detail || 'Failed to create property');
            await loadProperties();
            const created = data.property || { code, name };
            setSelectedProperty(created);
            if (onPropertyChange) {
                onPropertyChange({
                    property_code: created.code,
                    name: created.name,
                    address: created.address,
                    city: created.city,
                    state: created.state,
                    zip: created.zip
                });
            }
            if (onDataChange) onDataChange();
            handleCloseAddProperty();
        } catch (err) {
            setAddPropertyError(err.message || 'Failed to create property.');
        } finally {
            setSavingNewProperty(false);
        }
    };

    // ═══════════════════════════════════════════════════════════════════════════
    // RENDER
    // ═══════════════════════════════════════════════════════════════════════════

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 overflow-hidden">
            <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose}></div>
            <div className="absolute inset-4 md:inset-8 lg:inset-12 bg-white rounded-2xl shadow-2xl flex flex-col overflow-hidden">

                {/* Header */}
                <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-primary to-primary-hover">
                    <div className="flex items-center gap-3">
                        <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                        </svg>
                        <h2 className="text-xl font-bold text-white">Property Management</h2>
                    </div>
                    <button onClick={onClose} className="p-2 rounded-lg hover:bg-white/20 transition-colors">
                        <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                {/* Content */}
                <div className="flex flex-1 overflow-hidden">

                    {/* Left Panel - Property List (users who can see all properties) */}
                    {canSeeAllProperties && (
                        <div className="w-80 bg-gray-50 border-r border-gray-200 flex flex-col flex-shrink-0">
                            <div className="p-4 border-b border-gray-200">
                                <div className="relative">
                                    <input
                                        type="text"
                                        placeholder="Search properties..."
                                        value={searchText}
                                        onChange={(e) => setSearchText(e.target.value)}
                                        className="w-full border border-gray-300 rounded-lg pl-9 pr-4 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                                    />
                                    <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                </div>
                            </div>

                            <div className="flex-1 overflow-y-auto scrollbar-thin">
                                {isLoading ? (
                                    <div className="p-6 text-center">
                                        <svg className="animate-spin h-6 w-6 mx-auto text-primary" fill="none" viewBox="0 0 24 24">
                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                    </div>
                                ) : loadError ? (
                                    <div className="p-4 text-center">
                                        <p className="text-red-600 text-sm">{loadError}</p>
                                        <button onClick={loadProperties} className="mt-2 text-primary hover:text-primary-hover text-sm font-semibold">Try Again</button>
                                    </div>
                                ) : (
                                    <>
                                        {canAddProperties && (
                                            <div
                                                onClick={handleOpenAddProperty}
                                                className="px-4 py-3 border-b border-gray-100 cursor-pointer transition-colors hover:bg-gray-100 border-l-4 border-l-transparent flex items-center gap-3"
                                            >
                                                <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                                                    <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="M12 4v16m8-8H4" />
                                                    </svg>
                                                </div>
                                                <div>
                                                    <div className="font-semibold text-primary text-sm">Add Property</div>
                                                    <div className="text-xs text-gray-500">Create a new property</div>
                                                </div>
                                            </div>
                                        )}
                                        {filteredProperties.length === 0 ? (
                                            <div className="p-4 text-center text-gray-500 text-sm">{searchText ? 'No matches' : 'No properties'}</div>
                                        ) : (
                                            filteredProperties.map(prop => (
                                        <div
                                            key={prop.code}
                                            onClick={() => {
                                                setSelectedProperty(prop);
                                                // Also update parent's selected property
                                                if (onPropertyChange) {
                                                    onPropertyChange({
                                                        property_code: prop.code,
                                                        name: prop.name,
                                                        address: prop.address,
                                                        city: prop.city,
                                                        state: prop.state,
                                                        zip: prop.zip
                                                    });
                                                }
                                                setIsEditingDetails(false);
                                                setEditingVendor(null);
                                                setSaveMessage({ type: '', text: '' });
                                                setVendorSaveMessage({ type: '', text: '' });
                                                setActiveTab('details');
                                            }}
                                            className={`px-4 py-3 border-b border-gray-100 cursor-pointer transition-colors ${selectedProperty?.code === prop.code
                                                    ? 'bg-primary/10 border-l-4 border-l-primary'
                                                    : 'hover:bg-gray-100 border-l-4 border-l-transparent'
                                                }`}
                                        >
                                            <div className="flex items-center gap-2">
                                                <span className="font-bold text-primary text-sm">{prop.code}</span>
                                                {prop.abbreviation && <span className="text-xs text-gray-400">({prop.abbreviation})</span>}
                                                {prop.code !== 'OTO' && !prop.general_manager_name && (
                                                    <svg className="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" title="Missing General Manager">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                                    </svg>
                                                )}
                                            </div>
                                            <div className="text-sm text-gray-700 truncate">{prop.name}</div>
                                            <div className="text-xs text-gray-500">{prop.city}, {prop.state}</div>
                                            {prop.general_manager_name ? (
                                                <div className="text-xs text-gray-500 mt-1">GM: {prop.general_manager_name}</div>
                                            ) : (
                                                prop.code !== 'OTO' && (
                                                    <div className="text-xs text-amber-600 mt-1 font-medium">⚠ No GM assigned</div>
                                                )
                                            )}
                                        </div>
                                    ))
                                        )}
                                    </>
                                )}
                            </div>
                            <div className="px-4 py-2 border-t border-gray-200 bg-white text-xs text-gray-500">
                                {filteredProperties.length} of {properties.length} properties
                            </div>
                        </div>
                    )}

                    {/* Right Panel - Property Details & Vendors */}
                    <div className="flex-1 overflow-y-auto bg-white flex flex-col">
                        {isLoading ? (
                            <div className="flex-1 flex items-center justify-center">
                                <svg className="animate-spin h-8 w-8 text-primary" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                </svg>
                            </div>
                        ) : loadError ? (
                            <div className="flex-1 flex items-center justify-center">
                                <div className="max-w-md w-full bg-gray-50 border border-gray-200 rounded-xl p-5 text-center">
                                    <p className="text-red-600 text-sm">{loadError}</p>
                                    <button
                                        onClick={canSeeAllProperties ? loadProperties : loadSingleProperty}
                                        className="mt-3 px-4 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-semibold transition-colors"
                                    >
                                        Retry
                                    </button>
                                </div>
                            </div>
                        ) : selectedProperty ? (
                            <>
                                {/* Tabs */}
                                <div className="border-b border-gray-200 px-6">
                                    <div className="flex gap-1">
                                        <button
                                            onClick={() => setActiveTab('details')}
                                            className={`px-4 py-3 text-sm font-semibold border-b-2 transition-colors ${activeTab === 'details'
                                                    ? 'border-primary text-primary'
                                                    : 'border-transparent text-gray-500 hover:text-gray-700'
                                                }`}
                                        >
                                            Property Details
                                        </button>
                                        {selectedProperty.code === 'OTO' ? (
                                            /* OTO Property - Show Overview Tab */
                                            <button
                                                onClick={() => setActiveTab('statistics')}
                                                className={`px-4 py-3 text-sm font-semibold border-b-2 transition-colors ${activeTab === 'statistics'
                                                        ? 'border-primary text-primary'
                                                        : 'border-transparent text-gray-500 hover:text-gray-700'
                                                    }`}
                                            >
                                                Overview
                                            </button>
                                        ) : (
                                            /* Regular Properties - Show Vendor/Dining Tabs */
                                            <>
                                                <button
                                                    onClick={() => setActiveTab('vendors')}
                                                    className={`px-4 py-3 text-sm font-semibold border-b-2 transition-colors ${activeTab === 'vendors'
                                                            ? 'border-primary text-primary'
                                                            : 'border-transparent text-gray-500 hover:text-gray-700'
                                                        }`}
                                                >
                                                    Vendor Information
                                                </button>
                                                <button
                                                    onClick={() => setActiveTab('venues')}
                                                    className={`px-4 py-3 text-sm font-semibold border-b-2 transition-colors ${activeTab === 'venues'
                                                            ? 'border-primary text-primary'
                                                            : 'border-transparent text-gray-500 hover:text-gray-700'
                                                        }`}
                                                >
                                                    Amenities, Dining, & Restaurants
                                                </button>
                                            </>
                                        )}
                                    </div>
                                </div>

                                {/* Tab Content */}
                                <div className="flex-1 overflow-y-auto p-6 scrollbar-thin">
                                    <div className="max-w-3xl mx-auto">

                                        {activeTab === 'details' && (
                                            <div>
                                                <div className="flex items-start justify-between mb-6">
                                                    <div>
                                                        <h3 className="text-2xl font-bold text-gray-900">{selectedProperty.code}</h3>
                                                        <p className="text-gray-600">{selectedProperty.name}</p>
                                                    </div>
                                                    {!isEditingDetails && canEditDetails && (
                                                        <button
                                                            onClick={handleEditDetails}
                                                            className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-semibold transition-colors"
                                                        >
                                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                            </svg>
                                                            Edit
                                                        </button>
                                                    )}
                                                </div>

                                                {/* Notifications - Missing Information */}
                                                {selectedProperty.code !== 'OTO' && !selectedProperty.general_manager_name && (
                                                    <div className="mb-4 bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3">
                                                        <svg className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                                        </svg>
                                                        <div className="flex-1">
                                                            <p className="text-sm font-semibold text-amber-900">Missing General Manager</p>
                                                            <p className="text-xs text-amber-700 mt-1">This property does not have a General Manager assigned. Click "Edit" to assign one.</p>
                                                        </div>
                                                    </div>
                                                )}

                                                {saveMessage.text && (
                                                    <div className={`mb-4 p-3 rounded-lg text-sm ${saveMessage.type === 'success'
                                                            ? 'bg-primary/10 text-primary border border-primary/20'
                                                            : 'bg-red-50 text-red-700 border border-red-200'
                                                        }`}>
                                                        {saveMessage.text}
                                                    </div>
                                                )}

                                                {/* Property Information */}
                                                <div className="bg-gray-50 rounded-xl p-4 mb-4">
                                                    <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Property Information</h4>
                                                    <div className="grid grid-cols-2 gap-3 text-sm">
                                                        <div><span className="text-gray-500">Code:</span> <span className="font-medium">{selectedProperty.code}</span></div>
                                                        <div className="col-span-2"><span className="text-gray-500">Name:</span> <span className="font-medium">{selectedProperty.name}</span></div>
                                                        <div className="col-span-2"><span className="text-gray-500">Address:</span> <span className="font-medium">{selectedProperty.address}, {selectedProperty.city}, {selectedProperty.state} {selectedProperty.zip}</span></div>
                                                    </div>
                                                </div>

                                                {/* Management Settings */}
                                                <div className="bg-white border border-gray-200 rounded-xl p-4">
                                                    <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Management Settings</h4>
                                                    <div className="space-y-4">
                                                        {/* Phone Number */}
                                                        <div>
                                                            <label className="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                                                            {isEditingDetails ? (
                                                                <input
                                                                    type="tel"
                                                                    value={editPhone}
                                                                    onChange={handlePhoneChange}
                                                                    placeholder="(555) 123-4567"
                                                                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                                                                />
                                                            ) : (
                                                                <p className="text-gray-900">
                                                                    {selectedProperty.phone_number
                                                                        ? formatPhone(selectedProperty.phone_number)
                                                                        : <span className="text-gray-400 italic">Not set</span>
                                                                    }
                                                                </p>
                                                            )}
                                                        </div>

                                                        {/* JitBit abbreviation - only when editing property details */}
                                                        {isEditingDetails && (
                                                            <div>
                                                                <label className="block text-sm font-medium text-gray-700 mb-1">JitBit abbreviation</label>
                                                                <input
                                                                    type="text"
                                                                    value={editAbbreviation}
                                                                    onChange={(e) => setEditAbbreviation(e.target.value)}
                                                                    placeholder="e.g. OTODEV (for JitBit tickets)"
                                                                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                                                                />
                                                            </div>
                                                        )}

                                                        {/* Ownership & Management by OTO */}
                                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                            <div>
                                                                <label className="block text-sm font-medium text-gray-700 mb-1">Owned by OTO</label>
                                                                {isEditingDetails ? (
                                                                    <label className="inline-flex items-center gap-2 text-sm text-gray-700">
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={editIsOwned}
                                                                            onChange={(e) => setEditIsOwned(e.target.checked)}
                                                                            className="h-4 w-4 text-primary border-gray-300 rounded"
                                                                        />
                                                                        <span>{editIsOwned ? 'Yes, OTO owns this hotel' : 'No, OTO does not own this hotel'}</span>
                                                                    </label>
                                                                ) : (
                                                                    <p className="text-gray-900">
                                                                        {selectedProperty.is_owned
                                                                            ? 'Yes, OTO owns this hotel'
                                                                            : 'No, OTO does not own this hotel'}
                                                                    </p>
                                                                )}
                                                            </div>
                                                            <div>
                                                                <label className="block text-sm font-medium text-gray-700 mb-1">Managed by OTO</label>
                                                                {isEditingDetails ? (
                                                                    <label className="inline-flex items-center gap-2 text-sm text-gray-700">
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={editIsManagedByOto}
                                                                            onChange={(e) => setEditIsManagedByOto(e.target.checked)}
                                                                            className="h-4 w-4 text-primary border-gray-300 rounded"
                                                                        />
                                                                        <span>{editIsManagedByOto ? 'Yes, OTO manages this hotel' : 'No, OTO does not manage this hotel'}</span>
                                                                    </label>
                                                                ) : (
                                                                    <p className="text-gray-900">
                                                                        {(/oto/i.test(selectedProperty.managed_by || ''))
                                                                            ? 'Yes, OTO manages this hotel'
                                                                            : 'No, OTO does not manage this hotel'}
                                                                    </p>
                                                                )}
                                                            </div>
                                                        </div>

                                                        {/* General Manager - Hide for OTO corporate property */}
                                                        {selectedProperty.code !== 'OTO' && (
                                                            <div>
                                                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                                                    General Manager{!canEditDetails ? ' (read-only)' : ''}
                                                                </label>
                                                                {isEditingDetails ? (
                                                                    canEditDetails ? (
                                                                        <div className="relative">
                                                                            <select
                                                                                value={editGMUsername}
                                                                                onChange={(e) => setEditGMUsername(e.target.value)}
                                                                                disabled={loadingManagers}
                                                                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary bg-white"
                                                                            >
                                                                                <option value="">— No General Manager —</option>
                                                                                {eligibleManagers.map(mgr => (
                                                                                    <option key={mgr.username} value={mgr.username}>
                                                                                        {`${mgr.first_name || ''} ${mgr.last_name || ''}`.trim() || mgr.username} ({mgr.role_display_name || mgr.role_name || 'No Role'})
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                            {loadingManagers && (
                                                                                <div className="absolute right-8 top-1/2 -translate-y-1/2">
                                                                                    <svg className="animate-spin h-4 w-4 text-gray-400" fill="none" viewBox="0 0 24 24">
                                                                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                                                                    </svg>
                                                                                </div>
                                                                            )}
                                                                        </div>
                                                                    ) : (
                                                                        <p className="text-gray-900">
                                                                            {selectedProperty.general_manager_name || <span className="text-gray-400 italic">Not set</span>}
                                                                        </p>
                                                                    )
                                                                ) : (
                                                                    selectedProperty.general_manager_name ? (
                                                                        <div>
                                                                            <p className="text-gray-900 font-medium">{selectedProperty.general_manager_name}</p>
                                                                            <p className="text-sm text-gray-500">{selectedProperty.general_manager_email}</p>
                                                                        </div>
                                                                    ) : (
                                                                        <p className="text-gray-400 italic">Not assigned</p>
                                                                    )
                                                                )}
                                                            </div>
                                                        )}

                                                        {/* Action Buttons */}
                                                        {isEditingDetails && (
                                                            <div className="flex gap-3 pt-2">
                                                                <button
                                                                    onClick={handleCancelDetails}
                                                                    disabled={isSavingDetails}
                                                                    className="flex-1 px-4 py-2 border border-gray-300 rounded-lg text-sm font-semibold text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-50"
                                                                >
                                                                    Cancel
                                                                </button>
                                                                <button
                                                                    onClick={handleSaveDetails}
                                                                    disabled={isSavingDetails}
                                                                    className="flex-1 px-4 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-semibold transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                                                                >
                                                                    {isSavingDetails ? (
                                                                        <>
                                                                            <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                                                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                                                            </svg>
                                                                            Saving...
                                                                        </>
                                                                    ) : 'Save Changes'}
                                                                </button>
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        {/* OTO Overview Tab */}
                                        {activeTab === 'statistics' && selectedProperty.code === 'OTO' && (
                                            <div>
                                                <div className="mb-6">
                                                    <h3 className="text-2xl font-bold text-gray-900 mb-1">Overview</h3>
                                                    <p className="text-gray-600">Active properties, staff, dining venues, and knowledge base</p>
                                                </div>

                                                <div className="space-y-6">
                                                    {/* Properties — grouped: Active / segmentation (click for details) */}
                                                    <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
                                                        <div className="p-4 border-b border-gray-200">
                                                            <h4 className="font-semibold text-gray-900">Properties</h4>
                                                            <p className="text-sm text-gray-600 mt-0.5">Click a row to view the list</p>
                                                        </div>
                                                        <div className="divide-y divide-gray-100">
                                                            <button
                                                                type="button"
                                                                onClick={() => setOverviewPropertiesDetail('active')}
                                                                className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition-colors"
                                                            >
                                                                <span className="text-sm font-medium text-gray-900">Active Properties</span>
                                                                <span className="text-xl font-bold text-gray-900">{otoStats?.total_properties ?? 0}</span>
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => setOverviewPropertiesDetail('owned_managed')}
                                                                className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition-colors"
                                                            >
                                                                <span className="text-sm font-medium text-gray-900">Owned + Managed</span>
                                                                <span className="text-xl font-bold text-primary">{otoStats?.owned_managed_count ?? 0}</span>
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => setOverviewPropertiesDetail('owned_only')}
                                                                className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition-colors"
                                                            >
                                                                <span className="text-sm font-medium text-gray-900">Owned Only</span>
                                                                <span className="text-xl font-bold text-gray-900">{otoStats?.owned_only_count ?? 0}</span>
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => setOverviewPropertiesDetail('managed_only')}
                                                                className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition-colors"
                                                            >
                                                                <span className="text-sm font-medium text-gray-900">Managed Only</span>
                                                                <span className="text-xl font-bold text-gray-900">{otoStats?.managed_only_count ?? 0}</span>
                                                            </button>
                                                        </div>
                                                    </div>

                                                    {/* Active Staff */}
                                                    <div className="bg-white border border-gray-200 rounded-xl p-4">
                                                        <h4 className="font-semibold text-gray-900 mb-1">Active Staff</h4>
                                                        <div className="text-2xl font-bold text-gray-900">{otoStats?.total_active_staff ?? 0}</div>
                                                    </div>

                                                    {/* Dining & Venues */}
                                                    <div className="bg-white border border-gray-200 rounded-xl p-4">
                                                        <h4 className="font-semibold text-gray-900 mb-1">Dining &amp; Venues</h4>
                                                        <div className="text-sm text-gray-600">Total venue locations across properties</div>
                                                        <div className="text-2xl font-bold text-gray-900 mt-1">{otoStats?.total_dining_venues ?? 0}</div>
                                                    </div>

                                                    {/* Knowledge Base */}
                                                    <div className="bg-white border border-gray-200 rounded-xl p-4">
                                                        <h4 className="font-semibold text-gray-900 mb-3">Knowledge Base</h4>
                                                        <div className="grid grid-cols-2 gap-4">
                                                            <div>
                                                                <div className="text-sm text-gray-600">Published Articles</div>
                                                                <div className="text-2xl font-bold text-gray-900">{otoStats?.total_kb_articles ?? 0}</div>
                                                            </div>
                                                            <div>
                                                                <div className="text-sm text-gray-600">Pending Review</div>
                                                                <div className="text-2xl font-bold text-amber-600">{otoStats?.kb_pending_review ?? 0}</div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Modal: property list details (Active / Owned+Managed / Owned Only / Managed Only) */}
                                                {overviewPropertiesDetail && (
                                                    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4" onClick={() => setOverviewPropertiesDetail(null)}>
                                                        <div className="bg-white rounded-xl shadow-xl max-w-md w-full max-h-[80vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
                                                            <div className="p-4 border-b border-gray-200 flex items-center justify-between">
                                                                <h3 className="text-lg font-semibold text-gray-900">
                                                                    {overviewPropertiesDetail === 'active' && 'Active Properties'}
                                                                    {overviewPropertiesDetail === 'owned_managed' && 'Owned + Managed'}
                                                                    {overviewPropertiesDetail === 'owned_only' && 'Owned Only'}
                                                                    {overviewPropertiesDetail === 'managed_only' && 'Managed Only'}
                                                                </h3>
                                                                <button type="button" onClick={() => setOverviewPropertiesDetail(null)} className="p-2 text-gray-500 hover:bg-gray-100 rounded-lg" aria-label="Close">
                                                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                                                                </button>
                                                            </div>
                                                            <div className="p-4 overflow-y-auto flex-1">
                                                                {(() => {
                                                                    const allProps = otoStats?.properties_with_ownership || [];
                                                                    let list = allProps;
                                                                    if (overviewPropertiesDetail === 'owned_managed') {
                                                                        list = allProps.filter(p => p.is_owned && p.is_managed);
                                                                    } else if (overviewPropertiesDetail === 'owned_only') {
                                                                        list = allProps.filter(p => p.is_owned && !p.is_managed);
                                                                    } else if (overviewPropertiesDetail === 'managed_only') {
                                                                        list = allProps.filter(p => !p.is_owned && p.is_managed);
                                                                    }
                                                                    if (!list.length) {
                                                                        return <p className="text-sm text-gray-500">No properties in this category.</p>;
                                                                    }
                                                                    return (
                                                                        <ul className="space-y-2">
                                                                            {list.map((p, idx) => {
                                                                                const isOwned = !!p.is_owned;
                                                                                const isManaged = !!p.is_managed;
                                                                                const showOwnedTag = overviewPropertiesDetail === 'active'
                                                                                    ? isOwned
                                                                                    : (overviewPropertiesDetail === 'owned_managed' || overviewPropertiesDetail === 'owned_only');
                                                                                const showManagedTag = overviewPropertiesDetail === 'active'
                                                                                    ? isManaged
                                                                                    : (overviewPropertiesDetail === 'owned_managed' || overviewPropertiesDetail === 'managed_only');

                                                                                return (
                                                                                    <li key={idx} className="flex items-center justify-between gap-2 py-2 border-b border-gray-100 last:border-0 text-sm">
                                                                                        <span className="font-medium text-gray-900 truncate">{p.name}</span>
                                                                                        <span className="flex items-center gap-2 shrink-0">
                                                                                            {overviewPropertiesDetail === 'active' && (showOwnedTag || showManagedTag) && (
                                                                                                <span className="inline-flex items-center gap-1">
                                                                                                    {showOwnedTag && (
                                                                                                        <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Owned</span>
                                                                                                    )}
                                                                                                    {showManagedTag && (
                                                                                                        <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Managed</span>
                                                                                                    )}
                                                                                                </span>
                                                                                            )}
                                                                                            {overviewPropertiesDetail === 'owned_managed' && showOwnedTag && showManagedTag && (
                                                                                                <span className="inline-flex items-center gap-1">
                                                                                                    <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Owned</span>
                                                                                                    <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Managed</span>
                                                                                                </span>
                                                                                            )}
                                                                                            {overviewPropertiesDetail === 'owned_only' && showOwnedTag && !showManagedTag && (
                                                                                                <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Owned</span>
                                                                                            )}
                                                                                            {overviewPropertiesDetail === 'managed_only' && showManagedTag && !showOwnedTag && (
                                                                                                <span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">Managed</span>
                                                                                            )}
                                                                                            <span className="font-mono text-gray-600">{p.code}</span>
                                                                                        </span>
                                                                                    </li>
                                                                                );
                                                                            })}
                                                                        </ul>
                                                                    );
                                                                })()}
                                                            </div>
                                                            <div className="p-4 border-t border-gray-200">
                                                                <button type="button" onClick={() => setOverviewPropertiesDetail(null)} className="w-full px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-lg font-medium text-sm">
                                                                    Close
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                        )}

                                        {activeTab === 'vendors' && (
                                            <div>
                                                <div className="mb-6 flex items-center justify-between">
                                                    <div>
                                                        <h3 className="text-2xl font-bold text-gray-900 mb-1">Vendor Information</h3>
                                                        <p className="text-sm text-gray-600">Manage technology vendors for {selectedProperty.code}</p>
                                                    </div>

                                                    <div className="flex items-center gap-2">
                                                        {canManageVendors && !editingVendor && (
                                                            <button
                                                                onClick={startAddVendor}
                                                                className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-semibold transition-colors"
                                                            >
                                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                                                                </svg>
                                                                Add Vendor
                                                            </button>
                                                        )}
                                                    </div>
                                                </div>

                                                {vendorSaveMessage.text && (
                                                    <div className={`mb-4 p-3 rounded-lg text-sm ${vendorSaveMessage.type === 'success'
                                                            ? 'bg-primary/10 text-primary border border-primary/20'
                                                            : 'bg-red-50 text-red-700 border border-red-200'
                                                        }`}>
                                                        {vendorSaveMessage.text}
                                                    </div>
                                                )}

                                                {loadingVendors ? (
                                                    <div className="flex items-center justify-center py-12">
                                                        <svg className="animate-spin h-8 w-8 text-primary" fill="none" viewBox="0 0 24 24">
                                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                                        </svg>
                                                    </div>
                                                ) : (
                                                    <>
                                                        {vendors.length === 0 && !editingVendor ? (
                                                            <div className="text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
                                                                <svg className="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                                                </svg>
                                                                <p className="text-gray-600 font-medium mb-1">No vendor information yet</p>
                                                                <p className="text-sm text-gray-500">No vendors configured yet</p>
                                                            </div>
                                                        ) : (
                                                            <div className="space-y-3">
                                                                {/* Show editing vendor first if present */}
                                                                {editingVendor && (
                                                                    <div className="border-2 border-primary rounded-lg overflow-hidden">
                                                                        <div className="bg-primary/5 px-4 py-3 border-b border-primary/20 flex items-center justify-between">
                                                                            <h4 className="text-sm font-semibold text-primary">
                                                                                {editingVendor.mode === 'add' ? 'Add Vendor to Property' : 'Edit Vendor'}
                                                                            </h4>
                                                                            <span className="text-xs text-gray-500">
                                                                                {selectedProperty.code}
                                                                            </span>
                                                                        </div>

                                                                        <div className="p-4 space-y-3 bg-white">
                                                                            {!canManageVendors && (
                                                                                <div className="text-sm text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-3">
                                                                                    You do not have permission to edit vendors.
                                                                                </div>
                                                                            )}

                                                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Vendor</label>
                                                                                    <select
                                                                                        value={editingVendor.vendor_id || ''}
                                                                                        onChange={async (e) => {
                                                                                            const val = e.target.value;
                                                                                            setEditingVendor(prev => ({
                                                                                                ...prev,
                                                                                                vendor_id: val,
                                                                                                // Only allow creating a new vendor while adding
                                                                                                new_vendor_name: (prev.mode === 'add' && !val) ? prev.new_vendor_name : '',
                                                                                                // Reset service selection + details when vendor changes
                                                                                                service_select_id: '',
                                                                                                vendor_service_id: null,
                                                                                                service: '',
                                                                                                phone: '',
                                                                                                email: '',
                                                                                                url: '',
                                                                                                notes: '',
                                                                                                new_service_name: ''
                                                                                            }));
                                                                                            if (val) {
                                                                                                await loadServicesForVendor(val);
                                                                                            } else {
                                                                                                setVendorServices([]);
                                                                                            }
                                                                                        }}
                                                                                        disabled={!canManageVendors || loadingVendorCatalog}
                                                                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary bg-white disabled:opacity-50"
                                                                                    >
                                                                                        <option value="">— Select vendor —</option>
                                                                                        {allVendors.map(v => (
                                                                                            <option key={v.id} value={String(v.id)}>{v.name}</option>
                                                                                        ))}
                                                                                    </select>
                                                                                    <div className="mt-2">
                                                                                        <label className="text-xs text-gray-600">
                                                                                            {editingVendor.mode === 'add' ? 'New vendor (optional):' : 'Or create new vendor:'}
                                                                                        </label>
                                                                                        <input
                                                                                            type="text"
                                                                                            value={editingVendor.new_vendor_name || ''}
                                                                                            onChange={(e) => setEditingVendor(prev => ({ ...prev, vendor_id: '', new_vendor_name: e.target.value, service_select_id: '', new_service_name: '' }))}
                                                                                            disabled={!canManageVendors}
                                                                                            placeholder="New vendor name..."
                                                                                            className="mt-1 w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary disabled:opacity-50"
                                                                                        />
                                                                                    </div>

                                                                                </div>

                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">
                                                                                        Service
                                                                                    </label>
                                                                                    <>
                                                                                        <select
                                                                                            value={editingVendor.service_select_id || ''}
                                                                                            onChange={(e) => {
                                                                                                const val = e.target.value;
                                                                                                const selected = vendorServices.find(s => String(s.id) === String(val));
                                                                                                setEditingVendor(prev => ({
                                                                                                    ...prev,
                                                                                                    service_select_id: val,
                                                                                                    vendor_service_id: selected ? selected.id : prev.vendor_service_id,
                                                                                                    service: selected ? selected.service : prev.service,
                                                                                                    phone: selected ? (selected.phone || '') : prev.phone,
                                                                                                    email: selected ? (selected.email || '') : prev.email,
                                                                                                    url: selected ? (selected.url || '') : prev.url,
                                                                                                    notes: selected ? (selected.notes || '') : prev.notes,
                                                                                                    new_service_name: val ? '' : prev.new_service_name
                                                                                                }));
                                                                                            }}
                                                                                            disabled={!canManageVendors || loadingVendorCatalog || !(editingVendor.vendor_id || editingVendor.new_vendor_name)}
                                                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary bg-white disabled:opacity-50"
                                                                                        >
                                                                                            <option value="">— Select service —</option>
                                                                                            {vendorServices.map(s => (
                                                                                                <option key={s.id} value={String(s.id)}>{s.service}</option>
                                                                                            ))}
                                                                                        </select>

                                                                                        {/* Allow renaming the selected service OR creating a new service in edit mode */}
                                                                                        <div className="mt-2">
                                                                                            <label className="text-xs text-gray-600">
                                                                                                {editingVendor.mode === 'edit' && editingVendor.service_select_id
                                                                                                    ? 'Service name:'
                                                                                                    : editingVendor.mode === 'edit'
                                                                                                        ? 'Or create new service:'
                                                                                                        : 'New service (optional):'}
                                                                                            </label>
                                                                                            <input
                                                                                                type="text"
                                                                                                value={editingVendor.mode === 'edit' && editingVendor.service_select_id
                                                                                                    ? (editingVendor.service || '')
                                                                                                    : (editingVendor.new_service_name || '')}
                                                                                                onChange={(e) => {
                                                                                                    if (editingVendor.mode === 'edit' && editingVendor.service_select_id) {
                                                                                                        setEditingVendor(prev => ({ ...prev, service: e.target.value }));
                                                                                                    } else {
                                                                                                        setEditingVendor(prev => ({ ...prev, service_select_id: '', new_service_name: e.target.value }));
                                                                                                    }
                                                                                                }}
                                                                                                disabled={!canManageVendors || (editingVendor.mode === 'add' && !(editingVendor.vendor_id || editingVendor.new_vendor_name))}
                                                                                                placeholder={editingVendor.mode === 'edit' && editingVendor.service_select_id ? 'Service name...' : 'New service name...'}
                                                                                                className="mt-1 w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary disabled:opacity-50"
                                                                                            />
                                                                                        </div>
                                                                                    </>
                                                                                </div>
                                                                            </div>

                                                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Phone</label>
                                                                                    <input
                                                                                        type="text"
                                                                                        value={editingVendor.phone || ''}
                                                                                        onChange={(e) => setEditingVendor(prev => ({ ...prev, phone: e.target.value }))}
                                                                                        disabled={!canManageVendors}
                                                                                        placeholder="Phone..."
                                                                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary disabled:opacity-50"
                                                                                    />
                                                                                </div>
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Email</label>
                                                                                    <input
                                                                                        type="email"
                                                                                        value={editingVendor.email || ''}
                                                                                        onChange={(e) => setEditingVendor(prev => ({ ...prev, email: e.target.value }))}
                                                                                        disabled={!canManageVendors}
                                                                                        placeholder="Email..."
                                                                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary disabled:opacity-50"
                                                                                    />
                                                                                </div>
                                                                            </div>

                                                                            <div>
                                                                                <label className="block text-xs font-medium text-gray-700 mb-1">Support URL</label>
                                                                                <input
                                                                                    type="url"
                                                                                    value={editingVendor.url || ''}
                                                                                    onChange={(e) => setEditingVendor(prev => ({ ...prev, url: e.target.value }))}
                                                                                    disabled={!canManageVendors}
                                                                                    placeholder="https://..."
                                                                                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary disabled:opacity-50"
                                                                                />
                                                                            </div>

                                                                            <div>
                                                                                <label className="block text-xs font-medium text-gray-700 mb-1">Notes</label>
                                                                                <textarea
                                                                                    value={editingVendor.notes || ''}
                                                                                    onChange={(e) => setEditingVendor(prev => ({ ...prev, notes: e.target.value }))}
                                                                                    disabled={!canManageVendors}
                                                                                    placeholder="Additional notes..."
                                                                                    rows={3}
                                                                                    className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-none disabled:opacity-50"
                                                                                />
                                                                            </div>

                                                                            <div className="flex gap-2 pt-1">
                                                                                <button
                                                                                    onClick={handleCancelVendor}
                                                                                    disabled={isSavingVendor}
                                                                                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-xs font-semibold text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-50"
                                                                                >
                                                                                    Cancel
                                                                                </button>
                                                                                <button
                                                                                    onClick={handleSaveVendor}
                                                                                    disabled={isSavingVendor || !canManageVendors}
                                                                                    className="flex-1 px-3 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-xs font-semibold transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                                                                                >
                                                                                    {isSavingVendor ? (
                                                                                        <>
                                                                                            <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24">
                                                                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                                                                            </svg>
                                                                                            Saving...
                                                                                        </>
                                                                                    ) : 'Save'}
                                                                                </button>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                )}

                                                                {/* Show existing vendor services */}
                                                                {vendors.map(service => {
                                                                    // Hide this vendor's card if we're editing it
                                                                    if (editingVendor && editingVendor.pvs_id === service.id) {
                                                                        return null;
                                                                    }

                                                                    return (
                                                                        <div key={service.id} className="border border-gray-200 rounded-lg overflow-hidden">
                                                                            <div className="bg-gray-50 px-4 py-3 flex items-center justify-between">
                                                                                <div>
                                                                                    <h4 className="text-sm font-semibold text-gray-900">{service.vendor_name}</h4>
                                                                                    <p className="text-xs text-gray-600 mt-0.5">{service.service}</p>
                                                                                </div>
                                                                                {canManageVendors && (
                                                                                    <div className="flex items-center gap-2">
                                                                                        <button
                                                                                            onClick={() => startEditVendorAssignment(service)}
                                                                                            className="px-2 py-1 text-xs font-semibold text-gray-700 border border-gray-300 rounded-md hover:bg-white transition-colors"
                                                                                        >
                                                                                            Edit
                                                                                        </button>
                                                                                        <button
                                                                                            onClick={() => handleRemoveVendor(service)}
                                                                                            className="px-2 py-1 text-xs font-semibold text-red-700 border border-red-200 rounded-md hover:bg-red-50 transition-colors"
                                                                                        >
                                                                                            Remove
                                                                                        </button>
                                                                                    </div>
                                                                                )}
                                                                            </div>

                                                                            <div className="p-4 bg-white text-sm space-y-2">
                                                                                {service.phone && (
                                                                                    <div>
                                                                                        <span className="text-xs font-medium text-gray-500">Phone: </span>
                                                                                        <span className="text-gray-900">{formatPhoneForDisplay(service.phone)}</span>
                                                                                    </div>
                                                                                )}
                                                                                {service.email && (
                                                                                    <div>
                                                                                        <span className="text-xs font-medium text-gray-500">Email: </span>
                                                                                        <span className="text-gray-900">{service.email}</span>
                                                                                    </div>
                                                                                )}
                                                                                {service.url && (
                                                                                    <div>
                                                                                        <span className="text-xs font-medium text-gray-500">Support URL: </span>
                                                                                        <a href={service.url} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
                                                                                            {service.url}
                                                                                        </a>
                                                                                    </div>
                                                                                )}
                                                                                {service.notes && (
                                                                                    <div>
                                                                                        <span className="text-xs font-medium text-gray-500">Notes: </span>
                                                                                        <span className="text-gray-900">{service.notes}</span>
                                                                                    </div>
                                                                                )}





                                                                                {service.updated_at && (
                                                                                    <div className="text-xs text-gray-400 pt-1 border-t border-gray-100">
                                                                                        Last updated: {new Date(service.updated_at).toLocaleDateString()}
                                                                                    </div>
                                                                                )}
                                                                            </div>
                                                                        </div>
                                                                    );
                                                                })}
                                                            </div>
                                                        )}
                                                    </>
                                                )}
                                            </div>
                                        )}

                                        {/* DINING VENUES TAB */}
                                        {activeTab === 'venues' && (
                                            <div className="h-full flex flex-col">
                                                {/* Header */}
                                                <div className="mb-6">
                                                    <h3 className="text-2xl font-bold text-gray-900">Amenities, Dining, & Restaurants</h3>
                                                    <p className="text-sm text-gray-600 mt-1">Property amenities and venue locations for {selectedProperty.code}.</p>
                                                </div>

                                                {/* Amenities section - selection boxes (checkboxes) */}
                                                <div className="mb-6 bg-white border border-gray-200 rounded-xl p-4">
                                                    <div className="flex items-center justify-between gap-2 mb-2">
                                                        <h4 className="text-sm font-semibold text-gray-700">Amenities</h4>
                                                        {canManageDiningVenues && !isEditingAmenities && (
                                                            <button type="button" onClick={() => { setEditAmenitiesVenue(Array.isArray(selectedProperty.amenities) ? [...selectedProperty.amenities] : []); setIsEditingAmenities(true); }} className="p-1.5 text-gray-400 hover:text-primary hover:bg-gray-50 rounded transition-colors ml-auto" title="Edit"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg></button>
                                                        )}
                                                    </div>
                                                    {isEditingAmenities ? (
                                                        <div className="space-y-3">
                                                            <div className="flex flex-wrap gap-x-4 gap-y-2">
                                                                {(AMENITY_OPTIONS || []).map((opt) => (
                                                                    <label key={opt} className="inline-flex items-center gap-2 cursor-pointer">
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={Array.isArray(editAmenitiesVenue) && editAmenitiesVenue.includes(opt)}
                                                                            onChange={(e) => {
                                                                                if (e.target.checked) {
                                                                                    setEditAmenitiesVenue(prev => [...(prev || []), opt]);
                                                                                } else {
                                                                                    setEditAmenitiesVenue(prev => (prev || []).filter(a => a !== opt));
                                                                                }
                                                                            }}
                                                                            className="rounded border-gray-300 text-primary focus:ring-primary"
                                                                        />
                                                                        <span className="text-sm text-gray-700">{opt}</span>
                                                                    </label>
                                                                ))}
                                                            </div>
                                                            <div className="flex gap-2">
                                                                <button type="button" onClick={() => { setIsEditingAmenities(false); setEditAmenitiesVenue(Array.isArray(selectedProperty.amenities) ? [...selectedProperty.amenities] : []); }} className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">Cancel</button>
                                                                <button type="button" disabled={savingAmenities} onClick={async () => {
                                                                    if (!selectedProperty) return;
                                                                    setSavingAmenities(true);
                                                                    try {
                                                                        const res = await fetch(`/api/properties/${selectedProperty.code}/amenities`, {
                                                                            method: 'PUT',
                                                                            headers: { 'Content-Type': 'application/json', 'X-OTO-User': currentUsername },
                                                                            body: JSON.stringify({ amenities: editAmenitiesVenue || [] })
                                                                        });
                                                                        const data = await res.json();
                                                                        if (!res.ok) throw new Error(data.detail || 'Failed to save');
                                                                        setSelectedProperty(prev => ({ ...prev, amenities: editAmenitiesVenue || [] }));
                                                                        setProperties(prev => prev.map(p => p.code === selectedProperty.code ? { ...p, amenities: editAmenitiesVenue || [] } : p));
                                                                        setIsEditingAmenities(false);
                                                                    } catch (err) {
                                                                        window.otoNotify?.toast?.(err.message || 'Failed to save amenities', 'error');
                                                                    } finally {
                                                                        setSavingAmenities(false);
                                                                    }
                                                                }} className="px-3 py-1.5 text-sm bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50">{savingAmenities ? 'Saving...' : 'Save'}</button>
                                                            </div>
                                                        </div>
                                                    ) : (
                                                        <div className="flex flex-wrap items-center gap-2">
                                                            {(Array.isArray(selectedProperty.amenities) && selectedProperty.amenities.length > 0)
                                                                ? selectedProperty.amenities.map((a, i) => (
                                                                    <span key={i} className="px-2.5 py-1 rounded-full bg-primary/10 text-primary text-sm font-medium">{a}</span>
                                                                ))
                                                                : <span className="text-gray-500 text-sm">No amenities selected</span>}
                                                        </div>
                                                    )}
                                                </div>

                                                {/* Dining — single list (concepts → locations) from DB; Add concept + Add/Edit venue in one flow */}
                                                {(() => {
                                                    const prop = (selectedProperty?.property_code || selectedProperty?.code || selectedPropertyCode || '');
                                                    const hasPropField = (restaurants || []).some(x => x && (x.property_code !== undefined && x.property_code !== null));
                                                    const conceptsForProperty = hasPropField ? (restaurants || []).filter(x => String(x?.property_code || '') === String(prop)) : (restaurants || []);

                                                    // When venue form is open: show only form (back link + form)
                                                    if (editingVenue) {
                                                        return (
                                                            <div className="flex-1 flex flex-col bg-white rounded-xl border border-gray-200 min-h-0 overflow-hidden">
                                                                <div className="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                                                                    <button type="button" onClick={() => setEditingVenue(null)} className="text-sm text-gray-500 hover:text-gray-800">← Back</button>
                                                                    <span className="text-sm font-medium text-gray-700">{editingVenue.mode === 'add' ? 'Add location' : 'Edit location'}</span>
                                                                </div>
                                                                <div className="flex-1 overflow-y-auto p-4">
                                                                    {/* Venue form is rendered below in same block - we need to output it here */}
                                                                    <div className="bg-primary/5 rounded-lg p-4 border border-primary/20">
                                                                        <div className="space-y-3">
                                                                            <div>
                                                                                <label className="block text-xs font-medium text-gray-700 mb-1">Restaurant concept *</label>
                                                                                <select value={editingVenue.restaurant_id || ''} onChange={(e) => setEditingVenue(prev => ({ ...prev, restaurant_id: e.target.value }))} className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20">
                                                                                    <option value="">— Select —</option>
                                                                                    {conceptsForProperty.map(r => (<option key={r.id} value={r.id}>{r.name}</option>))}
                                                                                </select>
                                                                            </div>
                                                                            <div className="grid grid-cols-2 gap-3">
                                                                                <div><label className="block text-xs font-medium text-gray-700 mb-1">Location *</label><input type="text" value={editingVenue.name || ''} onChange={(e) => setEditingVenue(prev => ({ ...prev, name: e.target.value }))} placeholder="e.g. Lobby, Pool Bar" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20" /></div>
                                                                                <div><label className="block text-xs font-medium text-gray-700 mb-1">Type *</label><select value={editingVenue.type || 'Restaurant'} onChange={(e) => setEditingVenue(prev => ({ ...prev, type: e.target.value }))} className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"><option value="Restaurant">Restaurant</option><option value="Bar">Bar</option><option value="Cafe">Cafe</option><option value="Market">Market</option><option value="Room Service">Room Service</option></select></div>
                                                                            </div>
                                                                            <div className="grid grid-cols-2 gap-3">
                                                                                <div><label className="block text-xs font-medium text-gray-700 mb-1">Phone</label><input type="tel" value={editingVenue.phone_number || ''} onChange={(e) => setEditingVenue(prev => ({ ...prev, phone_number: e.target.value }))} placeholder="(555) 123-4567" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20" /></div>
                                                                                <div><label className="block text-xs font-medium text-gray-700 mb-1">Location hint</label><input type="text" value={editingVenue.location_hint || ''} onChange={(e) => setEditingVenue(prev => ({ ...prev, location_hint: e.target.value }))} placeholder="e.g. Next to pool" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20" /></div>
                                                                            </div>
                                                                            <div><label className="block text-xs font-medium text-gray-700 mb-1">Links</label><div className="flex flex-wrap gap-2">{Object.entries(editingVenue.links || {}).map(([key, link]) => (<div key={key} className="flex gap-1.5"><select value={link.type || 'menu'} onChange={(e) => { const n = { ...editingVenue.links }; n[key] = { ...n[key], type: e.target.value }; setEditingVenue(prev => ({ ...prev, links: n })); }} className="w-28 border border-gray-300 rounded px-2 py-1.5 text-xs"><option value="menu">Menu</option><option value="reservations">Reservations</option><option value="website">Website</option><option value="ordering">Online Order</option></select><input type="url" value={link.url || ''} onChange={(e) => { const n = { ...editingVenue.links }; n[key] = { ...n[key], url: e.target.value }; setEditingVenue(prev => ({ ...prev, links: n })); }} placeholder="https://…" className="flex-1 min-w-[120px] border border-gray-300 rounded px-2 py-1.5 text-xs" /><button type="button" onClick={() => { const n = { ...editingVenue.links }; delete n[key]; setEditingVenue(prev => ({ ...prev, links: n })); }} className="text-red-600 hover:bg-red-50 px-2 rounded">×</button></div>))}<button type="button" onClick={() => { const n = { ...(editingVenue.links || {}) }; n[`link_${Date.now()}`] = { type: 'menu', url: '' }; setEditingVenue(prev => ({ ...prev, links: n })); }} className="text-xs text-primary font-medium">+ Add link</button></div></div>
                                                                            <div><label className="block text-xs font-medium text-gray-700 mb-1">Features & systems</label><p className="text-xs text-gray-500 mb-1">e.g. self-pour beer. Add any; use “Other” for more.</p>{(() => { const FEATURE_OPTIONS = [{ id: 'self_pour_system', label: 'Self-pour beer system', defaultValue: 'e.g. iPourIt' }]; const predefinedIds = FEATURE_OPTIONS.map(o => o.id); const features = editingVenue.features || {}; const entries = [...FEATURE_OPTIONS.filter(o => features[o.id] != null).map(o => ({ key: o.id, label: o.label, defaultValue: o.defaultValue, isPredefined: true })), ...Object.entries(features).filter(([k]) => !predefinedIds.includes(k)).map(([k, v]) => ({ key: k, label: null, isPredefined: false }))]; return (<div className="space-y-2">{[{ key: 'self_pour_system', label: 'Self-pour beer system', defaultValue: 'e.g. iPourIt', isPredefined: true }, ...Object.entries(features).filter(([k]) => k !== 'self_pour_system').map(([k, v]) => ({ key: k, label: null, isPredefined: false }))].map(({ key, label, defaultValue, isPredefined }) => (<div key={key} className="flex gap-2 items-center flex-wrap"><div className="w-40 shrink-0">{isPredefined ? <span className="text-sm text-gray-700">{label}</span> : <input type="text" value={typeof features[key] === 'object' && features[key] !== null ? (features[key].key || '') : ''} onChange={(e) => { const n = { ...editingVenue.features }; const v = n[key]; n[key] = (v && typeof v === 'object' ? { ...v, key: e.target.value } : { key: e.target.value, value: '' }); setEditingVenue(prev => ({ ...prev, features: n })); }} placeholder="Feature name" className="w-full border border-gray-300 rounded px-2 py-1.5 text-sm" />}</div><input type="text" value={typeof features[key] === 'string' ? features[key] : (typeof features[key] === 'object' && features[key] !== null ? (features[key].value || '') : '')} onChange={(e) => { const n = { ...editingVenue.features }; if (predefinedIds.includes(key)) n[key] = e.target.value; else { const v = n[key]; n[key] = (v && typeof v === 'object' ? { ...v, value: e.target.value } : { key: key, value: e.target.value }); } setEditingVenue(prev => ({ ...prev, features: n })); }} placeholder={isPredefined ? (defaultValue || '') : 'Details'} className="flex-1 min-w-[120px] border border-gray-300 rounded px-2 py-1.5 text-sm" /><button type="button" onClick={() => { const n = { ...editingVenue.features }; delete n[key]; setEditingVenue(prev => ({ ...prev, features: n })); }} className="p-1.5 text-gray-400 hover:text-red-600 rounded shrink-0">×</button></div>))}<div className="flex gap-2 items-center pt-1"><span className="text-xs text-gray-500">Add:</span><select value="" onChange={(e) => { const v = e.target.value; if (!v) return; e.target.value = ''; const n = { ...(editingVenue.features || {}) }; if (v === '_other_') n[`custom_${Date.now()}`] = { key: '', value: '' }; else { const opt = FEATURE_OPTIONS.find(o => o.id === v); if (opt) n[opt.id] = opt.defaultValue || ''; } setEditingVenue(prev => ({ ...prev, features: n })); }} className="text-sm border border-gray-300 rounded px-2 py-1.5"><option value="">— Add —</option>{FEATURE_OPTIONS.filter(o => (features[o.id] == null || (typeof features[o.id] === 'string' && !features[o.id].trim()))).map(o => (<option key={o.id} value={o.id}>{o.label}</option>))}<option value="_other_">Other</option></select></div></div>); })()}</div>
                                                                            <div><label className="block text-xs font-medium text-gray-700 mb-1">Support & technology contacts</label><p className="text-xs text-gray-500 mb-1">Companies that support this location.</p><div className="flex flex-wrap gap-2">{(allVendors || []).map(v => (<label key={v.id} className="inline-flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={((editingVenue.vendor_ids || []).indexOf(v.id) !== -1) || ((editingVenue.vendors || []).some(vv => vv.id === v.id))} onChange={(e) => { const ids = editingVenue.vendor_ids != null ? [...editingVenue.vendor_ids] : (editingVenue.vendors || []).map(vv => vv.id); const set = new Set(ids); if (e.target.checked) set.add(v.id); else set.delete(v.id); setEditingVenue(prev => ({ ...prev, vendor_ids: Array.from(set) })); }} className="rounded border-gray-300 text-primary focus:ring-primary" /><span className="text-sm text-gray-700">{v.name}</span></label>))}{(allVendors || []).length === 0 && <span className="text-xs text-gray-500">None in catalog. Add in Vendor Information tab.</span>}</div></div>
                                                                            <div className="flex gap-2 pt-2"><button onClick={() => setEditingVenue(null)} className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50">Cancel</button><button onClick={handleSaveVenue} disabled={savingVenue} className="flex-1 px-3 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-medium disabled:opacity-50">{savingVenue ? 'Saving…' : 'Save'}</button></div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        );
                                                    }

                                                    // List view: concepts → locations
                                                    return (
                                                        <div className="flex-1 flex flex-col bg-white rounded-xl border border-gray-200 min-h-0 overflow-hidden">
                                                            <div className="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                                                                <h4 className="text-sm font-semibold text-gray-900">Dining</h4>
                                                                {canManageDiningVenues && (
                                                                    <button type="button" onClick={() => setAddingConcept(true)} className="text-sm text-primary hover:text-primary-hover font-medium">+ Add concept</button>
                                                                )}
                                                            </div>

                                                            {addingConcept && (
                                                                <div className="p-4 border-b border-gray-100 bg-gray-50/50">
                                                                    <p className="text-xs font-medium text-gray-700 mb-2">New restaurant concept</p>
                                                                    <p className="text-xs text-gray-500 mb-2">Type to see existing concepts; click a suggestion to use it and close the list.</p>
                                                                    <div className="flex flex-wrap items-end gap-3">
                                                                        <div className="min-w-[200px] relative">
                                                                            <label className="block text-xs text-gray-500 mb-1">Name *</label>
                                                                            <input
                                                                                ref={newConceptNameInputRef}
                                                                                type="text"
                                                                                value={newConceptName}
                                                                                onChange={(e) => setNewConceptName(e.target.value)}
                                                                                onBlur={() => setTimeout(() => setConceptNameSuggestions([]), 150)}
                                                                                placeholder="e.g. Pool Bar, Lobby Cafe"
                                                                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary"
                                                                            />
                                                                            {conceptNameSuggestions.length > 0 && (
                                                                                <ul className="absolute left-0 right-0 top-full mt-0.5 bg-white border border-gray-200 rounded-lg shadow-lg z-10 max-h-48 overflow-y-auto py-1">
                                                                                    {conceptNameSuggestions.map(name => (
                                                                                        <li key={name}>
                                                                                            <button
                                                                                                type="button"
                                                                                                onMouseDown={(e) => { e.preventDefault(); setNewConceptName(name); setConceptNameSuggestions([]); newConceptNameInputRef.current?.blur(); }}
                                                                                                className="w-full text-left px-3 py-2 text-sm text-gray-800 hover:bg-gray-100 focus:bg-gray-100 focus:outline-none"
                                                                                            >
                                                                                                {name}
                                                                                            </button>
                                                                                        </li>
                                                                                    ))}
                                                                                </ul>
                                                                            )}
                                                                        </div>
                                                                        <div className="min-w-[180px]"><label className="block text-xs text-gray-500 mb-1">Description</label><input type="text" value={newConceptDescription} onChange={(e) => setNewConceptDescription(e.target.value)} placeholder="Optional" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary" /></div>
                                                                        <button type="button" onClick={() => { setAddingConcept(false); setNewConceptName(''); setNewConceptDescription(''); setConceptNameSuggestions([]); }} className="px-3 py-2 text-sm border border-gray-300 rounded-lg text-gray-600 hover:bg-gray-100">Cancel</button>
                                                                        <button type="button" disabled={savingConcept || !newConceptName.trim()} onClick={handleSaveConcept} className="px-3 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50">{savingConcept ? 'Saving…' : 'Save'}</button>
                                                                    </div>
                                                                </div>
                                                            )}

                                                            <div className="flex-1 overflow-y-auto scrollbar-thin min-h-0 p-4">
                                                                    {venuesLoading ? (
                                                                        <div className="flex items-center justify-center py-12">
                                                                            <svg className="animate-spin h-6 w-6 text-primary" fill="none" viewBox="0 0 24 24">
                                                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                                                            </svg>
                                                                        </div>
                                                                    ) : editingVenue ? (
                                                                        <div className="mx-4 mt-4 bg-primary/5 rounded-lg p-4 border border-primary/20">
                                                                            <h5 className="text-sm font-semibold text-gray-900 mb-3">
                                                                                {editingVenue.mode === 'add' ? 'Add New Venue' : 'Edit Venue'}
                                                                            </h5>

                                                                            <div className="space-y-3">
                                                                                {/* Restaurant Selection */}
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Restaurant Concept *</label>
                                                                                    <select
                                                                                        value={editingVenue.restaurant_id || ''}
                                                                                        onChange={(e) => setEditingVenue(prev => ({ ...prev, restaurant_id: e.target.value }))}
                                                                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                                    >
                                                                                        <option value="">— Select Restaurant —</option>
                                                                                        {(() => {
                                                                                            const prop = (selectedProperty?.property_code || selectedProperty?.code || selectedPropertyCode || '');
                                                                                            const hasPropField = (restaurants || []).some(x => x && (x.property_code !== undefined && x.property_code !== null));
                                                                                            const concepts = hasPropField ? (restaurants || []).filter(x => String(x?.property_code || '') === String(prop)) : (restaurants || []);
                                                                                            return concepts;
                                                                                        })().map(r => (
                                                                                            <option key={r.id} value={r.id}>{r.name}</option>
                                                                                        ))}
                                                                                    </select>
                                                                                </div>

                                                                                {/* Location & Type */}
                                                                                <div className="grid grid-cols-2 gap-3">
                                                                                    <div>
                                                                                        <label className="block text-xs font-medium text-gray-700 mb-1">Location *</label>
                                                                                        <input
                                                                                            type="text"
                                                                                            value={editingVenue.name || ''}
                                                                                            onChange={(e) => setEditingVenue(prev => ({ ...prev, name: e.target.value }))}
                                                                                            placeholder="Lobby, Pool Bar, etc."
                                                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                                        />
                                                                                    </div>
                                                                                    <div>
                                                                                        <label className="block text-xs font-medium text-gray-700 mb-1">Type *</label>
                                                                                        <select
                                                                                            value={editingVenue.type || 'Restaurant'}
                                                                                            onChange={(e) => setEditingVenue(prev => ({ ...prev, type: e.target.value }))}
                                                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                                        >
                                                                                            <option value="Restaurant">Restaurant</option>
                                                                                            <option value="Bar">Bar</option>
                                                                                            <option value="Cafe">Cafe</option>
                                                                                            <option value="Market">Market</option>
                                                                                            <option value="Room Service">Room Service</option>
                                                                                        </select>
                                                                                    </div>
                                                                                </div>

                                                                                {/* Phone & Location Hint */}
                                                                                <div className="grid grid-cols-2 gap-3">
                                                                                    <div>
                                                                                        <label className="block text-xs font-medium text-gray-700 mb-1">Phone</label>
                                                                                        <input
                                                                                            type="tel"
                                                                                            value={editingVenue.phone_number || ''}
                                                                                            onChange={(e) => setEditingVenue(prev => ({ ...prev, phone_number: e.target.value }))}
                                                                                            placeholder="(555) 123-4567"
                                                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                                        />
                                                                                    </div>
                                                                                    <div>
                                                                                        <label className="block text-xs font-medium text-gray-700 mb-1">Location Hint</label>
                                                                                        <input
                                                                                            type="text"
                                                                                            value={editingVenue.location_hint || ''}
                                                                                            onChange={(e) => setEditingVenue(prev => ({ ...prev, location_hint: e.target.value }))}
                                                                                            placeholder="Next to pool, etc."
                                                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"
                                                                                        />
                                                                                    </div>
                                                                                </div>

                                                                                {/* Links */}
                                                                                <div>
                                                                                    <div className="flex items-center justify-between mb-1">
                                                                                        <label className="text-xs font-medium text-gray-700">Links</label>
                                                                                        <button
                                                                                            type="button"
                                                                                            onClick={() => {
                                                                                                const newLinks = { ...(editingVenue.links || {}) };
                                                                                                const key = `link_${Date.now()}`;
                                                                                                newLinks[key] = { type: 'menu', url: '' };
                                                                                                setEditingVenue(prev => ({ ...prev, links: newLinks }));
                                                                                            }}
                                                                                            className="text-xs text-primary hover:text-primary-hover font-medium"
                                                                                        >
                                                                                            + Add
                                                                                        </button>
                                                                                    </div>
                                                                                    <div className="space-y-1.5">
                                                                                        {Object.entries(editingVenue.links || {}).map(([key, link]) => (
                                                                                            <div key={key} className="flex gap-1.5">
                                                                                                <select
                                                                                                    value={link.type || 'menu'}
                                                                                                    onChange={(e) => {
                                                                                                        const newLinks = { ...editingVenue.links };
                                                                                                        newLinks[key] = { ...newLinks[key], type: e.target.value };
                                                                                                        setEditingVenue(prev => ({ ...prev, links: newLinks }));
                                                                                                    }}
                                                                                                    className="w-32 border border-gray-300 rounded px-2 py-1.5 text-xs focus:outline-none focus:border-primary"
                                                                                                >
                                                                                                    <option value="menu">Menu</option>
                                                                                                    <option value="reservations">Reservations</option>
                                                                                                    <option value="website">Website</option>
                                                                                                    <option value="ordering">Online Order</option>
                                                                                                </select>
                                                                                                <input
                                                                                                    type="url"
                                                                                                    value={link.url || ''}
                                                                                                    onChange={(e) => {
                                                                                                        const newLinks = { ...editingVenue.links };
                                                                                                        newLinks[key] = { ...newLinks[key], url: e.target.value };
                                                                                                        setEditingVenue(prev => ({ ...prev, links: newLinks }));
                                                                                                    }}
                                                                                                    placeholder="https://..."
                                                                                                    className="flex-1 border border-gray-300 rounded px-2 py-1.5 text-xs focus:outline-none focus:border-primary"
                                                                                                />
                                                                                                <button
                                                                                                    onClick={() => {
                                                                                                        const newLinks = { ...editingVenue.links };
                                                                                                        delete newLinks[key];
                                                                                                        setEditingVenue(prev => ({ ...prev, links: newLinks }));
                                                                                                    }}
                                                                                                    className="px-2 text-red-600 hover:bg-red-50 rounded"
                                                                                                >
                                                                                                    ×
                                                                                                </button>
                                                                                            </div>
                                                                                        ))}
                                                                                    </div>
                                                                                </div>

                                                                                {/* Features & systems — single list + "Add feature" dropdown (extensible) */}
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Features & systems</label>
                                                                                    <p className="text-xs text-gray-500 mb-2">e.g. self-pour beer, POS, reservation. Add any that apply; you can add more types anytime.</p>
                                                                                    {(() => {
                                                                                        const FEATURE_OPTIONS = [
                                                                                            { id: 'self_pour_system', label: 'Self-pour beer system', defaultValue: 'e.g. iPourIt' },
                                                                                        ];
                                                                                        const predefinedIds = FEATURE_OPTIONS.map(o => o.id);
                                                                                        const features = editingVenue.features || {};
                                                                                        const featureEntries = [
                                                                                            ...FEATURE_OPTIONS.filter(o => features[o.id] !== undefined && features[o.id] !== null).map(o => ({ key: o.id, label: o.label, defaultValue: o.defaultValue, isPredefined: true })),
                                                                                            ...Object.entries(features).filter(([k]) => !predefinedIds.includes(k)).map(([k, v]) => ({ key: k, label: null, defaultValue: '', isPredefined: false, value: typeof v === 'object' && v !== null ? v : v }))
                                                                                        ];
                                                                                        return (
                                                                                            <div className="space-y-2">
                                                                                                {featureEntries.map(({ key, label, defaultValue, isPredefined }) => (
                                                                                                    <div key={key} className="flex gap-2 items-center flex-wrap">
                                                                                                        {isPredefined ? (
                                                                                                            <>
                                                                                                                <span className="text-sm text-gray-700 w-40 shrink-0">{label}</span>
                                                                                                                <input
                                                                                                                    type="text"
                                                                                                                    value={typeof features[key] === 'string' ? features[key] : ''}
                                                                                                                    onChange={(e) => { const n = { ...editingVenue.features }; n[key] = e.target.value; setEditingVenue(prev => ({ ...prev, features: n })); }}
                                                                                                                    placeholder={defaultValue || 'Details'}
                                                                                                                    className="flex-1 min-w-[120px] border border-gray-300 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-primary"
                                                                                                                />
                                                                                                            </>
                                                                                                        ) : (
                                                                                                            <>
                                                                                                                <input
                                                                                                                    type="text"
                                                                                                                    value={typeof features[key] === 'object' && features[key] !== null ? (features[key].key || '') : ''}
                                                                                                                    onChange={(e) => { const n = { ...editingVenue.features }; const v = n[key]; n[key] = (v && typeof v === 'object' ? { ...v, key: e.target.value } : { key: e.target.value, value: '' }); setEditingVenue(prev => ({ ...prev, features: n })); }}
                                                                                                                    placeholder="Feature name"
                                                                                                                    className="w-40 border border-gray-300 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-primary"
                                                                                                                />
                                                                                                                <input
                                                                                                                    type="text"
                                                                                                                    value={typeof features[key] === 'object' && features[key] !== null ? (features[key].value || '') : ''}
                                                                                                                    onChange={(e) => { const n = { ...editingVenue.features }; const v = n[key]; n[key] = (v && typeof v === 'object' ? { ...v, value: e.target.value } : { key: (v && typeof v === 'object' ? v.key : key), value: e.target.value }); setEditingVenue(prev => ({ ...prev, features: n })); }}
                                                                                                                    placeholder="Details"
                                                                                                                    className="flex-1 min-w-[120px] border border-gray-300 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-primary"
                                                                                                                />
                                                                                                            </>
                                                                                                        )}
                                                                                                        <button type="button" onClick={() => { const n = { ...editingVenue.features }; delete n[key]; setEditingVenue(prev => ({ ...prev, features: n })); }} className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded shrink-0" aria-label="Remove">×</button>
                                                                                                    </div>
                                                                                                ))}
                                                                                                <div className="flex gap-2 items-center pt-1">
                                                                                                    <span className="text-xs text-gray-500">Add:</span>
                                                                                                    <select
                                                                                                        value=""
                                                                                                        onChange={(e) => {
                                                                                                            const v = e.target.value;
                                                                                                            if (!v) return;
                                                                                                            e.target.value = '';
                                                                                                            const n = { ...(editingVenue.features || {}) };
                                                                                                            if (v === '_other_') { n[`custom_${Date.now()}`] = { key: '', value: '' }; }
                                                                                                            else { const opt = FEATURE_OPTIONS.find(o => o.id === v); if (opt) n[opt.id] = opt.defaultValue || ''; }
                                                                                                            setEditingVenue(prev => ({ ...prev, features: n }));
                                                                                                        }}
                                                                                                        className="text-sm border border-gray-300 rounded px-2 py-1.5 focus:outline-none focus:border-primary"
                                                                                                    >
                                                                                                        <option value="">— Add a feature —</option>
                                                                                                        {FEATURE_OPTIONS.filter(o => (features[o.id] === undefined || features[o.id] === null || (typeof features[o.id] === 'string' && features[o.id].trim() === ''))).map(o => (
                                                                                                            <option key={o.id} value={o.id}>{o.label}</option>
                                                                                                        ))}
                                                                                                        <option value="_other_">Other (add any type)</option>
                                                                                                    </select>
                                                                                                </div>
                                                                                            </div>
                                                                                        );
                                                                                    })()}
                                                                                </div>

                                                                                {/* Support & technology contacts (linked to venue) */}
                                                                                <div>
                                                                                    <label className="block text-xs font-medium text-gray-700 mb-1">Support & technology contacts</label>
                                                                                    <p className="text-xs text-gray-500 mb-2">Companies or contacts that support this location (e.g. self-pour, POS, or other technology).</p>
                                                                                    <div className="flex flex-wrap gap-2">
                                                                                        {(allVendors || []).map(v => (
                                                                                            <label key={v.id} className="inline-flex items-center gap-2 cursor-pointer">
                                                                                                <input
                                                                                                    type="checkbox"
                                                                                                    checked={((editingVenue.vendor_ids || []).indexOf(v.id) !== -1) || ((editingVenue.vendors || []).some(vv => vv.id === v.id))}
                                                                                                    onChange={(e) => {
                                                                                                        const ids = editingVenue.vendor_ids != null ? [...editingVenue.vendor_ids] : (editingVenue.vendors || []).map(vv => vv.id);
                                                                                                        const set = new Set(ids);
                                                                                                        if (e.target.checked) set.add(v.id); else set.delete(v.id);
                                                                                                        setEditingVenue(prev => ({ ...prev, vendor_ids: Array.from(set) }));
                                                                                                    }}
                                                                                                    className="rounded border-gray-300 text-primary focus:ring-primary"
                                                                                                />
                                                                                                <span className="text-sm text-gray-700">{v.name}</span>
                                                                                            </label>
                                                                                        ))}
                                                                                        {(allVendors || []).length === 0 && <span className="text-xs text-gray-500">No contacts in catalog. Add them in the Vendor Information tab.</span>}
                                                                                    </div>
                                                                                </div>

                                                                                {/* Action Buttons */}
                                                                                <div className="flex gap-2 pt-2">
                                                                                    <button
                                                                                        onClick={() => setEditingVenue(null)}
                                                                                        className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                                                                    >
                                                                                        Cancel
                                                                                    </button>
                                                                                    <button
                                                                                        onClick={handleSaveVenue}
                                                                                        disabled={savingVenue}
                                                                                        className="flex-1 px-3 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
                                                                                    >
                                                                                        {savingVenue ? 'Saving...' : 'Save Venue'}
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    ) : (conceptsForProperty.length === 0 && (venues || []).length === 0) ? (
                                                                        <p className="text-sm text-gray-500 py-6">No concepts yet. Use “+ Add concept” above to add a restaurant concept, then add locations under it.</p>
                                                                    ) : (
                                                                        <ul className="space-y-4">
                                                                            {conceptsForProperty.map(concept => {
                                                                                const conceptVenues = (venues || []).filter(v => String(v?.restaurant_id || '') === String(concept.id));
                                                                                return (
                                                                                    <li key={concept.id} className="border-b border-gray-100 pb-4 last:border-0 last:pb-0">
                                                                                        <div className="flex items-center justify-between gap-2 mb-1">
                                                                                            <span className="font-semibold text-gray-900">{concept.name}</span>
                                                                                            {canManageDiningVenues && (
                                                                                                <span className="flex items-center gap-2">
                                                                                                    <button type="button" onClick={() => setEditingVenue({ mode: 'add', restaurant_id: String(concept.id), name: '', type: 'Restaurant', phone_number: '', location_hint: '', links: {}, features: {}, vendor_ids: [] })} className="text-xs text-primary hover:text-primary-hover">Add location</button>
                                                                                                    <button type="button" disabled={deletingConceptId === concept.id} onClick={() => handleDeleteConcept(concept.id, concept.name)} className="text-xs text-gray-500 hover:text-red-600 disabled:opacity-50">{deletingConceptId === concept.id ? '…' : 'Remove'}</button>
                                                                                                </span>
                                                                                            )}
                                                                                        </div>
                                                                                        <ul className="pl-4 space-y-1 text-sm">
                                                                                            {conceptVenues.length === 0 && <li className="text-gray-400 italic">No locations</li>}
                                                                                            {conceptVenues.map(venue => (
                                                                                                <li key={venue.id} className="flex items-center justify-between gap-2 py-0.5">
                                                                                                    <span className="text-gray-700">{venue.name || venue.restaurant_name} · {venue.type}</span>
                                                                                                    {canManageDiningVenues && (
                                                                                                        <span className="flex gap-1">
                                                                                                            <button type="button" onClick={() => { const featuresForm = {}; Object.entries(venue.features || {}).forEach(([k, v], i) => { const val = (v == null ? '' : String(v)).trim(); if (k === 'self_pour_system') featuresForm[k] = val; else featuresForm[`custom_${i}_${venue.id}`] = { key: k, value: val }; }); setEditingVenue({ ...venue, mode: 'edit', features: featuresForm, vendor_ids: (venue.vendors || []).map(v => v.id) }); }} className="text-gray-400 hover:text-primary">Edit</button>
                                                                                                            <button type="button" onClick={() => handleDeleteVenue(venue.id)} className="text-gray-400 hover:text-red-600">Delete</button>
                                                                                                        </span>
                                                                                                    )}
                                                                                                </li>
                                                                                            ))}
                                                                                        </ul>
                                                                                    </li>
                                                                                );
                                                                            })}
                                                                            {canManageDiningVenues && (
                                                                                <li className="pt-2">
                                                                                    <button type="button" onClick={() => setAddingConcept(true)} className="text-sm text-primary hover:text-primary-hover font-medium">+ Add concept</button>
                                                                                </li>
                                                                            )}
                                                                        </ul>
                                                                    )}
                                                                </div>
                                                            </div>
                                                    );
                                                })()}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </>
                        ) : (
                            <div className="flex-1 flex items-center justify-center text-gray-400">
                                <div className="text-center">
                                    <svg className="w-12 h-12 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                    </svg>
                                    <p>Select a property</p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Add Property modal */}
            {showAddProperty && (
                <div className="absolute inset-0 z-10 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4" onClick={handleCloseAddProperty}>
                    <div className="bg-white rounded-xl shadow-xl max-w-md w-full border border-gray-200 p-6" onClick={e => e.stopPropagation()}>
                        <h3 className="text-lg font-bold text-gray-900 mb-4">Add Property</h3>
                        <form onSubmit={handleCreateProperty} className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Property Code <span className="text-red-500">*</span></label>
                                <input
                                    type="text"
                                    value={newPropertyCode}
                                    onChange={e => setNewPropertyCode(e.target.value.toUpperCase())}
                                    placeholder="e.g. ANPMD"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                    maxLength={20}
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Property Name <span className="text-red-500">*</span></label>
                                <input
                                    type="text"
                                    value={newPropertyName}
                                    onChange={e => setNewPropertyName(e.target.value)}
                                    placeholder="e.g. Anaheim Property"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Address (optional)</label>
                                <input
                                    type="text"
                                    value={newPropertyAddress}
                                    onChange={e => setNewPropertyAddress(e.target.value)}
                                    placeholder="Street address"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">City</label>
                                    <input
                                        type="text"
                                        value={newPropertyCity}
                                        onChange={e => setNewPropertyCity(e.target.value)}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">State</label>
                                    <input
                                        type="text"
                                        value={newPropertyState}
                                        onChange={e => setNewPropertyState(e.target.value)}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">ZIP</label>
                                <input
                                    type="text"
                                    value={newPropertyZip}
                                    onChange={e => setNewPropertyZip(e.target.value)}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                                />
                            </div>
                            {addPropertyError && (
                                <p className="text-sm text-red-600">{addPropertyError}</p>
                            )}
                            <div className="flex gap-3 justify-end pt-2">
                                <button
                                    type="button"
                                    onClick={handleCloseAddProperty}
                                    className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={savingNewProperty || !newPropertyCode.trim() || !newPropertyName.trim()}
                                    className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50"
                                >
                                    {savingNewProperty ? 'Creating...' : 'Create Property'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

// Error Boundary Component