// ── REGION METADATA ───────────────────────────────────────────────────────────
const REGIONS = {
  norte: {
    label: "Norte",
    proposals: [],
    videos: [],
  },
  nordeste: {
    label: "Nordeste",
    proposals: [
      { icon: "🌾", title: "Agronegócio MATOPIBA", desc: "Sul do Maranhão como vetor de industrialização — milho, etanol, ração e química fina. O PIB per capita do sul já supera em muito o da capital São Luís." },
      { icon: "⛽", title: "Refinaria de Balsas", desc: "A refinaria da Impasa (MA) transforma milho em etanol exportado pelo Porto de Itaqui para os EUA, gerando empregos locais e reduzindo dependência do petróleo." },
      { icon: "🏭", title: "Polo Industrial no Interior", desc: "Atrair empresas que processem matéria-prima local no MATOPIBA, gerando empregos de qualidade e cidades desenvolvidas longe das capitais." },
      { icon: "💧", title: "Poço Comunitário — Ipanguaçu/RN", desc: "Poço na Comunidade Angélica entregue com doações privadas do MBL: painel solar, torre e caixa de 10 mil litros para 200+ moradores. Contraponto a R$ 1,2 bi gastos pelo Estado em poços abandonados." },
    ],
    videos: [
      { title: "Refinaria de Balsas — Etanol", href: "https://www.instagram.com/reel/DW9Aj8djVH5/" },
      { title: "MATOPIBA — Desenvolvimento Regional", href: "https://www.instagram.com/reel/DW64PJ8kR3C/" },
    ],
  },
  centroOeste: {
    label: "Centro-Oeste",
    proposals: [],
    videos: [],
  },
  sudeste: {
    label: "Sudeste",
    proposals: [
      { icon: "🏛️", title: "Estado da Guanabara", desc: "Separar a cidade do Rio de Janeiro do estado, transformando-a em cidade-estado autônoma com controle próprio sobre segurança, orçamento e desenvolvimento." },
      { icon: "🏗️", title: "Desfavelização — R$ 900 bi / 10 anos", desc: "Retomada territorial, regularização fundiária com títulos de propriedade, reurbanização e incentivos fiscais para eliminar favelas e integrar moradores à economia formal." },
      { icon: "💻", title: "Hub de Tecnologia e Turismo", desc: "Transformar o Rio em polo de empresas de tecnologia, mercado financeiro e turismo internacional, recuperando o papel histórico perdido após a mudança da capital." },
    ],
    videos: [
      { title: "Estado da Guanabara", href: "https://www.instagram.com/reel/DWcYEcaEfry/" },
      { title: "6 Medidas com Coronel Busnello", href: "https://www.instagram.com/reel/DWW4A1tEdSO/" },
    ],
  },
  sul: {
    label: "Sul",
    proposals: [
      { icon: "🏙️", title: "Retomada do Centro — Curitiba", desc: "Realocar albergues para fora do centro, encaminhar moradores de rua para assistência adequada e devolver o espaço público a cidadãos, comerciantes e turistas." },
      { icon: "🚫", title: "Tolerância Zero ao Tráfico — Curitiba", desc: "Traficantes identificados no Marco Zero encaminhados à polícia. Assistência social mal localizada — sopão a 100m do ponto de droga — será reestruturada para não financiar o tráfico." },
      { icon: "🏘️", title: "Desfavelização — Londrina", desc: "Enfrentar a favelização no Sul, que não é exclusividade do Rio nem do Nordeste. Desfavelizar Flores do Campo, dar dignidade e integrar imigrantes venezuelanos como cidadãos brasileiros." },
      { icon: "🛤️", title: "Ferrovias e Rodovias de Concreto", desc: "Malha ferroviária e duplicação de estradas para escoar a produção do 4º maior PIB do Brasil. Estradas de concreto que suportem o peso real dos caminhões, via parcerias privadas." },
      { icon: "⚖️", title: "Pacto Federativo Justo", desc: "Inverter a lógica que transfere recursos de estados produtivos para improdutivos. O Paraná produz em nível de excelência e merece infraestrutura à altura." },
    ],
    videos: [
      { title: "Paraná — Infraestrutura Logística", href: "https://www.instagram.com/reel/DVzO4-YkV9f/" },
      { title: "Londrina — Favela Flores do Campo", href: "https://www.instagram.com/reel/DV1Dyu2DZb6/" },
    ],
  },
};

