// Graph.jsx — visualização território ↔ cadeias produtivas
// Três abas:
//   • Sankey: fluxos município → cadeia (espessura ∝ produção)
//   • Matriz: heatmap município × cadeia (intensidade ∝ produção)
//   • Ranking: barras horizontais (top produtores por cadeia)
const { useState, useMemo } = React;

function fmtVal(n) {
  if (!n || n === 0) return '—';
  if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(1) + 'k';
  return Math.round(n).toLocaleString('pt-BR');
}

const CADEIAS_ORDER = ['acai', 'castanha', 'borracha', 'madeira', 'palmito', 'copaiba', 'sorva'];

// =============================================================
// SANKEY: fluxo município → cadeia produtiva
// Implementação SVG pura (sem d3-sankey)
// =============================================================
function SankeyTerritorial({ data, year, focusMun, onFocusMun }) {
  const meta = window.CADEIA_META || {};
  const [hoverLink, setHoverLink] = useState(null);
  const [hoverNode, setHoverNode] = useState(null);
  // Por padrão Sorva fica oculta (volume 30x maior ofusca demais)
  const [activeCadeias, setActiveCadeias] = useState(
    () => new Set(CADEIAS_ORDER.filter(c => c !== 'sorva'))
  );

  const toggleCadeia = (id) => {
    setActiveCadeias(prev => {
      const n = new Set(prev);
      if (n.has(id)) {
        if (n.size > 1) n.delete(id);
      } else n.add(id);
      return n;
    });
  };

  // Constrói links + totais a partir dos dados
  const layout = useMemo(() => {
    const W = 920, H = 600;
    const PAD_TOP = 12, PAD_BOT = 12;
    const innerH = H - PAD_TOP - PAD_BOT;
    const NODE_W = 14;
    const MARGIN_L = 130, MARGIN_R = 130;
    const NODE_PAD = 3;

    // 1. Constrói links válidos (valor > 0, cadeia ativa)
    const links = [];
    const muniTotals = {};
    const cadeiaTotals = {};

    data.municipios.forEach(m => {
      CADEIAS_ORDER.forEach(c => {
        if (!activeCadeias.has(c)) return;
        const v = Number(m.pevs[year]?.[c]) || 0;
        if (v > 0) {
          links.push({ source: m.nome, target: c, value: v, uf: m.uf, regiao: m.regiao });
          muniTotals[m.nome] = (muniTotals[m.nome] || 0) + v;
          cadeiaTotals[c] = (cadeiaTotals[c] || 0) + v;
        }
      });
    });

    // 2. Ordena nós: municípios pelo volume (desc), cadeias pela ordem fixa
    const muniKeys = Object.keys(muniTotals).sort((a, b) => muniTotals[b] - muniTotals[a]);
    const cadeiaKeys = CADEIAS_ORDER.filter(c => cadeiaTotals[c] > 0);

    // 3. Escala vertical para cada coluna
    const muniSum = Object.values(muniTotals).reduce((s, v) => s + v, 0) || 1;
    const cadeiaSum = Object.values(cadeiaTotals).reduce((s, v) => s + v, 0) || 1;
    const muniSpace = innerH - (muniKeys.length - 1) * NODE_PAD;
    const cadeiaSpace = innerH - (cadeiaKeys.length - 1) * NODE_PAD;
    const muniScale = muniSpace / muniSum;
    const cadeiaScale = cadeiaSpace / cadeiaSum;

    // 4. Posições dos nós
    const muniNodes = {};
    let cy = PAD_TOP;
    muniKeys.forEach(name => {
      const total = muniTotals[name];
      const h = total * muniScale;
      muniNodes[name] = { y: cy, h, total };
      cy += h + NODE_PAD;
    });

    const cadeiaNodes = {};
    cy = PAD_TOP;
    cadeiaKeys.forEach(c => {
      const total = cadeiaTotals[c];
      const h = total * cadeiaScale;
      cadeiaNodes[c] = { y: cy, h, total };
      cy += h + NODE_PAD;
    });

    // 5. Posiciona cada link dentro do nó (fila de empilhamento)
    const sortedLinks = [...links].sort((a, b) => {
      const ai = muniKeys.indexOf(a.source), bi = muniKeys.indexOf(b.source);
      if (ai !== bi) return ai - bi;
      return cadeiaKeys.indexOf(a.target) - cadeiaKeys.indexOf(b.target);
    });

    const srcUsed = {}, tgtUsed = {};
    sortedLinks.forEach(l => {
      const src = muniNodes[l.source], tgt = cadeiaNodes[l.target];
      if (!src || !tgt) return;
      const dyS = l.value * muniScale;
      const dyT = l.value * cadeiaScale;
      l._y0 = src.y + (srcUsed[l.source] || 0) + dyS / 2;
      l._y1 = tgt.y + (tgtUsed[l.target] || 0) + dyT / 2;
      l._h0 = dyS;
      l._h1 = dyT;
      srcUsed[l.source] = (srcUsed[l.source] || 0) + dyS;
      tgtUsed[l.target] = (tgtUsed[l.target] || 0) + dyT;
    });

    return { W, H, PAD_TOP, MARGIN_L, MARGIN_R, NODE_W,
             muniKeys, cadeiaKeys, muniNodes, cadeiaNodes, links: sortedLinks };
  }, [data, year, activeCadeias]);

  const { W, H, MARGIN_L, MARGIN_R, NODE_W,
          muniKeys, cadeiaKeys, muniNodes, cadeiaNodes, links } = layout;

  if (links.length === 0) {
    return (
      <div style={{ padding: 60, textAlign: 'center', color: 'var(--t4)', fontStyle: 'italic' }}>
        Sem dados de produção para {year}.
      </div>
    );
  }

  const x0 = MARGIN_L + NODE_W;
  const x1 = W - MARGIN_R - NODE_W;
  const xCtrl = (x0 + x1) / 2;

  // Define o que está em destaque (focusMun, hover, ou nada)
  const isLinkActive = (l) => {
    if (focusMun && l.source !== focusMun) return false;
    if (hoverLink && hoverLink !== l) return false;
    if (hoverNode?.kind === 'muni' && l.source !== hoverNode.id) return false;
    if (hoverNode?.kind === 'cadeia' && l.target !== hoverNode.id) return false;
    return true;
  };

  const dimLink = (l) => {
    if (!focusMun && !hoverLink && !hoverNode) return false;
    return !isLinkActive(l);
  };

  return (
    <div style={{ padding: 16, height: '100%', overflow: 'auto', position: 'relative' }}>
      {/* Toggles de cadeia */}
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14,
        paddingBottom: 12, borderBottom: '1px solid var(--border)',
        alignItems: 'center'
      }}>
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--t4)',
          textTransform: 'uppercase', letterSpacing: '0.08em', marginRight: 6
        }}>cadeias visíveis:</span>
        {CADEIAS_ORDER.map(c => {
          const m = meta[c] || {};
          const on = activeCadeias.has(c);
          return (
            <button key={c}
              className={'cadeia-toggle ' + (on ? 'on' : '')}
              onClick={() => toggleCadeia(c)}
              title={on ? 'Ocultar' : 'Mostrar'}
              style={{
                borderColor: on ? m.cor : 'var(--border)',
                color: on ? 'var(--t1)' : 'var(--t4)',
              }}
            >
              <span className="ct-dot" style={{ background: on ? m.cor : 'var(--border)' }}/>
              {m.rotulo}
            </button>
          );
        })}
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} width="100%"
        preserveAspectRatio="xMidYMid meet"
        style={{ display: 'block', maxWidth: '100%' }}>

        {/* Links (curvas Bezier) */}
        {links.map((l, i) => {
          const dim = dimLink(l);
          const path = `M${x0},${l._y0}` +
                       `C${xCtrl},${l._y0} ${xCtrl},${l._y1} ${x1},${l._y1}`;
          return (
            <path key={i} d={path}
              fill="none"
              stroke={meta[l.target]?.cor || 'var(--g2)'}
              strokeWidth={Math.max(0.5, Math.min(l._h0, l._h1))}
              strokeOpacity={dim ? 0.05 : (isLinkActive(l) && (focusMun || hoverLink || hoverNode) ? 0.55 : 0.28)}
              style={{ cursor: 'pointer', transition: 'stroke-opacity 0.15s' }}
              onMouseEnter={() => setHoverLink(l)}
              onMouseLeave={() => setHoverLink(null)}
              onClick={() => onFocusMun(l.source === focusMun ? null : l.source)}
            />
          );
        })}

        {/* Nós municípios (esquerda) */}
        {muniKeys.map(name => {
          const n = muniNodes[name];
          const isFocus = name === focusMun;
          const isHover = hoverNode?.kind === 'muni' && hoverNode?.id === name;
          const muni = data.municipios.find(m => m.nome === name);
          const reg = data.regioes.find(r => r.id === muni?.regiao);
          return (
            <g key={name}
              onMouseEnter={() => setHoverNode({ kind: 'muni', id: name })}
              onMouseLeave={() => setHoverNode(null)}
              onClick={() => onFocusMun(isFocus ? null : name)}
              style={{ cursor: 'pointer' }}
            >
              <rect
                x={MARGIN_L} y={n.y}
                width={NODE_W} height={Math.max(1, n.h)}
                fill={isFocus ? '#CD5D1C' : (reg?.cor || 'var(--g0)')}
                stroke={isFocus ? '#fff' : (isHover ? 'var(--g0)' : 'transparent')}
                strokeWidth={isFocus ? 1.5 : (isHover ? 1 : 0)}
              />
              {/* Só renderiza label se o nó for grande o suficiente OU em hover/focus */}
              {(n.h >= 8 || isFocus || isHover) && (
                <text
                  x={MARGIN_L - 6} y={n.y + n.h / 2 + 4}
                  textAnchor="end"
                  fontSize={n.h > 12 ? 11 : 10}
                  fontFamily="var(--font-body)"
                  fontWeight={isFocus || isHover ? 700 : 500}
                  fill={isFocus ? '#CD5D1C' : (isHover ? 'var(--g0)' : 'var(--t2)')}
                >
                  {name.length > 18 ? name.slice(0, 17) + '…' : name}
                </text>
              )}
            </g>
          );
        })}

        {/* Nós cadeias (direita) */}
        {cadeiaKeys.map(c => {
          const n = cadeiaNodes[c];
          const m = meta[c] || {};
          const isHover = hoverNode?.kind === 'cadeia' && hoverNode?.id === c;
          return (
            <g key={c}
              onMouseEnter={() => setHoverNode({ kind: 'cadeia', id: c })}
              onMouseLeave={() => setHoverNode(null)}
              style={{ cursor: 'pointer' }}
            >
              <rect
                x={W - MARGIN_R - NODE_W} y={n.y}
                width={NODE_W} height={Math.max(1, n.h)}
                fill={m.cor || 'var(--g2)'}
                stroke={isHover ? '#fff' : 'transparent'}
                strokeWidth={isHover ? 1.5 : 0}
              />
              <text
                x={W - MARGIN_R + 6} y={n.y + n.h / 2 + 4}
                fontSize={n.h > 9 ? 12 : 10}
                fontFamily="var(--font-display)"
                fontWeight={700}
                fill={isHover ? m.cor : 'var(--t1)'}
              >
                {m.rotulo || c}
              </text>
              <text
                x={W - MARGIN_R + 6} y={n.y + n.h / 2 + 18}
                fontSize={9}
                fontFamily="var(--font-mono)"
                fill="var(--t4)"
              >
                {fmtVal(n.total)} {m.unidade}
              </text>
            </g>
          );
        })}
      </svg>

      {/* Tooltip */}
      {hoverLink && (
        <div style={{
          position: 'absolute', top: 12, right: 16,
          background: 'var(--white)', border: '1px solid var(--border)',
          padding: '10px 14px', borderRadius: 6, boxShadow: 'var(--shadow-md)',
          fontSize: 12, lineHeight: 1.4, pointerEvents: 'none', zIndex: 10,
          maxWidth: 240,
        }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--g0)' }}>
            {hoverLink.source}
          </div>
          <div style={{
            color: 'var(--t2)', marginTop: 3,
            display: 'flex', alignItems: 'center', gap: 5
          }}>
            <span>→</span>
            <span style={{ color: meta[hoverLink.target]?.cor, fontWeight: 600 }}>
              {meta[hoverLink.target]?.rotulo}
            </span>
          </div>
          <div style={{ color: 'var(--t1)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>
            <b>{fmtVal(hoverLink.value)}</b> {meta[hoverLink.target]?.unidade}
          </div>
        </div>
      )}
    </div>
  );
}

