// diag-charts.jsx — Radar (araña 8 ejes con iconos) + brecha tipo dot-plot.

function polar(cx, cy, r, angleDeg) {
  const a = (angleDeg - 90) * Math.PI / 180;
  return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
}

function RadarChart({ scores, light }) {
  const size = 540, cx = size / 2, cy = size / 2, R = 156;
  const N = scores.length;
  const levels = [1, 2, 3, 4, 5];
  const angleAt = i => (360 / N) * i;

  const ring = (lvl) => {
    const r = R * (lvl / 5);
    return scores.map((_, i) => polar(cx, cy, r, angleAt(i)).join(',')).join(' ');
  };
  const poly = (accessor) => scores.map((s, i) => {
    const r = R * (accessor(s) / 5);
    return polar(cx, cy, r, angleAt(i)).join(',');
  }).join(' ');

  const curPts = poly(s => s.current);
  const tgtPts = poly(s => s.target);
  const cls = 'radar-svg' + (light ? ' light' : '');

  return (
    <div className="radar-wrap">
      <svg className={cls} viewBox={`0 0 ${size} ${size}`} role="img"
           aria-label="Radar de los 8 ejes: nivel actual vs tu siguiente nivel">
        {levels.map(l => <polygon key={l} className="radar-grid" points={ring(l)} />)}

        {scores.map((s, i) => {
          const [x, y] = polar(cx, cy, R, angleAt(i));
          return <line key={s.key} className="radar-spoke" x1={cx} y1={cy} x2={x} y2={y} />;
        })}

        {/* current + target areas */}
        <polygon className="radar-cur" points={curPts} />
        <polygon className="radar-tgt" points={tgtPts} />

        {scores.map((s, i) => {
          const [cxp, cyp] = polar(cx, cy, R * (s.current / 5), angleAt(i));
          const [txp, typ] = polar(cx, cy, R * (s.target / 5), angleAt(i));
          return (
            <g key={s.key}>
              <circle className="radar-dot-cur" cx={cxp} cy={cyp} r="3.5" />
              <circle className="radar-dot-tgt" cx={txp} cy={typ} r="3.5" />
            </g>
          );
        })}

        {/* icon badges + names at each vertex */}
        {scores.map((s, i) => {
          const [ix, iy] = polar(cx, cy, R + 26, angleAt(i));
          const [lx, ly] = polar(cx, cy, R + 54, angleAt(i));
          const anchor = Math.abs(lx - cx) < 14 ? 'middle' : (lx > cx ? 'start' : 'end');
          const icon = window.DIAG_EJE_ICONS[s.key] || '';
          return (
            <g key={s.key}>
              <g transform={`translate(${ix.toFixed(1)}, ${iy.toFixed(1)})`}>
                <g className="radar-ico-float" style={{ animationDelay: `${-i * 0.6}s` }}>
                  <circle className="radar-ico-disc" r="14" />
                  <g className="radar-ico-glyph" transform="translate(-8,-8) scale(0.66)"
                     dangerouslySetInnerHTML={{ __html: icon }} />
                </g>
              </g>
              <text className="radar-axis-label" x={lx.toFixed(1)} y={ly.toFixed(1)}
                    textAnchor={anchor} dominantBaseline="middle">{s.name}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

/* ---- BRECHA: dot-plot coloquial (gris = hoy, círculo rojo = tu siguiente nivel) ----
   light = versión compacta para el PDF (sin cambios).
   web   = versión enriquecida: ordena por prioridad, muestra los valores hoy → meta
           sobre la escala 1–5 y marca los ejes que más se deben trabajar.            */
function DetailBars({ scores, light }) {
  const pos = v => Math.max(0, Math.min(100, ((v - 1) / 4) * 100));

  /* ---------- versión compacta (PDF) ---------- */
  if (light) {
    return (
      <div className="gapplot light">
        {scores.map(s => {
          const cur = pos(s.current), tgt = pos(s.target);
          const gap = Math.round((s.target - s.current) * 10) / 10;
          const lo = Math.min(cur, tgt), hi = Math.max(cur, tgt);
          const icon = window.DIAG_EJE_ICONS[s.key] || '';
          return (
            <div className="gp-row" key={s.key}>
              <div className="gp-label">
                <span className="gp-ic" aria-hidden="true">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"
                       strokeLinecap="round" strokeLinejoin="round"
                       dangerouslySetInnerHTML={{ __html: icon }} />
                </span>
                <span className="gp-name">{s.name}</span>
              </div>
              <div className="gp-track">
                <div className="gp-baseline" />
                <div className="gp-connect" style={{ left: lo + '%', width: (hi - lo) + '%' }} />
                <div className="gp-now" style={{ left: cur + '%' }} title={`Hoy: ${s.current.toFixed(1)}`} />
                <div className="gp-goal" style={{ left: tgt + '%' }} title={`Tu siguiente nivel: ${s.target.toFixed(1)}`} />
              </div>
              <div className="gp-gap">{gap > 0.1 ? `+${gap.toFixed(1)}` : '✓'}</div>
            </div>
          );
        })}
      </div>
    );
  }

  /* ---------- versión web enriquecida ---------- */
  // Ordena por prioridad (mismo criterio que la recomendación): los ejes que
  // más se deben trabajar quedan arriba. Los 3 primeros se marcan como foco.
  const ranked = [...scores].sort((a, b) => (b.priority || 0) - (a.priority || 0));
  const focusCount = ranked.filter(s => (s.target - s.current) > 0.1).length >= 3 ? 3 : 0;

  return (
    <div className="gapplot v2">
      {/* escala 1–5 alineada con las pistas */}
      <div className="gp-scale" aria-hidden="true">
        <span className="gp-scale-cap">Tu ruta</span>
        <div className="gp-scale-ruler">
          {[1, 2, 3, 4, 5].map(n => (
            <span key={n} className="gp-tick" style={{ left: pos(n) + '%' }}>{n}</span>
          ))}
        </div>
        <span className="gp-scale-cap end">Falta</span>
      </div>

      {ranked.map((s, idx) => {
        const cur = pos(s.current), tgt = pos(s.target);
        const gap = Math.round((s.target - s.current) * 10) / 10;
        const lo = Math.min(cur, tgt), hi = Math.max(cur, tgt);
        const isFocus = idx < focusCount && gap > 0.1;
        const done = gap <= 0.1;
        const icon = window.DIAG_EJE_ICONS[s.key] || '';
        const cls = 'gp-row' + (isFocus ? ' focus' : '') + (done ? ' done' : '');
        return (
          <div className={cls} key={s.key} style={{ '--gp-i': idx }}>
            <div className="gp-label">
              <span className={'gp-rank' + (isFocus ? ' on' : '')}>{idx + 1}</span>
              <span className="gp-ic" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"
                     strokeLinecap="round" strokeLinejoin="round"
                     dangerouslySetInnerHTML={{ __html: icon }} />
              </span>
              <span className="gp-name-wrap">
                <span className="gp-name">{s.name}</span>
                {isFocus && <span className="gp-flag">{idx === 0 ? 'Empieza por aquí' : 'Prioridad'}</span>}
                {done && <span className="gp-flag done">Ya casi lo tienes</span>}
              </span>
            </div>

            <div className="gp-track">
              <div className="gp-baseline" />
              <div className="gp-connect" style={{ left: lo + '%', width: (hi - lo) + '%' }} />
              <div className="gp-now" style={{ left: cur + '%' }}>
                <span className="gp-mk-tag now">{s.current.toFixed(1)}</span>
              </div>
              <div className="gp-goal" style={{ left: tgt + '%' }}>
                <span className="gp-mk-tag goal">{s.target.toFixed(1)}</span>
              </div>
            </div>

            <div className="gp-delta">
              {gap > 0.1 ? (
                <React.Fragment>
                  <span className="gp-delta-v">+{gap.toFixed(1)}</span>
                  <span className="gp-delta-l">por subir</span>
                </React.Fragment>
              ) : (
                <span className="gp-delta-done" aria-label="logrado">✓</span>
              )}
            </div>
          </div>
        );
      })}

      <div className="gp-foot">
        <span className="gp-foot-note">Ordenado por dónde tu esfuerzo rinde más — empieza por arriba.</span>
      </div>
    </div>
  );
}

Object.assign(window, { RadarChart, DetailBars });
