/* global React, window */
const { useEffect, useState, useRef } = React;

// Loads /assets/edomex_cobertura.svg, finds every group with [data-municipio],
// and lets the parent know which one is hovered/clicked.
function EdomexMap({ activeName, onSelect }) {
  const ref = useRef(null);
  const [svgText, setSvgText] = useState(null);

  useEffect(() => {
    fetch('assets/edomex_cobertura.svg')
      .then(r => r.text())
      .then(t => setSvgText(t))
      .catch(() => setSvgText('<svg/>'));
  }, []);

  useEffect(() => {
    if (!svgText || !ref.current) return;
    const host = ref.current;
    host.innerHTML = svgText;
    const svg = host.querySelector('svg');
    if (!svg) return;
    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
    svg.style.width = '100%';
    svg.style.height = '100%';
    svg.style.display = 'block';

    const groups = svg.querySelectorAll('[data-municipio]');
    const handlers = [];
    groups.forEach(g => {
      g.style.cursor = 'pointer';
      const enter = () => onSelect(g.getAttribute('data-municipio'));
      const click = () => onSelect(g.getAttribute('data-municipio'));
      g.addEventListener('mouseenter', enter);
      g.addEventListener('click', click);
      handlers.push([g, enter, click]);
    });
    return () => {
      handlers.forEach(([g, enter, click]) => {
        g.removeEventListener('mouseenter', enter);
        g.removeEventListener('click', click);
      });
    };
  }, [svgText, onSelect]);

  // Highlight the currently-active municipio (visually emphasized via class)
  useEffect(() => {
    if (!ref.current) return;
    const svg = ref.current.querySelector('svg');
    if (!svg) return;
    svg.querySelectorAll('[data-municipio]').forEach(g => {
      if (g.getAttribute('data-municipio') === activeName) {
        g.classList.add('mc-active');
      } else {
        g.classList.remove('mc-active');
      }
    });
  }, [activeName, svgText]);

  return <div ref={ref} className="edomex-svg-host" aria-label="Mapa de cobertura del Estado de México"/>;
}

window.EdomexMap = EdomexMap;
