// Plan de cuidados — single-of-each model with strict selection limits.
// • 1 diagnóstico (≤4 características, ≤1 factor)
// • 1 objetivo (N indicadores, Diana basal→meta usando la escala del propio objetivo)
// • 1 intervención (≤10 actividades)
// Relations between dx → obj/int are content-based (built offline in data/relations.json).

const { useState: pUS, useEffect: pUE, useMemo: pUM, useRef: pUR } = React;

// Limits
const MAX_CARS = 4;
const MAX_FACTORS = 1;
const MAX_INDICATORS = 5;
const MAX_ACTIVITIES = 10;

// ─── Diagnostic type detection ──────────────────────────────
function detectDxType(etiqueta = '') {
  const e = etiqueta.toLowerCase();
  if (/^riesgo\s+/.test(e)) return 'riesgo';
  if (/^disposici[oó]n\s+para\s+mejorar/.test(e) || /^disposici[oó]n\s+para/.test(e)) return 'promocion';
  if (/^s[ií]ndrome\s+/.test(e)) return 'sindrome';
  return 'real';
}

function dxTypeLabel(t) {
  return {
    real: 'Diagnóstico real (enfocado al problema)',
    riesgo: 'Diagnóstico de riesgo',
    promocion: 'Diagnóstico de promoción de la salud',
    sindrome: 'Diagnóstico de síndrome',
  }[t];
}

function dxTypeStructure(t) {
  return {
    real: 'PES — Etiqueta + relacionado con + factor + manifestado por + características',
    riesgo: 'PE — Etiqueta + relacionado con + factor de riesgo',
    promocion: 'Etiqueta + manifestado por + signos de deseo de mejora',
    sindrome: 'Etiqueta del síndrome + relacionado con + factor relacionado',
  }[t];
}

function buildDxSentence(dx) {
  if (!dx) return '';
  const etiqueta = dx.etiqueta || '';
  const factores = (dx.selectedFactores || []).filter(Boolean);
  const defin = (dx.selectedDefinitorias || []).filter(Boolean);
  const type = dx.type || detectDxType(etiqueta);

  const joinList = (arr) => {
    if (!arr.length) return '___';
    if (arr.length === 1) return arr[0].toLowerCase();
    if (arr.length === 2) return arr.join(' y ').toLowerCase();
    return arr.slice(0, -1).join(', ').toLowerCase() + ' y ' + arr.slice(-1)[0].toLowerCase();
  };

  if (type === 'real') {
    return `${etiqueta} relacionado con ${joinList(factores)}, manifestado por ${joinList(defin)}.`;
  }
  if (type === 'riesgo') {
    return `${etiqueta} relacionado con ${joinList(factores)}.`;
  }
  if (type === 'promocion') {
    return `${etiqueta} manifestado por ${joinList(defin)}.`;
  }
  return `${etiqueta} relacionado con ${joinList(factores)}.`;
}

// ─── Shared store ───────────────────────────────────────────
const PlanStore = {
  state: { dx: null, obj: null, int: null },
  listeners: new Set(),
  set(updater) {
    this.state = typeof updater === 'function' ? updater(this.state) : { ...this.state, ...updater };
    this.listeners.forEach(fn => fn(this.state));
  },
  use() {
    const [, force] = pUS(0);
    pUE(() => {
      const fn = () => force(t => t + 1);
      this.listeners.add(fn);
      return () => this.listeners.delete(fn);
    }, []);
    return [this.state, (u) => this.set(u)];
  },
  reset() { this.set({ dx: null, obj: null, int: null }); },
};

// ─── Mutators ──────────────────────────────────────────────
function setPlanDx(dx) {
  const type = detectDxType(dx.etiqueta);
  PlanStore.set({
    dx: {
      codigo: dx.codigo,
      etiqueta: dx.etiqueta,
      definicion: dx.definicion,
      dominio: dx.dominio,
      dominio_num: dx.dominio_num,
      clase: dx.clase,
      clase_num: dx.clase_num,
      type,
      selectedDefinitorias: [],
      selectedFactores: [],
      manifestaciones: '',
    }
  });
}

// Texto libre de manifestaciones clínicas (valoración del profesional)
function updatePlanDxManifestaciones(text) {
  PlanStore.set(s => s.dx ? ({ ...s, dx: { ...s.dx, manifestaciones: text } }) : s);
}

