"use client";

import Image from "next/image";
import type { CSSProperties, RefObject } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { vsiProductionMasterSvg } from "./vsi-production-master-svg";
import { vsiTargetDotsAndScansSvg } from "./vsi-target-dots-scans-svg";
import styles from "./vsi-hero-demo.module.css";

type VsiPhase =
  | "idle"
  | "detect-landmarks"
  | "build-skeleton"
  | "resolve-outline"
  | "place-captures"
  | "scan-captures"
  | "coverage-complete"
  | "coverage-confirmed"
  | "verification-sweep"
  | "verify"
  | "trusted-record";

type VsiRailStage = "observe" | "understand" | "register" | "guide" | "verify" | "trusted-record";
type VsiPlaybackMode = "auto" | "present" | "static";

type VsiProductionSceneProps = {
  playback?: VsiPlaybackMode;
  selectedStage?: VsiRailStage;
  onActiveStageChange?: (stage: VsiRailStage) => void;
};

type SequenceFrame = {
  activeCaptureIndex?: number;
  activeLandmarkGroupIndex?: number;
  duration: number;
  outlineBatch?: number;
  phase: VsiPhase;
  registerProgress?: number;
  scanMode?: "complete" | "hold" | "scan";
  skeletonGroup?: number;
};

type OverlayPosition = {
  direction: "left" | "right";
  left: number;
  top: number;
};

type LandmarkLabelOverlay = OverlayPosition & {
  delay: number;
  feature: string;
  label: string;
  offset: number;
  state: "current" | "recent";
};

type ScanBounds = {
  height: number;
  width: number;
  x: number;
  y: number;
};

const REGISTER_CLIP_ID = "vsi-register-reveal-clip";
const registerProgressSteps = [0, 0.18, 0.36, 0.58, 0.8, 1];

const landmarkOrder = [
  "left-front-bumper-corner",
  "front-grille-left",
  "front-grille-right",
  "left-headlight",
  "hood-edge-left",
  "hood-edge-right",
  "roof-edge-front-left",
  "a-pillar-bottom",
  "mid-left-a-pillar",
  "left-mirror",
  "roof-edge-front-right",
  "b-pillar-top",
  "b-pillar-mid",
  "b-pillar-bottom",
  "front-left-wheel",
  "rocker-front-left",
  "c-pillar-top",
  "c-pillar-mid",
  "rear-left-wheel",
  "rocker-rear-left",
  "roof-edge-rear-left",
  "d-pillar-mid",
  "left-rear-tail-light",
  "left-rear-bumper-corner"
];

const landmarkGroups = [
  {
    features: ["left-front-bumper-corner", "front-grille-left", "front-grille-right"],
    label: "front_bumper · grille"
  },
  {
    features: ["left-headlight", "hood-edge-left", "hood-edge-right"],
    label: "headlight · hood_edge"
  },
  {
    features: ["roof-edge-front-left", "a-pillar-bottom", "mid-left-a-pillar"],
    label: "a_pillar · roof_edge"
  },
  {
    features: ["left-mirror", "roof-edge-front-right", "b-pillar-top"],
    label: "mirror · roof_datum"
  },
  {
    features: ["b-pillar-mid", "b-pillar-bottom", "front-left-wheel"],
    label: "b_pillar · front_wheel"
  },
  {
    features: ["rocker-front-left", "c-pillar-top", "c-pillar-mid"],
    label: "rocker · c_pillar"
  },
  {
    features: ["rear-left-wheel", "rocker-rear-left", "roof-edge-rear-left"],
    label: "rear_wheel · rear_roof"
  },
  {
    features: ["d-pillar-mid", "left-rear-tail-light", "left-rear-bumper-corner"],
    label: "d_pillar · taillight"
  }
];

const captureSequence = [
  { key: "front", scanId: "front", targetId: "target_front" },
  { key: "front-left", scanId: "left_front", targetId: "target_front_left" },
  { key: "front-left-fender", scanId: "left_front_fender", targetId: "target_front_left_fender" },
  { key: "front-left-door", scanId: "left_driver_door", targetId: "target_front_left_door" },
  { key: "rear-left-door", scanId: "left_rear_door", targetId: "target_rear_left_door" },
  { key: "mid-left-rear", scanId: "left_mid_rear", targetId: "target_mid_left_rear" },
  { key: "rear-left", scanId: "left_rear", targetId: "target_rear_left" }
];

const railStages: Array<{ key: VsiRailStage; label: string }> = [
  { key: "observe", label: "Observe" },
  { key: "understand", label: "Understand" },
  { key: "register", label: "Register" },
  { key: "guide", label: "Guide" },
  { key: "verify", label: "Verify" },
  { key: "trusted-record", label: "Trusted Record" }
];

const railCopy: Record<
  VsiRailStage,
  {
    detail?: string;
    fieldLabel?: string;
    label: string;
    metric: string;
  }
> = {
  observe: {
    label: "Observe",
    metric: "Stable vehicle features detected"
  },
  understand: {
    detail: "Detected landmarks are related into one vehicle-relative state.",
    label: "Understand",
    metric: "Vehicle structure connected"
  },
  register: {
    detail: "The observed structure is being resolved into one stable vehicle-relative model.",
    label: "Register",
    metric: "Vehicle geometry registering"
  },
  guide: {
    fieldLabel: "Current capture",
    label: "Guide",
    metric: "Next observation calculated"
  },
  verify: {
    detail: "Every required capture section has been observed.",
    label: "Verify",
    metric: "Required coverage confirmed"
  },
  "trusted-record": {
    detail: "The completed perception state becomes a VIN-linked record.",
    label: "Trusted record",
    metric: "VIN-linked visual record ready"
  }
};

