/* ============================================================
   DASHBOARD EJECUTIVO — Panel de dirección
   Filtros · KPIs · Radar por área · Distribución · Mapa de calor
   Ranking · Histórico · Matriz de prioridades · Recomendaciones
   Exporta: ScreenExec
   ============================================================ */
const IHE = window.IH;
const { useState: useStateE, useEffect: useEffectE } = React;

function ScreenExec({ onBack, onReport, onLogout }) {
  const [f, setF] = useStateE({ area: 'Todas', sucursal: 'Todas', puesto: 'Todos', periodo: 'Mes actual' });
  const [data, setData] = useStateE(null);
  const [loading, setLoading] = useStateE(true);
  const [error, setError] = useStateE(null);
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));

  useEffectE(() => {
    setLoading(true);
    setError(null);
    IHA.getDashboardReport(f)
      .then(d => { setData(d); setLoading(false); })
      .catch(e => { setError(e.message || 'Error al cargar datos'); setLoading(false); });
  }, [f]);

  const avg = data?.scores || {};
  const dist = data?.distribution || {};
  const rank = data?.ranking || [];
  const hist = data?.historical || [];
  const reco = data?.recommendations || {};
  const total = data?.summary?.total || 0;
  const evolIdx = data?.summary?.evolIndex || 0;
  const dominant = data?.summary?.dominant || 'guerrero';
  const rseries = buildRadarSeries(data, f);

  const puestos = ['Todos', ...new Set(Object.values(IHE.puestosByArea).flat())];

  return (
    <div className="fade-in" style={{ minHeight: '100vh', background: 'var(--paper)' }}>
      {/* header */}
      <header className="no-print" style={{ position: 'sticky', top: 0, zIndex: 30, background: 'var(--paper)', borderBottom: '1px solid var(--hair)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 40px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
            <Brand small />
            <div style={{ width: 1, height: 22, background: 'var(--hair-2)' }}></div>
            <span className="serif" style={{ fontSize: 18, fontWeight: 600 }}>Panel ejecutivo</span>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <button className="btn btn-ghost" onClick={onBack} style={{ fontSize: 13 }}>← Evaluación</button>
            <button className="btn btn-ghost" onClick={onLogout} style={{ fontSize: 13, color: 'var(--ink-3)' }}>Cerrar sesión</button>
            <button className="btn btn-gold" onClick={() => onReport(f)} style={{ fontSize: 13 }}>Generar PDF ejecutivo</button>
          </div>
        </div>
        {/* filtros */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 40px', borderTop: '1px solid var(--hair)', background: 'var(--panel-soft)', flexWrap: 'wrap' }}>
          <span className="eyebrow" style={{ marginRight: 4 }}>Filtrar</span>
          <Filt label="Área" value={f.area} opts={['Todas', ...IHE.areas]} onChange={v => set('area', v)} />
          <Filt label="Sucursal" value={f.sucursal} opts={['Todas', ...IHE.sucursales]} onChange={v => set('sucursal', v)} />
          <Filt label="Puesto" value={f.puesto} opts={puestos} onChange={v => set('puesto', v)} />
          <Filt label="Periodo" value={f.periodo} opts={['Todos', ...IHE.periodos]} onChange={v => set('periodo', v)} />
          <span className="mono" style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)' }}>
            {loading ? 'Cargando…' : `${total} colaboradores`}
          </span>
        </div>
      </header>

      {error && (
        <div style={{ margin: '20px 40px', padding: '14px 18px', background: 'oklch(0.56 0.13 28 / 0.08)', border: '1px solid var(--risk)', borderRadius: 8, color: 'var(--risk)', fontSize: 13 }}>
          {error}
        </div>
      )}

      <div style={{ maxWidth: 1360, margin: '0 auto', padding: '28px 40px 80px', opacity: loading ? 0.5 : 1, transition: 'opacity .2s' }}>
        {/* KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 18, marginBottom: 24 }}>
          <Kpi label="Colaboradores evaluados" value={total} unit="" />
          <Kpi label="Índice de evolución" value={evolIdx} unit="/100" accent="var(--gold)" />
          <KpiArch label="Arquetipo predominante" id={dominant} />
          <Kpi label="Área más evolucionada" value={rank[0]?.area || '—'} small accent="var(--good)" sub={rank[0] ? `${rank[0].evol}/100` : ''} />
        </div>

        {/* fila 1: radar + distribución */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.15fr 0.85fr', gap: 18, marginBottom: 18 }}>
          <Card title="Radar promedio" sub={f.area === 'Todas' ? 'Organización vs. áreas seleccionadas' : `Área de ${f.area} vs. organización`}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 260px', gap: 20, alignItems: 'center' }}>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Radar size={330} series={rseries} />
              </div>
              <div>
                <AxisLegend scores={avg} />
                <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {rseries.map((s, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12.5, color: 'var(--ink-2)' }}>
                      <span style={{ width: 16, height: 3, background: s.color, borderRadius: 2, opacity: s.dash ? 0.6 : 1 }}></span>
                      {s.label}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Card>
          <Card title="Distribución de arquetipos" sub="¿Por cuál está gobernado cada colaborador?">
            <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22 }}>
              <Donut dist={dist} total={total} size={150} thickness={22} />
              <div style={{ flex: 1 }}>
                <DistMini dist={dist} total={total} />
              </div>
            </div>
          </Card>
        </div>

        {/* fila 2: mapa de calor */}
        <Card title="Mapa de calor organizacional" sub="Intensidad de cada arquetipo por área · más oscuro = mayor presencia" style={{ marginBottom: 18 }}>
          <Heatmap areaMap={data?.heatmap || {}} />
          <HeatLegend />
        </Card>

        {/* fila 3: ranking + histórico */}
        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 18, marginBottom: 18 }}>
          <Card title="Ranking de evolución" sub="Áreas ordenadas por índice de evolución">
            <EvolRanking rows={rank} />
          </Card>
          <Card title="Comparación histórica" sub="Índice de evolución (oro) y arquetipos por periodo">
            <HistLines hist={hist} width={560} height={210} />
          </Card>
        </div>

        {/* fila 4: matriz de prioridades */}
        <Card title="Matriz ejecutiva de prioridades" sub="Prevalencia × prioridad de intervención" style={{ marginBottom: 18 }}>
          <PriorityMatrix avg={avg} />
        </Card>

        {/* fila 5: recomendaciones org */}
        <Card title="Recomendaciones organizacionales" sub="Acciones sugeridas a partir del perfil promedio">
          <RecoSection reco={reco} />
        </Card>
      </div>
    </div>
  );
}

