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

/**
 * _sdInlineMarkdown / _sdMarkdownBlocks / SdSpeciesAssessment — the smallest
 * markdown renderer that reads honestly, and nothing more.
 *
 * WHY NOT A LIBRARY: this app has no build step and no module system, so every
 * dependency is a script tag on the critical path of a phone on mobile data. The
 * one string that needs rendering is a short, model-authored assessment using
 * headings, bold and bullets. A parser for exactly those three, in ~40 lines, is
 * cheaper than a 30KB library and cannot execute anything: no raw HTML is ever
 * produced — React builds the elements, so the markdown text cannot inject markup
 * even though it arrives from a model rather than from us.
 *
 * Unsupported syntax degrades to plain text, deliberately. A stray marker showing
 * through is a cosmetic flaw; silently dropping a line of a species assessment is
 * a content one.
 */
var _sdInlineMarkdown = function (text, keyPrefix) {
    // Odd indices are the **bold** captures; everything else is literal text.
    var parts = String(text).split(/\*\*(.+?)\*\*/g);
    var out = [];
    for (var i = 0; i < parts.length; i++) {
        if (!parts[i]) continue;
        if (i % 2 === 1) {
            out.push(<strong key={keyPrefix + 'b' + i} className="font-extrabold">{parts[i]}</strong>);
        } else {
            out.push(<React.Fragment key={keyPrefix + 't' + i}>{parts[i]}</React.Fragment>);
        }
    }
    return out;
};

