var _useState = React.useState;
var _useCallback = React.useCallback;
var _useNavigate = ReactRouterDOM.useNavigate;
var _useLocation = ReactRouterDOM.useLocation;

var ROOM_TYPES = AppConstants.ROOM_TYPES;
var BUILDING_TYPES = AppConstants.BUILDING_TYPES;

/**
 * LocationDetails — Property management + post-scan location/observation capture.
 *
 * Two user journeys:
 *   1. Post-scan: assign property, room, observations to the latest scan
 *   2. Property management: add, edit, delete properties
 *
 * Observations (room, odour, texture, severity, notes) only shown when a scan exists.
 * Property cards show building type, scan count, and last scan time for decision-making.
 */
var LocationDetails = function () {

    var manageProperty = useFeatureFlag('MANAGE_PROPERTY');
    var manageMould    = useFeatureFlag('MANAGE_MOULD');

    // ─── Upgrade panel config ─────────────────────────────────────────────────────
    const LOCATION_UPGRADE_FEATURES = [
        { icon: 'add_home',       label: 'Add unlimited properties' },
        { icon: 'nest_multi_room',label: 'Organise scans by room across locations' },
        { icon: 'finance',        label: 'Per-property severity reports & charts' },
        { icon: 'notifications',  label: 'High & critical severity alerts per property' },
    ];

    var navigate = _useNavigate();
    var location = _useLocation();
    var fromScan = location.state && location.state.fromScan;
    var store = useScanStore();
    var latest = store.getLatestScan();
    var existingProperties = store.getProperties();
    var primaryProp = store.getPrimaryProperty();

    // --- Selection state ---
    var selectedPropState = _useState(primaryProp ? primaryProp.id : null);
    var selectedPropertyId = selectedPropState[0];
    var setSelectedPropertyId = selectedPropState[1];

    // --- Search + filter state ---
    var searchState = _useState('');
    var searchQuery = searchState[0];
    var setSearchQuery = searchState[1];

    var filterState = _useState('all');
    var activeFilter = filterState[0];
    var setActiveFilter = filterState[1];

    // --- Property form mode: 'add' | propertyId | null ---
    var editPropState = _useState(existingProperties.length === 0 ? 'add' : null);
    var editPropId = editPropState[0];
    var setEditPropId = editPropState[1];

    // --- Property form fields (shared for add + edit) ---
    var epNameState = _useState('');
    var epName = epNameState[0]; var setEpName = epNameState[1];
    var epAddrState = _useState('');
    var epAddr = epAddrState[0]; var setEpAddr = epAddrState[1];
    var epBuildState = _useState('House');
    var epBuild = epBuildState[0]; var setEpBuild = epBuildState[1];
    var epPrimaryState = _useState(existingProperties.length === 0);
    var epPrimary = epPrimaryState[0]; var setEpPrimary = epPrimaryState[1];

    // --- Scan observation state (only used when latest scan exists) ---
    var roomState = _useState('');
    var roomType = roomState[0]; var setRoomType = roomState[1];
    var odourState = _useState(null);
    var odourLevel = odourState[0]; var setOdourLevel = odourState[1];
    var odourSourceState = _useState('');
    var odourSource = odourSourceState[0]; var setOdourSource = odourSourceState[1];
    var textureState = _useState([]);
    var surfaceTextures = textureState[0]; var setSurfaceTextures = textureState[1];
    var severityState = _useState(0);
    var severityRating = severityState[0]; var setSeverityRating = severityState[1];
    var notesState = _useState('');
    var notes = notesState[0]; var setNotes = notesState[1];

    // --- Enterprise assessment state (only used when MANAGE_MOULD is on) ---
    var enterpriseState = _useState(window._EMA_DEFAULT_ASSESSMENT);
    var enterpriseAssessment = enterpriseState[0];
    var setEnterpriseAssessment = enterpriseState[1];

    // --- Delete confirmation: { type: 'property', id } | null ---
    var confirmState = _useState(null);
    var confirmDelete = confirmState[0]; var setConfirmDelete = confirmState[1];

    var inputClass = 'bg-surface border-none rounded-xl text-sm p-3 shadow-soft ring-1 ring-sage/20 focus:ring-2 focus:ring-primary font-semibold text-forest placeholder:text-sage/60 placeholder:font-medium';

    // --- Property search + filter ---
    var matchesProperty = function (prop, query) {
        if (!query) return true;
        var q = query.toLowerCase();
        if (prop.name && prop.name.toLowerCase().indexOf(q) >= 0) return true;
        if (prop.address && prop.address.toLowerCase().indexOf(q) >= 0) return true;
        if (prop.buildingType && prop.buildingType.toLowerCase().indexOf(q) >= 0) return true;
        return false;
    };

    var filteredProperties = [];
    for (var fp = 0; fp < existingProperties.length; fp++) {
        var p = existingProperties[fp];
        if (activeFilter !== 'all' && p.buildingType !== activeFilter) continue;
        if (matchesProperty(p, searchQuery)) filteredProperties.push(p);
    }

    // Derive unique building types for filter lozenges
    var buildingTypeFilters = [];
    var btSeen = {};
    for (var bt = 0; bt < existingProperties.length; bt++) {
        var bType = existingProperties[bt].buildingType || 'House';
        if (!btSeen[bType]) {
            btSeen[bType] = true;
            buildingTypeFilters.push(bType);
        }
    }
    buildingTypeFilters.sort();

    var PROP_FILTERS = [{ key: 'all', label: 'All', icon: 'list' }];
    for (var pf = 0; pf < buildingTypeFilters.length; pf++) {
        PROP_FILTERS.push({ key: buildingTypeFilters[pf], label: buildingTypeFilters[pf], icon: 'apartment' });
    }

    var showSearch = existingProperties.length >= 2;

    // --- Property form helpers ---
    var resetPropertyForm = function () {
        setEpName(''); setEpAddr(''); setEpBuild('House'); setEpPrimary(false);
    };

    var startAddProperty = function () {
        resetPropertyForm();
        setEpPrimary(existingProperties.length === 0);
        setEditPropId('add');
    };

    var startEditProperty = _useCallback(function (prop) {
        setEditPropId(prop.id);
        setEpName(prop.name || '');
        setEpAddr(prop.address || '');
        setEpBuild(prop.buildingType || 'House');
        setEpPrimary(prop.isPrimary || false);
    }, []);

    var cancelPropertyForm = function () {
        setEditPropId(null);
        resetPropertyForm();
    };

    var savePropertyForm = _useCallback(function () {
        if (!epName.trim() && !epAddr.trim()) return;
        if (editPropId === 'add') {
            var newProp = store.addProperty({
                name: epName.trim() || 'My Property',
                address: epAddr.trim(),
                buildingType: epBuild,
                isPrimary: epPrimary,
            });
            setSelectedPropertyId(newProp.id);
        } else {
            store.updateProperty(editPropId, {
                name: epName.trim(),
                address: epAddr.trim(),
                buildingType: epBuild,
                isPrimary: epPrimary,
            });
        }
        setEditPropId(null);
        resetPropertyForm();
    }, [editPropId, epName, epAddr, epBuild, epPrimary, store]);

    var handleConfirmDelete = _useCallback(function () {
        if (!confirmDelete) return;
        store.deleteProperty(confirmDelete.id);
        if (selectedPropertyId === confirmDelete.id) {
            setSelectedPropertyId(null);
        }
        setConfirmDelete(null);
        setEditPropId(null);
    }, [confirmDelete, selectedPropertyId, store]);

    // --- Observation handlers ---
    var toggleTexture = _useCallback(function (tex) {
        setSurfaceTextures(function (prev) {
            var idx = prev.indexOf(tex);
            if (idx >= 0) return prev.slice(0, idx).concat(prev.slice(idx + 1));
            return prev.concat([tex]);
        });
    }, []);

    var handleSave = _useCallback(function () {
        var fields = {
            propertyId:     manageProperty ? (selectedPropertyId || null) : null,
            roomName:       roomType || null,
            odourLevel:     manageMould ? (enterpriseAssessment.odourLevel || null) : odourLevel,
            odourSource:    manageMould ? (enterpriseAssessment.odourSource || null) : odourSource,
            surfaceTextures: manageMould ? [] : surfaceTextures,
            severityRating: severityRating,
            notes:          manageMould ? (enterpriseAssessment.generalNotes || '') : notes,
        };
        // Enterprise-only fields
        if (manageMould) {
            fields.assessmentComponents  = enterpriseAssessment.components || null;
            fields.environmentalReadings = {
                temp:          enterpriseAssessment.envTemp,
                humidity:      enterpriseAssessment.envHumidity,
                co2:           enterpriseAssessment.envCO2,
                lightMin:      enterpriseAssessment.envLightMin,
                lightMax:      enterpriseAssessment.envLightMax,
                formaldehyde:  enterpriseAssessment.envFormaldehyde,
                vocs:          enterpriseAssessment.envVOCs,
            };
            fields.riskClassification = enterpriseAssessment.overallRisk || null;
            fields.remediationMethod  = enterpriseAssessment.remediationMethod || null;
            fields.containmentType    = enterpriseAssessment.containmentType || null;
            fields.ppeLevel           = enterpriseAssessment.ppeLevel || null;
            fields.technicianName     = enterpriseAssessment.technicianName || null;
            fields.technicianCertNo   = enterpriseAssessment.technicianCertNo || null;
            fields.assessmentDate     = enterpriseAssessment.assessmentDate || null;
        }
        store.updateLatestScan(fields);
        navigate('/reports');
    }, [selectedPropertyId, roomType, odourLevel, odourSource, surfaceTextures, severityRating, notes, enterpriseAssessment, manageMould, manageProperty, store, navigate]);

    // --- Shared property form renderer ---
    var renderPropertyForm = function (isAdd) {
        return (
            <div className="bio-bg bio-bg-10 rounded-xl p-5 shadow-soft border border-stone-100/50 space-y-4">
                <div className="flex items-center justify-between">
                    <h3 className="text-sm font-extrabold text-forest">{isAdd ? 'Add Your Property' : 'Edit Property'}</h3>
                    {(isAdd ? existingProperties.length > 0 : true) && (
                        <button onClick={cancelPropertyForm} className="text-[10px] font-black text-sage uppercase tracking-widest btn-nature">Cancel</button>
                    )}
                </div>
                {isAdd && existingProperties.length === 0 && (
                    <p className="text-xs text-muted font-medium leading-relaxed -mt-2">Add your property details so scans are organised by location.</p>
                )}
                <div className="space-y-3">
                    <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-black text-sage uppercase tracking-[0.15em] ml-1">Property Name</label>
                        <input type="text" className={inputClass} placeholder="e.g. Main Residence, Holiday Home" value={epName} onChange={function (e) { setEpName(e.target.value); }} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-black text-sage uppercase tracking-[0.15em] ml-1">Address</label>
                        <input type="text" className={inputClass} placeholder="Street address" value={epAddr} onChange={function (e) { setEpAddr(e.target.value); }} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-black text-sage uppercase tracking-[0.15em] ml-1">Building Type</label>
                        <select className={inputClass + ' appearance-none'} value={epBuild} onChange={function (e) { setEpBuild(e.target.value); }}>
                            {BUILDING_TYPES.map(function (bt) { return <option key={bt} value={bt}>{bt}</option>; })}
                        </select>
                    </div>
                    <button type="button" onClick={function () { setEpPrimary(!epPrimary); }} className="flex items-center gap-3 p-2 w-full text-left btn-nature">
                        <div className={'w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors ' + (epPrimary ? 'bg-forest border-forest' : 'border-sage/30 bg-surface')}>
                            {epPrimary && <span className="material-symbols-outlined text-white text-sm">check</span>}
                        </div>
                        <span className="text-sm font-semibold text-forest">Set as primary residence</span>
                    </button>
                    <div className="flex gap-2">
                        <button
                            onClick={savePropertyForm}
                            disabled={!epName.trim() && !epAddr.trim()}
                            className="flex-1 bg-forest text-white font-extrabold py-3 rounded-xl shadow-clay flex items-center justify-center gap-2 btn-nature hover:brightness-110 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                        >
                            <span className="material-symbols-outlined text-lg">{isAdd ? 'add_home' : 'check_circle'}</span>
                            {isAdd ? 'Save Property' : 'Save Changes'}
                        </button>
                        {!isAdd && (
                            <button
                                onClick={function () { setConfirmDelete({ type: 'property', id: editPropId }); }}
                                className="py-3 px-4 rounded-xl border border-warning/30 text-warning btn-nature"
                            >
                                <span className="material-symbols-outlined text-lg">delete</span>
                            </button>
                        )}
                    </div>
                </div>
            </div>
        );
    };

    return (
        <Layout>
            <main className="flex-1 w-full mx-auto pb-36 overflow-y-auto overflow-x-hidden">
                <PageHeader title="Location Details" showMenu={true} backColor="text-forest" titleClass="font-extrabold text-xl text-forest tracking-tight" className="z-50" />

                {/* Delete confirmation */}
                <ConfirmDialog
                    isOpen={!!confirmDelete}
                    onConfirm={handleConfirmDelete}
                    onCancel={function () { setConfirmDelete(null); }}
                    title="Delete Property?"
                    description="This will remove the property. Scans linked to it will become unassigned."
                />

                {/* 1. Scan Reference Card — only during post-scan flow */}
                {fromScan && latest && (
                    <section className="px-6 py-2 mt-4">
                        <div className="bio-bg bio-bg-20 rounded-xl p-4 shadow-soft border border-stone-100/50 btn-nature">
                            <div className="flex items-center gap-4">
                                <div className="w-20 h-20 rounded-xl overflow-hidden flex-shrink-0 bg-background-light">
                                    {latest.thumbnail ? (
                                        <img alt={latest.fileName} className="w-full h-full object-cover" src={latest.thumbnail} />
                                    ) : (
                                        <div className="w-full h-full flex items-center justify-center">
                                            <span className="material-symbols-outlined text-sage text-2xl">image</span>
                                        </div>
                                    )}
                                </div>
                                <div className="flex-1">
                                    <span className="text-[10px] font-black text-sage uppercase tracking-[0.15em]">Last Scan</span>
                                    <h3 className="text-sm font-extrabold text-forest">{latest.verdict}</h3>
                                    <p className="text-[11px] font-semibold text-muted">{latest.fileName}</p>
                                </div>
                            </div>
                        </div>
                    </section>
                )}

                {/* 2. Property Section — gated by MANAGE_PROPERTY flag */}
                {manageProperty && (
                <section className="px-6 py-4 space-y-3">
                    <div className="flex items-center justify-between">
                        <h2 className="text-base font-extrabold text-forest">Property</h2>
                        {existingProperties.length > 0 && editPropId === null && (
                            <button onClick={startAddProperty} className="text-[10px] font-black text-forest uppercase tracking-widest flex items-center gap-1 btn-nature">
                                <span className="material-symbols-outlined text-sm">add_circle</span> Add New
                            </button>
                        )}
                    </div>

                    {/* Search + Filters — shown when 2+ properties */}
                    {showSearch && editPropId === null && (
                        <div className="space-y-3">
                            <div className="relative">
                                <span className="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-forest text-lg pointer-events-none">search</span>
                                <input type="text" className="w-full bg-surface border-none rounded-xl text-sm py-3 pl-10 pr-10 shadow-soft ring-1 ring-sage/20 focus:ring-2 focus:ring-primary font-semibold text-forest placeholder:text-forest/60 placeholder:font-medium" placeholder="Search by name, address, type..." value={searchQuery} onChange={function (e) { setSearchQuery(e.target.value); }} />
                                {searchQuery && (
                                    <button onClick={function () { setSearchQuery(''); }} className="absolute right-3 top-1/2 -translate-y-1/2 text-forest hover:text-forest transition-colors">
                                        <span className="material-symbols-outlined text-lg">close</span>
                                    </button>
                                )}
                            </div>
                            {searchQuery && (
                                <p className="text-xs font-semibold text-forest px-1">{filteredProperties.length} result{filteredProperties.length !== 1 ? 's' : ''} for "<span className="font-bold text-forest">{searchQuery}</span>"</p>
                            )}
                            {PROP_FILTERS.length > 2 && (
                                <div className="flex gap-2 overflow-x-auto no-scrollbar pb-1">
                                    {PROP_FILTERS.map(function (f) {
                                        var isActive = activeFilter === f.key;
                                        return (
                                            <button key={f.key} onClick={function () { setActiveFilter(f.key); }} className={'flex items-center gap-1.5 px-4 py-2.5 rounded-xl text-xs font-bold whitespace-nowrap transition-all btn-nature shrink-0 ' + (isActive ? 'bg-forest text-white shadow-clay' : 'bg-surface border border-stone-100/50 text-forest shadow-soft hover:bg-forest hover:text-white')}>
                                                <span className="material-symbols-outlined text-[16px]">{f.icon}</span>
                                                {f.label}
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                            {activeFilter === 'all' && filteredProperties.length > 0 && (
                                <div className="flex items-center justify-between px-1">
                                    <h4 className="font-extrabold text-forest">Total Properties</h4>
                                    <span className="text-[10px] font-black text-forest uppercase tracking-widest">{filteredProperties.length} propert{filteredProperties.length !== 1 ? 'ies' : 'y'}</span>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Add property form */}
                    {editPropId === 'add' && renderPropertyForm(true)}

                    {/* Property list — hidden when adding */}
                    {editPropId !== 'add' && filteredProperties.length > 0 && (
                        <div className="space-y-2">
                            {filteredProperties.map(function (prop) {
                                var isSelected = selectedPropertyId === prop.id;
                                var isEditing = editPropId === prop.id;
                                var propScans = store.getScansForProperty(prop.id);
                                var scanCount = propScans.length;
                                var lastScanTime = '';
                                if (scanCount > 0) {
                                    var newest = propScans[0];
                                    for (var s = 1; s < propScans.length; s++) {
                                        if (propScans[s].timestamp > newest.timestamp) newest = propScans[s];
                                    }
                                    lastScanTime = FormatUtils.timeAgo(newest.timestamp);
                                }

                                // Show edit form inline for this property
                                if (isEditing) return (
                                    <div key={prop.id}>{renderPropertyForm(false)}</div>
                                );

                                return (
                                    <div key={prop.id} className={'group rounded-xl transition-all duration-300 btn-nature ' + (isSelected ? 'bg-forest shadow-clay' : 'bio-bg bio-bg-10 shadow-soft border border-stone-100/50 hover:bg-forest cursor-pointer')}>
                                        {/* Property card — tap to select */}
                                        <button
                                            onClick={function () { setSelectedPropertyId(isSelected ? null : prop.id); }}
                                            className="group w-full flex items-center gap-3 p-3 text-left btn-nature"
                                        >
                                            <div className={'w-10 h-10 rounded-2xl flex items-center justify-center shrink-0 transition-colors ' + (isSelected ? 'bg-white/15 text-white' : 'bg-background-light text-forest group-hover:bg-primary/20 group-hover:text-primary')}>
                                                <span className="material-symbols-outlined text-lg">{prop.isPrimary ? 'home' : 'apartment'}</span>
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <div className="flex items-center gap-2">
                                                    <p className={'text-sm font-extrabold truncate transition-colors ' + (isSelected ? 'text-white' : 'text-forest group-hover:text-white')}>{prop.name || 'Unnamed'}</p>
                                                    {prop.isPrimary && (
                                                        <span className={'text-[9px] px-1.5 py-0.5 rounded-full font-black uppercase tracking-tight shrink-0 ' + (isSelected ? 'bg-white/15 text-accent' : 'bg-primary/15 text-primary')}>Primary</span>
                                                    )}
                                                </div>
                                                {prop.address && <p className={'text-[11px] font-semibold truncate transition-colors ' + (isSelected ? 'text-accent/60' : 'text-muted group-hover:text-accent/60')}>{prop.address}</p>}
                                                <p className={'text-[10px] font-bold transition-colors ' + (isSelected ? 'text-white/40' : 'text-sage group-hover:text-white/40')}>
                                                    {prop.buildingType}
                                                    {scanCount > 0 ? ' • ' + scanCount + ' scan' + (scanCount !== 1 ? 's' : '') + ' • ' + lastScanTime : ' • No scans'}
                                                </p>
                                            </div>
                                            {isSelected && (
                                                <span className="material-symbols-outlined text-primary text-lg shrink-0">check_circle</span>
                                            )}
                                        </button>

                                        {/* Edit/Delete actions — shown when selected */}
                                        {isSelected && (
                                            <div className="flex gap-2 px-3 pb-3">
                                                <button
                                                    onClick={function () { startEditProperty(prop); }}
                                                    className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl bg-white/10 text-white/80 text-xs font-bold btn-nature hover:bg-white/20 transition-colors"
                                                >
                                                    <span className="material-symbols-outlined text-[16px]">edit</span> Edit
                                                </button>
                                                <button
                                                    onClick={function () { setConfirmDelete({ type: 'property', id: prop.id }); }}
                                                    className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl bg-white/10 text-warning text-xs font-bold btn-nature hover:bg-warning/20 transition-colors"
                                                >
                                                    <span className="material-symbols-outlined text-[16px]">delete</span> Delete
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    )}

                    {/* No matching properties */}
                    {editPropId !== 'add' && existingProperties.length > 0 && filteredProperties.length === 0 && (
                        <div className="bio-bg bio-bg-20 rounded-xl shadow-soft p-8 border border-stone-100/50 text-center">
                            <span className="material-symbols-outlined text-forest text-4xl mb-2">search_off</span>
                            <p className="text-sm font-extrabold text-forest mb-1">No matching properties</p>
                            <p className="text-xs font-medium text-forest">Try a different search term or filter.</p>
                        </div>
                    )}

                    <UpgradePanel 
                        title="Manage Multiple Properties"
                        description="Sign up free to add more properties and track mould risk across all your locations."
                        features={LOCATION_UPGRADE_FEATURES}
                        ctaLabel="Sign Up Free — No Credit Card"
                    />
                </section>
                )}

                {/* 3. Room + Observations + Save — only during post-scan flow */}
                {fromScan && latest && (
                    <div>
                        {/* Room Selection */}
                        <section className="px-6 py-2 space-y-3">
                            <h2 className="text-base font-extrabold text-forest">Room</h2>
                            <Typeahead options={ROOM_TYPES} placeholder="Search rooms..." value={roomType} onChange={setRoomType} />
                        </section>

                        {/* Observations — standard or enterprise based on flag */}
                        <section className="px-6 py-4 space-y-5">
                            <div className="flex items-center justify-between">
                                <h2 className="text-base font-extrabold text-forest">
                                    {manageMould ? 'Mould Assessment' : 'Observations'}
                                </h2>
                            </div>
                            {manageMould ? (
                                <EnterpriseMouldAssessment
                                    value={enterpriseAssessment}
                                    onChange={setEnterpriseAssessment}
                                    aiResult={latest}
                                />
                            ) : (
                                <ScanObservationForm
                                    odour={odourLevel}
                                    onOdourChange={setOdourLevel}
                                    odourSource={odourSource}
                                    onOdourSource={setOdourSource}
                                    textures={surfaceTextures}
                                    onTextureToggle={toggleTexture}
                                    severityRating={severityRating}
                                    onSeverityChange={setSeverityRating}
                                    notes={notes}
                                    onNotesChange={setNotes}
                                />
                            )}
                        </section>

                        {/* Save */}
                        <div className="px-6 pb-8 space-y-3">
                            <button onClick={handleSave} className="w-full bg-forest text-white font-extrabold py-4 rounded-xl shadow-clay flex items-center justify-center gap-2 btn-nature hover:brightness-110 transition-all">
                                <span className="material-symbols-outlined">check_circle</span>
                                Save Scan and Location Details
                            </button>
                            <button onClick={function () { navigate(-1); }} className="w-full text-forest font-bold py-2 text-sm btn-nature hover:text-forest transition-colors">
                                Skip for now
                            </button>
                        </div>
                        <div className="px-6">
                            <FindSpecialistPanel context="location" />
                        </div>
                    </div>
                )}

                {/* When visiting from menu (not post-scan), show property-only message */}
                {manageProperty && !fromScan && existingProperties.length > 0 && editPropId === null && (
                    <div className="px-6 pt-4">
                        <div className="bio-bg bio-bg-20 rounded-xl shadow-soft p-6 border border-stone-100/50 text-center">
                            <span className="material-symbols-outlined text-sage text-3xl mb-2">info</span>
                            <p className="text-sm font-extrabold text-forest">Manage your properties above</p>
                            <p className="text-xs font-medium text-forest mt-1">Room details and observations are captured when you upload a scan.</p>
                        </div>
                    </div>
                )}

                {/* When no scan exists during post-scan flow, prompt to upload */}
                {fromScan && !latest && (
                    <div className="px-6 pt-4">
                        <div onClick={function () { navigate('/analysis'); }} className="bio-bg bio-bg-10 rounded-xl shadow-soft p-6 border border-stone-100/50 text-center btn-nature cursor-pointer group hover:bg-forest transition-all duration-300">
                            <span className="material-symbols-outlined text-primary text-3xl mb-2">add_a_photo</span>
                            <p className="text-sm font-extrabold text-forest group-hover:text-primary transition-colors">Upload a photo to add scan details</p>
                            <p className="text-xs font-medium text-muted group-hover:text-accent/60 transition-colors mt-1">Room, observations, and notes are captured per scan.</p>
                        </div>
                    </div>
                )}
            </main>
        </Layout>
    );
};

window.LocationDetails = LocationDetails;