const finalFrame: SequenceFrame = { duration: 1500, phase: "trusted-record" };

function getRegisteredOutlineBounds(): ScanBounds {
  const linesMarkup =
    vsiProductionMasterSvg.match(/<g id="lines"[\s\S]*?<\/g>\s*<g id="skeleton-lines"/)?.[0] ?? "";
  const points: Array<{ x: number; y: number }> = [];
  const pushPair = (x?: string, y?: string) => {
    if (x === undefined || y === undefined) return;
    points.push({ x: Number(x), y: Number(y) });
  };

  for (const match of linesMarkup.matchAll(
    /\s(?:x1|x2)="(-?\d+(?:\.\d+)?)"\s(?:y1|y2)="(-?\d+(?:\.\d+)?)"/g
  )) {
    pushPair(match[1], match[2]);
  }

  for (const match of linesMarkup.matchAll(/\spoints="([^"]+)"/g)) {
    const values = match[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
    for (let index = 0; index < values.length - 1; index += 2) {
      points.push({ x: values[index], y: values[index + 1] });
    }
  }

  for (const match of linesMarkup.matchAll(/\sd="([^"]+)"/g)) {
    const values = match[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
    for (let index = 0; index < values.length - 1; index += 2) {
      points.push({ x: values[index], y: values[index + 1] });
    }
  }

  if (points.length === 0) return { height: 1840, width: 3820, x: 30, y: 500 };

  const xs = points.map((point) => point.x);
  const ys = points.map((point) => point.y);
  const padding = 36;
  const minX = Math.max(0, Math.min(...xs) - padding);
  const maxX = Math.min(3879, Math.max(...xs) + padding);
  const minY = Math.max(0, Math.min(...ys) - padding);
  const maxY = Math.min(2736, Math.max(...ys) + padding);

  return {
    height: maxY - minY,
    width: maxX - minX,
    x: minX,
    y: minY
  };
}

const registerRevealBounds = getRegisteredOutlineBounds();

function getLandmarkCenterX(feature: string) {
  const match = vsiProductionMasterSvg.match(
    new RegExp(
      `<g id="landmark-${feature}"[^>]*transform="translate\\((-?\\d+(?:\\.\\d+)?),\\s*(-?\\d+(?:\\.\\d+)?)\\)"`
    )
  );

  return match ? Number(match[1]) + 25 : undefined;
}

function getMarkupCenterX(markup: string) {
  const points: number[] = [];
  const push = (value?: string) => {
    if (value === undefined) return;
    points.push(Number(value));
  };

  for (const match of markup.matchAll(/\s(?:x1|x2)="(-?\d+(?:\.\d+)?)"/g)) {
    push(match[1]);
  }

  for (const match of markup.matchAll(/\spoints="([^"]+)"/g)) {
    const values = match[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
    for (let index = 0; index < values.length - 1; index += 2) {
      points.push(values[index]);
    }
  }

  for (const match of markup.matchAll(/\sd="([^"]+)"/g)) {
    const values = match[1].match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
    for (let index = 0; index < values.length - 1; index += 2) {
      points.push(values[index]);
    }
  }

  if (points.length === 0) return undefined;

  return points.reduce((sum, point) => sum + point, 0) / points.length;
}

function createSequenceFrames(): SequenceFrame[] {
  return [
    { duration: 560, phase: "idle" },
    ...landmarkGroups.map((_, activeLandmarkGroupIndex) => ({
      activeLandmarkGroupIndex,
      duration: 280,
      phase: "detect-landmarks" as const
    })),
    { activeLandmarkGroupIndex: landmarkGroups.length - 1, duration: 80, phase: "detect-landmarks" },
    { duration: 160, phase: "build-skeleton", skeletonGroup: -1 },
    { duration: 220, phase: "build-skeleton", skeletonGroup: 0 },
    { duration: 220, phase: "build-skeleton", skeletonGroup: 1 },
    { duration: 220, phase: "build-skeleton", skeletonGroup: 2 },
    { duration: 260, phase: "build-skeleton", skeletonGroup: 3 },
    { duration: 180, phase: "build-skeleton", skeletonGroup: 4 },
    { duration: 160, phase: "resolve-outline", registerProgress: registerProgressSteps[0] },
    { duration: 190, phase: "resolve-outline", registerProgress: registerProgressSteps[1] },
    { duration: 190, phase: "resolve-outline", registerProgress: registerProgressSteps[2] },
    { duration: 190, phase: "resolve-outline", registerProgress: registerProgressSteps[3] },
    { duration: 190, phase: "resolve-outline", registerProgress: registerProgressSteps[4] },
    { duration: 230, phase: "resolve-outline", registerProgress: registerProgressSteps[5] },
    { duration: 220, phase: "resolve-outline", registerProgress: 1 },
    { duration: 260, phase: "place-captures" },
    ...captureSequence.flatMap((_, activeCaptureIndex) => [
      {
        activeCaptureIndex,
        duration: 200,
        phase: "scan-captures" as const,
        scanMode: "hold" as const
      },
      {
        activeCaptureIndex,
        duration: 740,
        phase: "scan-captures" as const,
        scanMode: "scan" as const
      },
      {
        activeCaptureIndex,
        duration: 150,
        phase: "scan-captures" as const,
        scanMode: "complete" as const
      }
    ]),
    { duration: 200, phase: "coverage-complete" },
    { duration: 420, phase: "coverage-confirmed" },
    { duration: 600, phase: "verification-sweep" },
    { duration: 460, phase: "verify" },
    finalFrame
  ];
}