function buildRadarSeries(data, f) {
  if (!data?.scores) return [];
  const avg = data.scores;
  const rank = data.ranking || [];
  if (f.area === 'Todas') {
    const out = [{ scores: avg, color: 'var(--gold)', fillOpacity: 0.12, label: 'Organización', width: 2.5 }];
    if (rank[0]) out.push({ scores: rank[0].scores, color: IHE.byId.sabio.hex, fillOpacity: 0.04, dash: '4 4', dots: false, label: `${rank[0].area} (líder)` });
    const bottom = rank[rank.length - 1];
    if (bottom && bottom !== rank[0]) out.push({ scores: bottom.scores, color: IHE.byId.guerrero.hex, fillOpacity: 0.04, dash: '4 4', dots: false, label: `${bottom.area} (rezago)` });
    return out;
  }
  return [{ scores: avg, color: 'var(--gold)', fillOpacity: 0.13, label: f.area, width: 2.5 }];
}

/* —— Filtro select —— */
function Filt({ label, value, opts, onChange, disabled }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
      <select disabled={disabled} value={value} onChange={e => onChange && onChange(e.target.value)}
        style={{ appearance: 'none', fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 500, color: disabled ? 'var(--ink-3)' : 'var(--ink)',
          background: 'var(--panel)', border: '1px solid var(--hair-2)', borderRadius: 7, padding: '7px 28px 7px 12px', cursor: disabled ? 'default' : 'pointer',
          backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' fill='none' stroke='%238a857b' stroke-width='1.6'%3E%3Cpath d='M1 3l4 4 4-4'/%3E%3C/svg%3E\")",
          backgroundRepeat: 'no-repeat', backgroundPosition: 'right 10px center' }}>
        {opts.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

/* —— Card —— */
function Card({ title, sub, children, style }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 'var(--r-lg)', padding: 26, boxShadow: 'var(--shadow)', ...style }}>
      <div style={{ marginBottom: 22 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
          <h3 className="serif" style={{ fontSize: 19, fontWeight: 600, margin: 0 }}>{title}</h3>
        </div>
        {sub && <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 4 }}>{sub}</div>}
      </div>
      {children}
    </div>
  );
}

