"use client";

import React, { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { EffectComposer, Bloom, Vignette } from "@react-three/postprocessing";
import { KernelSize } from "postprocessing";
import { COLORS } from "./constants";
import { damp, lerp } from "./math";
import HologramCity from "./HologramCity";
import RouteSystem from "./RouteSystem";
import VehicleFleet from "./VehicleFleet";
import AICore from "./AICore";

type Props = {
  progress: React.RefObject<number>;
  reduced?: boolean;
  isMobile?: boolean;
  /** Pause the render loop when the section is scrolled off-screen. */
  active?: boolean;
};

/** Slow cinematic camera move from a high chaotic view to a settled framing. */
function CameraRig({ progress }: { progress: React.RefObject<number> }) {
  const eased = useRef(0);
  useFrame((state, dt) => {
    const p = progress.current ?? 0;
    eased.current = damp(eased.current, p, 1.5, dt);
    const e = eased.current;
    const t = state.clock.elapsedTime;

    const radius = lerp(17, 13, e);
    const angle = lerp(-0.5, 0.45, e) + t * 0.02;
    const height = lerp(9, 6.5, e) + Math.sin(t * 0.4) * 0.3;

    const cam = state.camera;
    cam.position.x = Math.sin(angle) * radius;
    cam.position.z = Math.cos(angle) * radius;
    cam.position.y = height;
    cam.lookAt(0, 2.4, 0);
  });
  return null;
}

function OptimizationCanvas({ progress, reduced = false, isMobile = false, active = true }: Props) {
  const cityCount = isMobile ? 48 : 90;

  return (
    <Canvas
      flat
      dpr={[1, isMobile || reduced ? 1.3 : 1.6]}
      camera={{ position: [0, 9, 19], fov: 50, near: 0.1, far: 120 }}
      gl={{ antialias: !isMobile, powerPreference: "high-performance", alpha: false }}
      frameloop={active ? "always" : "never"}
    >
      <color attach="background" args={[COLORS.bg]} />
      <fog attach="fog" args={[COLORS.bg, 18, 52]} />
      <ambientLight intensity={0.6} />

      <CameraRig progress={progress} />
      <HologramCity progress={progress} count={cityCount} reduced={reduced} />
      <RouteSystem progress={progress} reduced={reduced} isMobile={isMobile} />
      <VehicleFleet progress={progress} reduced={reduced} />
      <AICore progress={progress} reduced={reduced} />

      {/* Bloom is what turns the additive-blended wireframes/beams into a real
          glowing hologram. Skipped under reduced-motion; lighter on mobile. */}
      {!reduced && (
        <EffectComposer multisampling={isMobile ? 0 : 2}>
          <Bloom
            mipmapBlur
            intensity={isMobile ? 0.7 : 1.0}
            luminanceThreshold={0.15}
            luminanceSmoothing={0.04}
            radius={isMobile ? 0.6 : 0.75}
            kernelSize={KernelSize.MEDIUM}
          />
          <Vignette eskil={false} offset={0.25} darkness={0.5} />
        </EffectComposer>
      )}
    </Canvas>
  );
}

export default React.memo(OptimizationCanvas);
