// ProductDetail.jsx — with lang support + full studio 3D viewer

// ── Viewer3D (원본 js/3d-viewer.js 동일 품질) ────────────────────────────────
const Viewer3D = ({ variant }) => {
  const mountRef = React.useRef(null);
  React.useEffect(() => {
    const container = mountRef.current;
    if (!container || !window.THREE) return;
    const T = window.THREE;
    const isHorizontal = variant !== "90";
    const glbFile = isHorizontal ? "beam_horizontal.glb" : "beam_vertical.glb";
    const glbPath = "assets/models/" + glbFile;

    // ── Renderer ──
    const w = container.clientWidth || 600;
    const h = container.clientHeight || 720;
    const renderer = new T.WebGLRenderer({ antialias: true, alpha: false });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    renderer.setSize(w, h);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = T.PCFSoftShadowMap;
    renderer.outputEncoding = T.sRGBEncoding;
    renderer.toneMapping = T.ReinhardToneMapping;
    renderer.toneMappingExposure = 1.2;
    container.appendChild(renderer.domElement);

    // ── Scene ──
    const scene = new T.Scene();
    scene.background = new T.Color(0x080808);

    // ── Camera ──
    const camera = new T.PerspectiveCamera(45, w / h, 0.001, 1000);
    camera.position.set(0.6, 0.4, 3.5);

    // ── Lighting ──
    if (T.RectAreaLightUniformsLib) T.RectAreaLightUniformsLib.init();
    scene.add(new T.AmbientLight(0xffffff, 0.03));

    const keyRect = new T.RectAreaLight(0xfff8f0, 3, 3.0, 1.2);
    keyRect.position.set(-0.5, 3.2, 1.8); keyRect.lookAt(0, 0, 0);
    scene.add(keyRect);

    const fillRect = new T.RectAreaLight(0xddeeff, 1.5, 1.5, 3.5);
    fillRect.position.set(-3.0, 1.0, 0.5); fillRect.lookAt(0, 0, 0);
    scene.add(fillRect);

    const rimLight = new T.DirectionalLight(0xffffff, 0.3);
    rimLight.position.set(3, 4, -4);
    scene.add(rimLight);

    const cameraLight = new T.PointLight(0xffffff, 1.5, 20, 2);
    scene.add(cameraLight);

    // ── Environment Map ──
    let envMap = null;
    try {
      const pmrem = new T.PMREMGenerator(renderer);
      const envScene = new T.Scene();
      envScene.add(Object.assign(new T.Mesh(new T.SphereGeometry(50,16,8), new T.MeshBasicMaterial({color:0x3a3a3a,side:T.BackSide}))));
      const top = new T.Mesh(new T.PlaneGeometry(10,40), new T.MeshBasicMaterial({color:0xffffff}));
      top.position.set(0,14,0); top.rotation.x = Math.PI/2; envScene.add(top);
      const left = new T.Mesh(new T.PlaneGeometry(12,24), new T.MeshBasicMaterial({color:0x999eaa}));
      left.position.set(-14,2,-2); left.rotation.y = Math.PI/2; envScene.add(left);
      const front = new T.Mesh(new T.PlaneGeometry(16,20), new T.MeshBasicMaterial({color:0xe8e8e8}));
      front.position.set(9,1,12); front.lookAt(0,0,0); envScene.add(front);
      const backLeft = new T.Mesh(new T.PlaneGeometry(12,16), new T.MeshBasicMaterial({color:0xbbbbcc}));
      backLeft.position.set(-9,1,-12); backLeft.lookAt(0,0,0); envScene.add(backLeft);
      envMap = pmrem.fromScene(envScene).texture;
      scene.environment = envMap;
      pmrem.dispose();
    } catch(e) { console.warn('[3D] envMap failed', e); }

    // ── OrbitControls ──
    const controls = new T.OrbitControls(camera, renderer.domElement);
    controls.enablePan = false; controls.enableZoom = true;
    controls.minDistance = 0.5; controls.maxDistance = 20;
    controls.autoRotate = true; controls.autoRotateSpeed = -0.35;
    controls.enableDamping = true; controls.dampingFactor = 0.06;
    controls.rotateSpeed = 0.8;

    // ── fitCamera ──
    const fitCamera = (model) => {
      let box = new T.Box3().setFromObject(model);
      const size = box.getSize(new T.Vector3());
      const maxDim = Math.max(size.x, size.y, size.z);
      if (maxDim > 0) model.scale.setScalar(2.2 / maxDim);
      box = new T.Box3().setFromObject(model);
      const center = box.getCenter(new T.Vector3());
      model.position.sub(center);
      box = new T.Box3().setFromObject(model);
      const sz = box.getSize(new T.Vector3());
      const md = Math.max(sz.x, sz.y, sz.z);
      const fovRad = (camera.fov * Math.PI) / 180;
      const dist = md / (1.4 * Math.tan(fovRad / 2));
      if (isHorizontal) {
        camera.position.set(dist*0.77, dist*0.31, dist*0.55);
      } else {
        camera.position.set(dist*0.65, dist*0.08, dist*0.85);
      }
      camera.lookAt(0, 0, 0);
      controls.target.set(0, 0, 0);
      controls.update();
    };

    // ── Load GLB ──
    let animId;
    if (T.GLTFLoader) {
      const loader = new T.GLTFLoader();
      loader.load(glbPath, (gltf) => {
        const model = gltf.scene;
        model.traverse((node) => {
          if (!node.isMesh) return;
          node.castShadow = true; node.receiveShadow = true;
          const mats = Array.isArray(node.material) ? node.material : [node.material];
          mats.forEach((mat) => {
            if (!mat || !mat.isMeshStandardMaterial) return;
            const n = mat.name || '', mesh = node.name || '';
            if (mesh === '로고파트') {
              mat.metalness=0.85; mat.roughness=0.30; mat.color.setHex(0xb0b0b0);
              mat.envMap=envMap; mat.envMapIntensity=1.0; mat.needsUpdate=true; return;
            }
            if (n === 'Satin_Acrylic') {
              mat.metalness=0; mat.roughness=0.45; mat.transparent=true; mat.opacity=0.88;
              mat.depthWrite=false; mat.side=T.DoubleSide; mat.color.setHex(0xfffaf4);
              mat.emissive.setHex(0xfff2d8); mat.emissiveIntensity=12.0;
              mat.envMap=envMap; mat.envMapIntensity=0.4; mat.needsUpdate=true; return;
            }
            if (n === '실크 스크린') {
              mat.metalness=0; mat.roughness=0.8; mat.color.setHex(0xffffff);
              mat.emissive.setHex(0x000000); mat.emissiveIntensity=0; mat.needsUpdate=true; return;
            }
            mat.envMap=envMap; mat.envMapIntensity=1.0;
            if (mat.metalness >= 0.9) {
              mat.roughnessMap=null;
              if (n.indexOf('Smooth')!==-1) { mat.metalness=0.90; mat.roughness=0.12; mat.color.setHex(0xb8b8b8); mat.envMapIntensity=1.2; }
              else if (n.indexOf('Brushed Chrome')!==-1) { mat.metalness=0.80; mat.roughness=0.62; mat.color.setHex(0x888888); mat.envMapIntensity=0.5; }
              else { mat.metalness=0.78; mat.roughness=0.55; mat.color.setHex(0x909090); mat.envMapIntensity=0.6; }
            }
            mat.needsUpdate=true;
          });
        });
        // LED 발광 라이트
        const parSpot = new T.SpotLight(0xffeedd, 300, 16, Math.PI/5, 0.4, 1.1);
        parSpot.position.set(0,-0.75,0.15); parSpot.target.position.set(0,3.0,0.15);
        model.add(parSpot); model.add(parSpot.target);
        const bulbGlow = new T.PointLight(0xfff0d8, 60, 4.0, 1.2);
        bulbGlow.position.set(0,-0.7,0.15); model.add(bulbGlow);
        const bodyGlow = new T.PointLight(0xffe8c0, 30, 2.5, 1.5);
        bodyGlow.position.set(0,-0.9,0.1); model.add(bodyGlow);
        scene.add(model);
        fitCamera(model);
      }, undefined, (err) => console.warn('[3D] load failed', err));
    }

    // ── Animate ──
    const animate = () => {
      animId = requestAnimationFrame(animate);
      controls.update();
      cameraLight.position.copy(camera.position);
      renderer.render(scene, camera);
    };
    animate();

    // ── Resize ──
    const onResize = () => {
      const nw = container.clientWidth, nh = container.clientHeight;
      if (!nh) return;
      camera.aspect = nw/nh; camera.updateProjectionMatrix();
      renderer.setSize(nw, nh);
    };
    window.addEventListener("resize", onResize);

    return () => {
      cancelAnimationFrame(animId);
      window.removeEventListener("resize", onResize);
      renderer.dispose();
      if (container.contains(renderer.domElement)) container.removeChild(renderer.domElement);
    };
  }, [variant]);
  return <div ref={mountRef} style={{ position:"absolute", inset:0, width:"100%", height:"100%" }}/>;
};

