import React, { Suspense, useEffect, useMemo, useRef ,useState} from 'react'
import { Canvas, useThree } from '@react-three/fiber'
import { Html } from '@react-three/drei'
import Scene, { useFetchLoader, OverlayLoader } from './scene'

// 获取 URL 参数 src:完整模型链接 max:最大缩放比 min:最小缩放比
function readParams() {
  const params = new URLSearchParams(window.location.search)
  const src = params.get('src') || ''
  const rawMin = Number(params.get('min'))
  const rawMax = Number(params.get('max'))
  const minZoom = Number.isFinite(rawMin) && rawMin > 0 ? rawMin : 1
  const maxZoom = Number.isFinite(rawMax) && rawMax > 0 ? rawMax : 4
  let zoomMin = Math.min(minZoom, maxZoom)
  const zoomMax = Math.max(minZoom, maxZoom)
  zoomMin = Math.max(1, zoomMin)
  const progressColor = params.get('progressColor')
  return { src, zoomMin, zoomMax, progressColor }
}

export default function App() {
  const { src, zoomMin, zoomMax, progressColor } = useMemo(readParams, [])
  const fetchState = useFetchLoader(src);
  const [isModelReady, setIsModelReady] = useState(false);

  // 当 URL 变化时，重置 isModelReady
  useEffect(() => {
    setIsModelReady(false);
  }, [src]);

  return (
    <div style={{ width: '100vw', height: '100vh'}}>
      <OverlayLoader 
        fetchState={fetchState} 
        isModelReady={isModelReady} 
        color={progressColor} 
        active={!!src}
      />
      <Canvas
        dpr={[1, 2]}
        gl={{ antialias: true }}
        style={{ touchAction: 'none' }}
      >
        {fetchState.blobUrl ? (
          <Scene 
            blobUrl={fetchState.blobUrl} 
            zoomMin={zoomMin} 
            zoomMax={zoomMax} 
            progressColor={progressColor}
            onModelReady={() => setIsModelReady(true)}
          />
        ) : (
           !src && <Html center style={{ width: "200px", color: "#222", fontSize: 14 }}>
            请在地址栏提供 ?src=GLB地址
          </Html>
        )}
      </Canvas>
    </div>
  )
}
