var _useState_GF = React.useState;

/**
 * GenusFeedback — lab-confirmation capture for genus classification (plan §7).
 *
 * WHY THIS EXISTS: professionals send scans to laboratories and get genus
 * confirmation back days-to-weeks later. Recording that confirmed result
 * against the scan — prediction (genusSnapshot) alongside lab ground truth
 * (genusLabConfirmation) — is the professional-tier feedback loop, and the
 * accumulated pairs are the v3 training set. This capture UI is the whole
 * strategic point of shipping the v2 classifier.
 *
 * Renders for ANY scan with a genusSnapshot, including abstained ones: an
 * abstained prediction paired with a lab result is still training data —
 * arguably the most valuable kind, since it documents exactly what the
 * model could not see. The parent gates on scan.genusSnapshot (broader than
 * LocalSpeciesPanel's scan.speciesTop gate) for precisely this reason.
 *
 * Props:
 *   scan    (object) — the scan record (reads scan.genusLabConfirmation)
 *   onSave  (func)   — called with the fields to patch onto the scan; the
 *                      parent wires this to ScanStore's updateScan.
 */
var GenusFeedback = function (props) {
    var scan = props.scan;
    var onSave = props.onSave;

    var confirmation = scan ? scan.genusLabConfirmation : null;

    // Genus options in ALPHABETICAL order, per ADR-0007: genus is descriptive,
    // never a danger ranking — so the list is never re-ordered by risk (or by
    // model confidence). Derived from GenusCatalog where available (single
    // source of truth for the six labels), with a hardcoded fallback so the
    // form still works if the catalog script ever fails to load.
    var gfGenusOptions = (typeof window.GenusCatalog !== 'undefined')
        ? Object.keys(window.GenusCatalog.ENTRIES).sort()
        : ['Acremonium', 'Aspergillus', 'Chaetomium', 'Cladosporium', 'Penicillium', 'Stachybotrys'];

    // Local YYYY-MM-DD for the date input default (toISOString would give UTC,
    // which is yesterday for an Australian evening — wrong default).
    var gfTodayISO = function () {
        var d = new Date();
        var m = d.getMonth() + 1;
        var day = d.getDate();
        return d.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (day < 10 ? '0' + day : day);
    };

    // Display text for the two non-genus select values.
    var gfDisplayGenus = function (value) {
        if (value === 'none_detected') return 'No mould genus identified';
        if (value === 'other') return 'Other / not listed';
        return value;
    };

    // ---- Local state -------------------------------------------------------
    var openState = _useState_GF(false);
    var formOpen = openState[0]; var setFormOpen = openState[1];

    var genusState = _useState_GF('');
    var genus = genusState[0]; var setGenus = genusState[1];

    var labState = _useState_GF('');
    var lab = labState[0]; var setLab = labState[1];

    var dateState = _useState_GF(gfTodayISO());
    var confirmedAt = dateState[0]; var setConfirmedAt = dateState[1];

    var notesState = _useState_GF('');
    var notes = notesState[0]; var setNotes = notesState[1];

    if (!scan) return null;

    // Open the form, prefilled from an existing confirmation when editing.
    var openForm = function () {
        if (confirmation) {
            setGenus(confirmation.confirmedGenus || '');
            setLab(confirmation.lab || '');
            setConfirmedAt(confirmation.confirmedAt || gfTodayISO());
            setNotes(confirmation.notes || '');
        } else {
            setGenus('');
            setLab('');
            setConfirmedAt(gfTodayISO());
            setNotes('');
        }
        setFormOpen(true);
    };

    var handleSave = function () {
        if (!genus) return; // Save is disabled, but belt-and-braces.
        // JSON primitives only (string/number/null), never undefined — the
        // data-moat sync contract: this block must ride the future opaque S3
        // cloud sync unchanged, exactly like genusSnapshot and captureContext.
        onSave({
            genusLabConfirmation: {
                v: 1,
                confirmedGenus: genus,
                lab: lab.trim() ? lab.trim() : null,
                confirmedAt: confirmedAt || gfTodayISO(),
                notes: notes.trim() ? notes.trim() : null,
                recordedAt: new Date().toISOString(),
            }
        });
        setFormOpen(false);
    };

    // Same input idiom as ScanObservationForm — light surface, forest text.
    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-forest/60 placeholder:font-medium w-full';
    var labelClass = 'text-[10px] font-black text-forest uppercase tracking-[0.15em]';

    // ---- FORM (new entry, or editing an existing confirmation) -------------
    if (formOpen) {
        return (
            <div className="bio-bg bio-bg-20 rounded-xl border border-stone-100/50 shadow-soft p-4 space-y-4">
                <div className="flex items-center gap-2">
                    <span className="material-symbols-outlined text-forest">science</span>
                    <h3 className="text-sm font-extrabold text-forest">Record lab result</h3>
                </div>

                {/* Lab-confirmed genus (required) */}
                <div className="space-y-1.5">
                    <label className={labelClass}>Lab-confirmed genus</label>
                    <select
                        className={inputClass}
                        value={genus}
                        onChange={function (e) { setGenus(e.target.value); }}
                    >
                        <option value="">Select a result...</option>
                        {gfGenusOptions.map(function (g) {
                            return <option key={g} value={g}>{g}</option>;
                        })}
                        <option value="none_detected">No mould genus identified</option>
                        <option value="other">Other / not listed</option>
                    </select>
                </div>

                {/* Laboratory (optional) */}
                <div className="space-y-1.5">
                    <label className={labelClass}>Laboratory (optional)</label>
                    <input
                        type="text"
                        className={inputClass}
                        placeholder="e.g. state lab, university mycology dept..."
                        value={lab}
                        onChange={function (e) { setLab(e.target.value); }}
                    />
                </div>

                {/* Result date */}
                <div className="space-y-1.5">
                    <label className={labelClass}>Result date</label>
                    <input
                        type="date"
                        className={inputClass}
                        value={confirmedAt}
                        onChange={function (e) { setConfirmedAt(e.target.value); }}
                    />
                </div>

                {/* Notes (optional) */}
                <div className="space-y-1.5">
                    <label className={labelClass}>Notes (optional)</label>
                    <textarea
                        className={inputClass + ' text-xs'}
                        rows={3}
                        maxLength={300}
                        placeholder="Sample method, colony counts, anything relevant..."
                        value={notes}
                        onChange={function (e) { setNotes(e.target.value); }}
                    />
                </div>

                <div className="flex gap-2">
                    <button
                        onClick={handleSave}
                        disabled={!genus}
                        className={'flex-1 py-3 rounded-xl text-sm font-extrabold transition-all btn-nature ' + (genus ? 'bg-forest text-white shadow-clay hover:brightness-110' : 'bg-forest/15 text-forest/40 cursor-not-allowed')}
                    >
                        Save
                    </button>
                    <button
                        onClick={function () { setFormOpen(false); }}
                        className="flex-1 py-3 rounded-xl text-sm font-bold bg-surface border border-stone-100/50 text-forest shadow-soft btn-nature hover:bg-forest hover:text-white transition-all"
                    >
                        Cancel
                    </button>
                </div>
            </div>
        );
    }

    // ---- SAVED state — compact confirmation card ---------------------------
    if (confirmation) {
        return (
            <div className="bio-bg bio-bg-20 rounded-xl border border-stone-100/50 shadow-soft p-4">
                <div className="flex items-start gap-2.5">
                    <span className="material-symbols-outlined text-primary shrink-0" style={{ fontVariationSettings: "'FILL' 1" }}>check_circle</span>
                    <div className="flex-1 min-w-0">
                        <p className="text-sm font-extrabold text-forest leading-snug">
                            Lab result recorded: {gfDisplayGenus(confirmation.confirmedGenus)}
                        </p>
                        {(confirmation.lab || confirmation.confirmedAt) && (
                            <p className="text-[11px] font-semibold text-forest/70 mt-0.5">
                                {confirmation.lab ? confirmation.lab : ''}
                                {confirmation.lab && confirmation.confirmedAt ? ' · ' : ''}
                                {confirmation.confirmedAt ? FormatUtils.fullDate(new Date(confirmation.confirmedAt).getTime()) : ''}
                            </p>
                        )}
                        <p className="text-[11px] font-medium text-forest/70 leading-relaxed mt-2">
                            Thank you — real-world lab confirmations directly improve genus classification.
                        </p>
                        <button
                            onClick={openForm}
                            className="mt-2 flex items-center gap-1 text-[11px] font-bold text-forest hover:text-primary transition-colors btn-nature"
                        >
                            <span className="material-symbols-outlined text-sm">edit</span>
                            Edit
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    // ---- COLLAPSED affordance ----------------------------------------------
    return (
        <div className="bio-bg bio-bg-20 rounded-xl border border-stone-100/50 shadow-soft p-4">
            <button
                onClick={openForm}
                className="flex items-center gap-2 text-sm font-extrabold text-forest hover:text-primary transition-colors btn-nature"
            >
                <span className="material-symbols-outlined text-lg">science</span>
                Record lab result
            </button>
            <p className="text-[11px] font-medium text-forest/70 leading-relaxed mt-1.5">
                Confirmed a genus with laboratory testing? Recording it here builds the lab-verified reference set behind this feature.
            </p>
        </div>
    );
};

window.GenusFeedback = GenusFeedback;