function togglePlanDxItem(group, value) {
  const limit = group === 'selectedFactores' ? MAX_FACTORS : MAX_CARS;
  PlanStore.set(s => {
    if (!s.dx) return s;
    const list = s.dx[group] || [];
    let next;
    if (list.includes(value)) {
      next = list.filter(v => v !== value);
    } else {
      if (list.length >= limit) {
        // Auto-evict oldest when at limit.
        next = [...list.slice(1), value];
      } else {
        next = [...list, value];
      }
    }
    return { ...s, dx: { ...s.dx, [group]: next } };
  });
}

function setPlanObjective(obj) {
  PlanStore.set({
    obj: {
      codigo: obj.codigo,
      titulo: obj.titulo,
      definicion: obj.definicion,
      dominio: obj.dominio,
      dominio_num: obj.dominio_num,
      clase: obj.clase,
      clase_codigo: obj.clase_codigo,
      escala: obj.escala || [],
      indicadores: obj.indicadores || [],
      selectedIndicadores: [],
      indScores: {},   // { [codigo]: { basal, meta } } — escala individual por indicador
      basal: 1,
      meta: 5,
    }
  });
}

function clearPlanObjective() { PlanStore.set({ obj: null }); }

// Diana por defecto según número de niveles de la escala (basal bajo, meta alta)
function defaultScores(escala) {
  const n = (escala && escala.length) || 5;
  return { basal: Math.min(3, Math.max(1, Math.round(n / 2))), meta: n };
}

function togglePlanObjectiveIndicator(codigo) {
  PlanStore.set(s => {
    if (!s.obj) return s;
    const sel = s.obj.selectedIndicadores || [];
    const scores = { ...(s.obj.indScores || {}) };
    if (sel.includes(codigo)) {
      delete scores[codigo];
      return { ...s, obj: { ...s.obj, selectedIndicadores: sel.filter(v => v !== codigo), indScores: scores } };
    }
    if (sel.length >= MAX_INDICATORS) return s; // hard cap
    scores[codigo] = defaultScores(s.obj.escala);
    return { ...s, obj: { ...s.obj, selectedIndicadores: [...sel, codigo], indScores: scores } };
  });
}

// Actualiza la escala basal/meta de UN indicador concreto
function updatePlanObjectiveIndicator(codigo, patch) {
  PlanStore.set(s => {
    if (!s.obj) return s;
    const scores = { ...(s.obj.indScores || {}) };
    scores[codigo] = { ...(scores[codigo] || defaultScores(s.obj.escala)), ...patch };
    return { ...s, obj: { ...s.obj, indScores: scores } };
  });
}

function updatePlanObjective(patch) {
  PlanStore.set(s => s.obj ? ({ ...s, obj: { ...s.obj, ...patch } }) : s);
}

function setPlanIntervention(int) {
  PlanStore.set({
    int: {
      codigo: int.codigo,
      nombre: int.nombre,
      dominio: int.dominio,
      dominio_num: int.dominio_num,
      clase: int.clase,
      clase_codigo: int.clase_codigo,
      definicion: int.definicion,
      actividades: int.actividades || [],
      selectedActividades: [],
    }
  });
}
function clearPlanIntervention() { PlanStore.set({ int: null }); }
function togglePlanInterventionActivity(value) {
  PlanStore.set(s => {
    if (!s.int) return s;
    const sel = s.int.selectedActividades || [];
    if (sel.includes(value)) {
      return { ...s, int: { ...s.int, selectedActividades: sel.filter(v => v !== value) } };
    }
    if (sel.length >= MAX_ACTIVITIES) return s; // hard cap
    return { ...s, int: { ...s.int, selectedActividades: [...sel, value] } };
  });
}

// ─── Plan readiness flags ───────────────────────────────────
function isDxReady(dx) {
  if (!dx) return false;
  const t = dx.type;
  if (t === 'riesgo' || t === 'sindrome') return dx.selectedFactores?.length > 0;
  if (t === 'promocion') return dx.selectedDefinitorias?.length > 0;
  return dx.selectedDefinitorias?.length > 0 && dx.selectedFactores?.length > 0;
}
function isObjReady(obj) {
  return !!obj && obj.selectedIndicadores?.length > 0;
}
function isIntReady(intv) {
  return !!intv && intv.selectedActividades?.length > 0;
}

