/* ============================================================
   RESULTADO INDIVIDUAL — Dashboard de la persona
   Incluye 3 variaciones de composición (Editorial · Tablero · Enfoque)
   Exporta: ScreenResult
   ============================================================ */
const IHR = window.IH;

function ScreenResult({ profile, scores, onRestart, onExec, onPDF }) {
  const [variant, setVariant] = React.useState('editorial');
  const diag = IHR.diagnose(scores);
  const reco = IHR.recommend(scores);
  const dom = IHR.byId[diag.dominant];

  return (
    <div className="fade-in" style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      {/* header */}
      <header className="no-print" style={{ position: 'sticky', top: 0, zIndex: 20, background: 'var(--paper)', borderBottom: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 48px' }}>
        <Brand small />
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <VariantSwitch value={variant} onChange={setVariant} />
          <div style={{ width: 1, height: 22, background: 'var(--hair-2)' }}></div>
          <button className="btn btn-ghost" onClick={onExec} style={{ fontSize: 13 }}>Panel ejecutivo</button>
          <button className="btn btn-gold" onClick={onPDF} style={{ fontSize: 13 }}>Exportar PDF</button>
        </div>
      </header>

      <div style={{ maxWidth: 1180, margin: '0 auto', padding: '44px 48px 90px' }}>
        {/* encabezado de identidad */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 34, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Radiografía conductual individual</div>
            <h1 className="serif" style={{ fontSize: 40, fontWeight: 500, margin: 0, letterSpacing: '-0.01em' }}>{profile.nombre || 'Colaborador'}</h1>
            <div style={{ display: 'flex', gap: 10, marginTop: 10, flexWrap: 'wrap' }}>
              {[profile.puesto, profile.area, profile.empresa, profile.antiguedad].filter(Boolean).map((t, i) => (
                <span key={i} className="mono" style={{ fontSize: 11.5, color: 'var(--ink-2)', background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 20, padding: '5px 13px' }}>{t}</span>
              ))}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.08em' }}>{new Date().toLocaleDateString('es-MX', { day: '2-digit', month: 'long', year: 'numeric' })}</div>
          </div>
        </div>

        {/* frase diagnóstica — el diferenciador */}
        <DiagnosticHeadline scores={scores} />

        {variant === 'editorial' && <VariantEditorial scores={scores} diag={diag} dom={dom} />}
        {variant === 'tablero' && <VariantTablero scores={scores} diag={diag} dom={dom} />}
        {variant === 'enfoque' && <VariantEnfoque scores={scores} diag={diag} dom={dom} />}

        {/* INTERPRETACIÓN */}
        <Interpretacion dom={dom} diag={diag} />

        {/* RECOMENDACIONES */}
        <RecoSection reco={reco} />

        {/* pie */}
        <div style={{ marginTop: 50, paddingTop: 22, borderTop: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <p className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', margin: 0, maxWidth: 560, lineHeight: 1.5 }}>
            Este mapa describe qué arquetipo gobierna hoy tus decisiones. No es una calificación ni una etiqueta permanente: es una fotografía del momento, y se puede transformar.
          </p>
          <button className="btn btn-ghost no-print" onClick={onRestart} style={{ fontSize: 13 }}>↺ Nueva evaluación</button>
        </div>
      </div>
    </div>
  );
}

/* —— Switch de variante —— */
function VariantSwitch({ value, onChange }) {
  const opts = [['editorial', 'Editorial'], ['tablero', 'Tablero'], ['enfoque', 'Enfoque']];
  return (
    <div style={{ display: 'flex', background: 'var(--paper-2)', borderRadius: 8, padding: 3, gap: 2 }}>
      {opts.map(([k, l]) => (
        <button key={k} onClick={() => onChange(k)} style={{ border: 'none', cursor: 'pointer', fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 500,
          padding: '6px 13px', borderRadius: 6, transition: 'all .15s',
          background: value === k ? 'var(--panel)' : 'transparent', color: value === k ? 'var(--ink)' : 'var(--ink-3)',
          boxShadow: value === k ? 'var(--shadow)' : 'none' }}>{l}</button>
      ))}
    </div>
  );
}

/* —— Frase diagnóstica automática (pull-quote) —— */
function DiagnosticHeadline({ scores }) {
  const d = IHR.diagnosticLine(scores);
  const accentColor = d.strong ? 'var(--risk)' : 'var(--gold)';
  return (
    <div style={{ position: 'relative', background: 'var(--panel)', border: '1px solid var(--hair)', borderLeft: `3px solid ${accentColor}`, borderRadius: 'var(--r-lg)', padding: '30px 36px', marginBottom: 24, boxShadow: 'var(--shadow)' }}>
      <div className="eyebrow" style={{ marginBottom: 16 }}>Lectura inmediata</div>
      <p className="serif" style={{ fontSize: 30, lineHeight: 1.3, fontWeight: 500, margin: 0, letterSpacing: '-0.01em', color: 'var(--ink)' }}>
        {d.lead}{d.strong ? '… ' : ' '}
        <span style={{ color: accentColor, fontStyle: 'italic' }}>{d.turn}</span>
      </p>
    </div>
  );
}

/* —— Diagnóstico principal (reutilizable) —— */
function DiagPrincipal({ diag, dom, big }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 14 }}>Actualmente operas principalmente desde</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 18 }}>
        <div style={{ width: big ? 72 : 58, height: big ? 72 : 58, borderRadius: 16, background: dom.hex + '1c', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
          <Glyph id={dom.id} size={big ? 40 : 32} stroke={2} />
        </div>
        <div>
          <div className="serif" style={{ fontSize: big ? 52 : 40, fontWeight: 600, lineHeight: 1, color: dom.hex }}>{dom.name}</div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 6 }}>{dom.glyph}</div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Arquetipos secundarios</span>
        <div style={{ display: 'flex', gap: 8 }}>
          {diag.secondary.map(id => {
            const a = IHR.byId[id];
            return (
              <span key={id} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 500,
                background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 20, padding: '5px 12px 5px 9px' }}>
                <Glyph id={id} size={15} stroke={1.6} /> {a.name}
              </span>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* —— Card contenedor —— */
function Panel({ children, style, title, sub }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 'var(--r-lg)', padding: 30, boxShadow: 'var(--shadow)', ...style }}>
      {title && <div style={{ marginBottom: 20 }}>
        <div className="eyebrow">{title}</div>
        {sub && <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>{sub}</div>}
      </div>}
      {children}
    </div>
  );
}

/* ============== VARIANTE A · EDITORIAL ============== */
function VariantEditorial({ scores, diag, dom }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 24, marginBottom: 24 }}>
      <Panel title="Diagnóstico principal" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <DiagPrincipal diag={diag} dom={dom} big />
        <div style={{ marginTop: 30, paddingTop: 26, borderTop: '1px solid var(--hair)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
            <span className="eyebrow">Mapa conductual</span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>6 arquetipos · % independiente</span>
          </div>
          <AxisLegend scores={scores} />
        </div>
      </Panel>
      <Panel title="Radar conductual" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Radar series={[{ scores, color: dom.hex, fillOpacity: 0.13 }]} size={340} />
        <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 10 }}>
          <RingStat value={diag.evolIndex} label="Índice de evolución" size={104} />
        </div>
      </Panel>
    </div>
  );
}

