const OUTLINE: [number, number][] = [
  [-51.05, -19.9], [-50.2, -18.4], [-49.5, -18.3], [-47.9, -18.0], [-47.3, -16.0],
  [-46.4, -16.0], [-46.0, -14.2], [-44.5, -14.3], [-43.5, -14.8], [-42.9, -15.1],
  [-41.5, -14.8], [-40.9, -15.8], [-40.0, -16.0], [-39.9, -17.0], [-40.9, -17.9],
  [-41.5, -18.5], [-41.0, -19.5], [-41.7, -20.4], [-41.9, -21.2], [-42.5, -21.3],
  [-43.3, -22.0], [-44.2, -22.4], [-44.7, -22.4], [-46.0, -22.9], [-46.8, -22.4],
  [-47.5, -22.6], [-48.0, -22.0], [-49.0, -20.5], [-50.3, -20.0],
];

const CITIES: { name: string; lon: number; lat: number; anchor?: "start" | "end" }[] = [
  { name: "Uberlândia", lon: -48.28, lat: -18.92, anchor: "end" },
  { name: "Uberaba", lon: -47.93, lat: -19.75, anchor: "end" },
  { name: "Araxá", lon: -46.94, lat: -19.59 },
  { name: "Formiga", lon: -45.43, lat: -20.46, anchor: "end" },
  { name: "Sete Lagoas", lon: -44.25, lat: -19.46, anchor: "end" },
  { name: "Juiz de Fora", lon: -43.35, lat: -21.76 },
  { name: "Ipatinga", lon: -42.54, lat: -19.47 },
  { name: "Gov. Valadares", lon: -41.95, lat: -18.85 },
];

const W = 620;
const H = 470;
const LON0 = -51.6;
const LON1 = -39.5;
const LAT0 = -13.8;
const LAT1 = -23.4;

const px = (lon: number) => ((lon - LON0) / (LON1 - LON0)) * W;
const py = (lat: number) => ((lat - LAT0) / (LAT1 - LAT0)) * H;

const path =
  OUTLINE.map(([lon, lat], i) => `${i === 0 ? "M" : "L"}${px(lon).toFixed(1)},${py(lat).toFixed(1)}`).join(" ") + " Z";

const bh = { lon: -43.94, lat: -19.92 };

export function TrechoMap() {
  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      role="img"
      aria-label="Mapa de Minas Gerais com as cidades já percorridas pelo Minas Summit no Trecho"
      className="h-auto w-full"
    >
      <path
        d={path}
        className="fill-primary/10 stroke-primary/50"
        strokeWidth={2}
        strokeLinejoin="round"
      />
      {CITIES.map((c) => (
        <line
          key={`l-${c.name}`}
          x1={px(bh.lon)}
          y1={py(bh.lat)}
          x2={px(c.lon)}
          y2={py(c.lat)}
          className="stroke-primary/35"
          strokeWidth={1.2}
          strokeDasharray="4 5"
        />
      ))}

      <circle cx={px(bh.lon)} cy={py(bh.lat)} r={8} className="fill-accent" />
      <text
        x={px(bh.lon)}
        y={py(bh.lat) + 24}
        textAnchor="middle"
        className="fill-foreground text-[13px] font-semibold"
      >
        Belo Horizonte
      </text>

      {CITIES.map((c) => (
        <g key={c.name}>
          <circle cx={px(c.lon)} cy={py(c.lat)} r={5.5} className="fill-primary" />
          <text
            x={px(c.lon) + (c.anchor === "end" ? -10 : 10)}
            y={py(c.lat) + 4}
            textAnchor={c.anchor === "end" ? "end" : "start"}
            className="fill-muted-foreground text-[12px]"
          >
            {c.name}
          </text>
        </g>
      ))}
    </svg>
  );
}