function useReducedMotion() {
  const [reduced, setReduced] = useState(false);

  useEffect(() => {
    const media = window.matchMedia("(prefers-reduced-motion: reduce)");
    setReduced(media.matches);

    const onChange = () => setReduced(media.matches);
    media.addEventListener("change", onChange);

    return () => media.removeEventListener("change", onChange);
  }, []);

  return reduced;
}

function useInView<T extends HTMLElement>() {
  const ref = useRef<T | null>(null);
  const [inView, setInView] = useState(false);

  useEffect(() => {
    const node = ref.current;

    if (!node) return;

    const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), {
      threshold: 0.34
    });

    observer.observe(node);

    return () => observer.disconnect();
  }, []);

  return { inView, ref };
}

function featureToLabel(feature?: string) {
  return feature?.replaceAll("-", "_") ?? "";
}

function featureToObserveLabel(feature: string) {
  const labels: Record<string, string> = {
    "a-pillar-bottom": "A-PILLAR",
    "b-pillar-bottom": "B-PILLAR",
    "b-pillar-mid": "B-PILLAR",
    "b-pillar-top": "B-PILLAR",
    "c-pillar-mid": "C-PILLAR",
    "c-pillar-top": "C-PILLAR",
    "d-pillar-mid": "D-PILLAR",
    "front-grille-left": "FRONT GRILLE",
    "front-grille-right": "FRONT GRILLE",
    "front-left-wheel": "FRONT WHEEL",
    "hood-edge-left": "HOOD EDGE",
    "hood-edge-right": "HOOD EDGE",
    "left-front-bumper-corner": "BUMPER CORNER",
    "left-headlight": "FRONT LIGHT",
    "left-mirror": "MIRROR",
    "left-rear-bumper-corner": "REAR BUMPER",
    "left-rear-tail-light": "TAILLIGHT",
    "mid-left-a-pillar": "A-PILLAR",
    "rear-left-wheel": "REAR WHEEL",
    "rocker-front-left": "ROCKER",
    "rocker-rear-left": "ROCKER",
    "roof-edge-front-left": "ROOF EDGE",
    "roof-edge-front-right": "ROOF EDGE",
    "roof-edge-rear-left": "ROOF EDGE"
  };

  return labels[feature] ?? feature.replaceAll("-", " ").toUpperCase();
}

function getRailStage(frame: SequenceFrame): VsiRailStage {
  if (frame.phase === "detect-landmarks" || frame.phase === "idle") return "observe";
  if (frame.phase === "build-skeleton") return "understand";
  if (frame.phase === "resolve-outline") return "register";
  if (frame.phase === "place-captures" || frame.phase === "scan-captures") return "guide";
  if (
    frame.phase === "coverage-complete" ||
    frame.phase === "coverage-confirmed" ||
    frame.phase === "verification-sweep"
  )
    return "verify";
  if (frame.phase === "verify") return "trusted-record";
  return "trusted-record";
}

function getStageState(stage: VsiRailStage, activeStage: VsiRailStage) {
  const stageIndex = railStages.findIndex((item) => item.key === stage);
  const activeIndex = railStages.findIndex((item) => item.key === activeStage);

  if (stageIndex < activeIndex) return "complete";
  if (stageIndex === activeIndex) return "active";
  return "pending";
}

function getPanelCopy(stage: VsiRailStage, frame: SequenceFrame) {
  if (stage !== "register") return railCopy[stage];

  if ((frame.registerProgress ?? 0) >= 1) {
    return {
      detail: "The observed structure becomes a stable vehicle-relative model.",
      label: "Register",
      metric: "Vehicle geometry resolved"
    };
  }

  return railCopy.register;
}

function getStageRange(frames: SequenceFrame[], stage: VsiRailStage) {
  const indexes = frames
    .map((frame, index) => ({ index, stage: getRailStage(frame) }))
    .filter((item) => item.stage === stage)
    .map((item) => item.index);

  if (indexes.length === 0) {
    const finalIndex = Math.max(0, frames.length - 1);
    return { end: finalIndex, start: finalIndex };
  }

  let start = indexes[0];

  if (stage === "observe" && frames[start]?.phase === "idle" && indexes.length > 1) {
    start = indexes[1];
  }

  return { end: indexes[indexes.length - 1], start };
}

