// Tools — orchestrator for Herramientas tab.
// Sub-tabs: Paciente · Calculadoras · Mi calculadora · Escalas
// All heavy lifting lives in Calculators.jsx / PatientPanel.jsx / CustomCalc.jsx.

const { useState: useTS } = React;

// ─── Scales viewer (kept here, lightweight) ────────────────
function ScalesGallery() {
  const [active, setActive] = useTS(null);
  return (
    <>
      <div className="scales-grid">
        {ESCALAS.map(s => (
          <button key={s.id} className="scale-card" onClick={() => setActive(s)}>
            <div className="scale-thumb"><img src={s.img} alt={s.name} loading="lazy"/></div>
            <div className="scale-info">
              <h4>{s.name}</h4>
              <p>{s.desc}</p>
              <div className="scale-range mono">{s.rangos}</div>
            </div>
            <div className="scale-zoom">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="11" cy="11" r="7"/>
                <path d="M11 8v6M8 11h6M20 20l-3.5-3.5"/>
              </svg>
            </div>
          </button>
        ))}
      </div>
      {active && (
        <div className="scale-modal" onClick={() => setActive(null)}>
          <div className="scale-modal-inner" onClick={e => e.stopPropagation()}>
            <header>
              <div>
                <div className="mono" style={{ color: 'var(--fg-muted)', fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Escala</div>
                <h3>{active.name}</h3>
                <div className="scale-range mono">{active.rangos}</div>
              </div>
              <button className="scale-close" onClick={() => setActive(null)} aria-label="Cerrar">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
              </button>
            </header>
            <div className="scale-modal-img"><img src={active.img} alt={active.name}/></div>
          </div>
        </div>
      )}
    </>
  );
}

// ─── ToolsSection ───────────────────────────────────────────
function ToolsSection() {
  const [cat, setCat] = useTS('paciente');
  const [openCalc, setOpenCalc] = useTS('ped');

  const C = window.Calc || {};
  const calcs = [
    { id: 'ped',    name: 'Pérdidas insensibles · Pediátrico',  group: 'Pérdidas insensibles', Comp: C.PerdidasPediatricas },
    { id: 'prem',   name: 'Pérdidas insensibles · Prematuro',   group: 'Pérdidas insensibles', Comp: C.PerdidasPrematuros, soon: true },
    { id: 'adult',  name: 'Pérdidas insensibles · Adulto',      group: 'Pérdidas insensibles', Comp: C.PerdidasAdultos },
    { id: 'gotas',  name: 'Factor goteo · Velocidad infusión',  group: 'Soluciones',            Comp: C.FactorGoteo },
    { id: 'tabla',  name: 'Tabla de líquidos infundidos',       group: 'Soluciones',            Comp: C.TablaLiquidos },
    { id: 'imc',    name: 'IMC · clasificación OMS',            group: 'Antropometría',         Comp: C.IMCalc },
    { id: 'choque', name: 'Índice de choque',                   group: 'Hemodinamia',           Comp: C.IndiceChoque },
    { id: 'pam',    name: 'Presión arterial media (PAM)',       group: 'Hemodinamia',           Comp: C.PAM },
  ];

  // group by section for sidebar
  const groups = {};
  calcs.forEach(c => { (groups[c.group] = groups[c.group] || []).push(c); });

  const Active = (calcs.find(c => c.id === openCalc) || calcs[0]).Comp || (() => <div>Cargando…</div>);

  return (
    <div className="fade-in" data-screen-label="App — Herramientas">
      <div className="tools-tabs">
        {[
          ['paciente', 'Paciente'],
          ['calc',     'Calculadoras', calcs.length],
          ['mine',     'Mi calculadora'],
          ['scales',   'Escalas',      ESCALAS.length],
        ].map(([k, l, n]) => (
          <button key={k} className={'tools-chip ' + (cat === k ? 'on' : '')} onClick={() => setCat(k)}>
            {l}{n != null && <span style={{ opacity: 0.6, marginLeft: 6 }}>· {n}</span>}
          </button>
        ))}
      </div>

      {cat === 'paciente' && window.PatientPanel && <window.PatientPanel/>}

      {cat === 'calc' && (
        <div className="calc-layout">
          <aside className="calc-side">
            <h4>Fórmulas</h4>
            {Object.entries(groups).map(([gn, arr]) => (
              <div key={gn} className="calc-side-group">
                <div className="calc-side-group-head">{gn}</div>
                <ul>
                  {arr.map(c => (
                    <li key={c.id}>
                      <button
                        className={'calc-side-btn ' + (openCalc === c.id ? 'on' : '')}
                        onClick={() => setOpenCalc(c.id)}
                      >
                        <span>{c.name.replace(c.group + ' · ', '').replace('Pérdidas insensibles · ', '')}</span>
                        {c.soon && <span className="cc-pip">Pronto</span>}
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
            <div className="calc-tip">
              <div className="calc-tip-eyebrow">Recordatorio</div>
              <p>Todos los cálculos son orientativos. Verifica con la guía clínica de tu unidad antes de aplicarlos.</p>
            </div>
          </aside>
          <div className="calc-main"><Active/></div>
        </div>
      )}

      {cat === 'mine' && window.CustomCalc && <window.CustomCalc/>}
      {cat === 'scales' && <ScalesGallery/>}
    </div>
  );
}

window.ToolsSection = ToolsSection;
