"use client";

import { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { Float, Stars } from "@react-three/drei";
import * as THREE from "three";

type OrbProps = {
  position: [number, number, number];
  scale: number;
  color: string;
  speed: number;
};

function Orb({ position, scale, color, speed }: OrbProps) {
  const meshRef = useRef<THREE.Mesh>(null);

  useFrame(({ clock }) => {
    const mesh = meshRef.current;
    if (!mesh) {
      return;
    }

    const t = clock.getElapsedTime() * speed;
    mesh.position.y = position[1] + Math.sin(t) * 0.2;
    mesh.rotation.x = t * 0.2;
    mesh.rotation.y = t * 0.28;
  });

  return (
    <Float speed={1.2} rotationIntensity={0.6} floatIntensity={0.5}>
      <mesh ref={meshRef} position={position} scale={scale}>
        <icosahedronGeometry args={[0.9, 10]} />
        <meshStandardMaterial
          color={color}
          roughness={0.2}
          metalness={0.4}
          transparent
          opacity={0.34}
          emissive={color}
          emissiveIntensity={0.09}
        />
      </mesh>
    </Float>
  );
}

function AccentPlane() {
  const planeRef = useRef<THREE.Mesh>(null);

  useFrame(({ clock }) => {
    const mesh = planeRef.current;
    if (!mesh) {
      return;
    }

    mesh.rotation.z = Math.sin(clock.getElapsedTime() * 0.08) * 0.1;
  });

  return (
    <mesh ref={planeRef} position={[0, -2.8, -3]} rotation={[-0.8, 0, 0]}>
      <planeGeometry args={[18, 8, 1, 1]} />
      <meshStandardMaterial color="#dcefe9" transparent opacity={0.4} />
    </mesh>
  );
}

export function ThreeBackdrop() {
  return (
    <Canvas camera={{ position: [0, 0, 7], fov: 48 }} dpr={[1, 1.6]}>
      <color attach="background" args={["#e9f2ee"]} />
      <fog attach="fog" args={["#e9f2ee", 7, 15]} />

      <ambientLight intensity={0.8} />
      <directionalLight position={[3, 6, 7]} intensity={1.1} />
      <pointLight position={[-4, 2, 4]} intensity={0.7} color="#2f7e74" />
      <pointLight position={[4, -1, 3]} intensity={0.55} color="#d97706" />

      <Stars radius={45} depth={20} count={900} factor={2.2} saturation={0.35} fade speed={0.4} />
      <AccentPlane />
      <Orb position={[-3.6, 0.8, -1.6]} scale={1.2} color="#2c8a7a" speed={0.9} />
      <Orb position={[3.2, -0.2, -2.2]} scale={1.45} color="#dc7c3f" speed={0.75} />
      <Orb position={[0, 2.1, -3.1]} scale={1.05} color="#26839a" speed={1.15} />
    </Canvas>
  );
}