function useSequence(
  playback: VsiPlaybackMode,
  reducedMotion: boolean,
  inView: boolean,
  selectedStage: VsiRailStage
) {
  const frames = useMemo(createSequenceFrames, []);
  const [frameIndex, setFrameIndex] = useState(playback === "static" ? frames.length - 1 : 0);
  const presentRange = useMemo(() => getStageRange(frames, selectedStage), [frames, selectedStage]);
  const canAnimate = playback === "auto" && !reducedMotion;
  const canPresent = playback === "present" && !reducedMotion;

  useEffect(() => {
    if (playback === "present") {
      setFrameIndex(presentRange.start);
      return;
    }

    if (!canAnimate) {
      setFrameIndex(frames.length - 1);
      return;
    }

    if (!inView) return;

    setFrameIndex(0);
  }, [canAnimate, frames.length, inView, playback, presentRange.start]);

  useEffect(() => {
    if (!canAnimate || !inView) return;

    const timer = window.setTimeout(
      () => setFrameIndex((current) => (current + 1) % frames.length),
      frames[frameIndex].duration
    );

    return () => window.clearTimeout(timer);
  }, [canAnimate, frameIndex, frames, inView]);

  useEffect(() => {
    if (!canPresent || !inView || frameIndex >= presentRange.end) return;

    const timer = window.setTimeout(
      () => setFrameIndex((current) => Math.min(current + 1, presentRange.end)),
      frames[frameIndex].duration
    );

    return () => window.clearTimeout(timer);
  }, [canPresent, frameIndex, frames, inView, presentRange.end]);

  return frames[frameIndex];
}

function getLandmarkState(feature: string, index: number, frame: SequenceFrame) {
  const activeGroupIndex = frame.activeLandmarkGroupIndex ?? -1;
  const currentGroup = landmarkGroups[activeGroupIndex]?.features ?? [];
  const lastDetectedIndex =
    activeGroupIndex < 0
      ? -1
      : Math.max(
          ...landmarkGroups
            .slice(0, activeGroupIndex + 1)
            .flatMap((group) => group.features.map((item) => landmarkOrder.indexOf(item)))
        );

  if (frame.phase === "trusted-record" || frame.phase === "verify") return "hidden";
  if (
    frame.phase === "coverage-complete" ||
    frame.phase === "coverage-confirmed" ||
    frame.phase === "verification-sweep"
  ) {
    return ["front-left-wheel", "left-mirror", "rear-left-wheel"].includes(feature) ? "faint" : "hidden";
  }
  if (frame.phase === "scan-captures" || frame.phase === "place-captures") return "hidden";
  if (frame.phase === "resolve-outline") {
    if (index >= 0 && index < landmarkOrder.length) {
      const progress = frame.registerProgress ?? 0;
      const landmarkX = getLandmarkCenterX(feature);

      if (progress >= 1) return "registered";
      if (progress <= 0 || landmarkX === undefined) return "detected";

      const sweepX = registerRevealBounds.x + registerRevealBounds.width * progress;
      const progressIndex = registerProgressSteps.findIndex((step) => step === progress);
      const previousProgress = progressIndex > 0 ? registerProgressSteps[progressIndex - 1] : 0;
      const previousSweepX = registerRevealBounds.x + registerRevealBounds.width * previousProgress;

      if (landmarkX > previousSweepX && landmarkX <= sweepX) return "registering";
      if (landmarkX <= previousSweepX) return "registered";
      return "detected";
    } else {
      return "hidden";
    }
  }
  if (frame.phase === "build-skeleton")
    return index >= 0 && index < landmarkOrder.length ? "detected" : "hidden";
  if (frame.phase !== "detect-landmarks") return "hidden";
  if (index < 0 || index > lastDetectedIndex) return "hidden";
  if (currentGroup.includes(feature)) return "active";
  return "detected";
}

function getSkeletonState(index: number, total: number, frame: SequenceFrame, centerX?: number) {
  const group = Math.min(3, Math.floor((index / total) * 4));

  if (frame.phase === "build-skeleton") {
    if (group < (frame.skeletonGroup ?? -1)) return { group, state: "complete" };
    if (group === frame.skeletonGroup) return { group, state: "active" };
    return { group, state: "hidden" };
  }

  if (frame.phase === "resolve-outline") {
    const progress = frame.registerProgress ?? 0;

    if (progress <= 0) return { group, state: "register-pending" };
    if (progress >= 1) return { group, state: "register-gone" };

    if (centerX === undefined) return { group, state: "register-settled" };

    const sweepX = registerRevealBounds.x + registerRevealBounds.width * progress;
    const transitionWidth = 120;

    if (centerX <= sweepX - transitionWidth) return { group, state: "register-gone" };
    if (centerX <= sweepX + transitionWidth) return { group, state: "register-fading" };
    return { group, state: "register-pending" };
  }
  return { group, state: "hidden" };
}

function getOutlineState(index: number, total: number, frame: SequenceFrame, centerX?: number) {
  const batch = Math.min(8, Math.floor((index / total) * 9));

  if (frame.phase === "resolve-outline") {
    const progress = frame.registerProgress ?? 0;

    if (progress <= 0) return { batch, state: "hidden" };
    if (progress >= 1) return { batch, state: "registered" };
    if (centerX === undefined) return { batch, state: "registering" };

    const progressIndex = registerProgressSteps.findIndex((step) => step === progress);
    const previousProgress = progressIndex > 0 ? registerProgressSteps[progressIndex - 1] : 0;
    const previousSweepX = registerRevealBounds.x + registerRevealBounds.width * previousProgress;
    const sweepX = registerRevealBounds.x + registerRevealBounds.width * progress;

    if (centerX > previousSweepX && centerX <= sweepX) return { batch, state: "registering" };
    if (centerX <= previousSweepX) return { batch, state: "registered" };
    return { batch, state: "hidden" };
  }

  if (frame.phase === "place-captures") return { batch, state: "clearing" };

  if (frame.phase === "verify") return { batch, state: "clearing" };
  return { batch, state: "hidden" };
}