var _sdMarkdownBlocks = function (markdown) {
    var lines = String(markdown || '').replace(/\r\n/g, '\n').split('\n');
    var blocks = [];
    var listItems = [];
    var paragraph = [];

    var flushList = function () {
        if (listItems.length) { blocks.push({ type: 'list', items: listItems }); listItems = []; }
    };
    var flushParagraph = function () {
        if (paragraph.length) { blocks.push({ type: 'p', text: paragraph.join(' ') }); paragraph = []; }
    };

    for (var i = 0; i < lines.length; i++) {
        var line = lines[i].trim();
        if (!line) { flushList(); flushParagraph(); continue; }

        var heading = line.match(/^(#{1,6})\s+(.*)$/);
        if (heading) {
            flushList(); flushParagraph();
            blocks.push({ type: 'h', level: heading[1].length, text: heading[2] });
            continue;
        }
        // Bullets ("- x", "* x") and numbered items ("1. x") render the same way:
        // the visual distinction carries no meaning in an assessment this short.
        var bullet = line.match(/^(?:[-*+]|\d+[.)])\s+(.*)$/);
        if (bullet) {
            flushParagraph();
            listItems.push(bullet[1]);
            continue;
        }
        flushList();
        paragraph.push(line);
    }
    flushList();
    flushParagraph();
    return blocks;
};

/**
 * The indicative species assessment, collapsed by default.
 *
 * Collapsed because it is prose written by a model about something the app has
 * NOT determined — it must not read as the headline finding of the scan. The
 * disclaimer is part of the panel, not a footnote elsewhere: this is decision
 * support, not a diagnosis (ADR-0007), and lab testing is the standing
 * recommendation after any in-app detection.
 */
var SdSpeciesAssessment = function (props) {
    var openState = _useState_SD(false);
    var open = openState[0];
    var setOpen = openState[1];
    var blocks = _sdMarkdownBlocks(props.markdown);
    if (!blocks.length) return null;

    return (
        <section className="px-6 mb-4">
            <div className="bio-bg bio-bg-20 rounded-xl border border-stone-100/50 shadow-soft overflow-hidden">
                <button
                    type="button"
                    onClick={function () { setOpen(!open); }}
                    aria-expanded={open}
                    className="w-full flex items-center justify-between gap-3 px-4 py-3.5 text-left btn-nature"
                >
                    <span className="flex items-center gap-2 min-w-0">
                        <span className="material-symbols-outlined text-forest text-lg shrink-0" style={{ fontVariationSettings: "'FILL' 1" }}>science</span>
                        <span className="text-[10px] font-black text-forest uppercase tracking-[0.15em] leading-tight">
                            AI species assessment (indicative)
                        </span>
                    </span>
                    <span className="material-symbols-outlined text-forest text-lg shrink-0">{open ? 'expand_less' : 'expand_more'}</span>
                </button>

                {open && (
                    <div className="px-4 pb-4">
                        <p className="bg-forest/10 rounded-lg px-3 py-2 text-[11px] font-bold text-forest leading-snug mb-3">
                            Indicative only — not a diagnosis. Confirm with laboratory testing.
                        </p>
                        <div className="space-y-2">
                            {blocks.map(function (block, idx) {
                                var key = 'sd-md-' + idx;
                                if (block.type === 'h') {
                                    return (
                                        <p key={key} className={'text-forest ' + (block.level <= 2 ? 'text-sm font-extrabold' : 'text-xs font-bold uppercase tracking-[0.08em]')}>
                                            {_sdInlineMarkdown(block.text, key)}
                                        </p>
                                    );
                                }
                                if (block.type === 'list') {
                                    return (
                                        <ul key={key} className="space-y-1.5 pl-1">
                                            {block.items.map(function (item, j) {
                                                return (
                                                    <li key={key + '-' + j} className="flex gap-2">
                                                        <span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-forest/50 shrink-0"></span>
                                                        <span className="text-sm font-medium text-forest leading-relaxed">
                                                            {_sdInlineMarkdown(item, key + '-' + j)}
                                                        </span>
                                                    </li>
                                                );
                                            })}
                                        </ul>
                                    );
                                }
                                return (
                                    <p key={key} className="text-sm font-medium text-forest leading-relaxed">
                                        {_sdInlineMarkdown(block.text, key)}
                                    </p>
                                );
                            })}
                        </div>
                        {/* Model identifier deliberately NOT displayed (owner decision
                            2026-08-13, stack privacy): modelVersion stays on the scan
                            record for internal telemetry but never in consumer UI. */}
                    </div>
                )}
            </div>
        </section>
    );
};

/**
 * 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>
                            {/* Named the vendor and the topology, which is implementation
                                detail rather than anything a reader benefits from. Where the
                                analysis ran is still worth saying — "on this device" is a
                                genuine privacy property — but which supplier performed it is
                                not. */}
                            {scan.aiEngine && (
                                <span className={'text-[10px] font-bold mt-1 ' + (scan.aiEngine === 'local_cnn' ? 'text-primary' : 'text-forest/40')}>
                                    {scan.aiEngine === 'local_cnn' ? 'Analysed on this device' : 'AI vision analysis'}
                                </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>
                )}

                {/* Mould Genus — gated by SPECIES_LIST flag. The species* field names
                    stay: they are already written into IndexedDB scan records, and
                    renaming them would orphan every existing scan. */}
                {speciesEnabled && scan.speciesTop && (
                    <section className="px-6 mb-4">
                        <LocalSpeciesPanel
                            speciesTop={scan.speciesTop}
                            speciesRanked={scan.speciesRanked}
                            speciesSummary={scan.speciesSummary}
                            isUncertain={scan.speciesIsUncertain}
                        />
                    </section>
                )}

                {/* AI species assessment — the Cloud Assembly engine's INDICATIVE
                    narrative, under the genus panel and behind the SAME SPECIES_LIST
                    gate: it is the same claim class (what this might be), so it must
                    not become a way to show genus-adjacent content to a cohort the
                    genus panel itself is withheld from. Capture is unconditional
                    (caSnapshot); only this display is gated. */}
                {speciesEnabled && scan.caSnapshot && scan.caSnapshot.speciesSuggestion && (
                    <SdSpeciesAssessment
                        markdown={scan.caSnapshot.speciesSuggestion}
                        modelVersion={scan.caSnapshot.modelVersion}
                    />
                )}

                {/* Lab-confirmation capture (plan §7) — gated on genusSnapshot,
                    deliberately BROADER than the panel's speciesTop gate above:
                    abstained/low-signal scans carry a genusSnapshot but no
                    speciesTop, and a lab result on an abstained scan is still
                    v3 training data — exactly what the model couldn't see. */}
                {/* Genus abstention note — mirrors AnalysisPage: an abstained scan shows
                    WHY there is no genus panel (visible honesty, 2026-08-11) before
                    offering the lab-result capture below. */}
                {speciesEnabled && scan.genusSnapshot && scan.genusSnapshot.abstained === true && !scan.speciesTop && (
                    <section className="px-6 mb-4">
                        <div className="bio-bg bio-bg-30 rounded-xl border border-stone-100/50 shadow-soft px-4 py-3">
                            <p className="text-[11px] font-medium text-forest leading-relaxed text-center">
                                <span className="font-black uppercase tracking-[0.12em] text-[10px]">Mould Genus:</span> the
                                visual signals on this scan were inconclusive — no genus suggestion was offered.
                                If a laboratory identifies the genus, recording it below directly improves the model.
                            </p>
                        </div>
                    </section>
                )}
                {speciesEnabled && scan.genusSnapshot && (
                    <section className="px-6 mb-4">
                        <GenusFeedback
                            scan={scan}
                            onSave={function (fields) { store.updateScan(scan.id, fields); }}
                        />
                    </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>

                {/* Photo Details — capture metadata persisted with the scan.
                    Absent for scans taken before the feature shipped, which is why
                    this is gated on the stored block rather than always rendered. */}
                {scan.captureContext && typeof ExifService !== 'undefined' && (
                    <CaptureDetailsPanel
                        fields={ExifService.fieldsFromCaptureContext(scan.captureContext)}
                        variant="details"
                    />
                )}

                {/* 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;
