/**
 * Scene3D
 * Creates the React Three Fiber canvas used by the editor, including camera
 * reset behavior, staged lighting, and orbit controls around the loaded model.
 */
import React, { Suspense, useEffect } from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, Stage } from '@react-three/drei';
import Model from './Model';

export default function Scene3D({
  modelUrl,
  textureUrl,
  lightIntensity,
  lightAngle,
  controlsRef,
  isAutoRotate,
  visualSettings
}) {
  const intensity = Array.isArray(lightIntensity) ? lightIntensity[0] : lightIntensity;
  const angle = Array.isArray(lightAngle) ? lightAngle[0] : lightAngle;

  useEffect(() => {
    if (controlsRef.current && modelUrl) {
      controlsRef.current.reset();
    }
  }, [modelUrl, controlsRef]);

  const lightX = Math.sin(angle) * 100;
  const lightZ = Math.cos(angle) * 100;

  return (
    <Canvas camera={{ position: [0, 0, 150], fov: 20 }} className="w-full h-full">
      <Suspense fallback={null}>
        <ambientLight intensity={intensity * 0.4} />

        <directionalLight
          intensity={intensity}
          position={[lightX, 20, lightZ]}
          castShadow
        />

        <directionalLight 
          intensity={intensity * 0.2} 
          position={[-20, 50, -50]} 
          color="#ffffff" 
        />

        <Stage 
          intensity={0}
          adjustCamera={false} 
          environment={null} 
          shadows="contact"
        >
          {modelUrl && (
            <Model 
              url={modelUrl} 
              textureUrl={textureUrl || null} 
              settings={visualSettings} 
            />
          )}
        </Stage>
      </Suspense>

      <OrbitControls
        ref={controlsRef}
        makeDefault
        autoRotate={isAutoRotate}
      />
    </Canvas>
  );
}