function getTargetState(targetId: string, frame: SequenceFrame) {
  const index = captureSequence.findIndex((section) => section.targetId === targetId);

  if (frame.phase === "place-captures") return { index, state: "pending" };
  if (frame.phase === "scan-captures") {
    if (index < (frame.activeCaptureIndex ?? -1)) return { index, state: "complete" };
    if (index === frame.activeCaptureIndex) return { index, state: "active" };
    return { index, state: "pending" };
  }

  return { index, state: "hidden" };
}

function getScanState(scanId: string, frame: SequenceFrame) {
  const index = captureSequence.findIndex((section) => section.scanId === scanId);

  if (frame.phase === "scan-captures") {
    const activeIndex = frame.activeCaptureIndex ?? -1;
    if (index < activeIndex)
      return { index, state: index === activeIndex - 1 ? "complete-recent" : "complete-old" };
    if (index === frame.activeCaptureIndex) {
      if (frame.scanMode === "hold") return { index, state: "primed" };
      if (frame.scanMode === "complete") return { index, state: "just-complete" };
      return { index, state: "active" };
    }
    return { index, state: "hidden" };
  }

  if (frame.phase === "coverage-complete") return { index, state: "verified" };
  if (frame.phase === "coverage-confirmed") return { index, state: "confirmed" };
  if (frame.phase === "verification-sweep") return { index, state: "sweeping" };
  if (frame.phase === "verify") return { index, state: "clearing" };
  return { index, state: "hidden" };
}

function getLandmarkClasses(state: string) {
  if (state === "active") return "vsi-landmark is-detected is-active";
  if (state === "hidden") return "vsi-landmark";
  return `vsi-landmark is-detected is-${state}`;
}

function getLandmarkGroupOffset(feature: string, frame: SequenceFrame) {
  if (frame.phase !== "detect-landmarks" || frame.activeLandmarkGroupIndex === undefined) return 0;
  return Math.max(0, landmarkGroups[frame.activeLandmarkGroupIndex]?.features.indexOf(feature) ?? 0);
}

function getTargetClasses(state: string) {
  if (state === "active") return "vsi-guide-target is-active";
  if (state === "complete") return "vsi-guide-target is-complete";
  return "vsi-guide-target";
}

function getScanClasses(state: string) {
  if (state === "primed") return "vsi-scan-section is-primed";
  if (state === "active") return "vsi-scan-section is-active";
  if (state === "just-complete") return "vsi-scan-section is-just-complete";
  if (state === "complete-recent") return "vsi-scan-section is-complete is-complete-recent";
  if (state === "complete-old") return "vsi-scan-section is-complete is-complete-old";
  if (state === "complete") return "vsi-scan-section is-complete";
  if (state === "verified") return "vsi-scan-section is-verified";
  if (state === "confirmed") return "vsi-scan-section is-confirmed verify-section--fully-confirmed";
  if (state === "sweeping") return "vsi-scan-section is-sweeping verify-section--fully-confirmed";
  if (state === "clearing") return "vsi-scan-section is-clearing";
  if (state === "final") return "vsi-scan-section is-final";
  return "vsi-scan-section";
}

function getPathData(markup: string) {
  return markup.match(/\sd="([^"]+)"/)?.[1] ?? "";
}

function getPathBounds(pathData: string): ScanBounds {
  const values = pathData.match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
  const points: Array<{ x: number; y: number }> = [];

  for (let index = 0; index < values.length - 1; index += 2) {
    points.push({ x: values[index], y: values[index + 1] });
  }

  if (points.length === 0) return { height: 1, width: 1, x: 0, y: 0 };

  const xs = points.map((point) => point.x);
  const ys = points.map((point) => point.y);
  const padding = 12;
  const minX = Math.min(...xs) - padding;
  const maxX = Math.max(...xs) + padding;
  const minY = Math.min(...ys) - padding;
  const maxY = Math.max(...ys) + padding;

  return {
    height: Math.max(1, maxY - minY),
    width: Math.max(1, maxX - minX),
    x: minX,
    y: minY
  };
}

function renderScanSection(scanId: string, classes: string, index: number, state: string, pathData: string) {
  const bounds = getPathBounds(pathData);
  const clipId = `vsi-scan-clip-${scanId}`;
  const bandWidth = Math.min(Math.max(bounds.width * 0.055, 64), 132);
  const frontWidth = 3;
  const scanDistance = bounds.width + bandWidth;

  return `<g id="${scanId}" class="${classes}" data-vsi-scan-index="${index}" data-vsi-state="${state}" style="--vsi-scan-distance: ${scanDistance}px;">
    <clipPath id="${clipId}">
      <path d="${pathData}"></path>
    </clipPath>
    <path class="vsi-scan-outline" d="${pathData}" pathLength="1" vector-effect="non-scaling-stroke"></path>
    <g class="vsi-scan-mask" clip-path="url(#${clipId})">
      <rect class="vsi-scan-fill" x="${bounds.x}" y="${bounds.y}" width="${bounds.width}" height="${bounds.height}"></rect>
      <rect class="vsi-scan-band" x="${bounds.x - bandWidth}" y="${bounds.y}" width="${bandWidth}" height="${bounds.height}"></rect>
      <rect class="vsi-scan-front" x="${bounds.x}" y="${bounds.y}" width="${frontWidth}" height="${bounds.height}"></rect>
    </g>
  </g>`;
}

