// ============================================================
// Recomendações médicas — clinical "Alvo → Recomendação" chapter.
// Mirrors the Target/Recommendation table of the B-Life plan.
// ============================================================

function RecMedRow({ item, index, onChange, onDelete, onMoveUp, onMoveDown, canUp, canDown }) {
  const set = (patch) => onChange({ ...item, ...patch });
  return (
    <SectionCard
      title={item.target || `Alvo ${index + 1}`}
      onDelete={onDelete}
      right={
        <div style={{ display: 'flex', gap: 2 }}>
          <button className="btn ghost xs" onClick={onMoveUp} disabled={!canUp} title="Subir" style={!canUp ? { opacity: 0.3, pointerEvents: 'none' } : {}}><Ico.ArrowUp/></button>
          <button className="btn ghost xs" onClick={onMoveDown} disabled={!canDown} title="Descer" style={!canDown ? { opacity: 0.3, pointerEvents: 'none' } : {}}><Ico.ArrowDown/></button>
        </div>
      }
    >
      <div className="field" style={{ marginBottom: 12 }}>
        <label>Alvo</label>
        <input
          className="input lg"
          value={item.target || ''}
          placeholder="Ex.: Otimizar saúde cardiovascular"
          onChange={e => set({ target: e.target.value })}
        />
      </div>
      <div className="field">
        <label>Recomendação</label>
        <RichText
          value={item.recommendation || ''}
          onChange={html => set({ recommendation: html })}
          placeholder="Conduta clínica para este alvo. Use a lista (•) para detalhar os passos…"
        />
      </div>
    </SectionCard>
  );
}

function RecMedicasEditor() {
  const [data, setData] = useChapter('recmedicas', { intro: '', items: [{ id: 1, target: '', recommendation: '' }] });
  const items = data.items || [];
  const setItems = (next) => setData({ ...data, items: typeof next === 'function' ? next(items) : next });

  const add = () => setItems([...items, { id: Date.now(), target: '', recommendation: '' }]);
  const update = (i, next) => setItems(items.map((x, j) => j === i ? next : x));
  const remove = (i) => setItems(items.filter((_, j) => j !== i));
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= items.length) return;
    const next = [...items];
    [next[i], next[j]] = [next[j], next[i]];
    setItems(next);
  };

  return (
    <>
      <SectionHeader
        title="Recomendações médicas"
        sub="Conduta clínica por alvo (sistema). Vira a tabela Alvo → Recomendação do plano do paciente."
        chapterId="recmedicas"
      />

      <SectionCard title="Introdução do capítulo" right={<span className="muted tiny">Opcional · abre o capítulo no PDF</span>}>
        <RichText
          value={data.intro || ''}
          onChange={html => setData({ ...data, intro: html })}
          placeholder="Texto que abre as recomendações médicas…"
        />
      </SectionCard>

      <div className="spacer-16"/>

      {items.map((item, i) => (
        <RecMedRow
          key={item.id || i}
          item={item}
          index={i}
          onChange={next => update(i, next)}
          onDelete={() => remove(i)}
          onMoveUp={() => move(i, -1)}
          onMoveDown={() => move(i, 1)}
          canUp={i > 0}
          canDown={i < items.length - 1}
        />
      ))}

      <AddSection label="Adicionar alvo" onClick={add}/>
    </>
  );
}

window.RecMedicasEditor = RecMedicasEditor;
