const { useState, useRef, useEffect, useCallback } = React;

function Sidebar({ chapters, activeId, onSelect, plan }) {
  const { checks, filled, total } = chapterProgress(plan);
  const pct = Math.round((filled / total) * 100);
  return (
    <aside className="sidebar">
      <div className="sidebar__section">
        <div className="sidebar__heading">Capítulos</div>
        <ul className="sidebar__list">
          {chapters.map(ch => (
            <li
              key={ch.id}
              className={`sidebar__item ${activeId === ch.id ? 'sidebar__item--active' : ''}`}
              onClick={() => onSelect(ch.id)}
            >
              <span className="sidebar__item-num">{ch.num}</span>
              <span className="sidebar__item-label">{ch.label}</span>
              <span className={`sidebar__item-dot ${checks[ch.id] ? 'sidebar__item-dot--filled' : ''}`} />
            </li>
          ))}
        </ul>
      </div>

      <div className="sidebar__footer">
        <div className="sidebar__progress">
          <div className="sidebar__progress-label">
            <span>Completude</span>
            <span style={{ fontFamily: 'var(--font-brand)', fontWeight: 500, color: 'var(--ink)' }}>
              {filled}/{total}
            </span>
          </div>
          <div className="sidebar__progress-bar">
            <div className="sidebar__progress-fill" style={{ width: `${pct}%` }} />
          </div>
        </div>
      </div>
    </aside>
  );
}

function BulletEditor({ value, onChange, placeholder = 'Adicionar item…' }) {
  const items = value && value.length ? value : [''];

  function update(i, v) {
    const next = [...items];
    next[i] = v;
    onChange(next);
  }
  function remove(i) {
    const next = items.filter((_, idx) => idx !== i);
    onChange(next.length ? next : ['']);
  }
  function add() {
    onChange([...items, '']);
  }
  function onKeyDown(e, i) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      const next = [...items];
      next.splice(i + 1, 0, '');
      onChange(next);
      requestAnimationFrame(() => {
        const inputs = e.currentTarget.closest('.bullets').querySelectorAll('.bullet-row__input');
        if (inputs[i + 1]) inputs[i + 1].focus();
      });
    } else if (e.key === 'Backspace' && items[i] === '' && items.length > 1) {
      e.preventDefault();
      remove(i);
      requestAnimationFrame(() => {
        const inputs = document.querySelectorAll('.bullet-row__input');
        const prev = inputs[Math.max(0, i - 1)];
        if (prev) prev.focus();
      });
    }
  }
  return (
    <div className="bullets">
      {items.map((it, i) => (
        <div key={i} className="bullet-row">
          <span className="bullet-row__dot" />
          <input
            className="bullet-row__input"
            value={it}
            placeholder={placeholder}
            onChange={e => update(i, e.target.value)}
            onKeyDown={e => onKeyDown(e, i)}
          />
          <button className="bullet-row__remove" onClick={() => remove(i)} title="Remover">
            <Icon name="x" size={14} />
          </button>
        </div>
      ))}
      <button className="add-button" onClick={add}>
        <Icon name="plus" size={12} />
        Adicionar
      </button>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div className="field">
      <div className="field__label">{label}</div>
      {children}
      {hint && <div className="field__hint">{hint}</div>}
    </div>
  );
}

function TextInput(props) {
  return <input className="input" type="text" {...props} />;
}
function TextArea(props) {
  return <textarea className="textarea" {...props} />;
}

function PatientEditor({ patient, onChange }) {
  const upd = (k) => e => onChange({ ...patient, [k]: e.target.value });
  return (
    <div className="editor__body">
      <Field label="Nome completo">
        <TextInput
          value={patient.name}
          placeholder="ex. Guilherme Hilsdorf"
          onChange={upd('name')}
        />
      </Field>
      <div className="field__row">
        <Field label="Processo">
          <TextInput
            value={patient.processo}
            placeholder="E102567"
            onChange={upd('processo')}
          />
        </Field>
        <Field label="SNS">
          <TextInput
            value={patient.sns}
            placeholder="Opcional"
            onChange={upd('sns')}
          />
        </Field>
      </div>
      <Field label="Data de nascimento" hint="Opcional — não aparece no PDF se vazio">
        <TextInput
          type="date"
          value={patient.birthdate}
          onChange={upd('birthdate')}
        />
      </Field>
    </div>
  );
}

