var _useParams = ReactRouterDOM.useParams;
var _useNavigate = ReactRouterDOM.useNavigate;
var _useState_SD = React.useState;
var _useEffect_SD = React.useEffect;

/**
 * ScanDetails — Detailed view of a single scan.
 * Route: /scan/:id
 * Reads scan + property data from ScanStore context.
 *
 * CR-02: heatmapDataURL is stripped from in-memory ScanStore state to
 * prevent base64 accumulation. It is loaded on-demand from IndexedDB
 * via StorageService.getScanById() when this component mounts.
 */
var ScanDetails = function () {
    var manageProperty = useFeatureFlag('MANAGE_PROPERTY');
    var speciesEnabled  = useFeatureFlag('SPECIES_LIST');
    var params = _useParams();
    var navigate = _useNavigate();
    var store = useScanStore();

    // CR-02: on-demand heatmap load state
    var heatmapState = _useState_SD(null);
    var heatmapDataURL = heatmapState[0]; var setHeatmapDataURL = heatmapState[1];

    var scan = null;
    var allScans = store.scans;
    for (var i = 0; i < allScans.length; i++) {
        if (allScans[i].id === params.id) { scan = allScans[i]; break; }
    }

    // CR-02: Load heatmapDataURL on-demand from IndexedDB when scan mounts.
    // Avoids holding base64 in React state for every scan across the session.
    _useEffect_SD(function () {
        if (!scan) return;
        var cancelled = false;
        setHeatmapDataURL(null);
        StorageService.getScanById(scan.id).then(function (fullRecord) {
            if (cancelled) return;
            if (fullRecord && fullRecord.heatmapDataURL) {
                setHeatmapDataURL(fullRecord.heatmapDataURL);
            }
        })['catch'](function (err) {
            if (cancelled) return;
            console.warn('[ScanDetails] Could not load heatmap:', err.message);
        });
        return function () { cancelled = true; };
    }, [scan && scan.id]);

    // Resolve property
    var property = scan && scan.propertyId ? store.getPropertyById(scan.propertyId) : null;

    // Severity config
    var formatDateTime = FormatUtils.dateTime;

    // Remediation tips based on severity
    var tips = [
        { num: '01', title: 'Vinegar Solution', desc: 'Spray undiluted white vinegar on the affected area. Let sit for 1 hour before wiping clean with warm water.' },
        { num: '02', title: 'Tea Tree Oil', desc: 'Mix 1 tsp of tea tree oil with 1 cup of water. Spray and do not rinse; the oil helps prevent regrowth.' },
        { num: '03', title: 'Improve Ventilation', desc: 'Open windows or use exhaust fans to reduce moisture. Consider a dehumidifier for persistent damp areas.' },
    ];

    if (!scan) {
        return (
            <Layout>
                <main className="flex-1 overflow-y-auto overflow-x-hidden px-6 pb-36 flex flex-col items-center justify-center gap-4">
                    <PageHeader title="Scan Details" />
                    <span className="material-symbols-outlined text-forest text-5xl">search_off</span>
                    <p className="text-sm font-semibold text-forest">Scan not found</p>
                    <button onClick={function () { navigate('/'); }} className="text-sm font-extrabold text-forest btn-nature">Go Home</button>
                </main>
            </Layout>
        );
    }

    var sev = SeverityConfig.get(scan.severity);
    var displayName = scan.roomName || scan.verdict || scan.fileName;
    var propertyAddr = property ? (property.address || property.name) : null;

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

                {/* Scan Image with severity badge */}
                <div className="px-6 mt-4">
                    <div className="relative rounded-xl h-64 shadow-soft overflow-hidden bg-background-light">
                        {scan.thumbnail ? (
                            <img className="w-full h-full object-cover" src={scan.thumbnail} alt={displayName} />
                        ) : (
                            <div className="w-full h-full flex items-center justify-center">
                                <span className="material-symbols-outlined text-muted text-5xl">image</span>
                            </div>
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent"></div>
                        <div className={'absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider flex items-center gap-1 shadow-sm ' + sev.bg + ' text-white'}>
                            <span className="material-symbols-outlined text-sm" style={{ fontVariationSettings: "'FILL' 1" }}>{sev.icon}</span>
                            {sev.labelLong}
                        </div>
                        <div className="absolute bottom-0 left-0 right-0 p-4">
                            <p className="text-white text-xl font-bold leading-tight">{displayName}</p>
                        </div>
                    </div>
                </div>

                {/* Confidence Score */}
                <section className="px-6 mt-4 mb-4">
                    <div className="bio-bg bio-bg-20 p-5 rounded-xl border border-stone-100/50 flex items-center justify-between shadow-soft">
                        <div className="flex flex-col">
                            <span className="text-[10px] font-black text-forest uppercase tracking-[0.15em]">Confidence Score</span>
                            <span className="text-3xl font-extrabold text-forest">{scan.percentage}%</span>
                            <span className={'text-xs font-bold mt-1 ' + (scan.percentage >= 60 ? 'text-warning' : 'text-primary')}>
                                {scan.verdict}
                            </span>
                            {scan.aiEngine && (
                                <span className={'text-[10px] font-bold mt-1 ' + (scan.aiEngine === 'local_cnn' ? 'text-primary' : 'text-forest/40')}>
                                    {scan.aiEngine === 'local_cnn' ? '🧠 Local AI' : '☁️ Nyckel API'}
                                </span>
                            )}
                        </div>
                        <ConfidenceRing percentage={scan.percentage} severity={scan.severity} size={80} label="" icon="biotech" />
                    </div>
                </section>

                {/* Frequency Spectrum — Local CNN scans only */}
                {scan.freqSpectrum && (
                    <section className="px-6 mb-4">
                        <FrequencySpectrumBar freqSpectrum={scan.freqSpectrum} />
                    </section>
                )}

                {/* Heatmap — present when heatmap data exists */}
                {heatmapDataURL && (
                    <section className="px-6 mb-4">
                        <LocalHeatmapPanel
                            heatmapDataURL={heatmapDataURL}
                            originalDataURL={scan.thumbnail}
                            isMould={scan.percentage >= 50}
                            saliencyLevel={scan.saliencyLevel}
                            isShortcut={scan.isShortcut}
                            speciesLabel={speciesEnabled && scan.speciesTop ? scan.speciesTop.label : ''}
                        />
                    </section>
                )}

                {/* Species Identification — gated by SPECIES_LIST flag */}
                {speciesEnabled && scan.speciesTop && (
                    <section className="px-6 mb-4">
                        <LocalSpeciesPanel
                            speciesTop={scan.speciesTop}
                            speciesRanked={scan.speciesRanked}
                            speciesSummary={scan.speciesSummary}
                            isUncertain={scan.speciesIsUncertain}
                        />
                    </section>
                )}

                {/* Scan Summary */}
                <section className="px-6 mb-6">
                    <h3 className="text-[10px] font-black text-forest uppercase tracking-[0.15em] mb-3 px-1">Scan Summary</h3>
                    <div className="bio-bg bio-bg-20 rounded-xl border border-stone-100/50 overflow-hidden shadow-soft">
                        <div className="grid grid-cols-[100px_1fr] border-b border-sage/10 p-4 items-center">
                            <p className="text-[10px] font-black text-forest uppercase">Date/Time</p>
                            <p className="text-sm font-semibold text-forest">{formatDateTime(scan.timestamp)}</p>
                        </div>
                        <div className="grid grid-cols-[100px_1fr] border-b border-sage/10 p-4 items-center">
                            <p className="text-[10px] font-black text-forest uppercase">Room</p>
                            <p className="text-sm font-semibold text-forest">{scan.roomName || 'Unassigned'}</p>
                        </div>
                        {manageProperty && (
                        <div className="grid grid-cols-[100px_1fr] border-b border-sage/10 p-4 items-center">
                            <p className="text-[10px] font-black text-forest uppercase">Address</p>
                            <p className="text-sm font-semibold text-forest leading-tight">{propertyAddr || 'No property assigned'}</p>
                        </div>
                        )}
                        <div className="grid grid-cols-[100px_1fr] p-4 items-center">
                            <p className="text-[10px] font-black text-forest uppercase">File</p>
                            <p className="text-sm font-semibold text-forest truncate">{scan.fileName}</p>
                        </div>
                    </div>
                </section>

                {/* Sensory Observations */}
                {(scan.odourLevel || (scan.surfaceTextures && scan.surfaceTextures.length > 0)) && (
                    <section className="px-6 mb-6">
                        <h3 className="text-[10px] font-black text-forest uppercase tracking-[0.15em] mb-3 px-1">Sensory Observations</h3>
                        <div className="grid grid-cols-2 gap-3">
                            {scan.odourLevel && (
                                <div className="bio-bg bio-bg-20 p-4 rounded-xl border border-stone-100/50 shadow-soft">
                                    <span className="material-symbols-outlined text-forest mb-1">air</span>
                                    <p className="text-[10px] font-black text-forest uppercase">Odour Level</p>
                                    <p className="text-sm font-extrabold text-forest">{scan.odourLevel}</p>
                                </div>
                            )}
                            {scan.surfaceTextures && scan.surfaceTextures.length > 0 && (
                                <div className="bio-bg bio-bg-30 p-4 rounded-xl border border-stone-100/50 shadow-soft">
                                    <span className="material-symbols-outlined text-forest mb-1">texture</span>
                                    <p className="text-[10px] font-black text-forest uppercase">Surface</p>
                                    <p className="text-sm font-extrabold text-forest">{scan.surfaceTextures.join(', ')}</p>
                                </div>
                            )}
                        </div>
                    </section>
                )}

                {/* User Severity + Notes */}
                {(scan.severityRating || scan.notes) && (
                    <section className="px-6 mb-6">
                        <div className="bio-bg bio-bg-50 p-5 rounded-xl border border-stone-100/50 shadow-soft space-y-4">
                            {scan.severityRating > 0 && (
                                <div>
                                    <div className="flex justify-between items-center mb-2">
                                        <p className="text-[10px] font-black text-forest uppercase tracking-[0.15em]">Reported Severity</p>
                                        <span className="text-forest font-extrabold text-sm">{scan.severityRating}/5</span>
                                    </div>
                                    <div className="flex gap-1.5">
                                        {[1,2,3,4,5].map(function (n) {
                                            return <div key={n} className={'w-full h-2 rounded-full ' + (n <= scan.severityRating ? 'bg-forest' : 'bg-forest/15')} />;
                                        })}
                                    </div>
                                </div>
                            )}
                            {scan.notes && (
                                <div>
                                    <p className="text-[10px] font-black text-forest uppercase mb-1">Additional Notes</p>
                                    <p className="text-sm italic font-medium text-forest bg-background-light p-3 rounded-lg border border-dashed border-sage/20">
                                        "{scan.notes}"
                                    </p>
                                </div>
                            )}
                        </div>
                    </section>
                )}

                {/* AI Insight */}
                {scan.insight && (
                    <section className="px-6 mb-6">
                        <div className="bio-bg bio-bg-10 p-5 rounded-xl border border-stone-100/50 shadow-soft">
                            <div className="flex items-center gap-2 mb-2">
                                <span className="material-symbols-outlined text-forest" style={{ fontVariationSettings: "'FILL' 1" }}>biotech</span>
                                <h3 className="text-sm font-extrabold text-forest">AI Analysis Insight</h3>
                            </div>
                            <p className="text-sm font-medium text-forest leading-relaxed">{scan.insight}</p>
                        </div>
                    </section>
                )}

                {/* Natural Remediation Advice */}
                <section className="px-6 mb-8">
                    <div className="bg-forest/70 text-white p-6 rounded-xl shadow-clay relative overflow-hidden">
                        <div className="absolute -right-8 -top-8 w-32 h-32 bg-white/5 rounded-full"></div>
                        <div className="relative z-10">
                            <div className="flex items-center gap-2 mb-3">
                                <span className="material-symbols-outlined text-primary" style={{ fontVariationSettings: "'FILL' 1" }}>eco</span>
                                <h3 className="text-lg font-bold">Natural Remediation</h3>
                            </div>
                            <ul className="space-y-4">
                                {tips.map(function (tip) {
                                    return (
                                        <li key={tip.num} className="flex gap-3">
                                            <div className="bg-white/20 w-6 h-6 rounded-full flex items-center justify-center shrink-0">
                                                <span className="text-[10px] font-bold">{tip.num}</span>
                                            </div>
                                            <div>
                                                <p className="text-sm font-bold">{tip.title}</p>
                                                <p className="text-xs text-white/80">{tip.desc}</p>
                                            </div>
                                        </li>
                                    );
                                })}
                            </ul>
                        </div>
                    </div>
                </section>

                {/* Actions */}
                <div className="px-6 pb-4">
                    <button
                        onClick={function () { navigate('/scans'); }}
                        className="w-full bg-forest text-white font-extrabold py-3.5 rounded-xl shadow-clay flex items-center justify-center gap-2 btn-nature hover:brightness-110 transition-all"
                    >
                        <span className="material-symbols-outlined text-lg">reorder</span>
                        View All Scans
                    </button>
                </div>

                <div className="px-6 pb-8">
                    <FindSpecialistPanel context="scan-details" />
                </div>
            </main>
        </Layout>
    );
};

window.ScanDetails = ScanDetails;