function renderEmptyVsiSvg() {
  return '<svg width="2048px" height="1444px" viewBox="0 0 2048 1444" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" aria-hidden="true" focusable="false"></svg>';
}

function renderEmptyTargetSvg() {
  return '<svg width="3879px" height="2736px" viewBox="0 0 3879 2736" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" aria-hidden="true" focusable="false"></svg>';
}

function buildVsiSvg(frame: SequenceFrame) {
  if (frame.phase === "trusted-record") return renderEmptyVsiSvg();

  const outlineTotal = vsiProductionMasterSvg.match(/class="vsi-line/g)?.length ?? 1;
  const skeletonTotal = vsiProductionMasterSvg.match(/class="vsi-skeleton-line/g)?.length ?? 1;
  const registerProgress = Math.min(Math.max(frame.registerProgress ?? 0, 0), 1);
  const registerClipWidth = registerRevealBounds.width * registerProgress;
  const registerClip =
    frame.phase === "resolve-outline"
      ? `<clipPath id="${REGISTER_CLIP_ID}"><rect x="${registerRevealBounds.x}" y="${registerRevealBounds.y}" width="${registerClipWidth}" height="${registerRevealBounds.height}"></rect></clipPath>`
      : "";
  let outlineIndex = 0;
  let skeletonIndex = 0;

  return vsiProductionMasterSvg
    .replace('<defs id="vsi-defs">', `<defs id="vsi-defs">${registerClip}`)
    .replace(/<g id="lines"([^>]*)>/, (match, attributes: string) => {
      if (frame.phase !== "resolve-outline") return match;
      return `<g id="lines"${attributes} clip-path="url(#${REGISTER_CLIP_ID})" data-register-progress="${registerProgress}">`;
    })
    .replace(/<g id="landmark-([^"]+)"([^>]*class="vsi-landmark"[^>]*)>/g, (match, feature: string) => {
      const index = landmarkOrder.indexOf(feature);
      const state = getLandmarkState(feature, index, frame);
      const offset = getLandmarkGroupOffset(feature, frame);
      return match
        .replace('class="vsi-landmark"', `class="${getLandmarkClasses(state)}"`)
        .replace(
          ">",
          ` data-vsi-landmark-index="${index}" data-vsi-state="${state}" style="--vsi-point-delay: ${offset * 55}ms">`
        );
    })
    .replace(/<g id="capture-([^"]+)"([^>]*class="vsi-capture-section"[^>]*)>/g, (match, section: string) => {
      return match.replace(
        ">",
        ` data-vsi-capture-index="-1" data-vsi-state="hidden" data-legacy-section="${section}">`
      );
    })
    .replace(/<((?:line|polyline|path)[^>]*class="vsi-skeleton-line"[^>]*)\/>/g, (match, tag: string) => {
      const { group, state } = getSkeletonState(skeletonIndex, skeletonTotal, frame, getMarkupCenterX(match));
      const order = skeletonIndex;
      skeletonIndex += 1;
      return `<${tag} data-vsi-skeleton-group="${group}" data-vsi-state="${state}" style="--vsi-order: ${order}" />`;
    })
    .replace(/<((?:line|polyline|path)[^>]*class="vsi-line[^"]*"[^>]*)\/>/g, (match, tag: string) => {
      const { batch, state } = getOutlineState(outlineIndex, outlineTotal, frame, getMarkupCenterX(match));
      const order = outlineIndex;
      outlineIndex += 1;
      return `<${tag} data-vsi-outline-batch="${batch}" data-vsi-state="${state}" style="--vsi-order: ${order}" />`;
    });
}

function buildTargetSvg(frame: SequenceFrame) {
  if (frame.phase === "trusted-record") return renderEmptyTargetSvg();

  return vsiTargetDotsAndScansSvg
    .replace(
      "<defs>",
      `<defs><linearGradient id="vsi-scan-band-gradient" x1="0%" x2="100%" y1="0%" y2="0%"><stop offset="0%" stop-color="rgb(241, 58, 173)" stop-opacity="0.03"/><stop offset="38%" stop-color="rgb(241, 58, 173)" stop-opacity="0.10"/><stop offset="76%" stop-color="rgb(241, 58, 173)" stop-opacity="0.22"/><stop offset="90%" stop-color="rgb(255, 156, 220)" stop-opacity="0.36"/><stop offset="100%" stop-color="rgb(241, 58, 173)" stop-opacity="0.04"/></linearGradient>`
    )
    .replace(/<g id="(target_[^"]+)"([^>]*class="vsi-guide-target"[^>]*)>/g, (match, targetId: string) => {
      const { index, state } = getTargetState(targetId, frame);
      return match
        .replace('class="vsi-guide-target"', `class="${getTargetClasses(state)}"`)
        .replace(">", ` data-vsi-target-index="${index}" data-vsi-state="${state}">`);
    })
    .replace(
      /<path([^>]*?) id="([^"]+)"([^>]*class="vsi-scan-section"[^>]*)>/g,
      (match, _before: string, scanId: string) => {
        const { index, state } = getScanState(scanId, frame);
        return renderScanSection(scanId, getScanClasses(state), index, state, getPathData(match));
      }
    )
    .replace(/<polyline([^>]*class="vsi-scan-context-line"[^>]*)>/g, (match) =>
      match.replace(
        ">",
        ` data-vsi-state="${frame.phase === "scan-captures" || frame.phase === "coverage-complete" ? "visible" : "hidden"}">`
      )
    );
}