function DoctorEditor({ doctor, onChange }) {
  const upd = (k) => e => onChange({ ...doctor, [k]: e.target.value });
  return (
    <div className="editor__body">
      <Field label="Nome do médico">
        <TextInput
          value={doctor.name}
          placeholder="ex. Joana Costa"
          onChange={upd('name')}
        />
      </Field>
      <Field label="Especialidade / Função">
        <TextInput
          value={doctor.specialty}
          placeholder="ex. Medicina Funcional · Health Coach"
          onChange={upd('specialty')}
        />
      </Field>
      <div className="field__row">
        <Field label="Cédula profissional">
          <TextInput
            value={doctor.license}
            placeholder="Opcional"
            onChange={upd('license')}
          />
        </Field>
        <Field label="Data do plano">
          <TextInput
            type="date"
            value={doctor.date}
            onChange={upd('date')}
          />
        </Field>
      </div>
    </div>
  );
}

function SupplementsEditor({ supplements, onChange }) {
  function updGroup(gi, patch) {
    const next = supplements.map((g, i) => i === gi ? { ...g, ...patch } : g);
    onChange(next);
  }
  function updItem(gi, ii, patch) {
    const next = supplements.map((g, i) => {
      if (i !== gi) return g;
      return { ...g, items: g.items.map((it, j) => j === ii ? { ...it, ...patch } : it) };
    });
    onChange(next);
  }
  function addItem(gi) {
    const next = supplements.map((g, i) => {
      if (i !== gi) return g;
      return { ...g, items: [...g.items, { name: '', dose: '', frequency: '', notes: '' }] };
    });
    onChange(next);
  }
  function removeItem(gi, ii) {
    const next = supplements.map((g, i) => {
      if (i !== gi) return g;
      const items = g.items.filter((_, j) => j !== ii);
      return { ...g, items: items.length ? items : [{ name: '', dose: '', frequency: '', notes: '' }] };
    });
    onChange(next);
  }
  function addGroup() {
    onChange([...supplements, { group: 'Novo grupo', items: [{ name: '', dose: '', frequency: '', notes: '' }] }]);
  }
  function removeGroup(gi) {
    onChange(supplements.filter((_, i) => i !== gi));
  }

  return (
    <div className="editor__body">
      {supplements.map((g, gi) => (
        <div key={gi} className="suppl-group">
          <div className="suppl-group__head">
            <input
              className="suppl-group__title"
              value={g.group}
              placeholder="Nome do grupo (ex. Suporte da Metilação)"
              onChange={e => updGroup(gi, { group: e.target.value })}
            />
            <button className="group-remove" onClick={() => removeGroup(gi)}>Remover grupo</button>
          </div>

          <div className="suppl-item__header-row">
            <span>Suplemento</span>
            <span>Dose</span>
            <span>Frequência / notas</span>
            <span />
          </div>

          {g.items.map((it, ii) => (
            <div key={ii} className="suppl-item">
              <input
                className="suppl-item__field"
                value={it.name}
                placeholder="ex. Metilfolato"
                onChange={e => updItem(gi, ii, { name: e.target.value })}
              />
              <input
                className="suppl-item__field"
                value={it.dose}
                placeholder="400 µg"
                onChange={e => updItem(gi, ii, { dose: e.target.value })}
              />
              <input
                className="suppl-item__field"
                value={it.frequency}
                placeholder="1× ao dia"
                onChange={e => updItem(gi, ii, { frequency: e.target.value })}
              />
              <button className="suppl-item__remove" onClick={() => removeItem(gi, ii)} title="Remover">
                <Icon name="x" size={14} />
              </button>
            </div>
          ))}

          <button className="add-button" onClick={() => addItem(gi)}>
            <Icon name="plus" size={12} />
            Adicionar suplemento
          </button>
        </div>
      ))}

      <button className="add-button" onClick={addGroup} style={{ alignSelf: 'flex-start' }}>
        <Icon name="plus" size={12} />
        Adicionar novo grupo
      </button>
    </div>
  );
}