// ─── Inline Plan Summary (right rail) ───────────────────────
function PlanSummary({ onOpenFinal, onGoToKind, currentKind }) {
  const [plan] = PlanStore.use();

  const dxReady = isDxReady(plan.dx);
  const objReady = isObjReady(plan.obj);
  const intReady = isIntReady(plan.int);
  const ready = dxReady && objReady && intReady;
  const completed = [dxReady, objReady, intReady].filter(Boolean).length;

  return (
    <aside className="plan-summary" data-screen-label="App — Resumen del plan">
      <div className="plan-summary-head">
        <div>
          <div className="plan-summary-eyebrow">Tu plan</div>
          <h4 className="plan-summary-title">Resumen en construcción</h4>
        </div>
        <div className="plan-summary-pips">
          <span className={dxReady ? 'on' : (plan.dx ? 'half' : '')} title="Diagnóstico"/>
          <span className={objReady ? 'on' : (plan.obj ? 'half' : '')} title="Objetivo"/>
          <span className={intReady ? 'on' : (plan.int ? 'half' : '')} title="Intervención"/>
        </div>
      </div>
      <div className="plan-summary-progress-text">{completed}/3 secciones completas</div>

      {/* Diagnóstico */}
      <div className={'plan-summary-section ' + (currentKind === 'dx' ? 'is-current ' : '') + (plan.dx ? 'has' : 'empty')}>
        <button className="plan-summary-section-head" onClick={() => onGoToKind?.('dx')}>
          <span className="dot wine"/>
          <span className="head-label">Diagnóstico</span>
          <span className={'mini-pip ' + (dxReady ? 'ready' : (plan.dx ? 'progress' : ''))}>{dxReady ? '✓' : (plan.dx ? '·' : '○')}</span>
        </button>
        {plan.dx ? (
          <div className="plan-summary-body">
            <div className="mono small code-line">{plan.dx.codigo}</div>
            <div className="plan-summary-name">{plan.dx.etiqueta}</div>
            {plan.dx.dominio && <div className="plan-summary-meta">{plan.dx.dominio.replace(/^Dominio\s*\d+:\s*/, 'Dominio ' + (plan.dx.dominio_num || '—') + ' · ')}</div>}
            {(plan.dx.selectedDefinitorias.length > 0 || plan.dx.selectedFactores.length > 0) && (
              <div className="plan-summary-sentence">
                <span className="ps-eyebrow">Vista previa</span>
                <p>{buildDxSentence(plan.dx)}</p>
              </div>
            )}
            <div className="plan-summary-divider"/>
            <div className="plan-summary-chip-row">
              <span className="ps-eyebrow">Características · {plan.dx.selectedDefinitorias.length}/{MAX_CARS}</span>
              {plan.dx.selectedDefinitorias.length === 0 ? (
                <div className="plan-summary-empty">Sin selección</div>
              ) : (
                <ul className="plan-summary-list">
                  {plan.dx.selectedDefinitorias.map((c, i) => <li key={i}>{c}</li>)}
                </ul>
              )}
            </div>
            <div className="plan-summary-chip-row">
              <span className="ps-eyebrow">{plan.dx.type === 'riesgo' ? 'Factor de riesgo' : 'Factor relacionado'} · {plan.dx.selectedFactores.length}/{MAX_FACTORS}</span>
              {plan.dx.selectedFactores.length === 0 ? (
                <div className="plan-summary-empty">Sin selección</div>
              ) : (
                <ul className="plan-summary-list">
                  {plan.dx.selectedFactores.map((c, i) => <li key={i}>{c}</li>)}
                </ul>
              )}
            </div>
          </div>
        ) : (
          <div className="plan-summary-empty-state">
            <button className="plan-summary-cta" onClick={() => onGoToKind?.('dx')}>Elige un diagnóstico</button>
          </div>
        )}
      </div>

      {/* Objetivo */}
      <div className={'plan-summary-section ' + (currentKind === 'ob' ? 'is-current ' : '') + (plan.obj ? 'has' : 'empty')}>
        <button className="plan-summary-section-head" onClick={() => onGoToKind?.('ob')}>
          <span className="dot sage"/>
          <span className="head-label">Objetivo</span>
          <span className={'mini-pip ' + (objReady ? 'ready' : (plan.obj ? 'progress' : ''))}>{objReady ? '✓' : (plan.obj ? '·' : '○')}</span>
        </button>
        {plan.obj ? (
          <div className="plan-summary-body">
            <div className="mono small code-line">{plan.obj.codigo}</div>
            <div className="plan-summary-name">{plan.obj.titulo}</div>
            <div className="plan-summary-divider"/>
            <div className="plan-summary-chip-row">
              <span className="ps-eyebrow">Indicadores · {plan.obj.selectedIndicadores.length}/{MAX_INDICATORS}</span>
              {plan.obj.selectedIndicadores.length === 0 ? (
                <div className="plan-summary-empty">Sin selección</div>
              ) : (
                <ul className="plan-summary-list">
                  {plan.obj.selectedIndicadores.map((code) => {
                    const ind = plan.obj.indicadores.find(i => i.codigo === code);
                    const sc = (plan.obj.indScores && plan.obj.indScores[code]) || { basal: plan.obj.basal, meta: plan.obj.meta };
                    return <li key={code}><span className="mono small">{code}</span> {ind?.descripcion} <span className="ps-diana-mini mono">{sc.basal}→{sc.meta}</span></li>;
                  })}
                </ul>
              )}
            </div>
          </div>
        ) : (
          <div className="plan-summary-empty-state">
            <button className="plan-summary-cta" disabled={!plan.dx} onClick={() => plan.dx && onGoToKind?.('ob')} style={{ opacity: plan.dx ? 1 : 0.5 }}>
              {plan.dx ? 'Elige un objetivo' : 'Primero un diagnóstico'}
            </button>
          </div>
        )}
      </div>

      {/* Intervención */}
      <div className={'plan-summary-section ' + (currentKind === 'iv' ? 'is-current ' : '') + (plan.int ? 'has' : 'empty')}>
        <button className="plan-summary-section-head" onClick={() => onGoToKind?.('iv')}>
          <span className="dot blue"/>
          <span className="head-label">Intervención</span>
          <span className={'mini-pip ' + (intReady ? 'ready' : (plan.int ? 'progress' : ''))}>{intReady ? '✓' : (plan.int ? '·' : '○')}</span>
        </button>
        {plan.int ? (
          <div className="plan-summary-body">
            <div className="mono small code-line">{plan.int.codigo}</div>
            <div className="plan-summary-name">{plan.int.nombre}</div>
            <div className="plan-summary-divider"/>
            <div className="plan-summary-chip-row">
              <span className="ps-eyebrow">Actividades · {plan.int.selectedActividades.length}/{MAX_ACTIVITIES}</span>
              {plan.int.selectedActividades.length === 0 ? (
                <div className="plan-summary-empty">Sin selección</div>
              ) : (
                <ul className="plan-summary-list">
                  {plan.int.selectedActividades.map((a, i) => <li key={i}>{a}</li>)}
                </ul>
              )}
            </div>
          </div>
        ) : (
          <div className="plan-summary-empty-state">
            <button className="plan-summary-cta" disabled={!plan.dx} onClick={() => plan.dx && onGoToKind?.('iv')} style={{ opacity: plan.dx ? 1 : 0.5 }}>
              {plan.dx ? 'Elige una intervención' : 'Primero un diagnóstico'}
            </button>
          </div>
        )}
      </div>

      <div className="plan-summary-actions">
        <button
          className="btn-primary"
          disabled={!ready}
          onClick={() => ready && onOpenFinal?.()}
          style={{ opacity: ready ? 1 : 0.5, cursor: ready ? 'pointer' : 'not-allowed', width: '100%', justifyContent: 'center' }}
        >
          Ver tabla final
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
        </button>
        <button className="plan-summary-clear" onClick={() => PlanStore.reset()}>Vaciar plan</button>
      </div>
    </aside>
  );
}