// =============================================================
// MATRIZ: heatmap município × cadeia
// =============================================================
function MatrizTerritorial({ data, year, focusMun, onFocusMun }) {
  const meta = window.CADEIA_META || {};
  const [hover, setHover] = useState(null);

  const municipios = useMemo(() => {
    return [...data.municipios]
      .map(m => {
        const yr = m.pevs[year] || {};
        const total = CADEIAS_ORDER.reduce((s, k) => s + (Number(yr[k]) || 0), 0);
        return { ...m, _total: total, _yr: yr };
      })
      .sort((a, b) => b._total - a._total);
  }, [data, year]);

  const maxByCadeia = useMemo(() => {
    const out = {};
    CADEIAS_ORDER.forEach(k => {
      out[k] = Math.max(...municipios.map(m => Number(m._yr[k]) || 0), 1);
    });
    return out;
  }, [municipios]);

  const ROW_H = 26, COL_W = 60, LABEL_W = 130, HEADER_H = 60;
  const W = LABEL_W + COL_W * CADEIAS_ORDER.length + 20;
  const H = HEADER_H + ROW_H * municipios.length + 10;

  const cellOpacity = (v, max) => {
    if (!v) return 0;
    const t = Math.log10(v + 1) / Math.log10(max + 1);
    return Math.max(0.08, Math.min(1, t));
  };

  return (
    <div style={{ padding: 16, height: '100%', overflow: 'auto' }}>
      <div style={{ overflowX: 'auto', width: '100%' }}>
      <svg viewBox={`0 0 ${W} ${H}`}
        width={W} height={H}
        preserveAspectRatio="xMidYMid meet"
        style={{ display: 'block', maxWidth: '100%', height: 'auto' }}>
        {CADEIAS_ORDER.map((k, i) => {
          const cx = LABEL_W + i * COL_W + COL_W / 2;
          const c = meta[k] || {};
          return (
            <g key={k}>
              <rect x={LABEL_W + i * COL_W} y={0} width={COL_W} height={HEADER_H}
                fill={hover?.cadeia === k ? c.cor : 'transparent'}
                opacity={hover?.cadeia === k ? 0.08 : 1} />
              <text x={cx} y={HEADER_H - 18} textAnchor="middle" fontSize={11}
                fontFamily="var(--font-display)"
                fontWeight={hover?.cadeia === k ? 700 : 600}
                fill={hover?.cadeia === k ? c.cor : 'var(--g0)'}>
                {c.rotulo || k}
              </text>
              <text x={cx} y={HEADER_H - 4} textAnchor="middle" fontSize={9}
                fontFamily="var(--font-mono)" fill="var(--t4)">
                {c.unidade || ''}
              </text>
            </g>
          );
        })}
        {municipios.map((m, ri) => {
          const y = HEADER_H + ri * ROW_H;
          const isFocused = m.nome === focusMun;
          const isHovered = hover?.muni === m.nome;
          return (
            <g key={m.nome}>
              <rect x={0} y={y} width={W} height={ROW_H}
                fill={isFocused ? 'var(--orange-light)' :
                      isHovered ? 'var(--bg2)' :
                      ri % 2 ? 'var(--bg2)' : 'var(--white)'}
                opacity={isFocused ? 1 : 0.6} />
              <text x={LABEL_W - 8} y={y + ROW_H / 2 + 4} textAnchor="end"
                fontSize={11}
                fontWeight={isFocused || isHovered ? 600 : 400}
                fill={isFocused ? 'var(--orange)' : isHovered ? 'var(--g0)' : 'var(--t2)'}
                fontFamily="var(--font-body)" style={{ cursor: 'pointer' }}
                onClick={() => onFocusMun(isFocused ? null : m.nome)}
                onMouseEnter={() => setHover({ muni: m.nome })}
                onMouseLeave={() => setHover(null)}>
                {m.nome.length > 16 ? m.nome.slice(0, 15) + '…' : m.nome}
              </text>
              <rect x={6} y={y + ROW_H / 2 - 7} width={22} height={14} rx={2}
                fill="var(--bg2)" stroke="var(--border)" strokeWidth={0.5} />
              <text x={17} y={y + ROW_H / 2 + 4} textAnchor="middle" fontSize={9}
                fontFamily="var(--font-mono)" fontWeight={600} fill="var(--t3)">
                {m.uf}
              </text>
              {CADEIAS_ORDER.map((k, ci) => {
                const v = Number(m._yr[k]) || 0;
                const max = maxByCadeia[k];
                const op = cellOpacity(v, max);
                const c = meta[k] || {};
                const cx = LABEL_W + ci * COL_W;
                return (
                  <g key={k}
                    onMouseEnter={() => setHover({ muni: m.nome, cadeia: k, valor: v })}
                    onMouseLeave={() => setHover(null)}
                    onClick={() => onFocusMun(isFocused ? null : m.nome)}
                    style={{ cursor: 'pointer' }}>
                    <rect x={cx + 4} y={y + 3} width={COL_W - 8} height={ROW_H - 6} rx={2}
                      fill={c.cor || 'var(--g2)'} opacity={op} />
                    {v > 0 && (
                      <text x={cx + COL_W / 2} y={y + ROW_H / 2 + 3}
                        textAnchor="middle" fontSize={9}
                        fontFamily="var(--font-mono)"
                        fontWeight={op > 0.5 ? 600 : 400}
                        fill={op > 0.45 ? '#fff' : 'var(--t3)'}
                        style={{ pointerEvents: 'none' }}>
                        {fmtVal(v)}
                      </text>
                    )}
                  </g>
                );
              })}
            </g>
          );
        })}
      </svg>
      </div>
      {hover?.muni && hover?.cadeia && (
        <div style={{
          position: 'absolute', top: 16, right: 16,
          background: 'var(--white)', border: '1px solid var(--border)',
          padding: '10px 14px', borderRadius: 6, boxShadow: 'var(--shadow-md)',
          fontSize: 12, lineHeight: 1.4, pointerEvents: 'none', zIndex: 10,
        }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--g0)' }}>
            {hover.muni}
          </div>
          <div style={{ color: 'var(--t3)', marginTop: 2 }}>
            {meta[hover.cadeia]?.rotulo}: <b style={{ color: 'var(--t1)' }}>{fmtVal(hover.valor)}</b> {meta[hover.cadeia]?.unidade}
          </div>
        </div>
      )}
    </div>
  );
}