function PeptidesEditor({ peptides, onChange }) {
  function upd(i, patch) {
    onChange(peptides.map((p, idx) => idx === i ? { ...p, ...patch } : p));
  }
  function remove(i) {
    const next = peptides.filter((_, idx) => idx !== i);
    onChange(next.length ? next : [{ name: '', dose: '', frequency: '', route: '', notes: '' }]);
  }
  function add() {
    onChange([...peptides, { name: '', dose: '', frequency: '', route: '', notes: '' }]);
  }
  return (
    <div className="editor__body">
      <div className="suppl-group">
        <div className="suppl-item__header-row" style={{ gridTemplateColumns: '1.2fr 0.9fr 1fr 28px' }}>
          <span>Peptídeo</span>
          <span>Dose</span>
          <span>Frequência / via</span>
          <span />
        </div>
        {peptides.map((p, i) => (
          <div key={i} className="suppl-item" style={{ gridTemplateColumns: '1.2fr 0.9fr 1fr 28px' }}>
            <input
              className="suppl-item__field"
              value={p.name}
              placeholder="ex. BPC-157"
              onChange={e => upd(i, { name: e.target.value })}
            />
            <input
              className="suppl-item__field"
              value={p.dose}
              placeholder="10 mg · 0,1 mL"
              onChange={e => upd(i, { dose: e.target.value })}
            />
            <input
              className="suppl-item__field"
              value={p.frequency}
              placeholder="Diariamente · manhã · SC"
              onChange={e => upd(i, { frequency: e.target.value })}
            />
            <button className="suppl-item__remove" onClick={() => remove(i)} title="Remover">
              <Icon name="x" size={14} />
            </button>
          </div>
        ))}
        <button className="add-button" onClick={add}>
          <Icon name="plus" size={12} />
          Adicionar peptídeo
        </button>
      </div>
    </div>
  );
}

function FollowupsEditor({ followups, onChange }) {
  function upd(i, patch) {
    onChange(followups.map((f, idx) => idx === i ? { ...f, ...patch } : f));
  }
  function remove(i) {
    const next = followups.filter((_, idx) => idx !== i);
    onChange(next.length ? next : [{ title: '', date: '', notes: '' }]);
  }
  function add() {
    onChange([...followups, { title: '', date: '', notes: '' }]);
  }
  return (
    <div className="editor__body">
      {followups.map((f, i) => (
        <div key={i} className="followup">
          <div className="followup__col">
            <input
              className="suppl-item__field"
              value={f.title}
              placeholder="ex. Reavaliação clínica"
              onChange={e => upd(i, { title: e.target.value })}
            />
            <input
              className="suppl-item__field"
              value={f.notes}
              placeholder="Notas (opcional)"
              onChange={e => upd(i, { notes: e.target.value })}
              style={{ fontSize: 12, color: 'var(--ink-secondary)' }}
            />
          </div>
          <input
            className="suppl-item__field"
            value={f.date}
            placeholder="ex. 8 semanas"
            onChange={e => upd(i, { date: e.target.value })}
          />
          <button className="suppl-item__remove" onClick={() => remove(i)} title="Remover" style={{ opacity: 0.6, marginTop: 4 }}>
            <Icon name="x" size={14} />
          </button>
        </div>
      ))}
      <button className="add-button" onClick={add}>
        <Icon name="plus" size={12} />
        Adicionar follow-up
      </button>
    </div>
  );
}

