// SVG US Map — renders states or counties from TopoJSON using d3-geo + topojson-client.
// Albers USA projection. Used by Tab 03 (county choropleth), Tab 05 (name diffusion), Tab 06 (workforce).

function USMapSVG({ width = 960, height = 600, level = 'states', colorFn, strokeColor = '#2A2218', bgFill = 'rgba(30,24,16,0.3)', onHover, onClick }) {
  const [geo, setGeo] = React.useState(null);
  const [hoverFips, setHoverFips] = React.useState(null);

  // Load TopoJSON
  React.useEffect(() => {
    const file = level === 'counties' ? 'data/us-counties-topo.json' : 'data/us-states-topo.json';
    fetch(file)
      .then(r => r.json())
      .then(topo => {
        const objectKey = level === 'counties' ? 'counties' : 'states';
        const features = topojson.feature(topo, topo.objects[objectKey]).features;
        // Also extract state mesh for overlaying borders on county maps
        const stateMesh = level === 'counties' && topo.objects.states
          ? topojson.mesh(topo, topo.objects.states, (a, b) => a !== b)
          : null;
        setGeo({ features, stateMesh });
      })
      .catch(e => console.error('Map load error:', e));
  }, [level]);

  if (!geo) {
    return (
      <div style={{ width, height, display: 'flex', alignItems: 'center', justifyContent: 'center', background: bgFill, border: '1px solid #2A2218' }}>
        <span className="mono" style={{ color: '#5A4E3A', fontSize: 11 }}>Loading map{'…'}</span>
      </div>
    );
  }

  // Albers USA projection
  const projection = d3.geoAlbersUsa().fitSize([width - 20, height - 20], { type: 'FeatureCollection', features: geo.features });
  const path = d3.geoPath(projection);

  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <rect width={width} height={height} fill={bgFill} />
      {/* Features */}
      {geo.features.map((f, i) => {
        const d = path(f);
        if (!d) return null;
        const fips = f.id || f.properties?.GEOID || String(i);
        const fill = colorFn ? colorFn(fips, f.properties) : '#1E1810';
        const isHovered = hoverFips === fips;
        return (
          <path key={fips} d={d}
            fill={fill}
            stroke={isHovered ? '#C9A84C' : strokeColor}
            strokeWidth={isHovered ? 1.2 : (level === 'counties' ? 0.15 : 0.5)}
            opacity={isHovered ? 1 : 0.9}
            onMouseEnter={() => { setHoverFips(fips); onHover && onHover(fips, f.properties); }}
            onMouseLeave={() => { setHoverFips(null); onHover && onHover(null, null); }}
            onClick={() => onClick && onClick(fips, f.properties)}
            style={{ cursor: onClick ? 'pointer' : 'default', transition: 'fill 150ms' }}
          />
        );
      })}
      {/* State borders overlaid on county maps */}
      {geo.stateMesh && (
        <path d={path(geo.stateMesh)} fill="none" stroke="#5A4E3A" strokeWidth="0.6" />
      )}
    </svg>
  );
}

// State FIPS → name mapping
const STATE_FIPS = {
  '01':'AL','02':'AK','04':'AZ','05':'AR','06':'CA','08':'CO','09':'CT','10':'DE',
  '11':'DC','12':'FL','13':'GA','15':'HI','16':'ID','17':'IL','18':'IN','19':'IA',
  '20':'KS','21':'KY','22':'LA','23':'ME','24':'MD','25':'MA','26':'MI','27':'MN',
  '28':'MS','29':'MO','30':'MT','31':'NE','32':'NV','33':'NH','34':'NJ','35':'NM',
  '36':'NY','37':'NC','38':'ND','39':'OH','40':'OK','41':'OR','42':'PA','44':'RI',
  '45':'SC','46':'SD','47':'TN','48':'TX','49':'UT','50':'VT','51':'VA','53':'WA',
  '54':'WV','55':'WI','56':'WY',
};

Object.assign(window, { USMapSVG, STATE_FIPS });
