// ============================================================
// Section editors — one component per chapter
// ============================================================

/* ---------- 1. Paciente ---------- */
function CartaEditor() {
  const { patient, setPatient, doctor, setDoctor } = usePatient();
  const [carta, setCarta] = useChapter('carta', { mensagem: '' });

  return (
    <>
      <SectionHeader
        title="Paciente"
        responsavel={doctor.name}
       chapterId="carta"/>

      <SectionCard title={fl('Saudação e data')} count={null}>
        <div className="grid-2">
          <div className="field">
            <label>{fl('Nome do paciente')}</label>
            <input
              className="input"
              value={patient.name}
              placeholder="Nome completo do paciente"
              onChange={e => setPatient({ ...patient, name: e.target.value })}
            />
          </div>
          <div className="field">
            <label>{fl('Data do plano')}</label>
            <input
              className="input"
              value={patient.date}
              placeholder="15 mai 2026"
              onChange={e => setPatient({ ...patient, date: e.target.value })}
            />
          </div>
        </div>
        <div className="spacer-12"/>
        <div className="grid-2">
          <div className="field">
            <label>{fl('Gênero')} <span className="muted tiny" style={{ textTransform: 'none', letterSpacing: 0 }}>{fl('· usado na análise do exame')}</span></label>
            <select
              className="select"
              value={patient.sex || ''}
              onChange={e => setPatient({ ...patient, sex: e.target.value })}
            >
              <option value="">Não informado</option>
              <option value="Feminino">Feminino</option>
              <option value="Masculino">Masculino</option>
            </select>
          </div>
          <div className="field">
            <label>{fl('Idade')} <span className="muted tiny" style={{ textTransform: 'none', letterSpacing: 0 }}>{fl('· usado na análise do exame')}</span></label>
            <input
              className="input"
              value={patient.age || ''}
              placeholder="Ex.: 42"
              inputMode="numeric"
              onChange={e => setPatient({ ...patient, age: e.target.value.replace(/[^0-9]/g, '') })}
              style={{ maxWidth: 160 }}
            />
          </div>
        </div>
        <div className="spacer-12"/>
        <div className="field">
          <label>{fl('Médico responsável')}</label>
          <div className="grid-2" style={{ gap: 12 }}>
            <input
              className="input"
              value={doctor.name}
              placeholder="Nome do(a) médico(a)"
              onChange={e => setDoctor({ ...doctor, name: e.target.value })}
            />
            <input
              className="input"
              value={doctor.role}
              placeholder="Especialidade"
              onChange={e => setDoctor({ ...doctor, role: e.target.value })}
            />
          </div>
          <div className="spacer-12"/>
          <input
            className="input"
            value={doctor.license}
            placeholder="CRM"
            onChange={e => setDoctor({ ...doctor, license: e.target.value })}
            style={{ maxWidth: 240 }}
          />
        </div>
      </SectionCard>

      <SectionCard title={fl('Mensagem do Médico')}>
        <RichText
          value={carta.mensagem}
          onChange={(html) => setCarta({ ...carta, mensagem: html })}
          placeholder="Mensagem do médico que abre o plano do paciente…"
        />
      </SectionCard>
    </>
  );
}

/* ---------- Objetivos de saúde (merged with patient statement) ---------- */
const OBJ_OPTIONS = [
  'Enhancement of immune function', 'Chronic Disease Management', 'Disease Prevention & Vitality Optimization',
  'Energy Levels & Cognitive Performance', 'Gastrointestinal Health & Inflammation Reduction',
  'Hormonal Balance & Metabolic Health', 'Improvement of sleep quality', 'Longevity & Healthy Aging',
  'Mental Health Stress Management', 'Sports Performance Preparation & Recovery',
  'Weight Management & Body Composition Optimization', "Women's Health & Reproductive Wellbeing",
  'Increase energy and vitality', 'Weight control (lose or maintain)',
  'Reduce stress and improve emotional wellbeing', 'Build muscle mass', 'Prevent diseases and long-term health care',
];

