// IEDF 2026 — entity profile section
const { useMemo: usePMemo } = React;

const DIM_LABELS = { estructura: 'Estructura', operacion: 'Operación', resultado: 'Resultado' };

function normName(s) {
  return s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
}

// dimension bars for a state vs national mean
function DimBars({ row, ranking, palette }) {
  const dims = ['estructura', 'operacion', 'resultado'];
  return (
    <div style={{ display: 'grid', gap: 14 }}>
      {dims.map(dim => {
        const mean = ranking.reduce((a, d) => a + d[dim], 0) / ranking.length;
        const rk = [...ranking].sort((a, b) => b[dim] - a[dim]).findIndex(d => d.entidad_std === row.entidad_std) + 1;
        return (
          <div key={dim}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
              <span style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 700, fontSize: 13, letterSpacing: '.04em', textTransform: 'uppercase' }}>{DIM_LABELS[dim]}</span>
              <span style={{ fontSize: 13, color: '#76766f', whiteSpace: 'nowrap' }}>{rk}º nacional · <b style={{ color: INK }}>{fmt(row[dim])}</b></span>
            </div>
            <div style={{ position: 'relative', height: 18, background: '#edebe3' }}>
              <div style={{ position: 'absolute', inset: '0 auto 0 0', width: `${row[dim]}%`, background: rankColor(rk, 32, palette), outline: '1px solid rgba(0,0,0,.14)', outlineOffset: -1, transition: 'width .5s cubic-bezier(.22,1,.36,1)' }}></div>
              <div title={`Promedio nacional: ${fmt(mean)}`} style={{ position: 'absolute', top: -3, bottom: -3, left: `${mean}%`, width: 2, background: INK }}></div>
            </div>
          </div>
        );
      })}
      <div style={{ fontSize: 12.5, color: '#76766f', display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ display: 'inline-block', width: 2, height: 12, background: INK }}></span> promedio nacional
      </div>
    </div>
  );
}

