import React, { useEffect, useRef } from "react";
import { useFrame, useLoader } from "@react-three/fiber";
import { useGLTF } from "@react-three/drei";
import * as THREE from "three";
import { useControls } from "leva";
impport {useControls} from "leva";

export default function EarthAndSun() {
  const sunRef = useRef();
  const earthRef = useRef();

  const { scene: sunModel } = useGLTF("/models/sun.glb");
  const { scene: earthModel } = useGLTF("/models/earth.glb");

  // Gだけ調整可能にする
  const { G } = useControls({
    G: { value: 1, min: 0.1, max: 10, step: 0.1 },
  });
  
  const M_sun = 1000; //太陽の質量は固定
  const dt = 0.01;
  
  //速度ベクトルのrefで保持
  const velocity = useRef(new THREE.Vector3(0, 0, 0));

  //初期位置と速度設定
  useEffect(() => {
    if (!earthRef.current) return;

    earthRef.current.position.set(5, 0, 0);

    //初期速度を円運動に対応させる
    const r = 5;
    const v = Math.sqrt((G * M_sun) / r);
    velocity.current.set(0, 0, v);
  }, [G]); //Gが変わったら速度再計算

  useFrame(() => {
    if (!sunRef.current || !earthRef.current) return;

    // 太陽と地球の位置ベクトル
    const rVec = new THREE.Vector3().subVectors(earthRef.current.position, sunRef.current.position);
    const distance = rVec.length();
    const forceDir = rVec.clone().normalize().negate();

    // 万有引力加速度 a = G * M / r^2
    const acceleration = forceDir.multiplyScalar((G * M_sun) / (distance * distance));

    // 速度更新
    velocity.current.add(acceleration.multiplyScalar(dt));

    // 位置更新
    earthRef.current.position.add(velocity.current.clone().multiplyScalar(dt));

    // 自転
    earthRef.current.rotation.y += 0.01;
    sunRef.current.rotation.y += 0.002;
  });

  return (
    <>
      <primitive ref={sunRef} object={sunModel} scale={2} position={[0, 0, 0]} />
      <primitive ref={earthRef} object={earthModel} scale={0.8} />
    </>
  );
}
