/**
 * EnterpriseMouldAssessment — Section C: Component Scoring Matrix
 * DMAT-inspired: 8 components × (damage, mould, wet/damp, materials, notes)
 */

var ScoreSelector = function (props) {
    var current = props.value;
    var onChange = props.onChange;
    return (
        <div className="flex gap-1">
            {DMAT_SCORES_EMA.map(function (s) {
                var isActive = current === s.value;
                return (
                    <button
                        key={s.value}
                        type="button"
                        title={s.desc}
                        onClick={function () { onChange(isActive ? 0 : s.value); }}
                        className={'w-10 h-10 rounded-xl text-sm font-black transition-all btn-nature ' + (isActive ? 'bg-forest text-white shadow-clay' : 'bg-surface border border-stone-100/50 text-forest shadow-soft hover:bg-forest hover:text-white')}
                    >
                        {s.label}
                    </button>
                );
            })}
        </div>
    );
};

var NearExtWall = function (props) {
    return (
        <button
            type="button"
            onClick={props.onClick}
            className="flex items-center gap-1.5 mt-1 btn-nature"
        >
            <div className={'w-3.5 h-3.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ' + (props.checked ? 'bg-forest border-forest' : 'border-sage/40 bg-surface')}>
                {props.checked && <span className="material-symbols-outlined text-white text-[9px]">check</span>}
            </div>
            <span className="text-[10px] font-semibold text-muted">Near ext. wall</span>
        </button>
    );
};

