"use client";

import Image from "next/image";
import React, { useEffect, useId, useRef, useState } from "react";
import styles from "./guided-capture-live-demo.module.css";

type CapturePhase = "aligning" | "ready" | "accepted";

type GuidedCaptureLiveDemoProps = {
  variant?: "compact" | "presentation" | "showcase";
};

type CaptureMessage = {
  primary: string;
  secondary: string;
};

type MiniMapTarget = {
  x: number;
  y: number;
  angle: number;
};

const CAPTURE_MESSAGES: Record<CapturePhase, CaptureMessage> = {
  aligning: {
    primary: "Move right",
    secondary: "Move slightly right until the vehicle is centered in the guide."
  },
  ready: {
    primary: "Ready to capture",
    secondary: "Hold steady and tap the button when ready."
  },
  accepted: {
    primary: "Photo accepted",
    secondary: "Continue to the next step."
  }
};

// Current close-range target contract from halo-compass CoverageMiniMap.
const CLOSE_RANGE_TARGETS: readonly MiniMapTarget[] = [
  { x: 0.1913, y: 0.2252, angle: 315 },
  { x: 0.0306, y: 0.2583, angle: 270 },
  { x: 0.0306, y: 0.4207, angle: 270 },
  { x: 0.0306, y: 0.57, angle: 270 },
  { x: 0.0306, y: 0.7583, angle: 270 },
  { x: 0.1296, y: 0.9272, angle: 225 },
  { x: 0.3247, y: 0.9493, angle: 180 },
  { x: 0.5949, y: 0.953, angle: 180 },
  { x: 0.8622, y: 0.9142, angle: 135 },
  { x: 0.9613, y: 0.7583, angle: 90 },
  { x: 0.9613, y: 0.57, angle: 90 },
  { x: 0.9613, y: 0.4142, angle: 90 },
  { x: 0.9613, y: 0.2583, angle: 90 },
  { x: 0.8622, y: 0.0765, angle: 45 },
  { x: 0.4761, y: 0.0181, angle: 0 },
  { x: 0.1296, y: 0.0765, angle: 315 }
] as const;

const ALIGNING_SCORES = {
  distance: 0.91,
  level: 0.92,
  quality: 0.86,
  alignment: 0.81
} as const;

const READY_SCORES = {
  distance: 0.91,
  level: 0.92,
  quality: 0.86,
  alignment: 0.93
} as const;

const ARTBOARD_WIDTH = 393;
const CAPTURE_SHELL_CLIP_PATH = [
  "M 0 0 H 393 V 852 H 0 Z",
  "M 30 68 H 363",
  "A 12 12 0 0 1 375 80",
  "V 532",
  "A 12 12 0 0 1 363 544",
  "H 30",
  "A 12 12 0 0 1 18 532",
  "V 80",
  "A 12 12 0 0 1 30 68",
  "Z"
].join(" ");

function TargetReticle({ ready }: { ready: boolean }) {
  return (
    <div className={`${styles.reticleWrap} ${ready ? styles.reticleReady : styles.reticleWarning}`}>
      <div className={styles.reticleRings}>
        <span className={`${styles.reticleRing} ${styles.reticleOuter3}`} />
        <span className={`${styles.reticleRing} ${styles.reticleOuter2}`} />
        <span className={`${styles.reticleRing} ${styles.reticleOuter1}`} />
        <span className={`${styles.reticleRing} ${styles.reticlePrimary}`} />
        <span className={`${styles.reticleRing} ${styles.reticleInner1}`} />
        <span className={`${styles.reticleRing} ${styles.reticleInner2}`} />
        <span className={`${styles.reticleRing} ${styles.reticleInner3}`} />
      </div>
      <span className={`${styles.reticleCrosshair} ${styles.crosshairTop}`} />
      <span className={`${styles.reticleCrosshair} ${styles.crosshairBottom}`} />
      <span className={`${styles.reticleCrosshair} ${styles.crosshairLeft}`} />
      <span className={`${styles.reticleCrosshair} ${styles.crosshairRight}`} />
      <span className={styles.reticleCenter} />
    </div>
  );
}

