import { useEffect, useRef, useState } from "react";

interface Point {
  x: number;
  y: number;
}

interface DamageOverlay {
  zoneId: number;
  points: Point[];
}

interface Props {
  damagedZoneIds: number[];
  /** Координаты точек повреждений в композитной SVG-системе (827×1209). */
  damages?: DamageOverlay[];
  onZoneClick?: (zoneId: number) => void;
}

const SVG_NS = "http://www.w3.org/2000/svg";
const POINT_RADIUS = 9;

/** Композитная SVG-схема экстерьера машины с подсветкой зон + точками
 *  повреждений. Координаты точек в системе 827×1209 (та же что у vendor). */
export function TtDamageMap({ damagedZoneIds, damages, onZoneClick }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [svgText, setSvgText] = useState<string | null>(null);
  const damagedSet = new Set(damagedZoneIds.map(String));

  useEffect(() => {
    let cancelled = false;
    fetch("/scheme/exterior.svg")
      .then((r) => r.text())
      .then((text) => {
        if (cancelled) return;
        let mut = text;
        mut = mut.replace(/<script[\s\S]*?<\/script>/gi, "");
        mut = mut.replace(
          /(<svg\b[^>]*?)\s(?:width|height)\s*=\s*"[^"]*"/gi,
          "$1"
        );
        mut = mut.replace(
          /<svg\b/i,
          `<svg width="100%" height="100%" preserveAspectRatio="xMidYMid meet"`
        );
        setSvgText(mut);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // Tinting + cursors
  useEffect(() => {
    if (!svgText) return;
    const el = containerRef.current;
    if (!el) return;
    const svg = el.querySelector("svg") as SVGSVGElement | null;
    if (!svg) return;

    svg.querySelectorAll("path[class]").forEach((p) => {
      const cls = p.getAttribute("class") ?? "";
      if (damagedSet.has(cls)) {
        p.setAttribute("fill", "rgba(239, 68, 68, 0.35)");
        p.setAttribute("stroke", "rgb(239, 68, 68)");
        p.setAttribute("stroke-width", "2");
        (p as SVGElement).style.cursor = onZoneClick ? "pointer" : "default";
      } else {
        p.setAttribute("fill", "rgba(0,0,0,0.04)");
        p.setAttribute("stroke", "rgba(0,0,0,0.25)");
        p.setAttribute("stroke-width", "0.5");
        (p as SVGElement).style.cursor = "default";
      }
    });
    svg.querySelectorAll("path:not([class])").forEach((p) => {
      (p as SVGElement).style.opacity = "0.4";
      (p as SVGElement).style.pointerEvents = "none";
    });
  }, [svgText, damagedSet, onZoneClick]);

  // Point overlay — рисуем поверх SVG в его user-space (827×1209) чтобы
  // точки идеально совмещались с подсвеченными зонами при любом масштабе.
  useEffect(() => {
    if (!svgText) return;
    const el = containerRef.current;
    if (!el) return;
    const svg = el.querySelector("svg") as SVGSVGElement | null;
    if (!svg) return;

    const existing = svg.querySelector("g[data-tt-damage-points]");
    if (existing) existing.remove();

    if (!damages || damages.length === 0) return;

    const group = document.createElementNS(SVG_NS, "g");
    group.setAttribute("data-tt-damage-points", "1");

    let counter = 1;
    for (const dmg of damages) {
      for (const pt of dmg.points || []) {
        if (
          typeof pt.x !== "number" ||
          typeof pt.y !== "number" ||
          !Number.isFinite(pt.x) ||
          !Number.isFinite(pt.y)
        ) {
          continue;
        }
        const circle = document.createElementNS(SVG_NS, "circle");
        circle.setAttribute("cx", String(pt.x));
        circle.setAttribute("cy", String(pt.y));
        circle.setAttribute("r", String(POINT_RADIUS));
        circle.setAttribute("fill", "rgb(220, 38, 38)");
        circle.setAttribute("stroke", "white");
        circle.setAttribute("stroke-width", "2");
        (circle as SVGElement).style.pointerEvents = "none";
        group.appendChild(circle);

        const text = document.createElementNS(SVG_NS, "text");
        text.setAttribute("x", String(pt.x));
        text.setAttribute("y", String(pt.y));
        text.setAttribute("text-anchor", "middle");
        text.setAttribute("dominant-baseline", "central");
        text.setAttribute("fill", "white");
        text.setAttribute("font-size", "11");
        text.setAttribute("font-weight", "bold");
        (text as SVGElement).style.pointerEvents = "none";
        (text as SVGElement).style.userSelect = "none";
        text.textContent = String(counter);
        group.appendChild(text);
        counter += 1;
      }
    }

    svg.appendChild(group);
  }, [svgText, damages]);

  function handleClick(e: React.MouseEvent<HTMLDivElement>) {
    if (!onZoneClick) return;
    const target = e.target as Element;
    const cls = target.getAttribute?.("class");
    if (cls && damagedSet.has(cls)) {
      const zoneId = Number(cls);
      if (Number.isFinite(zoneId)) onZoneClick(zoneId);
    }
  }

  return (
    <div
      ref={containerRef}
      onClick={handleClick}
      className="w-full aspect-[827/1209] max-h-[60vh] mx-auto bg-card rounded-lg overflow-hidden"
      style={{ touchAction: "manipulation" }}
      dangerouslySetInnerHTML={svgText ? { __html: svgText } : undefined}
    />
  );
}
