/* ─── Colorado District Map (SVG-based) ──────────────────────────── */
/* Renders CO_DISTRICTS_GEO (GeoJSON) as an SVG choropleth map.       */
/* District fill = proficiency color scale. Click → navigate.         */

function ColoradoDistrictMap({ year, subject, onDistrictClick }) {
  const data = window.CMAS;
  const geo = window.CO_DISTRICTS_GEO;
  const svgRef = useRef(null);
  const [tooltip, setTooltip] = useState(null);
  const [hoveredCode, setHoveredCode] = useState(null);

  if (!geo || !geo.features) {
    return (
      <div style={{ textAlign: "center", padding: 40, color: "var(--text3)" }}>
        Map data not available.
      </div>
    );
  }

  // Build district proficiency lookup: cdeCode → pct
  const distPctMap = useMemo(() => {
    const m = {};
    data.districts.forEach(d => {
      const pct = d.years?.[year]?.[subject]?.pct;
      m[d.code] = pct;
    });
    return m;
  }, [data, year, subject]);

  // ── Projection: simple Mercator-like for Colorado ──────────────
  // Colorado bounds roughly: lon [-109.05, -102.04], lat [36.99, 41.00]
  const bounds = useMemo(() => {
    let minLon = Infinity, maxLon = -Infinity, minLat = Infinity, maxLat = -Infinity;
    geo.features.forEach(f => {
      const coords = f.geometry.coordinates;
      const flatten = (c) => {
        if (typeof c[0] === "number") {
          if (c[0] < minLon) minLon = c[0];
          if (c[0] > maxLon) maxLon = c[0];
          if (c[1] < minLat) minLat = c[1];
          if (c[1] > maxLat) maxLat = c[1];
        } else {
          c.forEach(flatten);
        }
      };
      flatten(coords);
    });
    return { minLon, maxLon, minLat, maxLat };
  }, [geo]);

  const svgWidth = 800;
  const svgHeight = 500;
  const padding = 20;

  const project = useCallback((lon, lat) => {
    const x = padding + ((lon - bounds.minLon) / (bounds.maxLon - bounds.minLon)) * (svgWidth - 2 * padding);
    const y = padding + ((bounds.maxLat - lat) / (bounds.maxLat - bounds.minLat)) * (svgHeight - 2 * padding);
    return [x, y];
  }, [bounds]);

  // ── Color scale: 0% → red, ~35% → yellow, ~70%+ → teal/green ──
  const getColor = useCallback((pct) => {
    if (pct == null) return "#2a3545";
    const t = Math.min(1, Math.max(0, pct / 80));
    // Interpolate: red(0) → amber(0.4) → teal(0.8) → green(1)
    if (t < 0.35) {
      const p = t / 0.35;
      const r = Math.round(220 - p * 40);
      const g = Math.round(50 + p * 120);
      const b = Math.round(50 + p * 10);
      return `rgb(${r},${g},${b})`;
    } else if (t < 0.65) {
      const p = (t - 0.35) / 0.3;
      const r = Math.round(180 - p * 100);
      const g = Math.round(170 + p * 30);
      const b = Math.round(60 + p * 60);
      return `rgb(${r},${g},${b})`;
    } else {
      const p = (t - 0.65) / 0.35;
      const r = Math.round(80 - p * 40);
      const g = Math.round(200 + p * 30);
      const b = Math.round(120 + p * 30);
      return `rgb(${r},${g},${b})`;
    }
  }, []);

  // ── Convert polygon rings to SVG path d string ─────────────────
  const ringToPath = useCallback((ring) => {
    return ring.map((coord, i) => {
      const [x, y] = project(coord[0], coord[1]);
      return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
    }).join("") + "Z";
  }, [project]);

  const featureToPath = useCallback((feature) => {
    const { type, coordinates } = feature.geometry;
    if (type === "Polygon") {
      return coordinates.map(ringToPath).join(" ");
    } else if (type === "MultiPolygon") {
      return coordinates.map(poly => poly.map(ringToPath).join(" ")).join(" ");
    }
    return "";
  }, [ringToPath]);

  // ── Tooltip handler ────────────────────────────────────────────
  const handleMouseMove = useCallback((e, feature) => {
    const code = feature.properties.c;
    const pct = distPctMap[code];
    const rect = svgRef.current?.getBoundingClientRect();
    if (!rect) return;
    setTooltip({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top - 12,
      name: feature.properties.n,
      pct: pct,
      code: code,
    });
    setHoveredCode(code);
  }, [distPctMap]);

  const handleMouseLeave = useCallback(() => {
    setTooltip(null);
    setHoveredCode(null);
  }, []);

  // ── Legend stops ───────────────────────────────────────────────
  const legendStops = [0, 10, 20, 30, 40, 50, 60, 70, 80];

  return (
    <div style={{ position: "relative" }}>
      <svg
        ref={svgRef}
        viewBox={`0 0 ${svgWidth} ${svgHeight}`}
        style={{ width: "100%", height: "auto", display: "block" }}
      >
        {/* ── District polygons ── */}
        {geo.features.map((feature, i) => {
          const code = feature.properties.c;
          const pct = distPctMap[code];
          const fill = getColor(pct);
          const isHovered = hoveredCode === code;
          return (
            <path
              key={code || i}
              d={featureToPath(feature)}
              fill={fill}
              stroke={isHovered ? "#fff" : "rgba(15,20,25,0.7)"}
              strokeWidth={isHovered ? 1.5 : 0.5}
              style={{ cursor: "pointer", transition: "fill 0.2s, stroke-width 0.15s" }}
              onMouseMove={(e) => handleMouseMove(e, feature)}
              onMouseLeave={handleMouseLeave}
              onClick={() => onDistrictClick && onDistrictClick(code)}
            />
          );
        })}
      </svg>

      {/* ── Tooltip ── */}
      {tooltip && (
        <div style={{
          position: "absolute",
          left: tooltip.x,
          top: tooltip.y,
          transform: "translate(-50%, -100%)",
          background: "var(--bg3)",
          border: "1px solid var(--border)",
          borderRadius: 8,
          padding: "8px 12px",
          fontSize: 12,
          pointerEvents: "none",
          zIndex: 10,
          whiteSpace: "nowrap",
          boxShadow: "0 4px 20px rgba(0,0,0,0.4)",
        }}>
          <div style={{ fontWeight: 600, color: "var(--text1)", marginBottom: 2 }}>{tooltip.name}</div>
          <div style={{ color: "var(--text3)" }}>
            {subject}: {tooltip.pct != null ? `${tooltip.pct.toFixed(1)}% met/exceeded` : "No data"}
          </div>
        </div>
      )}

      {/* ── Legend ── */}
      <div style={{
        display: "flex", alignItems: "center", gap: 4,
        justifyContent: "center", marginTop: 8, fontSize: 10, color: "var(--text3)",
      }}>
        <span>0%</span>
        <div style={{
          width: 200, height: 10, borderRadius: 5, marginLeft: 4, marginRight: 4,
          background: `linear-gradient(to right, ${legendStops.map(v => getColor(v)).join(", ")})`,
        }} />
        <span>80%+</span>
        <span style={{ marginLeft: 12, color: "var(--text3)" }}>■</span>
        <span style={{ color: "var(--text3)" }}> No data</span>
      </div>
    </div>
  );
}

/* ─── Keep legacy placeholder name for backward compat ──────────── */
function ColoradoMapPlaceholder(props) {
  return <ColoradoDistrictMap {...props} />;
}