function LevelIndicator({ locked }: { locked: boolean }) {
  const gradientId = useId().replace(/:/g, "");
  const activeLength = locked ? 12 : 8;
  const activeStart = locked ? 44 : 48.2;

  return (
    <div className={`${styles.levelIndicator} ${locked ? styles.levelLocked : styles.levelLow}`}>
      <svg aria-hidden="true" className={styles.levelArc} viewBox="0 0 155.371 114.869">
        <defs>
          <linearGradient gradientUnits="userSpaceOnUse" id={gradientId} x1="0" x2="0" y1="3.3" y2="111.569">
            <stop className={styles.levelStopTop} offset="0%" />
            <stop className={styles.levelStopMid} offset="35%" />
            <stop className={styles.levelStopBottom} offset="100%" />
          </linearGradient>
        </defs>
        <path
          className={styles.levelArcPath}
          d="M 3.3 111.569 A 79.684 79.684 0 1 1 152.071 111.569"
          stroke={`url(#${gradientId})`}
        />
        <path
          className={styles.levelArcActive}
          d="M 3.3 111.569 A 79.684 79.684 0 1 1 152.071 111.569"
          pathLength="100"
          style={{ strokeDasharray: `${activeLength} ${100 - activeLength}`, strokeDashoffset: -activeStart }}
        />
      </svg>
      <span className={styles.levelMarker} />
      <span className={styles.levelLabel}>LEVEL</span>
    </div>
  );
}

function ReadinessTrack({ phase, alignmentProgress }: { phase: CapturePhase; alignmentProgress: number }) {
  const scores = phase === "aligning" ? ALIGNING_SCORES : READY_SCORES;
  const items = [
    ["distance", "Distance", scores.distance],
    ["level", "Level", scores.level],
    ["quality", "Quality", scores.quality],
    ["alignment", "Alignment", scores.alignment]
  ] as const;

  return (
    <div aria-label="Readiness status" className={styles.readinessTrack}>
      {items.map(([key, label, score]) => {
        const active = phase === "aligning" && key === "alignment";
        const fillWidth = active ? 28 + alignmentProgress * 58 : score * 100;

        return (
          <div className={`${styles.readinessItem} ${active ? styles.readinessActive : ""}`} key={key}>
            <span className={styles.readinessLabel}>{label}</span>
            <span
              aria-label={`${label} readiness`}
              aria-valuemax={100}
              aria-valuemin={0}
              aria-valuenow={Math.round(fillWidth)}
              className={styles.readinessBar}
              role="progressbar"
            >
              <span className={styles.readinessFill} style={{ width: `${fillWidth}%` }} />
            </span>
          </div>
        );
      })}
    </div>
  );
}

function CoverageMiniMap() {
  const activeTarget = CLOSE_RANGE_TARGETS[2];

  return (
    <div aria-label="Close-range coverage map, left front door selected" className={styles.coverageMiniMap}>
      <Image
        alt=""
        aria-hidden="true"
        className={styles.miniMapWireframe}
        height={153}
        src="/product/capture-ui/VehicleWireframe.png"
        width={115}
      />
      {CLOSE_RANGE_TARGETS.map((target, index) => (
        <span
          aria-hidden="true"
          className={`${styles.mapDot} ${index < 2 ? styles.mapDotCompleted : ""} ${index === 2 ? styles.mapDotActive : ""}`}
          key={`${target.x}-${target.y}`}
          style={{ left: `${target.x * 100}%`, top: `${target.y * 100}%` }}
        />
      ))}
      <span
        aria-hidden="true"
        className={styles.nextTargetCursor}
        style={{
          left: `${activeTarget.x * 100}%`,
          top: `${activeTarget.y * 100}%`,
          transform: `translate(-50%, -50%) rotate(${activeTarget.angle}deg)`
        }}
      >
        <i className={styles.nextTargetHalo} />
        <i className={styles.nextTargetCore} />
        <i className={styles.nextTargetHeading} />
      </span>
    </div>
  );
}

function CaptureButton({ phase, onCapture }: { phase: CapturePhase; onCapture: () => void }) {
  const enabled = phase === "ready";
  const accepted = phase === "accepted";

  return (
    <button
      aria-disabled={!enabled}
      aria-label={enabled ? "Capture photo" : "Capture unavailable"}
      className={`${styles.captureButton} ${enabled ? styles.captureButtonReady : styles.captureButtonDisabled} ${
        enabled ? styles.captureButtonReadyRing : styles.captureButtonWarningRing
      } ${accepted ? styles.captureButtonSuccess : ""}`}
      disabled={!enabled}
      onClick={onCapture}
      title={enabled ? "Ready" : "Capture unavailable"}
      type="button"
    >
      <span className={styles.captureButtonOuter}>
        <span className={styles.captureButtonRing}>
          <span className={styles.captureButtonInner} />
        </span>
      </span>
    </button>
  );
}