function getGroupPosition(stage: HTMLDivElement, elements: Element[]): OverlayPosition | null {
  if (elements.length === 0) return null;

  const stageRect = stage.getBoundingClientRect();
  const centers = elements.map((element) => {
    const rect = element.getBoundingClientRect();
    return {
      x: rect.left - stageRect.left + rect.width / 2,
      y: rect.top - stageRect.top + rect.height / 2
    };
  });
  const x = centers.reduce((sum, point) => sum + point.x, 0) / centers.length;
  const y = centers.reduce((sum, point) => sum + point.y, 0) / centers.length;
  const direction: OverlayPosition["direction"] = x > stageRect.width * 0.62 ? "left" : "right";
  const left = direction === "left" ? Math.max(12, x - 12) : Math.min(stageRect.width - 12, x + 12);
  const top = Math.min(Math.max(18, y), stageRect.height - 28);

  return { direction, left, top };
}

function VsiGeometry({ geometryRef, svg }: { geometryRef: RefObject<HTMLDivElement | null>; svg: string }) {
  return (
    <div
      ref={geometryRef}
      aria-hidden="true"
      className={styles.geometry}
      dangerouslySetInnerHTML={{ __html: svg }}
    />
  );
}

function getRegisterScanStyle(frame: SequenceFrame) {
  const progress = frame.phase === "resolve-outline" ? (frame.registerProgress ?? 0) : 0;

  if (progress <= 0 || progress >= 1) return undefined;

  const scanX = registerRevealBounds.x + registerRevealBounds.width * progress;

  return {
    "--vsi-register-band-left": `${(scanX / 3879) * 100}%`,
    "--vsi-register-band-top": `${(registerRevealBounds.y / 2736) * 100}%`,
    "--vsi-register-band-height": `${(registerRevealBounds.height / 2736) * 100}%`
  } as CSSProperties;
}

function getVerificationSweepStyle(frame: SequenceFrame) {
  if (frame.phase !== "verification-sweep") return undefined;

  return {
    "--vsi-final-sweep-left": `${(registerRevealBounds.x / 3879) * 100}%`,
    "--vsi-final-sweep-top": `${(registerRevealBounds.y / 2736) * 100}%`,
    "--vsi-final-sweep-height": `${(registerRevealBounds.height / 2736) * 100}%`,
    "--vsi-final-sweep-distance": `${(registerRevealBounds.width / 3879) * 100}%`
  } as CSSProperties;
}