function IndicatorRows({ entidadStd, index, metadata, palette, setTip }) {
  const groups = [
    { key: 'estructura', label: 'Estructura' },
    { key: 'operacion', label: 'Operación' },
    { key: 'resultado', label: 'Resultado' },
  ];
  const rows = index[entidadStd] || {};
  // national mean of normalized per indicator
  const meanNorm = usePMemo(() => {
    const m = {};
    for (const meta of metadata) {
      let s = 0, c = 0;
      for (const ent of Object.keys(index)) {
        const r = index[ent][meta.id];
        if (r && r.n != null && !isNaN(r.n)) { s += r.n; c++; }
      }
      m[meta.id] = c ? s / c : null;
    }
    return m;
  }, [index, metadata]);

  return (
    <div style={{ display: 'grid', gap: 26 }}>
      {groups.map(g => {
        const metas = metadata.filter(m => m.dimension === g.key && rows[m.id]);
        if (!metas.length) return null;
        return (
          <div key={g.key}>
            <div style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 800, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase', color: '#76766f', borderBottom: `2px solid ${INK}`, paddingBottom: 5, marginBottom: 10 }}>{g.label}</div>
            <div style={{ display: 'grid', gap: 9 }}>
              {metas.map(meta => {
                const r = rows[meta.id];
                const t = (meta.direccion === 'negativo' ? r.n : r.n) / 100; // normalized already direction-adjusted
                return (
                  <div key={meta.id}
                    onMouseMove={e => setTip({
                      x: e.clientX, y: e.clientY,
                      body: (<div>
                        <div style={{ fontWeight: 700 }}>{meta.nombre}</div>
                        <div style={{ opacity: .8, fontSize: 12, margin: '3px 0' }}>{meta.descripcion}</div>
                        <div>Valor: <b>{fmt(r.v)}</b> {meta.unidad}</div>
                        <div>Puntaje normalizado: <b>{fmt(r.n)}</b> / 100</div>
                        <div style={{ opacity: .7, fontSize: 12 }}>Fuente: {meta.fuente} ({r.y}){meta.en_iedf ? '' : ' · no entra al IEDF'}</div>
                      </div>)
                    })}
                    onMouseLeave={() => setTip(null)}
                    style={{ display: 'grid', gridTemplateColumns: '210px 1fr 110px', gap: 12, alignItems: 'center', cursor: 'default' }}>
                    <div style={{ fontSize: 13.5, lineHeight: 1.25 }}>
                      {meta.nombre}
                    </div>
                    <div style={{ position: 'relative', height: 14, background: '#edebe3' }}>
                      <div style={{ position: 'absolute', inset: '0 auto 0 0', width: `${Math.max(1, r.n)}%`, background: semaforo(t, palette), outline: '1px solid rgba(0,0,0,.12)', outlineOffset: -1, transition: 'width .5s cubic-bezier(.22,1,.36,1)' }}></div>
                      {meanNorm[meta.id] != null && <div style={{ position: 'absolute', top: -3, bottom: -3, left: `${meanNorm[meta.id]}%`, width: 2, background: INK }}></div>}
                    </div>
                    <div style={{ fontSize: 12.5, textAlign: 'right', color: '#55554f', fontFamily: "Archivo, 'Helvetica Neue', sans-serif" }}>
                      <b style={{ color: INK, fontSize: 13.5 }}>{fmt(r.v)}</b>
                      <span style={{ display: 'block', fontSize: 10.5, color: '#9b9b94', lineHeight: 1.2 }}>{meta.fuente}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function AutonomiaCard({ entidad, autonomia }) {
  const rec = autonomia.find(a => normName(a.entidad) === normName(entidad) || normName(entidad).startsWith(normName(a.entidad)));
  if (!rec) return null;
  const cats = [
    { k: 'designacion', label: 'Designación' },
    { k: 'remocion', label: 'Remoción' },
    { k: 'estabilidad', label: 'Estabilidad' },
  ];
  return (
    <div style={{ border: `2px solid ${INK}`, padding: '18px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <span style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 800, fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase' }}>Autonomía de la fiscalía</span>
        <span style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 800, fontSize: 22 }}>{fmt(rec.total_pct)}<span style={{ fontSize: 13, fontWeight: 600 }}>%</span></span>
      </div>
      <div style={{ fontSize: 12.5, color: '#76766f', marginBottom: 12 }}>Indicador de Autonomía 2026</div>
      <p style={{ fontSize: 12.5, color: '#55554f', lineHeight: 1.5, margin: '0 0 14px' }}>
        El análisis de autonomía busca evaluar el grado de independencia con que operan las fiscalías. Se compone de tres ejes fundamentales para medir la resistencia institucional: 1) el proceso de designación, 2) el proceso de remoción y 3) la estabilidad de facto en el cargo de la persona titular.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {cats.map(c => (
          <div key={c.k}>
            <div style={{ fontSize: 12.5, marginBottom: 5 }}>{c.label}</div>
            <div style={{ display: 'flex', gap: 4 }}>
              {[1, 2, 3].map(i => (
                <span key={i} style={{ width: 16, height: 16, background: i <= rec[c.k] ? BRAND_BLUE : '#edebe3', outline: '1px solid rgba(0,0,0,.18)', outlineOffset: -1 }}></span>
              ))}
            </div>
            <div style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 700, fontSize: 12, marginTop: 4, color: '#55554f' }}>{rec[c.k]}/3</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProfileSection({ data, selected, onSelect, palette, setTip }) {
  const { ranking, index, metadata, autonomia } = data;
  const row = ranking.find(d => d.entidad_std === selected) || ranking[0];
  const idx = ranking.findIndex(d => d.entidad_std === row.entidad_std);
  const prev = ranking[(idx - 1 + ranking.length) % ranking.length];
  const next = ranking[(idx + 1) % ranking.length];
  return (
    <div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 26 }}>
        <button className="navbtn" onClick={() => onSelect(prev.entidad_std)} title={`Anterior: ${prev.entidad_std}`}>←</button>
        <select className="stateselect" value={row.entidad_std} onChange={e => onSelect(e.target.value)}>
          {[...ranking].sort((a, b) => a.entidad_std.localeCompare(b.entidad_std)).map(d => (
            <option key={d.entidad_std} value={d.entidad_std}>{d.entidad_std}</option>
          ))}
        </select>
        <button className="navbtn" onClick={() => onSelect(next.entidad_std)} title={`Siguiente: ${next.entidad_std}`}>→</button>
        <span style={{ fontSize: 13, color: '#76766f' }}>ordenado por ranking</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(280px, 360px) 1fr', gap: 44, alignItems: 'start' }} className="profile-grid">
        <div style={{ display: 'grid', gap: 26 }}>
          <div>
            <div style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 900, fontSize: 'clamp(28px, 3.2vw, 40px)', lineHeight: 1.02, letterSpacing: '-.015em' }}>{row.entidad}</div>
            <div style={{ display: 'flex', gap: 28, marginTop: 18, alignItems: 'baseline' }}>
              <div>
                <div style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 900, fontSize: 56, lineHeight: 1, color: rankColor(row.ranking, 32, palette) === '#ffffbf' ? INK : rankColor(row.ranking, 32, palette), WebkitTextStroke: '1px rgba(0,0,0,.25)' }}>{row.ranking}º</div>
                <div className="statlabel">de 32 entidades</div>
              </div>
              <div>
                <div style={{ fontFamily: "Archivo, 'Helvetica Neue', sans-serif", fontWeight: 900, fontSize: 56, lineHeight: 1 }}>{fmt(row.iedf_total)}</div>
                <div className="statlabel">IEDF 2026 / 100</div>
              </div>
            </div>
          </div>
          <DimBars row={row} ranking={ranking} palette={palette}></DimBars>
          <AutonomiaCard entidad={row.entidad} autonomia={autonomia}></AutonomiaCard>
        </div>
        <IndicatorRows entidadStd={row.entidad_std} index={index} metadata={metadata} palette={palette} setTip={setTip}></IndicatorRows>
      </div>
    </div>
  );
}

Object.assign(window, { ProfileSection, normName });
