/* Scan-preview — abstract Gewerbegebiet view (no fake Germany map).
   Shows building rooftops with roof-type / orientation / area overlays,
   and trafo stations with the 50m detection radius from the Nexiga API. */

const { useState, useEffect, useMemo } = React;

/* Each building = rectangle rooftop on a grid.
   Properties mirror what the real API delivers:
   kind: "pv" | "trafo" | "excluded"
   roofForm: "Sattel" | "Flach" | "Pult" | "Walm"
   orientation: degrees (0=N, 180=S)
   area_m2, firms, hasPV */
const BUILDINGS = [
  { id: 1, x: 40,  y: 60,  w: 120, h: 70,  kind: "pv", roof: "Flach", deg: 180, area: 1250, firms: 2, score: 88 },
  { id: 2, x: 190, y: 40,  w: 90,  h: 110, kind: "pv", roof: "Sattel", deg: 195, area: 3200, firms: 1, score: 96 },
  { id: 3, x: 310, y: 70,  w: 70,  h: 60,  kind: "excluded", roof: "Flach", deg: 180, area: 780, firms: 1, hasPV: true },
  { id: 4, x: 420, y: 50,  w: 140, h: 90,  kind: "pv", roof: "Pult", deg: 170, area: 2100, firms: 3, score: 91 },
  { id: 5, x: 600, y: 70,  w: 80,  h: 70,  kind: "trafo" },
  { id: 6, x: 50,  y: 180, w: 90,  h: 80,  kind: "pv", roof: "Sattel", deg: 210, area: 1800, firms: 2, score: 84 },
  { id: 7, x: 170, y: 200, w: 140, h: 60,  kind: "pv", roof: "Walm", deg: 160, area: 980,  firms: 1, score: 72 },
  { id: 8, x: 340, y: 180, w: 110, h: 100, kind: "pv", roof: "Flach", deg: 180, area: 5400, firms: 4, score: 98 },
  { id: 9, x: 480, y: 210, w: 70,  h: 60,  kind: "excluded", roof: "Flach", deg: 180, area: 650, hasPV: true },
  { id:10, x: 580, y: 190, w: 110, h: 90,  kind: "pv", roof: "Flach", deg: 175, area: 1450, firms: 2, score: 89 },
  { id:11, x: 60,  y: 310, w: 130, h: 70,  kind: "pv", roof: "Sattel", deg: 185, area: 920,  firms: 1, score: 76 },
  { id:12, x: 220, y: 310, w: 80,  h: 90,  kind: "trafo" },
  { id:13, x: 340, y: 320, w: 130, h: 80,  kind: "pv", roof: "Pult", deg: 180, area: 2400, firms: 3, score: 93 },
  { id:14, x: 500, y: 310, w: 80,  h: 70,  kind: "pv", roof: "Flach", deg: 190, area: 680,  firms: 1, score: 68 },
  { id:15, x: 610, y: 320, w: 80,  h: 70,  kind: "excluded", roof: "Sattel", deg: 180, area: 510, hasPV: true },
];

