/**
 * EnterpriseMouldAssessment — Enterprise-grade mould assessment form.
 *
 * Inspired by the RiteFlo Dampness and Mould Assessment Tool (DMAT).
 * Designed for Mould Remediators, Contract Cleaners, and Mycology Labs.
 *
 * Sections:
 *   A. General Information
 *   B. Odour Assessment
 *   C. Component Scoring Matrix (DMAT-style: Ceiling, Walls, Floor, etc.)
 *   D. Environmental Readings (optional — device-dependent)
 *   E. Remediation Planning
 *   F. Technician Sign-off
 *
 * Feature flag: MANAGE_MOULD — replaces ScanObservationForm in LocationDetails.
 *
 * Props:
 *   value      (object) — Full assessment state (controlled)
 *   onChange   (func)   — Called with updated assessment object on any field change
 *   aiResult   (object) — Latest scan result (pre-fills species, severity, confidence)
 *   compact    (bool)   — Compact layout for inline use (default: false)
 */

var _useState_EMA   = React.useState;
var _useCallback_EMA = React.useCallback;

// ── Shared constants ──────────────────────────────────────────────────────────
var COMPONENTS_EMA    = AppConstants.ASSESSMENT_COMPONENTS;
var DMAT_SCORES_EMA   = AppConstants.DMAT_SCORE_LABELS;
var ODOUR_OPTIONS_EMA = AppConstants.ODOUR_OPTIONS;
var RISK_LEVELS_EMA   = AppConstants.RISK_LEVELS;
var REMED_METHODS_EMA = AppConstants.REMEDIATION_METHODS;
var PPE_LEVELS_EMA    = AppConstants.PPE_LEVELS;
var CONTAIN_EMA       = AppConstants.CONTAINMENT_TYPES;

// ── Default empty assessment value ───────────────────────────────────────────
var EMPTY_COMPONENT_ROW = function (key) {
    return {
        key:              key,
        present:          false,
        nothingFound:     false,
        damageScore:      0,
        damageNearExt:    false,
        mouldScore:       0,
        mouldNearExt:     false,
        wetDampScore:     0,
        wetDampNearExt:   false,
        moistureReading:  '',
        affectedAreaM2:   '',
        materials:        [],
        assessmentNotes:  [],
        componentNotes:   '',
    };
};

var buildDefaultComponents = function () {
    var rows = {};
    for (var i = 0; i < COMPONENTS_EMA.length; i++) {
        var c = COMPONENTS_EMA[i];
        rows[c.key] = EMPTY_COMPONENT_ROW(c.key);
    }
    return rows;
};

var DEFAULT_ASSESSMENT = {
    // Section A
    observerName:       '',
    floor:              '',
    roomAreaId:         '',
    roomAreaTypeDesc:   '',
    assessmentDate:     '',
    // Section B
    odourLevel:         null,
    odourSource:        '',
    odourSourceUnknown: false,
    // Section C
    components:         buildDefaultComponents(),
    // Section D
    envTemp:            '',
    envHumidity:        '',
    envCO2:             '',
    envLightMin:        '',
    envLightMax:        '',
    envFormaldehyde:    '',
    envVOCs:            '',
    // Section E
    overallRisk:        '',
    remediationMethod:  '',
    containmentType:    '',
    ppeLevel:           '',
    // Section F
    technicianName:     '',
    technicianCertNo:   '',
    generalNotes:       '',
};

// ── Shared style tokens ───────────────────────────────────────────────────────
var INPUT_CLS  = 'bg-surface border-none rounded-2xl 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 SELECT_CLS = INPUT_CLS + ' appearance-none';
var LABEL_CLS  = 'text-[10px] font-black text-forest uppercase tracking-[0.15em]';
var SECTION_TITLE_CLS = 'text-base font-extrabold text-forest';
var SECTION_BADGE_CLS = 'w-6 h-6 rounded-full bg-forest text-white text-[10px] font-black flex items-center justify-center shrink-0';

// ── Small reusable sub-components ────────────────────────────────────────────

var SectionHeader = function (props) {
    return (
        <div className="flex items-center gap-3 mb-3">
            <div className={SECTION_BADGE_CLS}>{props.num}</div>
            <div>
                <h3 className={SECTION_TITLE_CLS}>{props.title}</h3>
                {props.subtitle && (
                    <p className="text-[11px] text-forest font-medium mt-0.5">{props.subtitle}</p>
                )}
            </div>
            {props.optional && (
                <span className="ml-auto text-[9px] font-black text-forest uppercase tracking-widest bg-primary/30 px-2 py-0.5 rounded-full">Optional</span>
            )}
        </div>
    );
};

var FieldRow = function (props) {
    return (
        <div className="flex flex-col gap-1">
            <label className={LABEL_CLS}>{props.label}{props.required && <span className="text-warning ml-0.5">*</span>}</label>
            {props.children}
        </div>
    );
};

var CheckPill = function (props) {
    var isActive = props.active;
    return (
        <button
            type="button"
            onClick={props.onClick}
            className={'px-4 py-2.5 rounded-full text-sm font-bold 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')}
        >
            {props.label}
        </button>
    );
};

// ── Section A: General Information ───────────────────────────────────────────
var SectionGeneralInfo = function (props) {
    var val = props.value;
    var set = props.onChange;

    var patch = function (field, v) {
        set(FormatUtils.patchObject(val, field, v));
    };

    return (
        <div className="space-y-4">
            <SectionHeader num="A" title="General Information" />

            <div className="grid grid-cols-2 gap-3">
                <FieldRow label="Observer Name">
                    <input type="text" className={INPUT_CLS} placeholder="Full name" value={val.observerName} onChange={function (e) { patch('observerName', e.target.value); }} />
                </FieldRow>
                <FieldRow label="Assessment Date">
                    <input type="date" className={INPUT_CLS} value={val.assessmentDate} onChange={function (e) { patch('assessmentDate', e.target.value); }} />
                </FieldRow>
            </div>

            <div className="grid grid-cols-2 gap-3">
                <FieldRow label="Floor / Level">
                    <input type="text" className={INPUT_CLS} placeholder="e.g. Ground, 1st, Basement" value={val.floor} onChange={function (e) { patch('floor', e.target.value); }} />
                </FieldRow>
                <FieldRow label="Room / Area ID">
                    <input type="text" className={INPUT_CLS} placeholder="e.g. Room 3B" value={val.roomAreaId} onChange={function (e) { patch('roomAreaId', e.target.value); }} />
                </FieldRow>
            </div>

            <FieldRow label="Room / Area Type Description">
                <textarea
                    className={INPUT_CLS + ' text-xs'}
                    rows={2}
                    placeholder="Describe the type of room or area being assessed..."
                    value={val.roomAreaTypeDesc}
                    onChange={function (e) { patch('roomAreaTypeDesc', e.target.value); }}
                />
            </FieldRow>
        </div>
    );
};

window._EMA_SectionGeneralInfo   = SectionGeneralInfo;
window._EMA_DEFAULT_ASSESSMENT   = DEFAULT_ASSESSMENT;
window._EMA_buildDefaultComponents = buildDefaultComponents;
window._EMA_INPUT_CLS            = INPUT_CLS;
window._EMA_SELECT_CLS           = SELECT_CLS;
window._EMA_LABEL_CLS            = LABEL_CLS;
window._EMA_SectionHeader        = SectionHeader;
window._EMA_FieldRow             = FieldRow;
window._EMA_CheckPill            = CheckPill;