function ObjetivosEditor() {
  const { doctor } = usePatient();
  const [data, setData] = useChapter('objetivos', { items: [{ id: 1, text: '' }], statement: '' });
  const objectives = data.items || [];
  const setObjectives = (next) => setData({ ...data, items: typeof next === 'function' ? next(objectives) : next });
  const add = () => objectives.length < 3 && setObjectives([...objectives, { id: Date.now(), text: '' }]);
  const upd = (id, text) => setObjectives(objectives.map(o => o.id === id ? { ...o, text } : o));
  const remove = id => setObjectives(objectives.filter(o => o.id !== id));

  return (
    <>
      <SectionHeader
        title="Objetivos de saúde"
        sub="Defina até 3 objetivos principais para guiar o plano de ação."
        responsavel={doctor.name}
       chapterId="objetivos"/>

      <SectionCard
        title={`${objectives.length} objetivo${objectives.length === 1 ? '' : 's'} do plano`}
        right={<span className="muted tiny">Máximo 3</span>}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {objectives.map((o, i) => (
            <div key={o.id} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <span style={{
                width: 26, height: 26, borderRadius: '50%',
                background: 'var(--brand-tint)', color: 'var(--brand)',
                display: 'grid', placeItems: 'center',
                fontFamily: 'var(--ff-brand)', fontSize: 11, fontWeight: 500,
                flexShrink: 0,
              }}>{i + 1}</span>
              <input
                className="input"
                value={o.text}
                placeholder="Ex.: Aumentar energia e performance cognitiva"
                onChange={e => upd(o.id, e.target.value)}
              />
              {objectives.length > 1 && (
                <button className="btn ghost xs" onClick={() => remove(o.id)} title="Remover">
                  <Ico.X/>
                </button>
              )}
            </div>
          ))}
        </div>
        {objectives.length < 3 && (
          <div className="add-section" style={{ padding: 12, marginTop: 10 }} onClick={add}>
            <Ico.Plus/> Adicionar objetivo
          </div>
        )}
      </SectionCard>
    </>
  );
}

/* ---------- 3. Biomarcadores em foco ---------- */

// Catalog the doctor searches. Loaded from biomarkers-catalog.js (imported
// from the Biomarks spreadsheet: J = name, D = category, H = unit). Each entry
// carries the unit + category so selecting it pre-fills the row; she then types
// the value and picks status. A tiny fallback keeps the editor usable if the
// generated file fails to load.
const BIO_CATALOG = (typeof window !== 'undefined' && Array.isArray(window.BIO_CATALOG) && window.BIO_CATALOG.length)
  ? window.BIO_CATALOG
  : [
      { name: 'Apolipoproteína B', category: 'Cardiovascular', unit: 'mg/dL' },
      { name: 'Colesterol HDL', category: 'Cardiovascular', unit: 'mg/dL' },
      { name: 'Homocisteína', category: 'Cardiovascular', unit: 'µmol/L' },
      { name: 'Ferritina', category: 'Energia & Resistência', unit: 'ng/mL' },
      { name: '25-OH Vitamina D', category: 'Imunitário', unit: 'ng/mL' },
    ];

const BIO_STATUS = [
  { value: 'otimo',   label: 'Ótimo',   kind: 'ok'   },
  { value: 'normal',  label: 'Normal',  kind: 'warn' },
  { value: 'atencao', label: 'Atenção', kind: 'risk' },
];

