// Patient Inputs zone — composed from controls.
const { useMemo: _useMemoInputs } = React;

function PatientInputs({ state, set }) {
  const { DIAGNOSES, COMORBIDITIES, ACTIVITY, FOOD_SECURITY, computeBMI, bmiStatus } = window.RD;

  const ageNum = parseFloat(state.age);
  const bmi = computeBMI(state);
  const status = bmi != null ? bmiStatus(bmi, ageNum) : null;
  const elderly = Number.isFinite(ageNum) && ageNum >= 65;

  function setUnitConverting(field, unitField, newUnit) {
    // Toggle unit *without* converting the typed number — the spec calls for a
    // simple unit toggle. Treat the value as authored in the new unit.
    set({ [unitField]: newUnit });
  }

  return (
    <section className="zone" aria-labelledby="zone-inputs">
      <header className="zone-head">
        <span className="zone-num">01</span>
        <h2 id="zone-inputs" className="zone-title">Patient Inputs</h2>
        <span className="zone-sub">Demographics, anthropometrics, diagnosis, context</span>
      </header>
      <div className="zone-body">

        {/* Demographics */}
        <div className="sub">
          <div className="sub-label">
            Demographics
            <span className="hint">Age, sex. No name, MRN, or DOB.</span>
          </div>
          <div className="sub-body">
            <div className="row-inline">
              <div>
                <span className="field-label">Age</span>
                <input
                  className="input tiny"
                  inputMode="numeric"
                  value={state.age}
                  onChange={e => set({ age: e.target.value.replace(/[^\d]/g, "") })}
                  placeholder="years"
                  aria-label="Age in years"
                />
              </div>
              <div>
                <span className="field-label">Sex</span>
                <Seg
                  ariaLabel="Sex"
                  value={state.sex}
                  onChange={v => set({ sex: v })}
                  options={[
                    { value: "F", label: "Female" },
                    { value: "M", label: "Male" },
                    // v1c: hidden — see work order Epic 5.2
                    // { value: "Other", label: "Other" },
                  ]}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Anthropometrics */}
        <div className="sub">
          <div className="sub-label">
            Anthropometrics
            <span className="hint">Height &amp; weight; BMI auto-derives.</span>
          </div>
          <div className="sub-body">
            <div className="row-inline">
              <div>
                <span className="field-label">Height</span>
                <UnitField
                  ariaLabel="Height"
                  value={state.height}
                  onChange={v => set({ height: v })}
                  unit={state.heightUnit}
                  units={["cm", "in"]}
                  onUnitChange={u => setUnitConverting("height", "heightUnit", u)}
                  placeholder={state.heightUnit === "cm" ? "e.g. 163" : "e.g. 64"}
                />
              </div>
              <div>
                <span className="field-label">Weight</span>
                <UnitField
                  ariaLabel="Weight"
                  value={state.weight}
                  onChange={v => set({ weight: v })}
                  unit={state.weightUnit}
                  units={["kg", "lb"]}
                  onUnitChange={u => setUnitConverting("weight", "weightUnit", u)}
                  placeholder={state.weightUnit === "kg" ? "e.g. 89.5" : "e.g. 197"}
                />
              </div>
              <div>
                <span className="field-label">BMI</span>
                {bmi != null ? (
                  <div className="bmi-display">
                    <span className="value">{bmi.toFixed(1)}</span>
                    <span className={`status-chip ${status.cls}`}>{status.label}</span>
                    {elderly && <span className="status-chip geri" title="Adjusted ranges for age ≥65 per ESPEN Geriatrics.">≥65 ranges</span>}
                  </div>
                ) : (
                  <div className="bmi-display">
                    <span className="value" style={{ color: "var(--ink-5)" }}>— —</span>
                    <span style={{ color: "var(--ink-4)", fontSize: 12 }}>height &amp; weight needed</span>
                  </div>
                )}
              </div>
            </div>
            <div style={{ marginTop: 14 }}>
              <span className="field-label">Weight history <span style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-4)", fontWeight: 400 }}>· optional</span></span>
              <textarea
                className="input"
                rows={2}
                placeholder="e.g. UBW 95 kg; lost ~6 kg over 4 months, unintentional"
                value={state.weightHistory}
                onChange={e => set({ weightHistory: e.target.value })}
                aria-label="Weight history"
              />
            </div>
          </div>
        </div>

        {/* Clinical context — diagnosis */}
        <div className="sub">
          <div className="sub-label">
            Clinical context
            <span className="hint">Primary diagnosis &amp; comorbidities.</span>
          </div>
          <div className="sub-body">
            <div className="row-stack">
              <div>
                <span className="field-label">Primary diagnosis</span>
                {state.diagnosis ? (
                  <div className="dx-display">
                    <Combo
                      options={DIAGNOSES}
                      value={state.diagnosis}
                      onSelect={d => set({ diagnosis: d, diagnosisOther: "" })}
                      onClear={() => set({ diagnosis: null, diagnosisOther: "" })}
                      placeholder="Search diagnoses…"
                    />
                    <TierChip tier={state.diagnosis.tier} />
                    {state.diagnosis.id === "other" && (
                      <input
                        className="input small"
                        style={{ width: 240 }}
                        placeholder="Describe…"
                        value={state.diagnosisOther}
                        onChange={e => set({ diagnosisOther: e.target.value })}
                        aria-label="Other diagnosis"
                      />
                    )}
                  </div>
                ) : (
                  <Combo
                    options={DIAGNOSES}
                    value={null}
                    onSelect={d => set({ diagnosis: d })}
                    onClear={() => set({ diagnosis: null })}
                    placeholder="Search diagnoses — CKD, T2DM, obesity…"
                  />
                )}
              </div>

              <div>
                <span className="field-label">Comorbidities</span>
                <div className="chip-group">
                  {COMORBIDITIES.map(c => (
                    <Chip
                      key={c}
                      active={state.comorbidities.includes(c)}
                      onToggle={() => {
                        const next = state.comorbidities.includes(c)
                          ? state.comorbidities.filter(x => x !== c)
                          : [...state.comorbidities, c];
                        set({ comorbidities: next });
                      }}
                    >{c}</Chip>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Lifestyle & intake */}
        <div className="sub">
          <div className="sub-label">
            Lifestyle &amp; intake
            <span className="hint">Activity level &amp; diet notes.</span>
          </div>
          <div className="sub-body">
            <div className="row-stack">
              <div>
                <span className="field-label">Activity level</span>
                <div className="activity-row">
                  <select
                    className="input"
                    value={state.activity}
                    onChange={e => set({ activity: e.target.value })}
                    aria-label="Activity level"
                  >
                    <option value="">Select activity level…</option>
                    {ACTIVITY.map(a => (
                      <option key={a.id} value={a.id}>{a.label} — {a.hint}</option>
                    ))}
                  </select>
                  {state.activity && (
                    <span className="multiplier">
                      ×{ACTIVITY.find(a => a.id === state.activity).mult.toFixed(3)}
                    </span>
                  )}
                </div>
              </div>
              <div>
                <span className="field-label">Diet notes <span style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-4)", fontWeight: 400 }}>· optional</span></span>
                <textarea
                  className="input"
                  rows={2}
                  placeholder="Typical day, preferences, restrictions, intake patterns…"
                  value={state.dietNotes}
                  onChange={e => set({ dietNotes: e.target.value })}
                  aria-label="Diet notes"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Contextual flags */}
        <div className="sub">
          <div className="sub-label">
            Contextual flags
            <span className="hint">Food security, feeding assistance, advance directives, interpreter.</span>
          </div>
          <div className="sub-body">
            <div className="row-stack">
              <div>
                <span className="field-label">Food security</span>
                <Tri
                  options={FOOD_SECURITY}
                  value={state.foodSecurity}
                  onChange={v => set({ foodSecurity: v })}
                />
              </div>

              <div className="toggle-list" role="group" aria-label="Other contextual flags">
                <div className="toggle-row">
                  <span className="label">Feeding assistance</span>
                  <span className="label-hint">patient needs help eating</span>
                  <span className="right">
                    <Switch
                      ariaLabel="Feeding assistance"
                      checked={state.feedingAssistance}
                      onChange={v => set({ feedingAssistance: v })}
                    />
                  </span>
                </div>
                <div className="toggle-row">
                  <span className="label">Advance directives</span>
                  <span className="label-hint">on file</span>
                  <span className="right">
                    <Switch
                      ariaLabel="Advance directives"
                      checked={state.advanceDirectives}
                      onChange={v => set({ advanceDirectives: v })}
                    />
                  </span>
                </div>
                <div className="toggle-row">
                  <span className="label">Interpreter</span>
                  <span className="label-hint">needed for visit</span>
                  <span className="right">
                    {state.interpreter && (
                      <input
                        className="lang-input"
                        placeholder="Language (optional)"
                        value={state.interpreterLang}
                        onChange={e => set({ interpreterLang: e.target.value })}
                        aria-label="Interpreter language"
                      />
                    )}
                    <Switch
                      ariaLabel="Interpreter needed"
                      checked={state.interpreter}
                      onChange={v => set({ interpreter: v, interpreterLang: v ? state.interpreterLang : "" })}
                    />
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Labs */}
        <div className="sub">
          <div className="sub-label">
            Labs
            <span className="hint">Optional · reference only — does not drive calculations in v1.</span>
          </div>
          <div className="sub-body">
            <textarea
              className="input"
              rows={3}
              placeholder="e.g. HbA1c 8.2%, eGFR 42, albumin 3.5 — include dates where available"
              value={state.labs}
              onChange={e => set({ labs: e.target.value })}
              aria-label="Labs"
            />
          </div>
        </div>

      </div>
    </section>
  );
}

window.PatientInputs = PatientInputs;
