import { useState, useRef } from 'react'
import { Canvas } from '@react-three/fiber'
import { Sky, Grid } from '@react-three/drei'
import { Character } from './Character'
import { Car } from './Car'
import { WorldBorder } from './WorldBorder'
import { Mesh } from 'three'

import { CheatMenu } from './CheatMenu'
import { Ramp } from './Ramp'
import { Vector3, Euler } from 'three'

export default function App() {
  const [isDriving, setIsDriving] = useState(false)
  const [showHitboxes, setShowHitboxes] = useState(false)
  const [ramps, setRamps] = useState<{ id: number; position: [number, number, number]; rotation: [number, number, number] }[]>([])
  const carRef = useRef<Mesh>(null)

  const spawnRamp = () => {
    if (carRef.current) {
      const carPos = carRef.current.position
      const carRot = carRef.current.rotation

      // Calculate position in front of car
      const forward = new Vector3(0, 0, 1).applyEuler(carRot)
      const spawnPos = carPos.clone().add(forward.multiplyScalar(10))

      // Rotation: same as car but pitched up slightly? Or just flat?
      // Let's make it flat but rotated to face the car's direction
      // Actually, a ramp usually goes UP. If we use a box, we need to pitch it.
      // Let's pitch it up by 15 degrees (approx 0.26 rad)
      const spawnRot: [number, number, number] = [0.26, carRot.y, 0]

      setRamps(prev => [...prev, {
        id: Date.now(),
        position: [spawnPos.x, 0.5, spawnPos.z], // Ensure it's on ground
        rotation: spawnRot
      }])
    }
  }

  return (
    <>
      <Canvas camera={{ position: [0, 5, 10] }} gl={{ antialias: true }}>
        <Sky sunPosition={[100, 20, 100]} distance={5000} />
        <ambientLight intensity={0.5} />
        <pointLight position={[10, 10, 10]} />

        {/* Ground */}
        <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.5, 0]} userData={{ isGround: true }}>
          <planeGeometry args={[2500, 2500]} />
          <meshStandardMaterial color="#55aaff" />
        </mesh>

        <Grid
          args={[2500, 2500]}
          fadeDistance={2000}
          sectionSize={10}
          sectionThickness={1}
          sectionColor="#ffffff"
          cellSize={1}
          cellThickness={0.5}
          cellColor="#aaccff"
        />

        <WorldBorder />

        {ramps.map(ramp => (
          <Ramp key={ramp.id} position={ramp.position} rotation={ramp.rotation} />
        ))}

        <Character
          isDriving={isDriving}
          onEnter={() => setIsDriving(true)}
          carRef={carRef}
          showHitboxes={showHitboxes}
        />
        <Car
          ref={carRef}
          isDriving={isDriving}
          onExit={() => setIsDriving(false)}
          showHitboxes={showHitboxes}
        />
      </Canvas>
      <CheatMenu
        showHitboxes={showHitboxes}
        setShowHitboxes={setShowHitboxes}
        onSpawnRamp={spawnRamp}
      />
    </>
  )
}
