/**
 * LocalSpeciesPanel — Mould Genus classification results (experimental).
 *
 * Reusable component. Shows the strongest-signal highlight card, a ranked
 * animated bar chart of candidate genera, and an uncertainty notice.
 * Only rendered when mould is detected.
 *
 * NAMING: user-facing copy says "Mould Genus" (all six classes are genus-level), but the
 * component/prop names keep the original "species" wording — speciesTop/speciesRanked/
 * speciesSummary are field names already written into IndexedDB scan records, and
 * renaming them would orphan every existing scan.
 *
 * HONESTY (plan §6, ADR-0007): candidates, never a verdict — "Strongest signal", not
 * "Most likely". The experimental note and lab-testing requirement always render, and no
 * overall accuracy figure is ever displayed.
 *
 * Props:
 *   speciesTop        { label, confidence, description, color }
 *   speciesRanked     [{ label, confidence, color, description }]
 *   speciesSummary    string
 *   isUncertain       boolean
 *   className         string — optional extra wrapper classes
 */
var LocalSpeciesPanel = function (props) {
    var speciesTop     = props.speciesTop;
    var speciesRanked  = props.speciesRanked || [];
    var speciesSummary = props.speciesSummary || '';
    var isUncertain    = props.isUncertain || false;
    var className      = props.className || '';

    var expandedState = React.useState(false);
    var expanded = expandedState[0];
    var setExpanded = expandedState[1];

    if (!speciesTop) return null;

    // Shared copy from GenusCatalog — guarded so the panel still renders if the
    // catalog script ever fails to load (it just drops the note/credit lines).
    var hasCatalog = typeof window.GenusCatalog !== 'undefined';
    var experimentalNote = hasCatalog ? window.GenusCatalog.EXPERIMENTAL_NOTE : '';
    var credit = hasCatalog ? window.GenusCatalog.CREDIT : '';

    return (
        <div className={'bio-bg bio-bg-30 rounded-xl border border-stone-100/50 shadow-soft overflow-hidden ' + className}>
            {/* Header — feature name + experimental chip (warning-light token: dark
                warm text on light fill, never white-on-light) */}
            <div className="px-4 pt-4 pb-1 flex items-center justify-center gap-2">
                <span className="text-[10px] font-black text-forest uppercase tracking-[0.15em]">Mould Genus</span>
                <span className="text-[8px] font-black uppercase tracking-[0.1em] px-1.5 py-0.5 rounded-full bg-[#FDECE8] text-[#a1543c]">Experimental</span>
            </div>

            {/* Summary text */}
            {speciesSummary && (
                <p className="px-4 pt-2 pb-3 text-[12px] font-medium text-forest leading-relaxed text-center border-b border-sage/10">
                    {speciesSummary}
                </p>
            )}

            {/* Strongest-signal highlight — a candidate, not a verdict */}
            <div className="mx-4 mt-3 p-4 rounded-xl border-2 bg-surface" style={{ borderColor: speciesTop.color }}>
                <p className="text-[10px] font-black text-forest uppercase tracking-[0.12em] mb-1 text-center">Strongest signal</p>
                <p className="text-xl font-black text-center mb-0.5" style={{ color: speciesTop.color }}>{speciesTop.label}</p>
                <p className="text-base font-extrabold text-center mb-2" style={{ color: speciesTop.color }}>{speciesTop.confidence.toFixed(1)}%</p>
                {speciesTop.description && (
                    <p className="text-[11px] font-medium text-forest text-center leading-relaxed">{speciesTop.description}</p>
                )}
            </div>

            {/* Experimental framing — always visible, not tucked in the expandable */}
            {experimentalNote && (
                <p className="px-4 mt-3 text-[10px] font-medium text-forest/70 leading-relaxed text-center">
                    {experimentalNote}
                </p>
            )}

            {/* Ranked bar chart */}
            <div className="px-4 mt-4">
                <p className="text-[10px] font-black text-forest uppercase tracking-[0.12em] mb-2">Candidate genera</p>
                <div className="space-y-2.5">
                    {speciesRanked.map(function (s, i) {
                        var barWidth = Math.max(s.confidence, 0.5).toFixed(1);
                        return (
                            <div
                                key={s.label}
                                className="flex items-center gap-2.5"
                                style={{ opacity: 0, animation: 'speciesBarIn 0.4s ease forwards', animationDelay: (i * 0.08) + 's' }}
                            >
                                <span className="text-[11px] font-bold text-forest w-20 text-right shrink-0">{s.label}</span>
                                <div className="flex-1 h-5 bg-forest/10 rounded-lg overflow-hidden relative">
                                    <div
                                        className="h-full rounded-lg"
                                        style={{
                                            width: barWidth + '%',
                                            background: s.color,
                                            transition: 'width 0.8s cubic-bezier(0.4,0,0.2,1)'
                                        }}
                                    />
                                </div>
                                <span className="text-[11px] font-extrabold w-12 shrink-0" style={{ color: s.color }}>
                                    {s.confidence.toFixed(1)}%
                                </span>
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* Uncertainty notice */}
            {isUncertain && (
                <div className="mx-4 mt-3 p-3 rounded-xl bg-[#FFF8E1] border border-[#d4a373]/20 flex items-start gap-2">
                    <span className="material-symbols-outlined text-[#d4a373] text-lg shrink-0 mt-0.5">help</span>
                    <p className="text-[11px] font-medium text-forest leading-relaxed">
                        The signals are spread across several genera. This can indicate mixed growth, a genus not yet well represented in our reference imagery, or an image the model has not learned. Professional laboratory testing is recommended.
                    </p>
                </div>
            )}

            {/* About genus classification — expandable */}
            <div className="px-4 mt-3">
                <button
                    onClick={function () { setExpanded(!expanded); }}
                    className="flex items-center gap-1 text-[11px] font-bold text-forest hover:text-primary transition-colors btn-nature"
                    aria-expanded={expanded}
                >
                    <span className="material-symbols-outlined text-sm">info</span>
                    About genus classification
                    <span className={'material-symbols-outlined text-sm transition-transform ' + (expanded ? 'rotate-180' : '')} style={{ transition: 'transform 0.2s' }}>expand_more</span>
                </button>
                {expanded && (
                    <div className="mt-2 space-y-1.5 text-[11px] font-medium text-forest leading-relaxed border-t border-sage/10 pt-2">
                        <p>Genus classification runs only after mould has been detected, and uses a separate AI model trained on laboratory-verified photographs of real building inspections. The scores show how closely the visual signals match each genus in that reference set.</p>
                        <p>Scores spread across several genera can mean mixed growth or a genus not yet in the reference set. This is an experimental, speculative analysis — professional laboratory testing is required for definitive identification.</p>
                    </div>
                )}
            </div>

            {/* Credits — reference imagery provenance (plan §6) */}
            {credit ? (
                <p className="mx-4 mt-3 mb-4 pt-2 border-t border-sage/10 text-[10px] font-medium text-forest/60 leading-relaxed">
                    {credit}
                </p>
            ) : (
                <div className="pb-4" />
            )}
        </div>
    );
};

window.LocalSpeciesPanel = LocalSpeciesPanel;