/* —— KPI —— */
function Kpi({ label, value, unit, accent, small, sub }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 'var(--r-lg)', padding: '22px 24px', boxShadow: 'var(--shadow)' }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span className="serif" style={{ fontSize: small ? 26 : 42, fontWeight: 600, lineHeight: 1, color: accent || 'var(--ink)' }}>{value}</span>
        {unit && <span className="mono" style={{ fontSize: 14, color: 'var(--ink-3)' }}>{unit}</span>}
      </div>
      {sub && <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{sub}</div>}
    </div>
  );
}
function KpiArch({ label, id }) {
  const a = IHE.byId[id] || IHE.byId.guerrero;
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--hair)', borderRadius: 'var(--r-lg)', padding: '22px 24px', boxShadow: 'var(--shadow)' }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 42, height: 42, borderRadius: 10, background: a.hex + '1c', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Glyph id={id} size={24} stroke={1.8} />
        </div>
        <span className="serif" style={{ fontSize: 28, fontWeight: 600, color: a.hex }}>{a.name}</span>
      </div>
    </div>
  );
}

/* —— Distribución mini (junto a la dona) —— */
function DistMini({ dist, total }) {
  const ranked = [...IHE.order].sort((a, b) => (dist[b] || 0) - (dist[a] || 0));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      {ranked.map(id => {
        const a = IHE.byId[id];
        const v = dist[id] || 0;
        return (
          <div key={id} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12.5 }}>
            <span style={{ width: 9, height: 9, borderRadius: 2, background: a.hex, flex: 'none' }}></span>
            <span style={{ flex: 1, color: 'var(--ink-2)' }}>{a.name}</span>
            <span className="mono" style={{ fontWeight: 600 }}>{v}</span>
          </div>
        );
      })}
    </div>
  );
}

/* —— Leyenda mapa de calor —— */
function HeatLegend() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--hair)' }}>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Riesgo</span>
      <div style={{ display: 'flex', gap: 4 }}>
        {['huerfano', 'vagabundo', 'martir'].map(id => <span key={id} style={{ width: 14, height: 14, borderRadius: 3, background: COL[id] }}></span>)}
      </div>
      <span style={{ color: 'var(--hair-2)' }}>·</span>
      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Evolución</span>
      <div style={{ display: 'flex', gap: 4 }}>
        {['guerrero', 'sabio', 'mago'].map(id => <span key={id} style={{ width: 14, height: 14, borderRadius: 3, background: COL[id] }}></span>)}
      </div>
      <span className="mono" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)' }}>Valor 0–100 · opacidad ∝ presencia</span>
    </div>
  );
}