const ScanPreview = ({ variant = "hero", scanTick = 0, filterKind = "all" }) => {
  const filtered = useMemo(() => {
    if (filterKind === "all") return BUILDINGS;
    if (filterKind === "pv") return BUILDINGS.filter(b => b.kind === "pv" || b.kind === "excluded");
    if (filterKind === "trafo") return BUILDINGS.filter(b => b.kind === "trafo");
    return BUILDINGS;
  }, [filterKind]);

  const [reveal, setReveal] = useState(variant === "hero" ? 0 : BUILDINGS.length);

  useEffect(() => {
    if (variant !== "hero") { setReveal(BUILDINGS.length); return; }
    setReveal(0);
    let i = 0;
    const id = setInterval(() => {
      i++; setReveal(i);
      if (i >= BUILDINGS.length) clearInterval(id);
    }, 180);
    return () => clearInterval(id);
  }, [scanTick, variant]);

  const hitCount = filtered.slice(0, reveal).filter(b => b.kind === "pv" || b.kind === "trafo").length;
  const excludedCount = filtered.slice(0, reveal).filter(b => b.kind === "excluded").length;

  return (
    <div style={{ position: "relative", width: "100%", aspectRatio: "7 / 5" }}>
      <svg viewBox="0 0 720 460" style={{ width: "100%", height: "100%", display: "block" }}>
        <defs>
          <pattern id="cadGrid" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(10,10,10,0.05)" strokeWidth="1" />
          </pattern>
          <pattern id="cadGridBig" width="100" height="100" patternUnits="userSpaceOnUse">
            <path d="M 100 0 L 0 0 0 100" fill="none" stroke="rgba(10,10,10,0.09)" strokeWidth="1" />
          </pattern>
          <linearGradient id="bgGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#FFFBEA" />
            <stop offset="100%" stopColor="#F5F4EE" />
          </linearGradient>
          <linearGradient id="scanLine" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="rgba(251,194,42,0)" />
            <stop offset="50%" stopColor="rgba(251,194,42,0.6)" />
            <stop offset="100%" stopColor="rgba(251,194,42,0)" />
          </linearGradient>
          <clipPath id="sceneClip"><rect x="0" y="0" width="720" height="460" rx="8" /></clipPath>
        </defs>

        <g clipPath="url(#sceneClip)">
          <rect x="0" y="0" width="720" height="460" fill="url(#bgGrad)" />
          <rect x="0" y="0" width="720" height="460" fill="url(#cadGrid)" />
          <rect x="0" y="0" width="720" height="460" fill="url(#cadGridBig)" />

          {/* Flurstück property lines */}
          <g stroke="rgba(10,10,10,0.12)" strokeWidth="1" strokeDasharray="3 4" fill="none">
            <path d="M0 150 L720 150 M0 280 L720 280 M160 0 L160 460 M320 0 L320 460 M460 0 L460 460 M580 0 L580 460" />
          </g>

          {/* Streets */}
          <g fill="rgba(10,10,10,0.06)">
            <rect x="0" y="142" width="720" height="16" />
            <rect x="0" y="272" width="720" height="16" />
          </g>

          {/* Scan line animation on hero */}
          {variant === "hero" && (
            <rect x="-80" y="0" width="80" height="460" fill="url(#scanLine)">
              <animate attributeName="x" from="-80" to="720" dur="2.6s" repeatCount="indefinite" />
            </rect>
          )}

          {/* Buildings */}
          {filtered.slice(0, reveal).map((b, i) => {
            const isTrafo = b.kind === "trafo";
            const isExcl = b.kind === "excluded";
            const isPV = b.kind === "pv";
            return (
              <g key={b.id} style={{ animation: `fadeUp 0.5s ${i * 0.03}s var(--ease) backwards` }}>
                {/* Trafo: 50m radius circle (~80px in viewBox scale) */}
                {isTrafo && (
                  <>
                    <circle cx={b.x + b.w / 2} cy={b.y + b.h / 2} r="80"
                      fill="rgba(251,194,42,0.10)" stroke="rgba(251,194,42,0.4)" strokeWidth="1" strokeDasharray="4 4" />
                    <circle cx={b.x + b.w / 2} cy={b.y + b.h / 2} r="80" fill="none" stroke="rgba(251,194,42,0.25)" strokeWidth="1">
                      <animate attributeName="r" values="40;100;40" dur="3s" repeatCount="indefinite" />
                      <animate attributeName="opacity" values="0.8;0;0.8" dur="3s" repeatCount="indefinite" />
                    </circle>
                  </>
                )}

                {/* Roof rectangle */}
                <rect x={b.x} y={b.y} width={b.w} height={b.h}
                  fill={isTrafo ? "#0A0A0A" : isExcl ? "rgba(10,10,10,0.08)" : "#FFFFFF"}
                  stroke={isTrafo ? "#0A0A0A" : isExcl ? "rgba(10,10,10,0.3)" : "#0A0A0A"}
                  strokeWidth={isPV ? 1.5 : 1}
                  strokeDasharray={isExcl ? "3 3" : "0"} />

                {/* Roof-form indicator (ridge line for Sattel, diagonal for Pult) */}
                {isPV && b.roof === "Sattel" && (
                  <line x1={b.x} y1={b.y + b.h / 2} x2={b.x + b.w} y2={b.y + b.h / 2}
                    stroke="rgba(10,10,10,0.25)" strokeWidth="1" />
                )}
                {isPV && b.roof === "Pult" && (
                  <line x1={b.x} y1={b.y + b.h} x2={b.x + b.w} y2={b.y}
                    stroke="rgba(10,10,10,0.2)" strokeWidth="1" />
                )}
                {isPV && b.roof === "Walm" && (
                  <g stroke="rgba(10,10,10,0.22)" strokeWidth="1" fill="none">
                    <path d={`M ${b.x} ${b.y} L ${b.x + 15} ${b.y + 15} L ${b.x + b.w - 15} ${b.y + 15} L ${b.x + b.w} ${b.y}`} />
                    <path d={`M ${b.x} ${b.y + b.h} L ${b.x + 15} ${b.y + b.h - 15} L ${b.x + b.w - 15} ${b.y + b.h - 15} L ${b.x + b.w} ${b.y + b.h}`} />
                  </g>
                )}

                {/* Yellow highlight fill for qualified PV roofs */}
                {isPV && (
                  <rect x={b.x + 3} y={b.y + 3} width={b.w - 6} height={b.h - 6}
                    fill="rgba(251,194,42,0.28)" stroke="rgba(251,194,42,0.7)" strokeWidth="1" />
                )}

                {/* Excluded: red cross */}
                {isExcl && (
                  <g stroke="#DC2626" strokeWidth="1.5">
                    <line x1={b.x + 8} y1={b.y + 8} x2={b.x + b.w - 8} y2={b.y + b.h - 8} />
                    <line x1={b.x + b.w - 8} y1={b.y + 8} x2={b.x + 8} y2={b.y + b.h - 8} />
                  </g>
                )}

                {/* Trafo: lightning bolt */}
                {isTrafo && (
                  <g transform={`translate(${b.x + b.w / 2 - 9}, ${b.y + b.h / 2 - 11})`}>
                    <path d="M 11 0 L 3 12 L 9 12 L 7 22 L 15 10 L 9 10 L 11 0 Z" fill="#FBC22A" />
                  </g>
                )}

                {/* North arrow for orientation (PV only) */}
                {isPV && b.w >= 90 && (
                  <g transform={`translate(${b.x + b.w - 14}, ${b.y + 14}) rotate(${b.deg})`}>
                    <circle r="8" fill="#FFFFFF" stroke="rgba(10,10,10,0.35)" strokeWidth="0.75" />
                    <path d="M 0 -5 L 3 3 L 0 1 L -3 3 Z" fill="#0A0A0A" />
                  </g>
                )}

                {/* Label: area or "PV bereits installiert" */}
                {isPV && b.w >= 90 && (
                  <text x={b.x + 6} y={b.y + b.h - 6} fontFamily="Geist, sans-serif" fontSize="10" fontWeight="600" fill="#0A0A0A">
                    {b.area.toLocaleString("de-DE")} m²
                  </text>
                )}
                {isExcl && b.w >= 70 && (
                  <text x={b.x + b.w / 2} y={b.y + b.h + 12} textAnchor="middle"
                    fontFamily="Inter, sans-serif" fontSize="9" fill="#DC2626" fontWeight="600">
                    PV vorhanden
                  </text>
                )}
              </g>
            );
          })}

          {/* Ground-truth overlays at corners */}
          <g fontFamily="Inter, sans-serif" fontSize="9" fill="rgba(10,10,10,0.4)" fontWeight="500">
            <text x="12" y="18">GEWERBEGEBIET · FLURSTÜCKE</text>
            <text x="12" y="450">MASSSTAB 1:2.500</text>
            <text x="630" y="450">NORD ↑</text>
          </g>
        </g>
      </svg>

      {/* Overlay: counters */}
      <div style={{ position: "absolute", top: 14, right: 14, display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
        <div className="chip yellow" style={{ fontSize: 12 }}>
          <span style={{ fontFamily: "var(--font-stat)", fontWeight: 600 }}>
            {hitCount.toString().padStart(2, "0")}
          </span>
          <span>qualifizierte Objekte</span>
        </div>
        {excludedCount > 0 && (
          <div className="chip" style={{ fontSize: 11, background: "#fff" }}>
            <span style={{ color: "var(--err)", fontWeight: 600 }}>— {excludedCount}</span>
            <span style={{ color: "var(--ink-4)" }}>mit Bestand ausgeschlossen</span>
          </div>
        )}
      </div>

      {/* Legend */}
      <div style={{ position: "absolute", bottom: 14, left: 14, display: "flex", gap: 12, alignItems: "center",
        background: "rgba(255,255,255,0.88)", backdropFilter: "blur(6px)", padding: "6px 10px", borderRadius: 99,
        border: "1px solid var(--line)", fontSize: 11, color: "var(--ink-3)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 10, height: 10, background: "rgba(251,194,42,0.5)", border: "1px solid #FBC22A" }} />Dach ≥ 500m²
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 10, height: 10, background: "#0A0A0A" }} />Trafo
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <span style={{ width: 10, height: 10, border: "1px dashed var(--err)", position: "relative" }} />Bestand
        </span>
      </div>
    </div>
  );
};

// Expose for other scripts
window.ScanPreview = ScanPreview;
window.MapPreview = ScanPreview; // legacy alias
window.BUILDINGS_DATA = BUILDINGS;

// Legacy hits alias for AppPreview
window.HITS_DATA = BUILDINGS.map(b => ({
  id: b.id,
  kind: b.kind === "excluded" ? "pv" : b.kind,
  excluded: b.kind === "excluded",
  size: b.area || 0,
  roof: b.roof,
  deg: b.deg,
  firms: b.firms || 0,
  company: b.kind === "trafo"
    ? ["Umspannstation Nord-West", "Trafo Gewerbepark Süd", "Mittelspannung Ost"][(b.id) % 3]
    : ["MetallWerk GmbH","Nordfrost Kühllager","Bauer Logistik","Keramik-Werk","Fischer Metallbau","Holzwerk Allgäu","Spedition Kessler","Recycling Ruhr","Glasmühle","Brauerei Passau","Autohaus Kirsch","Kunststofftechnik","Druckerei Rhein","Lackierwerk Ost","Textilzentrum"][(b.id - 1) % 15] + (b.kind === "excluded" ? " (PV vorhanden)" : ""),
  branch: ["Metallverarbeitung","Lebensmittel/Kühlung","Logistik","Industrie","Metallbau","Holzindustrie","Spedition","Entsorgung","Baustoffe","Getränke","Kfz-Handel","Kunststoff","Druck","Oberflächentechnik","Textil"][(b.id - 1) % 15],
  kwp: b.area ? Math.round(b.area * 0.32) : 0,
  score: b.score || 0,
}));