/* ============== VARIANTE B · TABLERO ============== */
function VariantTablero({ scores, diag, dom }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 24, marginBottom: 24 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        <Panel style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <RingStat value={diag.evolIndex} label="Índice de evolución" />
        </Panel>
        <Panel title="Diagnóstico" style={{ flex: 1 }}>
          <DiagPrincipal diag={diag} dom={dom} />
        </Panel>
      </div>
      <Panel title="Radar conductual" sub="Cada eje es independiente — no se suman entre sí" style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 24, alignItems: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Radar series={[{ scores, color: dom.hex, fillOpacity: 0.13 }]} size={330} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
          {IHR.order.map(id => <ScoreBar key={id} id={id} value={scores[id]} showGlyph />)}
        </div>
      </Panel>
    </div>
  );
}

/* ============== VARIANTE C · ENFOQUE ============== */
function VariantEnfoque({ scores, diag, dom }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ borderRadius: 'var(--r-lg)', overflow: 'hidden', border: '1px solid var(--hair)', boxShadow: 'var(--shadow)', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
        {/* panel de color con el arquetipo dominante */}
        <div style={{ background: `linear-gradient(150deg, ${dom.hex}, ${dom.hex}cc)`, padding: '44px 40px', color: '#fff', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 360 }}>
          <div>
            <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.85, marginBottom: 22 }}>Operas principalmente desde</div>
            <div style={{ marginBottom: 20 }}><Glyph id={dom.id} size={56} stroke={2.2} color="#fff" /></div>
            <div className="serif" style={{ fontSize: 60, fontWeight: 600, lineHeight: 0.95 }}>{dom.name}</div>
            <div style={{ fontSize: 15, opacity: 0.9, marginTop: 12 }}>{dom.glyph}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 30 }}>
            <div>
              <div className="serif" style={{ fontSize: 38, fontWeight: 600, lineHeight: 1 }}>{diag.evolIndex}</div>
              <div className="mono" style={{ fontSize: 9.5, opacity: 0.8, letterSpacing: '0.1em' }}>ÍNDICE DE EVOLUCIÓN</div>
            </div>
            <div style={{ width: 1, height: 40, background: 'rgba(255,255,255,0.3)' }}></div>
            <div style={{ display: 'flex', gap: 8 }}>
              {diag.secondary.map(id => (
                <span key={id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, background: 'rgba(255,255,255,0.16)', borderRadius: 20, padding: '5px 12px' }}>
                  <Glyph id={id} size={14} stroke={1.6} color="#fff" /> {IHR.byId[id].name}
                </span>
              ))}
            </div>
          </div>
        </div>
        {/* radar */}
        <div style={{ background: 'var(--panel)', padding: '34px 30px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <Radar series={[{ scores, color: dom.hex, fillOpacity: 0.13 }]} size={330} />
          <div style={{ marginTop: 16, width: '100%' }}><AxisLegend scores={scores} /></div>
        </div>
      </div>
    </div>
  );
}

