// petal-health.jsx — the saved health profile (view + edit). Exports HealthProfile.
const { useState: useH, useEffect: useHE } = React;

const SEX_OPTS = ['Female', 'Male', 'Other', 'Prefer not to say'];
const _csv = (v) => Array.isArray(v) ? v.join(', ') : (v || '');
const _arr = (s) => String(s || '').split(',').map(x => x.trim()).filter(Boolean);

function Field({ label, hint, children }) {
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 700, color: PAL.ink2, marginBottom: 7 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 11.5, color: PAL.mut, marginTop: 5 }}>{hint}</div>}
    </div>
  );
}

const hInput = {
  width: '100%', border: `1.5px solid ${PAL.border}`, background: '#fff', borderRadius: 13,
  padding: '12px 14px', fontSize: 15, fontFamily: FONT, color: PAL.ink, outline: 'none',
};

function HealthProfile({ user, onBack }) {
  const [data, setData] = useH(null);
  const [saved, setSaved] = useH(true);
  const [busy, setBusy] = useH(false);
  const isDoctor = user && user.role === 'doctor';

  useHE(() => { (async () => { setData(await PetalAPI.getHealth() || {}); })(); }, []);

  const set = (k, v) => { setData(d => ({ ...d, [k]: v })); setSaved(false); };

  async function save() {
    setBusy(true);
    const out = {
      ...data,
      conditions: _arr(data.conditions),
      allergies: _arr(data.allergies),
      medications: _arr(data.medications),
      age: data.age ? Number(data.age) : null,
      heightCm: data.heightCm ? Number(data.heightCm) : null,
      weightKg: data.weightKg ? Number(data.weightKg) : null,
    };
    await PetalAPI.saveHealth(out);
    setBusy(false); setSaved(true);
  }

  if (data === null) {
    return (
      <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: PAL.bg, flexDirection: 'column', gap: 12 }}>
        <div style={{ animation: 'petalspin 2.4s linear infinite' }}><Bloom size={34} /></div>
        <div style={{ fontSize: 13.5, color: PAL.mut }}>Loading profile…</div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PAL.bg }}>
      <div style={{ padding: '14px 20px', borderBottom: `1px solid ${PAL.borderSoft}`, background: '#fff' }}>
        <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'transparent',
          border: 'none', color: PAL.mut, fontFamily: FONT, fontSize: 13.5, cursor: 'pointer', padding: 0, marginBottom: 10 }}>
          ‹ Back
        </button>
        <div style={{ fontFamily: SERIF, fontSize: 26, color: PAL.ink, lineHeight: 1.1 }}>
          {isDoctor ? `${PEOPLE.patient}'s health profile` : 'Your health profile'}
        </div>
        <div style={{ fontSize: 13.5, color: PAL.mut, marginTop: 3 }}>
          {CFG.NURSE_NAME || 'Posy'} uses this to ask better, more tailored questions.
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 26px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          <Field label="Age">
            <input type="number" value={data.age || ''} onChange={e => set('age', e.target.value)} placeholder="—" style={hInput} />
          </Field>
          <Field label="Biological sex">
            <select value={data.sex || ''} onChange={e => set('sex', e.target.value)} style={{ ...hInput, appearance: 'none' }}>
              <option value="">—</option>
              {SEX_OPTS.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          </Field>
          <Field label="Height (cm)">
            <input type="number" value={data.heightCm || ''} onChange={e => set('heightCm', e.target.value)} placeholder="—" style={hInput} />
          </Field>
          <Field label="Weight (kg)">
            <input type="number" value={data.weightKg || ''} onChange={e => set('weightKg', e.target.value)} placeholder="—" style={hInput} />
          </Field>
        </div>

        <Field label="Ongoing conditions" hint="Separate with commas — e.g. migraines, asthma">
          <input value={_csv(data.conditions)} onChange={e => set('conditions', e.target.value)} placeholder="None" style={hInput} />
        </Field>
        <Field label="Allergies" hint="Medicines, foods, anything">
          <input value={_csv(data.allergies)} onChange={e => set('allergies', e.target.value)} placeholder="None" style={hInput} />
        </Field>
        <Field label="Current medications" hint="Including the pill, supplements, etc.">
          <input value={_csv(data.medications)} onChange={e => set('medications', e.target.value)} placeholder="None" style={hInput} />
        </Field>
        <Field label="Anything else for the record">
          <textarea value={data.notes || ''} onChange={e => set('notes', e.target.value)} rows={3} placeholder="History, past surgeries, family history, what you'd want a doctor to know…"
            style={{ ...hInput, resize: 'vertical', lineHeight: 1.5 }} />
        </Field>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: PAL.mut }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: PAL.green }} />
          Private — only {PEOPLE.patient} &amp; {PEOPLE.doctor} can see this.
        </div>
      </div>

      <div style={{ padding: '12px 18px', borderTop: `1px solid ${PAL.borderSoft}`, background: '#fff' }}>
        <PillButton onClick={save} disabled={busy || saved} style={{ width: '100%' }}>
          {saved ? 'Saved ✓' : (busy ? 'Saving…' : 'Save profile')}
        </PillButton>
      </div>
    </div>
  );
}

Object.assign(window, { HealthProfile });