// Region label positions — calibrated from real state starting coords
const LABEL_POS = {
  norte:       { x: 62000,  y: 52000  },
  nordeste:    { x: 163000, y: 68000  },
  centroOeste: { x: 96000,  y: 105000 },
  sudeste:     { x: 148000, y: 126000 },
  sul:         { x: 106000, y: 168000 },
};

// ── MAP SECTION ───────────────────────────────────────────────────────────────
const MapSection = () => {
  const [active, setActive] = React.useState(null);
  const [hovered, setHovered] = React.useState(null);
  const [panelVisible, setPanelVisible] = React.useState(false);
  const [tooltip, setTooltip] = React.useState({ visible: false, label: "", x: 0, y: 0 });
  const wrapRef = React.useRef(null);

  const handleClick = (regionId) => {
    setActive(regionId);
    setPanelVisible(false);
    setTimeout(() => setPanelVisible(true), 60);
  };

  const handleMouseMove = (e, regionId) => {
    const rect = wrapRef.current?.getBoundingClientRect();
    if (!rect) return;
    setTooltip({ visible: true, label: REGIONS[regionId].label, x: e.clientX - rect.left, y: e.clientY - rect.top });
  };

  const region = active ? REGIONS[active] : null;

  // Build per-region grouped paths from STATE_PATHS + REGION_STATES (loaded via brazil-paths.js)
  const regionPaths = React.useMemo(() => {
    if (typeof STATE_PATHS === 'undefined' || typeof REGION_STATES === 'undefined') return {};
    const result = {};
    for (const [regionId, states] of Object.entries(REGION_STATES)) {
      result[regionId] = states.map(s => STATE_PATHS[s]).filter(Boolean);
    }
    return result;
  }, []);

  return (
    <section id="propostas" className="map-section">
      <div className="section-header reveal">
        <span className="section-label">Plano de governo</span>
        <h2 className="section-title">PROPOSTAS POR <span className="yellow">REGIÃO</span></h2>
        <div className="divider-yellow" style={{ margin: "16px auto" }} />
        <p className="section-sub">
          Clique em cada região do Brasil para ver as propostas de Renan Santos para aquele território.
        </p>
      </div>

      <div className="map-layout reveal">
        {/* MAP */}
        <div className="map-svg-wrap" ref={wrapRef} style={{ position: "relative" }}>
          {tooltip.visible && (
            <div className="map-tooltip" style={{ left: tooltip.x, top: tooltip.y }} aria-hidden="true">
              {tooltip.label}
            </div>
          )}

          <svg
            viewBox="4000 7000 212000 192000"
            xmlns="http://www.w3.org/2000/svg"
            style={{ width: "100%", height: "auto" }}
            aria-label="Mapa do Brasil por regiões"
          >
            <defs>
              <filter id="region-glow" x="-30%" y="-30%" width="160%" height="160%">
                <feGaussianBlur stdDeviation="1200" result="blur" />
                <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
              </filter>
              <filter id="hover-glow" x="-20%" y="-20%" width="140%" height="140%">
                <feGaussianBlur stdDeviation="600" result="blur" />
                <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
              </filter>
            </defs>

            {/* Render each region as a group of state paths */}
            {Object.entries(regionPaths).map(([regionId, paths]) => {
              const isActive = active === regionId;
              const isHovered = hovered === regionId;
              const fill = isActive ? "#FFD100" : isHovered ? "rgba(255,209,0,0.25)" : "#1C1C1C";
              const stroke = "#FFD100";
              const strokeWidth = isActive ? 300 : 150;
              const strokeOpacity = isActive ? 1 : 0.35;

              return (
                <g
                  key={regionId}
                  onClick={() => handleClick(regionId)}
                  onMouseEnter={e => { setHovered(regionId); handleMouseMove(e, regionId); }}
                  onMouseMove={e => handleMouseMove(e, regionId)}
                  onMouseLeave={() => { setHovered(null); setTooltip(t => ({ ...t, visible: false })); }}
                  style={{ cursor: "pointer" }}
                  role="button"
                  aria-label={`Região ${REGIONS[regionId].label}`}
                  tabIndex={0}
                  onKeyDown={e => e.key === "Enter" && handleClick(regionId)}
                >
                  {/* Glow behind active region */}
                  {isActive && paths.map((d, i) => (
                    <path key={`glow-${i}`} d={d}
                      fill="rgba(255,209,0,0.2)" stroke="none"
                      filter="url(#region-glow)"
                      style={{ pointerEvents: "none" }}
                    />
                  ))}
                  {paths.map((d, i) => (
                    <path
                      key={i} d={d}
                      fill={fill}
                      stroke={stroke}
                      strokeWidth={strokeWidth}
                      strokeOpacity={strokeOpacity}
                      strokeLinejoin="round"
                      style={{
                        transition: "fill .22s ease",
                        filter: isHovered && !isActive ? "url(#hover-glow)" : "none",
                      }}
                    />
                  ))}
                </g>
              );
            })}

            {/* Region labels */}
            {Object.entries(LABEL_POS).map(([regionId, pos]) => {
              const isActive = active === regionId;
              return (
                <text
                  key={regionId}
                  x={pos.x} y={pos.y}
                  textAnchor="middle"
                  dominantBaseline="middle"
                  fill={isActive ? "#0A0A0A" : "rgba(255,255,255,0.6)"}
                  fontSize="6500"
                  fontFamily="'Barlow Condensed', sans-serif"
                  fontWeight="800"
                  letterSpacing="200"
                  style={{ pointerEvents: "none", userSelect: "none", transition: "fill .22s" }}
                >
                  {REGIONS[regionId]?.label.toUpperCase()}
                </text>
              );
            })}
          </svg>

          {/* Region chips */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 20 }}>
            {Object.entries(REGIONS).map(([id, r]) => (
              <button
                key={id}
                onClick={() => handleClick(id)}
                style={{
                  fontFamily: "'Barlow Condensed', sans-serif",
                  fontWeight: 700, fontSize: "0.75rem",
                  letterSpacing: "0.1em", textTransform: "uppercase",
                  padding: "6px 14px", borderRadius: 6, cursor: "pointer",
                  border: `1px solid ${active === id ? "#FFD100" : "rgba(255,255,255,0.12)"}`,
                  background: active === id ? "#FFD100" : "transparent",
                  color: active === id ? "#0A0A0A" : "rgba(255,255,255,0.5)",
                  transition: "all .18s",
                }}
              >
                {r.label}
              </button>
            ))}
          </div>
        </div>

        {/* PANEL */}
        <div className="map-panel" aria-live="polite">
          {!region ? (
            <div className="map-panel-empty">
              <svg className="arrow-anim" width="52" height="52" viewBox="0 0 52 52" fill="none" aria-hidden="true">
                <circle cx="26" cy="26" r="25" stroke="rgba(255,209,0,0.15)" strokeWidth="1.5" />
                <path d="M14,26 h24 M28,18 l10,8-10,8" stroke="#FFD100" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <p>Clique em uma<br />região do mapa</p>
            </div>
          ) : (
            <div style={{
              opacity: panelVisible ? 1 : 0,
              transform: panelVisible ? "translateY(0)" : "translateY(14px)",
              transition: "opacity .38s cubic-bezier(.16,1,.3,1), transform .38s cubic-bezier(.16,1,.3,1)",
            }}>
              <span className="section-label">Região selecionada</span>
              <h3 className="map-region-title">{region.label}</h3>
              <div className="divider-yellow" />
              {region.proposals.length === 0 ? (
                <p style={{
                  fontFamily: "'Barlow Condensed', sans-serif",
                  fontWeight: 600, fontSize: '1rem',
                  color: 'rgba(255,255,255,0.25)', fontStyle: 'italic',
                  padding: '8px 0 24px',
                }}>Em breve</p>
              ) : (
                <ul className="proposal-list">
                  {region.proposals.map((p, i) => (
                    <li key={i} className="proposal-item">
                      <div className="proposal-icon" aria-hidden="true">{p.icon}</div>
                      <div>
                        <div className="proposal-title">{p.title}</div>
                        <div className="proposal-desc">{p.desc}</div>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
              {region.videos.length > 0 && (
                <div className="video-section">
                  <div className="video-section-label">Vídeos do Renan sobre a região</div>
                  <div className="video-cards">
                    {region.videos.map((v, i) => (
                      <a key={i} href={v.href} className="video-card" target="_blank" rel="noopener noreferrer">
                        <div className="video-card-play" aria-hidden="true">
                          <svg width="11" height="13" viewBox="0 0 11 13" fill="#FFD100"><path d="M1 1l9 5.5-9 5.5V1z" /></svg>
                        </div>
                        <div className="video-card-body">
                          <div className="video-title">{v.title}</div>
                          <div style={{ fontFamily: "'Barlow Condensed', sans-serif", fontSize: '0.68rem', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.28)', marginTop: 3 }}>Instagram Reel</div>
                        </div>
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, opacity: 0.4 }}>
                          <path d="M2 12L12 2M12 2H6M12 2v6" stroke="rgba(255,255,255,0.7)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </a>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { MapSection });
