import  {  useEffect, useMemo,  useState } from "react";
import { Canvas } 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 : 0.01;
  const maxZoom = Number.isFinite(rawMax) && rawMax > 0 ? rawMax : 4;
  let zoomMin = Math.min(minZoom, maxZoom);
  const zoomMax = Math.max(minZoom, maxZoom);
  zoomMin = Math.min(1, zoomMin);
  const progressColor = params.get("progressColor");
  console.log("当前参数：src:", src);
  console.log("当前参数：srzoomMinc:", zoomMin);
  console.log("当前参数：zoomMax:", zoomMax);
  console.log("当前参数：progressColor:", 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);

  useEffect(() => {
    console.log("%c╔════════════════════════════════════════════", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%c示例链接：http://localhost:5173/?src=https://houseoss.4dkankan.com/project/DEMO/usdz/static/yw2-196-high.glb&progressColor=yellow&min=0.1&max=20", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%csrc:完整模型路径，支持glb/gltf，fbx格式", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%cprogressColor:进度条背景色      ", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%cmin:可缩小的最小倍数。默认0.01，选值区间[0.01,1]    ", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%cmax:可放大的最大倍数。默认4，选值区间[1,∞]    ", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
    console.log("%c╚════════════════════════════════════════════", "color: #ff6b6b; font-weight: bold; font-size: 12px;");
  }, []);

  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>
  );
}