export function VsiProductionScene({
  onActiveStageChange,
  playback = "auto",
  selectedStage = "observe"
}: VsiProductionSceneProps) {
  const reducedMotion = useReducedMotion();
  const { inView, ref } = useInView<HTMLElement>();
  const stageRef = useRef<HTMLDivElement | null>(null);
  const geometryRef = useRef<HTMLDivElement | null>(null);
  const frame = useSequence(playback, reducedMotion, inView, selectedStage);
  const [landmarkLabels, setLandmarkLabels] = useState<LandmarkLabelOverlay[]>([]);
  const activeRailStage = getRailStage(frame);
  const activeCopy = getPanelCopy(activeRailStage, frame);
  const activeLandmarkGroup =
    frame.activeLandmarkGroupIndex === undefined ? undefined : landmarkGroups[frame.activeLandmarkGroupIndex];
  const activeCapture =
    frame.activeCaptureIndex === undefined ? undefined : captureSequence[frame.activeCaptureIndex];
  const liveValue = activeRailStage === "observe" ? "" : featureToLabel(activeCapture?.key);
  const showLabel = frame.phase === "detect-landmarks" && Boolean(activeLandmarkGroup) && !reducedMotion;
  const geometrySvg = useMemo(() => buildVsiSvg(reducedMotion ? finalFrame : frame), [frame, reducedMotion]);
  const targetSvg = useMemo(() => buildTargetSvg(reducedMotion ? finalFrame : frame), [frame, reducedMotion]);
  const registerScanStyle = getRegisterScanStyle(frame);
  const verificationSweepStyle = getVerificationSweepStyle(frame);

  useEffect(() => {
    onActiveStageChange?.(reducedMotion ? "trusted-record" : activeRailStage);
  }, [activeRailStage, onActiveStageChange, reducedMotion]);

  useEffect(() => {
    const updateOverlays = () => {
      const stage = stageRef.current;
      const root = geometryRef.current;

      if (!stage || !root) return;

      if (frame.phase === "detect-landmarks" && frame.activeLandmarkGroupIndex !== undefined) {
        const visibleGroups = [
          { index: frame.activeLandmarkGroupIndex - 1, state: "recent" as const },
          { index: frame.activeLandmarkGroupIndex, state: "current" as const }
        ].filter((group) => group.index >= 0);
        const overlays = visibleGroups.flatMap(({ index: groupIndex, state }) => {
          const group = landmarkGroups[groupIndex];
          const centerIndex = (group.features.length - 1) / 2;

          return group.features.flatMap((feature, index) => {
            const landmark =
              root.querySelector(`#landmark-${feature}-core`) ??
              root.querySelector(`#landmark-${feature}-ring`) ??
              root.querySelector(`#landmark-${feature}`);
            const position = landmark ? getGroupPosition(stage, [landmark]) : null;

            return position
              ? [
                  {
                    ...position,
                    delay: state === "current" ? index * 55 : 0,
                    feature,
                    label: featureToObserveLabel(feature),
                    offset: (index - centerIndex) * 18,
                    state
                  }
                ]
              : [];
          });
        });
        setLandmarkLabels(overlays);
      } else {
        setLandmarkLabels([]);
      }
    };

    updateOverlays();
    window.addEventListener("resize", updateOverlays);

    return () => window.removeEventListener("resize", updateOverlays);
  }, [frame.activeLandmarkGroupIndex, frame.phase]);

  return (
    <figure
      ref={ref}
      aria-label="Vehicle Spatial Intelligence animation showing landmark detection, structure connection, geometry registration, capture guidance and verified coverage."
      className={styles.vsiTechnologyDemo}
      data-phase={reducedMotion ? "trusted-record" : frame.phase}
      data-ready={inView || playback === "static"}
      data-vsi-figure
    >
      <figcaption className={styles.panel}>
        <span className={styles.panelEyebrow}>{activeCopy.label}</span>
        <div className={styles.panelCurrent}>
          <span>Current state</span>
          <strong>{activeCopy.metric}</strong>
        </div>
        {activeCopy.fieldLabel && liveValue ? (
          <dl className={styles.liveField}>
            <dt>{activeCopy.fieldLabel}</dt>
            <dd>{liveValue}</dd>
          </dl>
        ) : null}
        {activeCopy.detail ? <p>{activeCopy.detail}</p> : null}
        <ol aria-label="Vehicle Spatial Intelligence sequence" className={styles.sequence}>
          {railStages.map((stage, index) => (
            <li data-state={getStageState(stage.key, activeRailStage)} key={stage.key}>
              <span>{String(index + 1).padStart(2, "0")}</span>
              {stage.label}
            </li>
          ))}
        </ol>
      </figcaption>

      <div ref={stageRef} className={styles.stage}>
        <Image
          alt=""
          aria-hidden="true"
          className={styles.baseVehicle}
          draggable={false}
          height={1444}
          priority
          src="/assets/vsi/production/base_vehicle.png"
          width={2048}
        />
        <VsiGeometry geometryRef={geometryRef} svg={geometrySvg} />
        <div aria-hidden="true" className={`${styles.geometry} ${styles.targetGeometry}`}>
          <div dangerouslySetInnerHTML={{ __html: targetSvg }} />
        </div>
        {registerScanStyle ? (
          <div aria-hidden="true" className={styles.registerScan} style={registerScanStyle}>
            <span />
          </div>
        ) : null}
        {verificationSweepStyle ? (
          <div aria-hidden="true" className={styles.finalVerifySweep} style={verificationSweepStyle}>
            <span />
          </div>
        ) : null}
        {showLabel
          ? landmarkLabels.map((label) => (
              <div
                aria-hidden="true"
                className={styles.landmarkLabel}
                data-direction={label.direction}
                data-state={label.state}
                data-vsi-landmark-label
                key={label.feature}
                style={
                  {
                    "--vsi-label-delay": `${label.delay}ms`,
                    "--vsi-label-left": `${label.left}px`,
                    "--vsi-label-offset": `${label.offset}px`,
                    "--vsi-label-top": `${label.top}px`
                  } as CSSProperties
                }
              >
                <span />
                <strong>{label.label}</strong>
              </div>
            ))
          : null}
        {frame.phase === "verify" || frame.phase === "trusted-record" || reducedMotion ? (
          <div aria-hidden="true" className={styles.verifiedIndicator}>
            <span />
            verified
          </div>
        ) : null}
      </div>
    </figure>
  );
}

export function VsiHeroDemo() {
  const [mode, setMode] = useState<VsiPlaybackMode>("auto");
  const [activeStage, setActiveStage] = useState<VsiRailStage>("observe");
  const [selectedStage, setSelectedStage] = useState<VsiRailStage>("observe");
  const controllerStage = mode === "present" ? selectedStage : activeStage;

  function selectStage(stage: VsiRailStage) {
    setSelectedStage(stage);
    setActiveStage(stage);
  }

  return (
    <div className={styles.demoShell} data-vsi-mode={mode}>
      <div className={styles.controller} aria-label="Vehicle Spatial Intelligence playback controls">
        <div className={styles.modeSwitch} aria-label="Playback mode">
          <button aria-pressed={mode === "auto"} onClick={() => setMode("auto")} type="button">
            Auto
          </button>
          <button aria-pressed={mode === "present"} onClick={() => setMode("present")} type="button">
            Tour
          </button>
        </div>
        <ol className={styles.stageRail}>
          {railStages.map((stage) => (
            <li key={stage.key}>
              <button
                aria-current={controllerStage === stage.key ? "step" : undefined}
                data-state={getStageState(stage.key, controllerStage)}
                disabled={mode !== "present"}
                onClick={() => selectStage(stage.key)}
                type="button"
              >
                {stage.label}
              </button>
            </li>
          ))}
        </ol>
      </div>
      <VsiProductionScene
        onActiveStageChange={mode === "auto" ? setActiveStage : undefined}
        playback={mode}
        selectedStage={selectedStage}
      />
    </div>
  );
}