/* —— Interpretación —— */
function Interpretacion({ dom, diag }) {
  const t = IHR.interpret[dom.id];
  return (
    <Panel title="Interpretación del perfil" sub={`Lectura del arquetipo dominante · ${dom.name}`} style={{ marginBottom: 24 }}>
      <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink)', margin: '0 0 28px', maxWidth: 820 }} className="serif">{t.desc}</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 22 }}>
        <InterpCol title="Fortalezas" color="var(--good)" items={t.fortalezas} />
        <InterpCol title="Áreas de riesgo" color="var(--risk)" items={t.riesgos} />
        <InterpCol title="Potencial de crecimiento" color="var(--gold)" items={[t.crecimiento]} />
      </div>
    </Panel>
  );
}
function InterpCol({ title, color, items }) {
  return (
    <div style={{ borderTop: `2px solid ${color}`, paddingTop: 16 }}>
      <div className="eyebrow" style={{ color: 'var(--ink-2)', marginBottom: 14 }}>{title}</div>
      <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 11 }}>
        {items.map((it, i) => (
          <li key={i} style={{ display: 'flex', gap: 10, fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)' }}>
            <span style={{ width: 5, height: 5, borderRadius: 5, background: color, marginTop: 7, flex: 'none' }}></span>
            <span>{it}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

/* —— Recomendaciones —— */
function RecoSection({ reco }) {
  const cols = [
    { k: 'urgente', label: 'Acciones urgentes', color: 'var(--risk)', tone: 'oklch(0.56 0.13 28 / 0.08)' },
    { k: 'importante', label: 'Acciones importantes', color: 'var(--warn)', tone: 'oklch(0.70 0.11 70 / 0.10)' },
    { k: 'mejora', label: 'Mejora continua', color: 'var(--good)', tone: 'oklch(0.60 0.09 150 / 0.08)' },
  ];
  return (
    <Panel title="Sistema de recomendaciones" sub="Generadas automáticamente a partir de tu mapa conductual">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 18 }}>
        {cols.map(c => {
          const items = reco[c.k] || [];
          return (
            <div key={c.k} style={{ background: c.tone, borderRadius: 'var(--r)', padding: 20, minHeight: 150 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 16 }}>
                <span style={{ width: 9, height: 9, borderRadius: 9, background: c.color }}></span>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>{c.label}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginLeft: 'auto' }}>{items.length}</span>
              </div>
              {items.length ? (
                <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 13 }}>
                  {items.map((it, i) => (
                    <li key={i} style={{ fontSize: 13.5, lineHeight: 1.45, color: 'var(--ink)' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                        <Glyph id={it.archetype} size={14} stroke={1.6} />
                        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{IHR.byId[it.archetype].name}</span>
                      </span>
                      <div style={{ color: 'var(--ink-2)' }}>{it.text}</div>
                    </li>
                  ))}
                </ul>
              ) : <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: 0 }}>Sin acciones en este nivel.</p>}
            </div>
          );
        })}
      </div>
    </Panel>
  );
}

Object.assign(window, { ScreenResult, Panel, DiagPrincipal });
