/**
 * Patches FrameworkMap.astro with generated dot map SVG content.
 *
 * Each region gets:
 * 1. An invisible merged-outline <path> for hover hit detection
 * 2. A <g> of small <circle> dots for the visual stipple effect
 *
 * No labels, no Global icon on the map.
 *
 * Run after generate-map-paths.mjs.
 */

import { readFileSync, writeFileSync } from "fs";

const data = JSON.parse(readFileSync("scripts/map-dots.json", "utf8"));
const componentPath = "src/components/FrameworkMap.astro";
const component = readFileSync(componentPath, "utf8");

const regionOrder = [
  "north_america",
  "south_america",
  "europe",
  "africa",
  "middle_east",
  "asia_pacific",
];

const regionLabels = {
  north_america: "North America",
  south_america: "South America",
  europe: "Europe",
  africa: "Africa",
  middle_east: "Middle East",
  asia_pacific: "Asia-Pacific",
};

const r = data.dotRadius;
const d2 = r * 2;
let svgInner = "\n";

for (const regionId of regionOrder) {
  const dots = data.dots[regionId];
  const hitPath = data.hitPaths[regionId];
  const label = regionLabels[regionId];
  if (!dots || !hitPath) continue;

  // Compute centroid for transform-origin
  const cx = Math.round(dots.reduce((s, d) => s + d.x, 0) / dots.length);
  const cy = Math.round(dots.reduce((s, d) => s + d.y, 0) / dots.length);

  // Encode all dots as a single <path> using arc commands for each circle
  const dotPath = dots
    .map((pt) => `M${pt.x - r},${pt.y}a${r},${r} 0 1,0 ${d2},0a${r},${r} 0 1,0 -${d2},0`)
    .join("");

  svgInner += `    <!-- ${label} -->
    <g class="region-group cursor-pointer" data-map-region="${regionId}" role="button" tabindex="0" aria-label={\`${label} — \${regionCounts["${regionId}"] ?? 0} frameworks\`}>
      <path d="${hitPath}" fill="transparent" pointer-events="all" class="stroke-none"/>
      <path class="region-dots fill-accent/[.65]" style="transform-origin: ${cx}px ${cy}px" d="${dotPath}"/>
    </g>

`;
}

const fullSvg = `  <svg
    viewBox="${data.viewBox}"
    class="w-full h-auto"
    xmlns="http://www.w3.org/2000/svg"
  >
${svgInner}  </svg>`;

const svgPattern = /  <svg\n\s+viewBox="[^"]+"\n\s+class="w-full h-auto"\n\s+xmlns="[^"]+"\n\s+>[\s\S]*?<\/svg>/;

if (!svgPattern.test(component)) {
  console.error("Could not find SVG block in component.");
  process.exit(1);
}

const patched = component.replace(svgPattern, fullSvg);
writeFileSync(componentPath, patched);

const totalDots = regionOrder.reduce(
  (sum, id) => sum + (data.dots[id]?.length ?? 0),
  0,
);
console.log(`Patched FrameworkMap.astro: ${totalDots} dots, 6 regions (no Global icon, no labels)`);
console.log(`SVG size: ${(fullSvg.length / 1024).toFixed(1)} KB`);