// =============================================================
// RANKING: barras horizontais
// =============================================================
function GrafoRanking({ data, year, focusMun, onFocusMun }) {
  const meta = window.CADEIA_META || {};
  const chains = Object.entries(meta);
  const [sel, setSel] = useState(chains[0]?.[0] || 'acai');

  const rows = useMemo(() => {
    return [...data.municipios]
      .map(m => ({
        nome: m.nome, uf: m.uf, regiao: m.regiao,
        value: Number(m.pevs[year]?.[sel]) || 0,
      }))
      .filter(d => d.value > 0)
      .sort((a, b) => b.value - a.value)
      .slice(0, 12);
  }, [data, year, sel]);

  const maxV = Math.max(...rows.map(d => d.value), 1);
  const chain = meta[sel] || {};

  return (
    <div style={{ padding: '20px 24px', overflowY: 'auto', height: '100%' }}>
      <div style={{
        marginBottom: 14, display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', gap: 12
      }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 700, color: 'var(--g0)' }}>
          Ranking de produção · {year}
        </div>
        <select className="select" value={sel} onChange={e => setSel(e.target.value)}
          style={{ fontSize: 11, padding: '4px 8px' }}>
          {chains.map(([id, c]) => (
            <option key={id} value={id}>{c.rotulo} ({c.unidade})</option>
          ))}
        </select>
      </div>
      {rows.length === 0
        ? <div style={{ fontSize: 12, color: 'var(--t4)', fontStyle: 'italic', textAlign: 'center', paddingTop: 32 }}>
            Sem produção registrada para {chain.rotulo} em {year}.
          </div>
        : <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {rows.map((d, i) => {
              const isFocus = d.nome === focusMun;
              return (
                <div key={d.nome}
                  onClick={() => onFocusMun(isFocus ? null : d.nome)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    cursor: 'pointer', padding: '2px 4px', borderRadius: 3,
                    background: isFocus ? 'var(--orange-light)' : 'transparent',
                  }}>
                  <div style={{
                    fontFamily: 'var(--font-mono)', fontSize: 9, fontWeight: 600,
                    color: i < 3 ? '#fff' : 'var(--t4)',
                    background: i < 3 ? (chain.cor || 'var(--g2)') : 'var(--bg2)',
                    border: '1px solid ' + (i < 3 ? (chain.cor || 'var(--g2)') : 'var(--border)'),
                    borderRadius: 3, padding: '2px 5px', minWidth: 22, textAlign: 'center',
                  }}>{i + 1}</div>
                  <div style={{
                    fontSize: 11, color: isFocus ? 'var(--orange)' : 'var(--t2)',
                    fontWeight: isFocus ? 600 : 400,
                    flex: '0 0 110px', overflow: 'hidden',
                    textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                  }}>{d.nome}</div>
                  <div style={{
                    flex: 1, background: 'var(--bg2)', borderRadius: 3,
                    height: 12, position: 'relative', border: '1px solid var(--border)'
                  }}>
                    <div style={{
                      position: 'absolute', left: 0, top: 0, bottom: 0,
                      width: (d.value / maxV * 100) + '%',
                      background: chain.cor || 'var(--g2)',
                      borderRadius: 3,
                      opacity: Math.max(0.45, 1 - i * 0.06),
                    }}/>
                  </div>
                  <div style={{
                    fontFamily: 'var(--font-mono)', fontSize: 10,
                    color: 'var(--t3)', minWidth: 52, textAlign: 'right'
                  }}>{fmtVal(d.value)}</div>
                </div>
              );
            })}
          </div>
      }
    </div>
  );
}