// ─── Floating Plan Widget (legacy — kept for fallback at narrow widths) ──
function PlanWidget({ onOpenFinal }) {
  const [plan] = PlanStore.use();
  const [expanded, setExpanded] = pUS(false);

  const dxReady = isDxReady(plan.dx);
  const objReady = isObjReady(plan.obj);
  const intReady = isIntReady(plan.int);
  const ready = dxReady && objReady && intReady;

  if (!plan.dx && !plan.obj && !plan.int) return null;

  return (
    <div className={'plan-widget ' + (expanded ? 'open' : '')}>
      <button className="plan-widget-handle" onClick={() => setExpanded(e => !e)}>
        <div className="plan-widget-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M9 11l3 3 8-8M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
        </div>
        <div className="plan-widget-body">
          <div className="plan-widget-title">Plan en construcción</div>
          <div className="plan-widget-meta">
            {[dxReady, objReady, intReady].filter(Boolean).length}/3 secciones completas
          </div>
        </div>
        <div className="plan-widget-progress">
          <span className={dxReady ? 'on' : (plan.dx ? 'half' : '')}/>
          <span className={objReady ? 'on' : (plan.obj ? 'half' : '')}/>
          <span className={intReady ? 'on' : (plan.int ? 'half' : '')}/>
        </div>
        <span className="plan-widget-chev">{expanded ? '⌃' : '⌄'}</span>
      </button>

      {expanded && (
        <div className="plan-widget-panel">
          <div className="plan-widget-section">
            <div className="plan-widget-section-head"><span className="dot wine"/> Diagnóstico</div>
            {plan.dx ? (
              <div className="plan-widget-item">
                <div>
                  <div className="mono small">{plan.dx.codigo}</div>
                  <div className="plan-widget-item-name">{plan.dx.etiqueta}</div>
                  <div className="plan-widget-item-sub">
                    {plan.dx.selectedDefinitorias.length}/{MAX_CARS} característica(s) · {plan.dx.selectedFactores.length}/{MAX_FACTORS} factor
                  </div>
                </div>
                <button className="plan-widget-x" onClick={() => PlanStore.set({ dx: null })}>×</button>
              </div>
            ) : (
              <div className="plan-widget-empty">Selecciona un diagnóstico para comenzar.</div>
            )}
          </div>

          <div className="plan-widget-section">
            <div className="plan-widget-section-head"><span className="dot sage"/> Objetivo</div>
            {plan.obj ? (
              <div className="plan-widget-item">
                <div>
                  <div className="mono small">{plan.obj.codigo}</div>
                  <div className="plan-widget-item-name">{plan.obj.titulo}</div>
                  <div className="plan-widget-item-sub">{plan.obj.selectedIndicadores.length}/{MAX_INDICATORS} indicador(es) · escala por indicador</div>
                </div>
                <button className="plan-widget-x" onClick={clearPlanObjective}>×</button>
              </div>
            ) : (
              <div className="plan-widget-empty">Aún no hay objetivo.</div>
            )}
          </div>

          <div className="plan-widget-section">
            <div className="plan-widget-section-head"><span className="dot blue"/> Intervención</div>
            {plan.int ? (
              <div className="plan-widget-item">
                <div>
                  <div className="mono small">{plan.int.codigo}</div>
                  <div className="plan-widget-item-name">{plan.int.nombre}</div>
                  <div className="plan-widget-item-sub">{plan.int.selectedActividades.length}/{MAX_ACTIVITIES} actividad(es)</div>
                </div>
                <button className="plan-widget-x" onClick={clearPlanIntervention}>×</button>
              </div>
            ) : (
              <div className="plan-widget-empty">Aún no hay intervención.</div>
            )}
          </div>

          <div className="plan-widget-actions">
            <button className="btn-secondary" onClick={() => PlanStore.reset()}>Vaciar</button>
            <button
              className="btn-primary"
              disabled={!ready}
              onClick={onOpenFinal}
              style={{ opacity: ready ? 1 : 0.5, cursor: ready ? 'pointer' : 'not-allowed' }}
            >
              Ver tabla final
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Final Table (matches reference image) ──────────────────
function FinalTable({ onClose }) {
  const [plan] = PlanStore.use();
  const [showShare, setShowShare] = pUS(false);
  const docRef = pUR(null);
  const editKey = plan.dx && plan.obj && plan.int
    ? `cyna_final_edit_${plan.dx.codigo}_${plan.obj.codigo}_${plan.int.codigo}`
    : null;
  const [editMode, setEditMode] = pUS(false);
  const [editedHtml, setEditedHtml] = pUS(() => {
    try { return editKey ? (localStorage.getItem(editKey) || null) : null; } catch { return null; }
  });

  const startEdit = () => {
    setEditMode(true);
    setTimeout(() => {
      if (docRef.current) {
        docRef.current.setAttribute('contenteditable', 'true');
        docRef.current.focus();
      }
    }, 30);
  };
  const saveEdit = () => {
    if (docRef.current) {
      docRef.current.removeAttribute('contenteditable');
      const html = docRef.current.innerHTML;
      setEditedHtml(html);
      try { if (editKey) localStorage.setItem(editKey, html); } catch {}
    }
    setEditMode(false);
  };
  const restoreOriginal = () => {
    if (!confirm('¿Descartar tus ediciones y restaurar el documento original?')) return;
    setEditedHtml(null);
    setEditMode(false);
    try { if (editKey) localStorage.removeItem(editKey); } catch {}
  };

  const { dx, obj, int: intv } = plan;
  if (!dx || !obj || !intv) return null;

  const sentence = buildDxSentence(dx);
  const dominioNum = dx.dominio_num ?? (dx.dominio || '').match(/\d+/)?.[0] ?? '—';
  const dominioName = (dx.dominio || '').replace(/^Dominio\s*\d+:?\s*/i, '');
  const claseNum = dx.clase_num ?? (dx.clase || '').match(/Clase\s*([\dA-Za-z]+)/i)?.[1] ?? '—';
  const claseName = (dx.clase || '').replace(/^Clase\s*[\w\d]+:?\s*/i, '');

  const objDominioNum = obj.dominio_num ?? '—';
  const objClaseCode = obj.clase_codigo ?? (obj.clase || '').match(/Clase\s*([A-Za-z\d]+)/i)?.[1] ?? '—';

  const intDominioNum = intv.dominio_num ?? '—';
  const intClaseCode = intv.clase_codigo ?? (intv.clase || '').match(/Clase\s*([A-Za-z\d]+)/i)?.[1] ?? '—';
  const intDominioName = (intv.dominio || '').replace(/^(Campo|Dominio)\s*\d+:?\s*/i, '');
  const intClaseName = (intv.clase || '').replace(/^Clase\s*[\w\d]+:?\s*/i, '');

  const selectedIndicators = obj.selectedIndicadores
    .map(code => obj.indicadores.find(i => i.codigo === code))
    .filter(Boolean);

  const print = () => window.print();

  const exportSummary = () => {
    const lines = [];
    lines.push(`DIAGNÓSTICO DE ENFERMERÍA: ${sentence}`);
    lines.push(`Dominio ${dominioNum}: ${dominioName} · Clase ${claseNum}: ${claseName}`);
    lines.push('');
    lines.push(`OBJETIVO (RESULTADO): ${obj.titulo} (${obj.codigo})`);
    lines.push(`Dominio ${objDominioNum} · Clase ${objClaseCode}`);
    selectedIndicators.forEach(i => {
      const sc = (obj.indScores && obj.indScores[i.codigo]) || { basal: obj.basal, meta: obj.meta };
      lines.push(`  • ${i.codigo} — ${i.descripcion}  [Diana: mantener ${sc.basal} → aumentar ${sc.meta}]`);
    });
    lines.push('Escala: ' + obj.escala.map((e, i) => `${e} (${i+1})`).join(' · '));
    lines.push('');
    lines.push(`INTERVENCIÓN: ${intv.nombre} (${intv.codigo})`);
    lines.push(`Campo ${intDominioNum} · Clase ${intClaseCode}`);
    intv.selectedActividades.forEach(a => lines.push(`  • ${a}`));
    return lines.join('\n');
  };

  const shareText = exportSummary();
  const shareNative = async () => {
    if (navigator.share) {
      try { await navigator.share({ title: 'Plan de cuidados', text: shareText }); } catch {}
    } else {
      setShowShare(true);
    }
  };
  const copyClipboard = async () => {
    try { await navigator.clipboard.writeText(shareText); alert('Copiado al portapapeles'); }
    catch { alert('No se pudo copiar'); }
  };
  const enc = encodeURIComponent(shareText);
  const subject = encodeURIComponent('Plan de cuidados de enfermería');
  const shareLinks = [
    { name: 'WhatsApp', icon: 'wa', url: `https://wa.me/?text=${enc}` },
    { name: 'Gmail',    icon: 'gm', url: `https://mail.google.com/mail/?view=cm&fs=1&su=${subject}&body=${enc}` },
    { name: 'Outlook',  icon: 'ol', url: `https://outlook.live.com/mail/0/deeplink/compose?subject=${subject}&body=${enc}` },
    { name: 'Correo',   icon: 'ml', url: `mailto:?subject=${subject}&body=${enc}` },
    { name: 'Telegram', icon: 'tg', url: `https://t.me/share/url?url=cynamonurs.com&text=${enc}` },
    { name: 'Facebook', icon: 'fb', url: `https://www.facebook.com/sharer/sharer.php?u=https://cynamonurs.com&quote=${enc}` },
  ];

  // Build table rows: one row per selected indicator. First row spans others.
  const rowCount = Math.max(1, selectedIndicators.length);

  return (
    <div className="final-overlay" onClick={onClose}>
      <div className="final-shell" onClick={e => e.stopPropagation()}>
        <div className="final-toolbar no-print">
          <div className="final-toolbar-left">
            <button className="final-back" onClick={onClose}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 18l-6-6 6-6"/></svg>
              Volver al plan
            </button>
            <div>
              <div className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>Resultado</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 20, color: 'var(--cinnamon-900)', letterSpacing: '-0.015em' }}>Plan de cuidados de enfermería</div>
            </div>
          </div>
          <div className="final-toolbar-right">
            {!editMode ? (
              <button className="btn-secondary" onClick={startEdit} title="Escribe directamente sobre el documento">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>
                Editar documento
              </button>
            ) : (
              <button className="btn-primary" onClick={saveEdit} title="Guardar tus cambios">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/></svg>
                Guardar cambios
              </button>
            )}
            {editedHtml && !editMode && (
              <button className="btn-secondary" onClick={restoreOriginal} title="Descartar ediciones">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5"/></svg>
                Restaurar
              </button>
            )}
            <button className="btn-secondary" onClick={shareNative} disabled={editMode} style={{ opacity: editMode ? 0.5 : 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7M16 6l-4-4-4 4M12 2v13"/></svg>
              Compartir
            </button>
            <button className="btn-primary" onClick={print} disabled={editMode} style={{ opacity: editMode ? 0.5 : 1 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 14h12v8H6z"/></svg>
              Exportar PDF
            </button>
          </div>
        </div>

        {editMode && (
          <div className="final-editbar no-print">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>
            Modo edición: escribe directamente sobre el documento. Pulsa <strong>Guardar cambios</strong> al terminar.
          </div>
        )}

        {editedHtml != null ? (
          <div className={'final-page' + (editMode ? ' editing' : '')} ref={docRef} dangerouslySetInnerHTML={{ __html: editedHtml }}/>
        ) : (
        <div className={'final-page' + (editMode ? ' editing' : '')} ref={docRef}>
          <table className="final-table">
            <colgroup>
              <col style={{ width: '22%' }}/>
              <col style={{ width: '9%' }}/>
              <col style={{ width: '24%' }}/>
              <col style={{ width: '27%' }}/>
              <col style={{ width: '18%' }}/>
            </colgroup>
            <thead>
              <tr>
                <th className="dx-cell" colSpan="3">
                  <div className="dx-cell-label">DIAGNÓSTICO DE ENFERMERÍA:</div>
                  <div className="dx-cell-sentence">{sentence}</div>
                  {dx.manifestaciones && dx.manifestaciones.trim() && (
                    <div className="dx-cell-manif"><strong>Manifestaciones:</strong> {dx.manifestaciones.trim()}</div>
                  )}
                </th>
                <th className="dx-meta">
                  <div><strong>Dominio:</strong> {dominioNum}{dominioName ? `, ${dominioName.toLowerCase()}` : ''}</div>
                </th>
                <th className="dx-meta">
                  <div><strong>Clase:</strong> {claseNum}{claseName ? `, ${claseName.toLowerCase()}` : ''}</div>
                </th>
              </tr>
              <tr className="final-thead-row">
                <th>RESULTADO(S)</th>
                <th>CÓDIGO(S)</th>
                <th>INDICADOR(ES)</th>
                <th>ESCALAS DE MEDICIÓN</th>
                <th>PUNTUACIÓN DIANA<br/><span className="mono small">Mantener &nbsp;&nbsp; Aumentar</span></th>
              </tr>
            </thead>
            <tbody>
              {selectedIndicators.map((ind, i) => {
                const sc = (obj.indScores && obj.indScores[ind.codigo]) || { basal: obj.basal, meta: obj.meta };
                return (
                  <tr key={ind.codigo}>
                    {i === 0 && (
                      <td rowSpan={rowCount} className="result-cell">
                        <strong>{obj.titulo}</strong>
                        <div className="small muted" style={{ marginTop: 6 }}>Dominio: {objDominioNum}</div>
                        <div className="small muted">Clase: {objClaseCode}</div>
                      </td>
                    )}
                    <td className="mono code-cell">{ind.codigo}</td>
                    <td>{ind.descripcion}</td>
                    {i === 0 && (
                      <td rowSpan={rowCount} className="escala-cell">
                        {obj.escala.map((e, idx) => (
                          <div key={idx}>{e} ({idx + 1})</div>
                        ))}
                      </td>
                    )}
                    <td className="diana-cell">
                      <div className="diana-row-inline">
                        <span className="val mono">{sc.basal}</span>
                        <span className="val mono">{sc.meta}</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Intervention block, matching the image */}
          <div className="final-intervention">
            <div className="int-header-row">
              <div><span className="int-cell-label">INTERVENCIÓN DE ENFERMERÍA:</span> {intv.nombre}</div>
              <div className="int-meta-cell"><strong>Campo:</strong> {intDominioNum}{intDominioName ? `. ${intDominioName.toLowerCase()}` : ''}</div>
              <div className="int-meta-cell"><strong>Clase:</strong> {intClaseCode}{intClaseName ? `. ${intClaseName.toLowerCase()}` : ''}</div>
            </div>
            <div className="int-name-row"><strong>{intv.nombre} ({intv.codigo})</strong></div>
            <ul className="int-activities">
              {intv.selectedActividades.map((a, idx) => <li key={idx}>{a}</li>)}
            </ul>
          </div>

          <div className="final-foot">
            <div>
              <div className="mono small muted">Cynamonurs · plan generado el {new Date().toLocaleDateString('es-MX', { day: '2-digit', month: 'long', year: 'numeric' })}</div>
            </div>
            <div className="final-sign">
              <div className="sign-line"/>
              <div className="sign-label">Enfermera responsable</div>
            </div>
          </div>
        </div>
        )}
      </div>

      {showShare && (
        <div className="share-modal no-print" onClick={() => setShowShare(false)}>
          <div className="share-modal-inner" onClick={e => e.stopPropagation()}>
            <h3>Compartir plan de cuidados</h3>
            <p>Elige una plataforma. Tu plan se envía como mensaje listo para enviar.</p>
            <div className="share-grid">
              {shareLinks.map(s => (
                <a key={s.name} className={'share-tile ' + s.icon} href={s.url} target="_blank" rel="noreferrer">
                  <div className="share-tile-icon">{shareIcon(s.icon)}</div>
                  <div className="share-tile-name">{s.name}</div>
                </a>
              ))}
              <button className="share-tile copy" onClick={copyClipboard}>
                <div className="share-tile-icon">
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                </div>
                <div className="share-tile-name">Copiar</div>
              </button>
            </div>
            <button className="btn-secondary" style={{ width: '100%', justifyContent: 'center', marginTop: 10 }} onClick={() => setShowShare(false)}>Cerrar</button>
          </div>
        </div>
      )}
    </div>
  );
}

function shareIcon(name) {
  const props = { width: 22, height: 22, viewBox: '0 0 24 24', fill: 'currentColor' };
  switch (name) {
    case 'wa': return <svg {...props}><path d="M20 12a8 8 0 0 1-12 6.9L4 20l1.1-3.8A8 8 0 1 1 20 12zm-8.6-3.5c-.3-.7-.6-.7-.9-.7H10c-.3 0-.7.1-1 .5s-1.2 1.2-1.2 2.8 1.2 3.3 1.4 3.5 2.4 3.8 6 5.2c3 1.2 3.6 1 4.2.9.7-.1 2.2-.9 2.5-1.7.3-.9.3-1.6.2-1.7-.1-.1-.4-.2-.8-.4l-2.3-1.1c-.3-.1-.5-.2-.7.2-.2.4-.8 1.1-1 1.3-.2.2-.4.2-.7.1-.3-.1-1.4-.5-2.7-1.6-1-.9-1.7-2-1.9-2.3-.2-.4 0-.5.1-.7l.6-.7c.2-.2.2-.4.4-.6.1-.2 0-.4 0-.6l-1-2.4z"/></svg>;
    case 'gm': return <svg {...props} fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m4 7 8 6 8-6"/></svg>;
    case 'ol': return <svg {...props}><path d="M3 5h11v14H3zm12 4l5 3-5 3z"/></svg>;
    case 'ml': return <svg {...props} fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m4 7 8 6 8-6"/></svg>;
    case 'tg': return <svg {...props}><path d="M22 4 2 11l6 2 2 6 4-4 6 5 2-16zM9 14l9-7-7 8z"/></svg>;
    case 'fb': return <svg {...props}><path d="M22 12a10 10 0 1 0-11.5 9.9V15h-2.5v-3H10.5V9.5c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.4h-1.2c-1.2 0-1.6.8-1.6 1.6V12h2.7l-.4 3H13.7V22A10 10 0 0 0 12 2z"/></svg>;
    default: return null;
  }
}

Object.assign(window, {
  PlanStore, MAX_CARS, MAX_FACTORS, MAX_INDICATORS, MAX_ACTIVITIES,
  detectDxType, dxTypeLabel, dxTypeStructure, buildDxSentence,
  setPlanDx, togglePlanDxItem, updatePlanDxManifestaciones,
  setPlanObjective, clearPlanObjective, togglePlanObjectiveIndicator, updatePlanObjective, updatePlanObjectiveIndicator,
  setPlanIntervention, clearPlanIntervention, togglePlanInterventionActivity,
  isDxReady, isObjReady, isIntReady,
  PlanWidget, PlanSummary, FinalTable
});