// ── ProductDetail ─────────────────────────────────────────────────────────────
const ProductDetail = ({ onAddToCart, onBack, t, onReadIdea }) => {
  const _t = t || ((k)=>k);
  const [variant, setVariant] = React.useState("90");
  const [view,    setView]    = React.useState("perspective");
  const [w, setW] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const handler = () => setW(window.innerWidth);
    window.addEventListener("resize", handler, { passive: true });
    return () => window.removeEventListener("resize", handler);
  }, []);
  const isMobile = w < 768;

  // 90° / 180° 전환 시 뷰를 perspective로 초기화
  React.useEffect(() => { setView("perspective"); }, [variant]);

  const imgMap = {
    "90-perspective":  "assets/images/001 BEAM 90 PERSPECTIVE VIEW.png",
    "90-front":        "assets/images/001 BEAM 90 FRONT VIEW.png",
    "90-side":         "assets/images/001 BEAM 90 SIDE VIEW.png",
    "180-perspective": "assets/images/001 BEAM 180 PERSPECTIVE VIEW.png",
    "180-front":       "assets/images/001 BEAM 180 FRONT VIEW.png",
    "180-side":        "assets/images/001 BEAM 180 SIDE VIEW.png",
  };
  const image = imgMap[`${variant}-${view}`] || imgMap["90-perspective"];

  return (
    <section style={{ background:"#FFFFFF", paddingBottom:96, paddingTop:72 }}>
      <style>{`
        @media (max-width: 768px) {
          .detail-spec-grid { grid-template-columns: 1fr !important; }
          .detail-spec-right { padding: 32px 20px !important; }
          .detail-image-viewer { height: 400px !important; position: relative !important; top: auto !important; }
          .detail-strip-grid { grid-template-columns: 1fr !important; }
          .detail-strip-grid > div { border-right: none !important; border-bottom: 1px solid #0A0A0A; }
        }
      `}</style>
      {/* breadcrumb */}
      <div style={{ padding:"24px 40px", borderBottom:"1px solid #E0E0E0",
        fontSize:10, letterSpacing:"0.2em", textTransform:"uppercase",
        fontWeight:500, color:"#737373", display:"flex", gap:10 }}>
        <a onClick={onBack} href="#" style={{ color:"#737373", border:0, cursor:"pointer" }}>
          {_t("breadcrumbCollection")}
        </a>
        <span>/</span>
        <span style={{ color:"#1A1A1A" }}>001 BEAM</span>
      </div>

      <div className="detail-spec-grid" style={{ display:"grid", gridTemplateColumns: isMobile ? "1fr" : "1.3fr 1fr", gap:0, alignItems:"start" }}>
        {/* image viewer — sticky left column */}
        <div className="detail-image-viewer" style={{
          background:"radial-gradient(ellipse at center,#3A3A3A 0%,#1A1A1A 70%,#0A0A0A 100%)",
          position: isMobile ? "relative" : "sticky",
          top: isMobile ? "auto" : 72,
          height: isMobile ? 400 : "calc(100vh - 72px)",
          borderRight: isMobile ? "none" : "1px solid #E0E0E0",
          borderBottom: isMobile ? "1px solid #E0E0E0" : "none",
          overflow: "hidden",
        }}>
          {view === "3d"
            ? <Viewer3D variant={variant}/>
            : <img src={image} alt="001 BEAM"
                style={{ position:"absolute", inset:0, width:"100%", height:"100%", objectFit:"cover" }}/>
          }
          {view === "3d" && (
            <span style={{
              position:"absolute", bottom:68, right:20, zIndex:11,
              fontSize:9, letterSpacing:"0.18em", textTransform:"uppercase",
              color:"rgba(255,255,255,0.35)", fontFamily:"'Inter',sans-serif",
              pointerEvents:"none",
            }}>
              ↺ DRAG TO ROTATE
            </span>
          )}
          <span style={{ position:"absolute", top:20, left:24, fontSize:10, letterSpacing:"0.2em",
            textTransform:"uppercase", fontWeight:500, color:"rgba(255,255,255,0.9)", zIndex:10 }}>
            001 BEAM · {variant}° · {view.toUpperCase()}
          </span>
          <div style={{ position:"absolute", bottom:24, left:24, display:"flex", gap:0, border:"1px solid rgba(255,255,255,0.3)", zIndex:10 }}>
            {["perspective","front","side","3d"].map(v=>(
              <button key={v} onClick={()=>setView(v)}
                style={{ background:view===v?"#FFFFFF":"transparent", color:view===v?"#000":"rgba(255,255,255,0.8)",
                  border:0, padding:"8px 14px", fontSize:10, letterSpacing:"0.15em",
                  textTransform:"uppercase", fontWeight:500, cursor:"pointer", borderRadius:0 }}>
                {v === "3d" ? "3D" : v}
              </button>
            ))}
          </div>
        </div>

        {/* spec */}
        <div className="detail-spec-right" style={{ padding: isMobile ? "32px 20px" : "56px 48px" }}>
          <div style={{ fontSize:10, letterSpacing:"0.2em", textTransform:"uppercase", fontWeight:500, color:"#737373", marginBottom:16 }}>
            {_t("detailLabel")}
          </div>
          <h1 style={{ fontSize: isMobile ? 32 : 56, fontWeight:300, letterSpacing:"-0.03em", lineHeight:1.05, margin:0, color:"#1A1A1A" }}>
            {_t("detailTitle")}
          </h1>
          <p style={{ fontFamily:"Georgia,serif", fontSize:18, lineHeight:1.7, color:"#1A1A1A", marginTop:20, maxWidth:480 }}>
            {_t("detailDesc")}
          </p>

          {/* variant selector */}
          <div style={{ marginTop:40 }}>
            <div style={{ fontSize:10, letterSpacing:"0.15em", textTransform:"uppercase", fontWeight:500, color:"#737373", marginBottom:10 }}>
              {_t("configLabel")}
            </div>
            <div style={{ display:"flex", gap:0, border:"1px solid #000" }}>
              {[{v:"90",key:"vertical"},{v:"180",key:"horizontal"}].map(opt=>(
                <button key={opt.v} onClick={()=>setVariant(opt.v)}
                  style={{ flex:1, background:variant===opt.v?"#000":"#FFF",
                    color:variant===opt.v?"#FFF":"#000", border:0, padding:"14px 18px",
                    fontSize:11, letterSpacing:"0.12em", textTransform:"uppercase", fontWeight:500,
                    cursor:"pointer", borderRadius:0, borderRight:opt.v==="90"?"1px solid #000":0 }}>
                  {_t(opt.key)}
                </button>
              ))}
            </div>
          </div>

          {/* specs */}
          <div style={{ marginTop:40 }}>
            <div style={{ fontSize:10, letterSpacing:"0.2em", textTransform:"uppercase", fontWeight:500, color:"#737373", marginBottom:0 }}>
              {_t("specLabel") || "SPEC"}
            </div>
            {[
              [_t("specMaterial"),   "SUS304 · Hairline No.4"],
              [_t("specFrame"),      "CR Steel · Powder Coat Silver"],
              [_t("specFasten"),     "M5 Threaded Rod · Flanged Nuts · Zero Adhesive"],
              [_t("specDimming"),    "Analog · Opaque Acrylic Slide · Magnetic Push-Button"],
              [_t("specDimensions"), variant==="90" ? "320 × 320 × 720 mm" : "720 × 320 × 360 mm"],
              [_t("specSocket")  || "SOCKET",   "GU10"],
              [_t("specBulb")    || "BULB",     "LED 7–10W Recommended"],
              [_t("specInput")   || "INPUT",    "AC 220V · 50/60Hz"],
              [_t("specEdition") || "EDITION",  "First Lot · 10 Units · Serial No. + Certificate"],
              [_t("specInBox")   || "IN THE BOX","001 BEAM · M5 Hex Key · User Guide"],
            ].map(([k,v])=>(
              <div key={k} style={{ display:"grid", gridTemplateColumns:"140px 1fr",
                padding:"12px 0", borderTop:"1px solid #E0E0E0" }}>
                <span style={{ fontSize:10, letterSpacing:"0.15em", textTransform:"uppercase", fontWeight:500, color:"#737373" }}>{k}</span>
                <span style={{ fontSize:13, color:"#1A1A1A", lineHeight:1.5 }}>{v}</span>
              </div>
            ))}
            <div style={{ borderTop:"1px solid #E0E0E0", paddingTop:20, marginTop:8,
              display:"flex", justifyContent:"space-between", alignItems:"baseline" }}>
              <span style={{ fontSize:10, letterSpacing:"0.15em", textTransform:"uppercase", fontWeight:500, color:"#737373" }}>{_t("specPrice")}</span>
              <span style={{ fontSize:24, fontWeight:400, letterSpacing:"-0.01em", color:"#1A1A1A" }}>₩990,000</span>
            </div>
          </div>

          <div style={{ display:"flex", gap:12, marginTop:32 }}>
            <button onClick={()=>onAddToCart?.({variant})}
              style={{ flex:1, background:"#000", color:"#FFF", border:"1px solid #000",
                padding:"16px 24px", fontSize:12, letterSpacing:"0.12em",
                textTransform:"uppercase", fontWeight:500, cursor:"pointer", borderRadius:0 }}>
              {_t("addCart")}
            </button>
            <button
              onClick={()=>onReadIdea?.()}
              style={{ background:"#FFF", color:"#000", border:"1px solid #000",
                padding:"16px 24px", fontSize:12, letterSpacing:"0.12em",
                textTransform:"uppercase", fontWeight:500, cursor:"pointer", borderRadius:0,
                transition:"background 0.2s, color 0.2s" }}
              onMouseEnter={e=>{ e.currentTarget.style.background="#000"; e.currentTarget.style.color="#FFF"; }}
              onMouseLeave={e=>{ e.currentTarget.style.background="#FFF"; e.currentTarget.style.color="#000"; }}
            >
              {_t("productIdea") || "READ THE IDEA"}
            </button>
          </div>
        </div>
      </div>

      {/* detail strip */}
      <div className="detail-strip-grid" style={{ display:"grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3,1fr)", gap:0 }}>
        {[
          "assets/images/001 BEAM DETAIL 1 VIEW.png",
          "assets/images/001 BEAM DETAIL 2 VIEW.png",
          "assets/images/001 BEAM DETAIL 3 VIEW.png",
        ].map((src,i)=>(
          <div key={src} style={{ background:"radial-gradient(ellipse at center,#3A3A3A 0%,#1A1A1A 70%,#0A0A0A 100%)",
            aspectRatio:"4/3", position:"relative", overflow:"hidden",
            borderRight:i<2?"1px solid #0A0A0A":0 }}>
            <img src={src} alt=""
              style={{ position:"absolute", inset:0, width:"100%", height:"100%", objectFit:"cover" }}/>
            <span style={{ position:"absolute", bottom:16, left:20, fontSize:9, letterSpacing:"0.2em",
              textTransform:"uppercase", fontWeight:500, color:"rgba(255,255,255,0.75)" }}>
              DETAIL · 0{i+1}
            </span>
          </div>
        ))}
      </div>
    </section>
  );
};

window.ProductDetail = ProductDetail;