export function GuidedCaptureLiveDemo({ variant = "showcase" }: GuidedCaptureLiveDemoProps) {
  const shellClipId = useId().replace(/:/g, "");
  const viewportRef = useRef<HTMLDivElement>(null);
  const [phase, setPhase] = useState<CapturePhase>("aligning");
  const [alignmentProgress, setAlignmentProgress] = useState(0);
  const [replayToken, setReplayToken] = useState(0);
  const [successFxToken, setSuccessFxToken] = useState(0);
  const [reducedMotion, setReducedMotion] = useState(false);
  const [artboardScale, setArtboardScale] = useState(1);

  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;

    const updateScale = () => setArtboardScale(Math.min(1, viewport.clientWidth / ARTBOARD_WIDTH));
    updateScale();

    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", updateScale);
      return () => window.removeEventListener("resize", updateScale);
    }

    const observer = new ResizeObserver(updateScale);
    observer.observe(viewport);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const updatePreference = () => setReducedMotion(query.matches);
    updatePreference();
    query.addEventListener("change", updatePreference);
    return () => query.removeEventListener("change", updatePreference);
  }, []);

  useEffect(() => {
    if (reducedMotion) {
      setAlignmentProgress(1);
      setPhase("ready");
      return;
    }

    setPhase("aligning");
    setAlignmentProgress(0);
    let tick = 0;
    let intervalId = 0;
    let readyId = 0;
    const startId = window.setTimeout(() => {
      intervalId = window.setInterval(() => {
        tick += 1;
        setAlignmentProgress(Math.min(1, tick / 10));
        if (tick >= 10) {
          window.clearInterval(intervalId);
          readyId = window.setTimeout(() => {
            setPhase("ready");
          }, 180);
        }
      }, 120);
    }, 420);

    return () => {
      window.clearTimeout(startId);
      window.clearInterval(intervalId);
      window.clearTimeout(readyId);
    };
  }, [reducedMotion, replayToken]);

  useEffect(() => {
    if (reducedMotion || phase !== "ready") return;

    const autoCaptureId = window.setTimeout(() => {
      setPhase("accepted");
      setSuccessFxToken((current) => current + 1);
    }, 720);

    return () => window.clearTimeout(autoCaptureId);
  }, [phase, reducedMotion]);

  useEffect(() => {
    if (reducedMotion || phase !== "accepted") return;

    const loopId = window.setTimeout(() => {
      setReplayToken((current) => current + 1);
    }, 1100);

    return () => window.clearTimeout(loopId);
  }, [phase, reducedMotion]);

  const message = CAPTURE_MESSAGES[phase];
  const ready = phase !== "aligning";
  const targetX = 0.64 - alignmentProgress * 0.14;
  const targetY = 55;
  const sceneOffset = (1 - alignmentProgress) * 5.6;
  const capturedDoor = phase === "accepted";
  const lastPhotoSrc = capturedDoor
    ? "/product/guided-capture-vehicle-test.webp"
    : "/product/capture-ui/previous-fender.png";
  const lastPhotoNumber = capturedDoor ? 2 : 1;

  const capture = () => {
    if (phase !== "ready") return;
    setPhase("accepted");
    setSuccessFxToken((current) => current + 1);
  };

  return (
    <div className={styles.demo} data-guided-capture-demo data-phase={phase} data-variant={variant}>
      <div className={styles.stageHeader}>
        <span>HALO CAPTURE · SOURCE UI</span>
        <span className={styles.stageStatus}>CAMERA FEED SIMULATED</span>
      </div>

      <div className={styles.stageBody}>
        <div className={styles.captureViewport} ref={viewportRef}>
          <div
            aria-label="Halo Capture interface demonstration"
            className={styles.captureArtboard}
            style={{ transform: `scale(${artboardScale})` }}
          >
            <svg aria-hidden="true" className={styles.captureCanvasGlassDefs} focusable="false">
              <defs>
                <clipPath clipPathUnits="userSpaceOnUse" id={shellClipId}>
                  <path clipRule="evenodd" d={CAPTURE_SHELL_CLIP_PATH} fillRule="evenodd" />
                </clipPath>
              </defs>
            </svg>

            <div className={styles.captureMediaLayer} data-capture-media-layer />

            <div
              aria-hidden="true"
              className={styles.captureShellGlass}
              data-capture-shell-glass
              style={{ clipPath: `url(#${shellClipId})`, WebkitClipPath: `url(#${shellClipId})` }}
            >
              <span className={styles.captureAtmosphere} />
              <span className={styles.captureScrim} />
              <span className={styles.captureDepth} />
              <span className={styles.captureSheen} />
              <span className={styles.captureRim} />
            </div>

            <button aria-label="Exit Halo Capture demonstration" className={styles.captureExit} type="button">
              EXIT
            </button>

            <div className={styles.captureStepHeader}>
              <div className={styles.captureHeader}>
                <div className={styles.captureTitle}>
                  <div className={styles.captureTitleTop}>Capture photo 2/16</div>
                  <div className={styles.captureTitleSub}>Left Front Door</div>
                </div>
              </div>
            </div>

            <div className={styles.captureVerticalStack}>
              <div className={styles.viewfinderWrapper}>
                <div
                  aria-hidden="true"
                  className={styles.viewfinderCameraPlate}
                  data-viewfinder-camera-plate
                  style={{ transform: `translate3d(${sceneOffset}%, 0, 0)` }}
                >
                  <Image
                    alt=""
                    fill
                    priority={false}
                    sizes="357px"
                    src="/product/guided-capture-vehicle-test.webp"
                  />
                </div>

                <div className={styles.viewfinderPrimaryGuidance}>
                  <div className={`${styles.capturePill} ${ready ? styles.capturePillReady : ""}`}>
                    <span aria-hidden="true" className={styles.capturePillIconSlot}>
                      {phase === "aligning" ? (
                        <Image
                          alt=""
                          className={styles.capturePillIcon}
                          height={20}
                          src="/product/capture-ui/move-right__almost-1.svg"
                          width={20}
                        />
                      ) : null}
                    </span>
                    <span aria-live="polite" className={styles.capturePillLabel}>
                      {message.primary}
                    </span>
                  </div>
                </div>

                <div
                  className={`${styles.viewfinderMask} ${successFxToken > 0 ? styles.viewfinderSuccess : ""}`}
                >
                  <span className={styles.viewfinderGlass} />
                  <span className={styles.viewfinderEdge} />
                  <span className={styles.viewfinderFlash} key={successFxToken} />
                  <div className={styles.viewfinderOverlay}>
                    <TargetReticle ready={ready} />
                    <span
                      aria-hidden="true"
                      className={`${styles.targetDot} ${ready ? styles.targetDotLocked : ""}`}
                      data-capture-target-dot
                      style={{ left: `${targetX * 100}%`, top: `${targetY}%` }}
                    />
                    <LevelIndicator locked={ready} />
                  </div>
                </div>

                <div className={styles.viewfinderSecondaryGuidance}>
                  <div aria-live="polite" className={styles.secondaryGuidanceCard}>
                    {message.secondary}
                  </div>
                </div>
              </div>

              <div className={styles.captureReadinessTrack}>
                <ReadinessTrack alignmentProgress={alignmentProgress} phase={phase} />
              </div>
            </div>

            <div className={styles.captureDock} data-capture-dock>
              <CoverageMiniMap />

              <div className={styles.captureButtonLock}>
                <CaptureButton onCapture={capture} phase={phase} />
              </div>

              <div
                aria-label={`Last captured photo preview, photo ${lastPhotoNumber}`}
                className={styles.lastPhotoThumbnail}
                data-last-photo-preview
              >
                <Image
                  alt=""
                  className={styles.lastPhotoImage}
                  fill
                  key={lastPhotoSrc}
                  sizes="62px"
                  src={lastPhotoSrc}
                />
                <span aria-hidden="true" className={styles.lastPhotoBadge} data-last-photo-count>
                  {lastPhotoNumber}
                </span>
                <span className={styles.lastPhotoFooter}>Review</span>
              </div>
            </div>

            <Image
              alt="Halo"
              className={styles.captureBrandMark}
              height={22}
              src="/product/capture-ui/BrandMark.svg"
              width={83}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