function NotesEditor({ notes, onChange }) {
  return (
    <div className="editor__body">
      <Field label="Observações finais" hint="Notas livres do médico ao paciente — incluídas no final do PDF.">
        <TextArea
          className="textarea textarea--lg"
          value={notes}
          placeholder="ex. O plano apresentado tem carácter exclusivamente informativo…"
          onChange={e => onChange(e.target.value)}
        />
      </Field>
    </div>
  );
}

function EditorPanel({ chapter, plan, updatePlan }) {
  if (!chapter) return null;
  const { id, label, num } = chapter;

  const subtitleByChapter = {
    patient:     'Identificação do paciente que receberá este plano.',
    doctor:      'Médico responsável e data de emissão.',
    objectives:  'Resultados esperados do plano. Cada linha é um objetivo.',
    exercise:    'Plano de atividade física, frequência e considerações.',
    nutrition:   'Recomendações alimentares — restrições, macros, fermentados.',
    prescription:'Indicações terapêuticas adicionais (hidratação, sauna, etc.).',
    supplements: 'Lista por subgrupo — metabolismo, detox, intestinal, etc.',
    peptides:    'Terapia peptídica · dose, frequência e via de administração.',
    followups:   'Próximas consultas, reavaliações e exames.',
    notes:       'Observações finais e disclaimers que aparecem no fim do PDF.',
  };

  return (
    <div className="editor">
      <div className="editor__header">
        <div className="editor__eyebrow">Capítulo {num}</div>
        <h2 className="editor__title">{label}</h2>
        <div className="editor__sub">{subtitleByChapter[id]}</div>
      </div>

      {id === 'patient' && (
        <PatientEditor patient={plan.patient} onChange={v => updatePlan({ patient: v })} />
      )}
      {id === 'doctor' && (
        <DoctorEditor doctor={plan.doctor} onChange={v => updatePlan({ doctor: v })} />
      )}
      {id === 'objectives' && (
        <div className="editor__body">
          <Field label="Objetivos do plano" hint="Enter para nova linha · Backspace numa linha vazia para remover.">
            <BulletEditor
              value={plan.objectives}
              onChange={v => updatePlan({ objectives: v })}
              placeholder="ex. Melhorar a saúde intestinal"
            />
          </Field>
        </div>
      )}
      {id === 'exercise' && (
        <div className="editor__body">
          <Field label="Recomendações" hint="Cada linha vira um marcador no PDF.">
            <BulletEditor
              value={plan.exercise}
              onChange={v => updatePlan({ exercise: v })}
              placeholder="ex. Treinos de força 5×/semana"
            />
          </Field>
        </div>
      )}
      {id === 'nutrition' && (
        <div className="editor__body">
          <Field label="Recomendações alimentares">
            <BulletEditor
              value={plan.nutrition}
              onChange={v => updatePlan({ nutrition: v })}
              placeholder="ex. Reduzir glúten"
            />
          </Field>
        </div>
      )}
      {id === 'prescription' && (
        <div className="editor__body">
          <Field label="Prescrições gerais">
            <BulletEditor
              value={plan.prescription}
              onChange={v => updatePlan({ prescription: v })}
              placeholder="ex. Hidratação 2 L/dia + eletrólitos"
            />
          </Field>
        </div>
      )}
      {id === 'supplements' && (
        <SupplementsEditor supplements={plan.supplements} onChange={v => updatePlan({ supplements: v })} />
      )}
      {id === 'peptides' && (
        <PeptidesEditor peptides={plan.peptides} onChange={v => updatePlan({ peptides: v })} />
      )}
      {id === 'followups' && (
        <FollowupsEditor followups={plan.followups} onChange={v => updatePlan({ followups: v })} />
      )}
      {id === 'notes' && (
        <NotesEditor notes={plan.notes} onChange={v => updatePlan({ notes: v })} />
      )}
    </div>
  );
}

Object.assign(window, {
  Sidebar, EditorPanel, BulletEditor, Field, TextInput, TextArea,
});