var ComponentRow = function (props) {
    var comp   = props.comp;   // component definition from AppConstants
    var row    = props.row;    // current row state
    var onChange = props.onChange; // called with updated row

    var patch = function (field, v) {
        onChange(FormatUtils.patchObject(row, field, v));
    };

    var toggleMaterial = function (mat) {
        var mats = row.materials || [];
        var idx = mats.indexOf(mat);
        if (idx >= 0) {
            patch('materials', mats.slice(0, idx).concat(mats.slice(idx + 1)));
        } else {
            patch('materials', mats.concat([mat]));
        }
    };

    var toggleNote = function (note) {
        var notes = row.assessmentNotes || [];
        var idx = notes.indexOf(note);
        if (idx >= 0) {
            patch('assessmentNotes', notes.slice(0, idx).concat(notes.slice(idx + 1)));
        } else {
            patch('assessmentNotes', notes.concat([note]));
        }
    };

    var isExpanded = row.present;

    return (
        <div className={'rounded-xl border transition-all ' + (isExpanded ? 'border-forest/20 bg-background-light' : 'border-stone-100/50 bio-bg bio-bg-10')}>
            {/* Row header — tap to expand/collapse */}
            <button
                type="button"
                onClick={function () { patch('present', !row.present); }}
                className="w-full flex items-center gap-3 p-3 text-left btn-nature"
            >
                <div className={'w-5 h-5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ' + (isExpanded ? 'bg-forest border-forest' : 'border-sage/40 bg-surface')}>
                    {isExpanded && <span className="material-symbols-outlined text-white text-[11px]">check</span>}
                </div>
                <span className="material-symbols-outlined text-forest text-lg">{comp.icon}</span>
                <span className="text-sm font-extrabold text-forest flex-1">{comp.label}</span>
                {!isExpanded && (
                    <span className="text-[10px] font-bold text-sage">Tap to assess</span>
                )}
                {isExpanded && (
                    <span className="material-symbols-outlined text-sage text-base">expand_less</span>
                )}
            </button>

            {/* Expanded detail */}
            {isExpanded && (
                <div className="px-3 pb-4 space-y-4 border-t border-stone-100/50 pt-3">

                    {/* Nothing Found shortcut */}
                    <button
                        type="button"
                        onClick={function () { patch('nothingFound', !row.nothingFound); }}
                        className="flex items-center gap-2 btn-nature"
                    >
                        <div className={'w-4 h-4 rounded border-2 flex items-center justify-center transition-colors shrink-0 ' + (row.nothingFound ? 'bg-primary border-primary' : 'border-sage/40 bg-surface')}>
                            {row.nothingFound && <span className="material-symbols-outlined text-white text-[11px]">check</span>}
                        </div>
                        <span className="text-xs font-bold text-forest">Nothing Found</span>
                    </button>

                    {!row.nothingFound && (
                        <div className="space-y-4">
                            {/* Scoring grid */}
                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <span className={window._EMA_LABEL_CLS}>Damage or Stains</span>
                                    <ScoreSelector value={row.damageScore} onChange={function (v) { patch('damageScore', v); }} />
                                    <NearExtWall checked={row.damageNearExt} onClick={function () { patch('damageNearExt', !row.damageNearExt); }} />
                                </div>
                                <div className="space-y-1">
                                    <span className={window._EMA_LABEL_CLS}>Visible Mould</span>
                                    <ScoreSelector value={row.mouldScore} onChange={function (v) { patch('mouldScore', v); }} />
                                    <NearExtWall checked={row.mouldNearExt} onClick={function () { patch('mouldNearExt', !row.mouldNearExt); }} />
                                </div>
                                <div className="space-y-1">
                                    <span className={window._EMA_LABEL_CLS}>Wet or Damp</span>
                                    <ScoreSelector value={row.wetDampScore} onChange={function (v) { patch('wetDampScore', v); }} />
                                    <NearExtWall checked={row.wetDampNearExt} onClick={function () { patch('wetDampNearExt', !row.wetDampNearExt); }} />
                                </div>
                            </div>

                            {/* Moisture reading + affected area */}
                            <div className="grid grid-cols-2 gap-3">
                                <window._EMA_FieldRow label="Moisture Reading (%)">
                                    <input
                                        type="number"
                                        min="0" max="100"
                                        className={window._EMA_INPUT_CLS + ' text-xs'}
                                        placeholder="e.g. 28"
                                        value={row.moistureReading}
                                        onChange={function (e) { patch('moistureReading', e.target.value); }}
                                    />
                                </window._EMA_FieldRow>
                                <window._EMA_FieldRow label="Affected Area (m²)">
                                    <input
                                        type="number"
                                        min="0"
                                        className={window._EMA_INPUT_CLS + ' text-xs'}
                                        placeholder="e.g. 2.5"
                                        value={row.affectedAreaM2}
                                        onChange={function (e) { patch('affectedAreaM2', e.target.value); }}
                                    />
                                </window._EMA_FieldRow>
                            </div>

                            {/* Materials */}
                            <div className="space-y-1.5">
                                <span className={window._EMA_LABEL_CLS}>Material Type</span>
                                <div className="flex flex-wrap gap-1.5">
                                    {comp.materials.map(function (mat) {
                                        var isActive = (row.materials || []).indexOf(mat) >= 0;
                                        return (
                                            <window._EMA_CheckPill
                                                key={mat}
                                                label={mat}
                                                active={isActive}
                                                onClick={function () { toggleMaterial(mat); }}
                                            />
                                        );
                                    })}
                                </div>
                            </div>

                            {/* Assessment notes */}
                            <div className="space-y-1.5">
                                <span className={window._EMA_LABEL_CLS}>Assessment Notes</span>
                                <div className="flex flex-wrap gap-1.5">
                                    {comp.assessmentNotes.map(function (note) {
                                        var isActive = (row.assessmentNotes || []).indexOf(note) >= 0;
                                        return (
                                            <window._EMA_CheckPill
                                                key={note}
                                                label={note}
                                                active={isActive}
                                                onClick={function () { toggleNote(note); }}
                                            />
                                        );
                                    })}
                                </div>
                            </div>

                            {/* Free-text component notes */}
                            <window._EMA_FieldRow label="Component Notes">
                                <textarea
                                    className={window._EMA_INPUT_CLS + ' text-xs'}
                                    rows={2}
                                    placeholder="Additional observations for this component..."
                                    value={row.componentNotes}
                                    onChange={function (e) { patch('componentNotes', e.target.value); }}
                                />
                            </window._EMA_FieldRow>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

var SectionComponents = function (props) {
    var val    = props.value;
    var set    = props.onChange;

    var updateComponent = function (key, updatedRow) {
        var updated = {};
        for (var k in val) { updated[k] = val[k]; }
        var updatedComponents = {};
        for (var ck in val.components) { updatedComponents[ck] = val.components[ck]; }
        updatedComponents[key] = updatedRow;
        updated.components = updatedComponents;
        set(updated);
    };

    return (
        <div className="space-y-3">
            <window._EMA_SectionHeader
                num="C"
                title="Component Assessment"
                subtitle="Score: 0=None  1=≤ Sheet of paper  2=Paper→Door  3=≥ Standard door"
            />
            {COMPONENTS_EMA.map(function (comp) {
                var row = (val.components && val.components[comp.key]) || window._EMA_buildDefaultComponents()[comp.key];
                return (
                    <ComponentRow
                        key={comp.key}
                        comp={comp}
                        row={row}
                        onChange={function (updatedRow) { updateComponent(comp.key, updatedRow); }}
                    />
                );
            })}
        </div>
    );
};

window._EMA_SectionComponents = SectionComponents;