// Searchable combobox to add a biomarker by name. Picks from the catalog
// (pre-fills unit + category) or accepts a free-typed custom name.
function BioSearch({ existing, onAdd, examList }) {
  const [query, setQuery] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const exFor = (name) => (window.resolveExamMarker && examList) ? window.resolveExamMarker(name, examList) : null;

  React.useEffect(() => {
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const q = query.trim().toLowerCase();
  const matches = BIO_CATALOG
    .filter(b => !existing.includes(b.name))
    .filter(b => q === '' || b.name.toLowerCase().includes(q) || b.category.toLowerCase().includes(q))
    .slice(0, 8);
  const exactExists = BIO_CATALOG.some(b => b.name.toLowerCase() === q) || existing.some(n => n.toLowerCase() === q);

  const pick = (entry) => {
    const ex = exFor(entry.name);
    onAdd({
      name: entry.name,
      category: entry.category || (ex && ex.category) || '',
      value: ex ? (ex.value || '') : '',
      unit: ex ? (ex.unit || entry.unit || '') : entry.unit,
      status: ex ? ex.status : 'normal',
    });
    setQuery(''); setOpen(false);
  };
  const addCustom = () => {
    const v = query.trim();
    if (!v) return;
    const ex = exFor(v);
    onAdd({
      name: v,
      category: ex ? (ex.category || '') : '',
      value: ex ? (ex.value || '') : '',
      unit: ex ? (ex.unit || '') : '',
      status: ex ? ex.status : 'normal',
    });
    setQuery(''); setOpen(false);
  };

  return (
    <div className="bio-search" ref={wrapRef} style={{ position: 'relative', maxWidth: 460 }}>
      <div className="bio-search-input">
        <Ico.Search/>
        <input
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          onKeyDown={e => {
            if (e.key === 'Enter') { e.preventDefault(); if (matches.length) pick(matches[0]); else if (q && !exactExists) addCustom(); }
            if (e.key === 'Escape') setOpen(false);
          }}
          placeholder="Buscar biomarcador pelo nome…"
        />
      </div>
      {open && (query !== '' || matches.length > 0) && (
        <div className="bio-dropdown">
          {matches.map(b => {
            const ex = exFor(b.name);
            const exLabel = ex ? (RES_STATUS_MAP[ex.status] || {}).label : null;
            return (
              <div key={b.name} className="bio-opt" onClick={() => pick(b)}>
                <div>
                  <div className="bio-opt-nm">{b.name}</div>
                  <div className="bio-opt-cat">{b.category}</div>
                </div>
                {ex ? (
                  <span className={'bio-opt-exam ' + (RES_STATUS_MAP[ex.status] || {}).kind}>
                    {ex.value}{ex.unit ? ' ' + ex.unit : ''} · {exLabel}
                  </span>
                ) : (
                  <span className="bio-opt-unit">{b.unit}</span>
                )}
              </div>
            );
          })}
          {q && !exactExists && (
            <div className="bio-opt custom" onClick={addCustom}>
              <Ico.Plus/> <span>Adicionar <strong>"{query.trim()}"</strong> como biomarcador</span>
            </div>
          )}
          {matches.length === 0 && !q && (
            <div className="bio-opt-empty">Digite para buscar entre {BIO_CATALOG.length} biomarcadores.</div>
          )}
        </div>
      )}
    </div>
  );
}

// Chip editor for "Biomarcadores relacionados" fields across chapters.
// Searches the same 136-item catalog (name or category); Enter / click adds
// the match, or adds the typed name manually if it isn't in the catalog.
function BioChipEditor({ items, onChange, placeholder = 'biomarcador' }) {
  const list = items || [];
  const [query, setQuery] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const q = query.trim().toLowerCase();
  const matches = BIO_CATALOG
    .filter(b => !list.includes(b.name))
    .filter(b => q === '' || b.name.toLowerCase().includes(q) || (b.category || '').toLowerCase().includes(q))
    .slice(0, 8);
  const exactExists = BIO_CATALOG.some(b => b.name.toLowerCase() === q) || list.some(n => n.toLowerCase() === q);

  const addName = (name) => {
    if (name && !list.includes(name)) onChange([...list, name]);
    setQuery(''); setOpen(false);
  };

  return (
    <div ref={wrapRef}>
      {list.length > 0 && (
        <div className="chips" style={{ marginBottom: 8 }}>
          {list.map(c => (
            <span key={c} className="chip selected removable" onClick={() => onChange(list.filter(x => x !== c))}>{c} <Ico.X/></span>
          ))}
        </div>
      )}
      <div className="bio-search" style={{ position: 'relative', maxWidth: 380 }}>
        <div className="bio-search-input">
          <Ico.Search/>
          <input
            value={query}
            onChange={e => { setQuery(e.target.value); setOpen(true); }}
            onFocus={() => setOpen(true)}
            onKeyDown={e => {
              if (e.key === 'Enter') { e.preventDefault(); if (matches.length) addName(matches[0].name); else if (q && !exactExists) addName(query.trim()); }
              if (e.key === 'Escape') setOpen(false);
            }}
            placeholder={'Buscar ' + placeholder + '…'}
          />
        </div>
        {open && (query !== '' || matches.length > 0) && (
          <div className="bio-dropdown">
            {matches.map(b => (
              <div key={b.name} className="bio-opt" onClick={() => addName(b.name)}>
                <div>
                  <div className="bio-opt-nm">{b.name}</div>
                  {b.category && <div className="bio-opt-cat">{b.category}</div>}
                </div>
                {b.unit && <span className="bio-opt-unit">{b.unit}</span>}
              </div>
            ))}
            {q && !exactExists && (
              <div className="bio-opt custom" onClick={() => addName(query.trim())}>
                <Ico.Plus/> <span>Adicionar <strong>"{query.trim()}"</strong></span>
              </div>
            )}
            {matches.length === 0 && !q && (
              <div className="bio-opt-empty">Digite para buscar entre {BIO_CATALOG.length} biomarcadores.</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// One editable row for a focused biomarker: value + unit + status.
function BioRow({ item, onChange, onRemove }) {
  return (
    <div className="bio-edit-row">
      <div className="bio-edit-id">
        <div className="bio-edit-nm">{item.name}</div>
        {item.category
          ? <div className="bio-edit-cat">{item.category}</div>
          : <input className="bio-edit-cat-input" value={item.category || ''} placeholder="Categoria (opcional)" onChange={e => onChange({ ...item, category: e.target.value })}/>}
      </div>
      <div className="bio-edit-field">
        <label>{fl('Valor')}</label>
        <input className="input" value={item.value || ''} placeholder="—" onChange={e => onChange({ ...item, value: e.target.value })}/>
      </div>
      <div className="bio-edit-field">
        <label>{fl('Unidade')}</label>
        <input className="input" value={item.unit || ''} placeholder="mg/dL" onChange={e => onChange({ ...item, unit: e.target.value })}/>
      </div>
      <div className="bio-edit-field" style={{ minWidth: 210 }}>
        <label>{fl('Status')}</label>
        <div className="period-tabs bio-status-tabs">
          {BIO_STATUS.map(s => (
            <button key={s.value} className={item.status === s.value ? 'active ' + s.kind : ''} onClick={() => onChange({ ...item, status: s.value })}>{s.label}</button>
          ))}
        </div>
      </div>
      <button className="btn ghost xs" onClick={onRemove} title="Remover biomarcador"><Ico.X/></button>
    </div>
  );
}

function BiomarcadoresEditor() {
  const { plan } = usePlan();
  const [data, setData] = useChapter('biomarcadores', { laudoData: '', comentario: '', focused: [] });
  // Normalize any legacy string entries into objects.
  const focused = (data.focused || []).map(f => typeof f === 'string' ? { name: f, category: '', value: '', unit: '', status: 'normal' } : f);
  const setFocused = (next) => setData({ ...data, focused: typeof next === 'function' ? next(focused) : next });

  // Index of the imported exam (Resultado de Exame) so adding a biomarker
  // pulls its current value + status automatically.
  const examList = (plan.chapters && plan.chapters.resultado && plan.chapters.resultado.biomarkers) || [];

  const add = (entry) => { if (!focused.some(f => f.name === entry.name)) setFocused([...focused, entry]); };
  const addMany = (entries) => setFocused(prev => {
    const have = new Set(prev.map(f => f.name));
    return [...prev, ...entries.filter(e => !have.has(e.name))];
  });
  const update = (i, entry) => setFocused(focused.map((f, j) => j === i ? entry : f));
  const remove = (i) => setFocused(focused.filter((_, j) => j !== i));
  const names = focused.map(f => f.name);
  const attentionFromExam = examList
    .filter(b => b.status === 'atencao' && !names.includes(b.name))
    .map(b => ({ name: b.name, category: b.category || '', value: b.value || '', unit: b.unit || '', status: b.status }));

  return (
    <>
      <SectionHeader title="Biomarcadores em foco" sub="Busque o biomarcador, informe o valor e a unidade do laudo e classifique o status. A tabela aparece no plano do paciente." chapterId="biomarcadores"/>

      {examList.length > 0 && (
        <div className="banner" style={{ marginBottom: 14, justifyContent: 'flex-start', textAlign: 'left' }}>
          <Ico.Lab/>
          <span style={{ flex: 1 }}>
            <strong>{examList.length} biomarcadores</strong> no exame importado · ao adicionar um marcador aqui, o valor e o status vêm automaticamente do exame.
          </span>
          {attentionFromExam.length > 0 && (
            <button className="btn xs" onClick={() => addMany(attentionFromExam)} title="Adicionar todos os biomarcadores classificados como Atenção">
              <Ico.Plus/> Adicionar {attentionFromExam.length} de Atenção
            </button>
          )}
        </div>
      )}

      <SectionCard title={fl('Comentário do médico')} right={<span className="muted tiny">Opcional · aparece acima da tabela</span>}>
        <div className="field" style={{ marginBottom: 12 }}>
          <label>{fl('Data do laudo')}</label>
          <input className="input" value={data.laudoData || ''} placeholder="18 abr 2026" onChange={e => setData({ ...data, laudoData: e.target.value })} style={{ maxWidth: 220 }}/>
        </div>
        <RichText
          value={data.comentario || ''}
          onChange={(html) => setData({ ...data, comentario: html })}
          placeholder="Observações da médica sobre os biomarcadores em foco…"
        />
      </SectionCard>

      <SectionCard title={`${focused.length} ${fl('biomarcadores em foco')}`}>
        {focused.length === 0 ? (
          <div className="muted tiny" style={{ textAlign: 'center', padding: 18 }}>
            Nenhum biomarcador em foco. Busque abaixo para adicionar.
          </div>
        ) : (
          <div className="bio-edit-list">
            {focused.map((item, i) => (
              <BioRow key={i} item={item} onChange={(e) => update(i, e)} onRemove={() => remove(i)}/>
            ))}
          </div>
        )}
        <div style={{ marginTop: 14 }}>
          <BioSearch existing={names} onAdd={add} examList={examList}/>
        </div>
      </SectionCard>
    </>
  );
}

/* ---------- 4. Medicamentos ---------- */
function MedCard({ m, onChange, onDelete }) {
  const set = (patch) => onChange({ ...m, ...patch });
  return (
    <SectionCard title={m.name || fl('Novo medicamento')} onDelete={onDelete}>
      <div className="grid-2">
        <div className="field"><label>{fl('Nome comercial / princípio ativo')}</label><input className="input" value={m.name || ''} onChange={e => set({ name: e.target.value })} placeholder="Ex.: Atorvastatina 10mg"/></div>
        <div className="field"><label>{fl('Dose')}</label><input className="input" value={m.dose || ''} onChange={e => set({ dose: e.target.value })} placeholder="1 comprimido"/></div>
      </div>
      <div className="spacer-12"/>
      <div className="grid-2">
        <div className="field"><label>{fl('Período')}</label>
          <select className="select" value={m.period || 'Manhã'} onChange={e => set({ period: e.target.value })}>
            <option>Manhã</option><option>Almoço</option><option>Noite</option><option>Ao deitar</option>
          </select>
        </div>
        <div className="field"><label>{fl('Duração')}</label><input className="input" value={m.duration || ''} onChange={e => set({ duration: e.target.value })} placeholder="Contínuo"/></div>
      </div>

      <div className="spacer-16"/>

      <div className="field" style={{ marginBottom: 12 }}>
        <label>{fl('Como tomar')}</label>
        <textarea className="textarea" value={m.howTo || ''} onChange={e => set({ howTo: e.target.value })} placeholder="Ex.: 1 comprimido após o jantar, com água, sempre no mesmo horário."/>
      </div>

      <div className="field" style={{ marginBottom: 12 }}>
        <label>{fl('Objetivo')}</label>
        <textarea className="textarea" value={m.objective || ''} onChange={e => set({ objective: e.target.value })} placeholder="Ex.: Reduzir LDL e Apo B em 30% nos próximos 90 dias."/>
      </div>

      <div className="field">
        <label>{fl('Biomarcadores relacionados')}</label>
        <BioChipEditor items={m.bio || []} onChange={v => set({ bio: v })}/>
      </div>
    </SectionCard>
  );
}

function MedicamentosEditor() {
  const [meds, setMeds] = useChapter('medicamentos', []);
  const list = meds || [];

  const addMed = () => setMeds([...list, { name: '', dose: '', period: 'Manhã', duration: '', howTo: '', objective: '', bio: [] }]);

  return (
    <>
      <SectionHeader title="Medicamentos" sub="Prescrição contínua que o paciente já toma ou que será iniciada." chapterId="medicamentos"/>

      {list.map((m, i) => (
        <MedCard key={i} m={m}
          onChange={next => setMeds(list.map((x, j) => j === i ? next : x))}
          onDelete={() => setMeds(list.filter((_, j) => j !== i))}/>
      ))}

      <AddSection label={fl('Adicionar medicamento')} onClick={addMed}/>

      <div className="spacer-16"/>
      <PeptideosSection/>
    </>
  );
}

/* ---------- Peptide Therapy (dentro de Medicamentos) ---------- */
function PeptideosSection() {
  const [list, setList] = useChapter('peptideos', []);
  const items = list || [];
  const add = () => setList([...items, { name: '', dose: '', freq: '' }]);
  const upd = (i, patch) => setList(items.map((x, j) => j === i ? { ...x, ...patch } : x));
  const rem = (i) => setList(items.filter((_, j) => j !== i));

  return (
    <SectionCard title={fl('Peptide Therapy')} right={<span className="muted tiny">Terapia peptídica · aparece no PDF</span>}>
      {items.length > 0 && (
        <div className="pept-head">
          <span>Peptídeo</span><span>Dose</span><span>Frequência / Via</span><span/>
        </div>
      )}
      {items.map((p, i) => (
        <div className="pept-row" key={i}>
          <input className="input" value={p.name || ''} placeholder="Ex.: BPC-157" onChange={e => upd(i, { name: e.target.value })}/>
          <input className="input" value={p.dose || ''} placeholder="10 mg · 0,1 mL" onChange={e => upd(i, { dose: e.target.value })}/>
          <input className="input" value={p.freq || ''} placeholder="Seg a sex · manhã" onChange={e => upd(i, { freq: e.target.value })}/>
          <button className="btn ghost xs" onClick={() => rem(i)} title="Remover peptídeo"><Ico.X/></button>
        </div>
      ))}
      <div className="add-section" style={{ padding: 12, marginTop: items.length ? 10 : 0 }} onClick={add}>
        <Ico.Plus/> Adicionar peptídeo
      </div>
    </SectionCard>
  );
}

/* ---------- 5. Suplementação ---------- */
const PERIODS = ['Manhã', 'Almoço', 'Noite'];

function SupCard({ s, onChange, onDelete }) {
  const set = (patch) => onChange({ ...s, ...patch });
  return (
    <SectionCard
      title={s.name || 'Nova suplementação'}
      right={
        <div className="period-tabs">
          {PERIODS.map(p => (
            <button key={p} className={(s.period || 'Manhã') === p ? 'active' : ''} onClick={() => set({ period: p })}>{p}</button>
          ))}
        </div>
      }
      onDelete={onDelete}
    >
      <div className="grid-2">
        <div className="field"><label>{fl('Título da seção')}</label><input className="input lg" value={s.name || ''} onChange={e => set({ name: e.target.value })} placeholder="Ex.: Coenzima Q10 com Methyl-B"/></div>
        <div className="grid-2" style={{ gap: 12 }}>
          <div className="field"><label>{fl('Dose')}</label><input className="input" value={s.dose || ''} onChange={e => set({ dose: e.target.value })}/></div>
          <div className="field"><label>{fl('Quantidade')}</label><input className="input" value={s.qty || ''} onChange={e => set({ qty: e.target.value })}/></div>
        </div>
      </div>

      <div className="spacer-12"/>
      <div className="field" style={{ maxWidth: 260 }}><label>{fl('Tomar com')}</label><input className="input" value={s.tomarCom || ''} onChange={e => set({ tomarCom: e.target.value })} placeholder="Ex.: Café da manhã"/></div>

      <div className="spacer-16"/>

      <div className="field" style={{ marginBottom: 12 }}>
        <label>{fl('Como tomar')}</label>
        <textarea className="textarea" value={s.howTo || ''} onChange={e => set({ howTo: e.target.value })} placeholder="Ex.: 2 cápsulas após o almoço, com gordura para melhor absorção."/>
      </div>

      <div className="field" style={{ marginBottom: 12 }}>
        <label>{fl('Objetivo')}</label>
        <textarea className="textarea" value={s.objective || ''} onChange={e => set({ objective: e.target.value })} placeholder="Ex.: Repor níveis de vitamina D e suportar imunidade."/>
      </div>

      <div className="field" style={{ marginBottom: 12 }}>
        <label>{fl('Onde comprar (link)')}</label>
        <input className="input" value={s.shop || ''} onChange={e => set({ shop: e.target.value })} placeholder="https://..."/>
      </div>

      <div className="field">
        <label>{fl('Biomarcadores relacionados')}</label>
        <BioChipEditor items={s.bio || []} onChange={v => set({ bio: v })}/>
      </div>
    </SectionCard>
  );
}

function SuplementacaoEditor() {
  const [list, setList] = useChapter('suplementacao', []);
  const items = list || [];
  return (
    <>
      <SectionHeader title="Suplementação" sub="Lista priorizada por horário. O paciente recebe lembretes via app." chapterId="suplementacao"/>

      <div className="banner muted">
        {items.length} suplementos · {items.filter(s=>s.period==='Manhã').length} manhã · {items.filter(s=>s.period==='Almoço').length} almoço · {items.filter(s=>s.period==='Noite').length} noite.
      </div>
      <div className="spacer-12"/>

      {items.map((s, i) => (
        <SupCard key={i} s={s}
          onChange={next => setList(items.map((x, j) => j === i ? next : x))}
          onDelete={() => setList(items.filter((_, j) => j !== i))}/>
      ))}

      <AddSection label={fl('Adicionar suplemento')} onClick={() => setList([...items, { name: '', dose: '', qty: '', period: 'Manhã', tomarCom: '', howTo: '', objective: '', shop: '', bio: [] }])}/>
    </>
  );
}

// Small helper so editors can pull the doctor name from context without
// repeating the destructure.
function useDoctorName() {
  const { doctor } = usePatient();
  return doctor.name;
}

window.CartaEditor = CartaEditor;
window.ObjetivosEditor = ObjetivosEditor;
window.BiomarcadoresEditor = BiomarcadoresEditor;
window.BioChipEditor = BioChipEditor;
window.MedicamentosEditor = MedicamentosEditor;
window.SuplementacaoEditor = SuplementacaoEditor;