// =============================================================
// CONTAINER PRINCIPAL — abas Sankey / Matriz / Ranking
// =============================================================
function GrafoTerritorial({ data, year, focusMun, onFocusMun }) {
  const [view, setView] = useState('sankey'); // 'sankey'|'matriz'|'ranking'

  const desc = {
    sankey: 'fluxos município → cadeia · espessura ∝ produção',
    matriz: 'intensidade = produção · clique para abrir município',
    ranking: 'top 12 produtores por cadeia',
  };

  return (
    <div className="graph-shell" style={{ position: 'relative' }}>
      <div className="graph-controls">
        <div className="graph-tabs">
          <button className={'g-tab ' + (view === 'sankey' ? 'on' : '')}
            onClick={() => setView('sankey')}>
            ⥯ Sankey
          </button>
          <button className={'g-tab ' + (view === 'matriz' ? 'on' : '')}
            onClick={() => setView('matriz')}>
            ▦ Matriz
          </button>
          <button className={'g-tab ' + (view === 'ranking' ? 'on' : '')}
            onClick={() => setView('ranking')}>
            ▬ Ranking
          </button>
        </div>
        <div style={{
          marginLeft: 'auto', fontSize: 11, color: 'var(--t4)',
          fontFamily: 'var(--font-mono)'
        }}>
          {desc[view]}
        </div>
      </div>
      <div style={{ background: 'var(--white)', minHeight: 620, position: 'relative' }}>
        {view === 'sankey' && (
          <SankeyTerritorial data={data} year={year}
            focusMun={focusMun} onFocusMun={onFocusMun} />
        )}
        {view === 'matriz' && (
          <MatrizTerritorial data={data} year={year}
            focusMun={focusMun} onFocusMun={onFocusMun} />
        )}
        {view === 'ranking' && (
          <GrafoRanking data={data} year={year}
            focusMun={focusMun} onFocusMun={onFocusMun} />
        )}
      </div>
    </div>
  );
}

window.GrafoTerritorial = GrafoTerritorial;