/* —— Matriz de prioridades (2×2 consultoría) —— */
function PriorityMatrix({ avg }) {
  const W = 760, H = 420, pad = 54;
  const innerW = W - pad * 2, innerH = H - pad * 2;
  const priorityOf = (id, v) => {
    const risk = ['huerfano', 'vagabundo', 'martir'].includes(id);
    return risk ? v : (100 - v);
  };
  const pts = IHE.order.map(id => {
    const v = avg[id] || 0;
    const prev = v;
    const pr = priorityOf(id, v);
    return { id, x: pad + (prev / 100) * innerW, y: pad + innerH - (pr / 100) * innerH, v, pr, prev };
  });
  const cx = pad + innerW / 2, cy = pad + innerH / 2;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 28, alignItems: 'center' }}>
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', overflow: 'visible' }}>
        {/* cuadrantes */}
        <rect x={cx} y={pad} width={innerW / 2} height={innerH / 2} fill="oklch(0.56 0.13 28 / 0.06)" />
        <rect x={pad} y={pad} width={innerW / 2} height={innerH / 2} fill="oklch(0.70 0.11 70 / 0.05)" />
        <rect x={pad} y={cy} width={innerW / 2} height={innerH / 2} fill="oklch(0.60 0.09 150 / 0.05)" />
        <rect x={cx} y={cy} width={innerW / 2} height={innerH / 2} fill="var(--panel-soft)" />
        {/* ejes */}
        <line x1={pad} y1={cy} x2={W - pad} y2={cy} stroke="var(--hair-2)" strokeWidth="1" />
        <line x1={cx} y1={pad} x2={cx} y2={H - pad} stroke="var(--hair-2)" strokeWidth="1" />
        <rect x={pad} y={pad} width={innerW} height={innerH} fill="none" stroke="var(--hair)" strokeWidth="1" />
        {/* etiquetas cuadrante */}
        <text x={W - pad - 12} y={pad + 22} textAnchor="end" fontFamily="var(--mono)" fontSize="12" fontWeight="600" fill="var(--risk)" letterSpacing="0.08em">URGENTE</text>
        <text x={pad + 12} y={pad + 22} fontFamily="var(--mono)" fontSize="12" fontWeight="600" fill="var(--warn)" letterSpacing="0.08em">IMPORTANTE</text>
        <text x={W - pad - 12} y={H - pad - 12} textAnchor="end" fontFamily="var(--mono)" fontSize="12" fontWeight="600" fill="var(--good)" letterSpacing="0.08em">OPORTUNIDAD</text>
        <text x={pad + 12} y={H - pad - 12} fontFamily="var(--mono)" fontSize="11" fontWeight="500" fill="var(--ink-3)" letterSpacing="0.08em">MONITOREAR</text>
        {/* ejes labels */}
        <text x={cx} y={H - 14} textAnchor="middle" fontFamily="var(--mono)" fontSize="10.5" fill="var(--ink-3)" letterSpacing="0.08em">PREVALENCIA →</text>
        <text x={16} y={cy} textAnchor="middle" fontFamily="var(--mono)" fontSize="10.5" fill="var(--ink-3)" letterSpacing="0.08em" transform={`rotate(-90 16 ${cy})`}>PRIORIDAD →</text>
        {/* burbujas */}
        {pts.map(p => {
          const r = 16 + (p.v / 100) * 14;
          return (
            <g key={p.id}>
              <circle cx={p.x} cy={p.y} r={r} fill={COL[p.id]} fillOpacity="0.16" stroke={COL[p.id]} strokeWidth="1.5" />
              <g transform={`translate(${p.x - 11}, ${p.y - 11})`}><Glyph id={p.id} size={22} stroke={1.8} /></g>
              <text x={p.x} y={p.y + r + 13} textAnchor="middle" fontFamily="var(--sans)" fontSize="11.5" fontWeight="600" fill="var(--ink)">{IHE.byId[p.id].name}</text>
            </g>
          );
        })}
      </svg>
      <div>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Lectura ejecutiva</div>
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 13 }}>
          {[...pts].sort((a, b) => b.pr - a.pr).slice(0, 3).map(p => (
            <li key={p.id} style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
              <Glyph id={p.id} size={18} stroke={1.6} />
              <div style={{ fontSize: 13, lineHeight: 1.45, color: 'var(--ink-2)' }}>
                <strong style={{ color: 'var(--ink)', fontWeight: 600 }}>{IHE.byId[p.id].name}</strong>
                {' '}— {p.pr >= 60 ? 'requiere intervención prioritaria' : 'mantener bajo observación'} ({p.v}% de prevalencia).
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenExec, Card, Kpi, PriorityMatrix });
