// ── DISEÑO 3D DE JOYAS — Three.js ────────────────────

function Diseno3D() {
  const { useState, useEffect, useRef } = React;

  const mountRef = useRef(null);
  const sceneRef = useRef(null);
  const rendRef  = useRef(null);
  const camRef   = useRef(null);
  const meshRef  = useRef(null);
  const animRef  = useRef(null);

  const [forma,    setForma]    = useState('anillo');
  const [metal,    setMetal]    = useState('plata');
  const [piedra,   setPiedra]   = useState('ninguna');
  const [acabado,  setAcabado]  = useState('pulido');
  const [tamano,   setTamano]   = useState(1.0);
  const [grosor,   setGrosor]   = useState(0.18);
  const [giro,     setGiro]     = useState(true);
  const [grabado,  setGrabado]  = useState('');
  const [loaded,   setLoaded]   = useState(false);
  const [error3d,  setError3d]  = useState(false);

  const METALES_3D = {
    plata:   { color:0xC0C0D0, roughness:0.15, metalness:0.95, label:'Plata 925' },
    oro18k:  { color:0xD4AF37, roughness:0.10, metalness:0.98, label:'Oro 18K'   },
    oro14k:  { color:0xCDA434, roughness:0.12, metalness:0.97, label:'Oro 14K'   },
    cobre:   { color:0xB87333, roughness:0.25, metalness:0.90, label:'Cobre'     },
    laton:   { color:0xCFB53B, roughness:0.20, metalness:0.88, label:'Latón'     },
    oroblanco:{ color:0xE8E8F0, roughness:0.10, metalness:0.99, label:'Oro Blanco'},
    ororosado:{ color:0xE8A090, roughness:0.12, metalness:0.96, label:'Oro Rosado'},
    platino: { color:0xD5D5E0, roughness:0.08, metalness:1.00, label:'Platino'   },
  };

  const PIEDRAS_3D = {
    ninguna:   null,
    diamante:  { color:0xFFFFFF, roughness:0.0,  metalness:0.1, opacity:0.85, label:'Diamante'   },
    rubi:      { color:0xCC1111, roughness:0.05, metalness:0.0, opacity:0.80, label:'Rubí'        },
    zafiro:    { color:0x1133CC, roughness:0.05, metalness:0.0, opacity:0.80, label:'Zafiro'      },
    esmeralda: { color:0x11AA44, roughness:0.05, metalness:0.0, opacity:0.80, label:'Esmeralda'   },
    amatista:  { color:0x9933AA, roughness:0.05, metalness:0.0, opacity:0.80, label:'Amatista'    },
    lapislazuli:{ color:0x2255AA, roughness:0.3, metalness:0.1, opacity:1.0,  label:'Lapislázuli' },
    turquesa:  { color:0x44AAAA, roughness:0.3, metalness:0.05,opacity:1.0,  label:'Turquesa'    },
    circones:  { color:0xEEEEFF, roughness:0.0, metalness:0.15,opacity:0.90, label:'Circones'    },
  };

  const FORMAS = [
    {id:'anillo',   label:'Anillo',    icon:'💍'},
    {id:'colgante', label:'Colgante',  icon:'📿'},
    {id:'pulsera',  label:'Pulsera',   icon:'⌚'},
    {id:'aros',     label:'Aros',      icon:'👂'},
    {id:'cadena',   label:'Cadena',    icon:'⛓'},
    {id:'argolla',  label:'Argolla',   icon:'💒'},
  ];

  // Inicializar Three.js
  useEffect(()=>{
    if (!mountRef.current) return;

    // Cargar Three.js dinámicamente
    const s = document.createElement('script');
    s.src = 'https://unpkg.com/three@0.158.0/build/three.min.js';
    s.onload = () => initScene();
    s.onerror = () => setError3d(true);
    document.head.appendChild(s);

    return () => {
      if (animRef.current) cancelAnimationFrame(animRef.current);
      if (rendRef.current) rendRef.current.dispose();
    };
  }, []);

  function initScene() {
    const THREE = window.THREE;
    if (!THREE || !mountRef.current) return;

    const w = mountRef.current.clientWidth || 400;
    const h = mountRef.current.clientHeight || 400;

    // Scene
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x0e0b08);
    sceneRef.current = scene;

    // Camera
    const camera = new THREE.PerspectiveCamera(45, w/h, 0.1, 100);
    camera.position.set(0, 0, 4);
    camRef.current = camera;

    // Renderer
    const renderer = new THREE.WebGLRenderer({ antialias:true });
    renderer.setSize(w, h);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.shadowMap.enabled = true;
    renderer.physicallyCorrectLights = true;
    mountRef.current.appendChild(renderer.domElement);
    rendRef.current = renderer;

    // Lights
    const ambient = new THREE.AmbientLight(0xffeedd, 0.6);
    scene.add(ambient);

    const dir1 = new THREE.DirectionalLight(0xffffff, 2.5);
    dir1.position.set(5, 5, 5);
    scene.add(dir1);

    const dir2 = new THREE.DirectionalLight(0xffd4a0, 1.5);
    dir2.position.set(-5, 3, -3);
    scene.add(dir2);

    const point = new THREE.PointLight(0xc9a84c, 2, 20);
    point.position.set(0, 3, 2);
    scene.add(point);

    // Orbit-like mouse control
    let isDragging = false, prevX=0, prevY=0, rotX=0, rotY=0;
    const el = renderer.domElement;
    el.addEventListener('mousedown', e=>{ isDragging=true; prevX=e.clientX; prevY=e.clientY; });
    el.addEventListener('mouseup', ()=>{ isDragging=false; });
    el.addEventListener('mousemove', e=>{
      if(!isDragging) return;
      rotY += (e.clientX-prevX)*0.01;
      rotX += (e.clientY-prevY)*0.01;
      prevX=e.clientX; prevY=e.clientY;
      if(meshRef.current) { meshRef.current.rotation.y=rotY; meshRef.current.rotation.x=rotX; }
    });

    setLoaded(true);
    buildMesh(THREE, scene, 'anillo','plata','ninguna','pulido', 1.0, 0.18);

    // Animation loop
    const animate = () => {
      animRef.current = requestAnimationFrame(animate);
      if (meshRef.current && giro) meshRef.current.rotation.y += 0.008;
      renderer.render(scene, camera);
    };
    animate();
  }

  function buildMesh(THREE, scene, forma, metal, piedra, acabado, tamano, grosor) {
    if (!THREE || !scene) return;
    // Remove old
    if (meshRef.current) { scene.remove(meshRef.current); meshRef.current = null; }

    const mInfo   = METALES_3D[metal]||METALES_3D.plata;
    const rough   = acabado==='pulido'?mInfo.roughness:acabado==='mate'?0.7:acabado==='martillado'?0.5:mInfo.roughness;
    const matMetal = new THREE.MeshStandardMaterial({
      color:mInfo.color, roughness:rough, metalness:mInfo.metalness,
      envMapIntensity:2.5
    });

    let geom;
    const group = new THREE.Group();

    if (forma==='anillo'||forma==='argolla') {
      const R = 0.9*tamano, r = grosor;
      geom = new THREE.TorusGeometry(R, r, 32, 128);
      const mesh = new THREE.Mesh(geom, matMetal);
      group.add(mesh);

      // Piedra central (solitario)
      if (piedra!=='ninguna') {
        const pInfo = PIEDRAS_3D[piedra];
        if (pInfo) {
          const pGeom = new THREE.SphereGeometry(0.22*tamano, 32, 32);
          const pMat  = new THREE.MeshStandardMaterial({
            color:pInfo.color, roughness:pInfo.roughness, metalness:pInfo.metalness,
            transparent:pInfo.opacity<1, opacity:pInfo.opacity, envMapIntensity:3
          });
          const pMesh = new THREE.Mesh(pGeom, pMat);
          pMesh.position.set(0, R+0.02, 0);
          // Engaste
          const engasteGeom = new THREE.CylinderGeometry(0.28*tamano, 0.22*tamano, 0.15, 8);
          const engaste = new THREE.Mesh(engasteGeom, matMetal);
          engaste.position.set(0, R-0.04, 0);
          group.add(pMesh, engaste);
        }
      }
    }
    else if (forma==='colgante') {
      // Teardrop / gota
      const shape = new THREE.Shape();
      shape.moveTo(0, -0.5*tamano);
      shape.bezierCurveTo(-0.4*tamano,-0.4*tamano, -0.5*tamano,0.1*tamano, 0,0.5*tamano);
      shape.bezierCurveTo(0.5*tamano,0.1*tamano, 0.4*tamano,-0.4*tamano, 0,-0.5*tamano);
      const extrudeSettings = { depth:0.08*tamano, bevelEnabled:true, bevelSize:0.04, bevelSegments:5 };
      geom = new THREE.ExtrudeGeometry(shape, extrudeSettings);
      geom.center();
      const mesh = new THREE.Mesh(geom, matMetal);
      group.add(mesh);
      // Argolla colgante
      const argGeom = new THREE.TorusGeometry(0.1*tamano, 0.03*tamano, 8, 32);
      const argMesh = new THREE.Mesh(argGeom, matMetal);
      argMesh.position.set(0, 0.6*tamano, 0);
      argMesh.rotation.x = Math.PI/2;
      group.add(argMesh);
      // Piedra incrustada
      if (piedra!=='ninguna') {
        const pInfo = PIEDRAS_3D[piedra];
        if (pInfo) {
          const pGeom = new THREE.CircleGeometry(0.2*tamano, 32);
          const pMat  = new THREE.MeshStandardMaterial({color:pInfo.color, roughness:0.02, metalness:0.1, transparent:true, opacity:pInfo.opacity});
          const pMesh = new THREE.Mesh(pGeom, pMat);
          pMesh.position.set(0, -0.05, 0.09*tamano);
          group.add(pMesh);
        }
      }
    }
    else if (forma==='pulsera') {
      geom = new THREE.TorusGeometry(1.3*tamano, grosor*0.8, 16, 120);
      const mesh = new THREE.Mesh(geom, matMetal);
      group.add(mesh);
      if (piedra!=='ninguna') {
        const pInfo = PIEDRAS_3D[piedra];
        if (pInfo) {
          for (let i=0; i<6; i++) {
            const ang = (i/6)*Math.PI*2;
            const pGeom = new THREE.SphereGeometry(0.09*tamano, 16, 16);
            const pMat  = new THREE.MeshStandardMaterial({color:pInfo.color, roughness:0.02, metalness:0.05, transparent:true, opacity:pInfo.opacity});
            const pm = new THREE.Mesh(pGeom, pMat);
            pm.position.set(Math.cos(ang)*1.3*tamano, Math.sin(ang)*1.3*tamano, 0);
            group.add(pm);
          }
        }
      }
    }
    else if (forma==='aros') {
      [-0.7,0.7].forEach(xPos=>{
        const aGeom = new THREE.TorusGeometry(0.5*tamano, grosor*0.7, 16, 64);
        const aMesh = new THREE.Mesh(aGeom, matMetal);
        aMesh.position.set(xPos*tamano, 0, 0);
        group.add(aMesh);
        if (piedra!=='ninguna') {
          const pInfo = PIEDRAS_3D[piedra];
          if(pInfo){
            const pGeom = new THREE.SphereGeometry(0.14*tamano,16,16);
            const pMat  = new THREE.MeshStandardMaterial({color:pInfo.color, roughness:0.02, metalness:0.05, transparent:true, opacity:pInfo.opacity});
            const pm = new THREE.Mesh(pGeom, pMat);
            pm.position.set(xPos*tamano, -0.5*tamano, 0);
            group.add(pm);
          }
        }
      });
    }
    else if (forma==='cadena') {
      for (let i=-4; i<=4; i++) {
        const lGeom = new THREE.TorusGeometry(0.18*tamano, 0.06*tamano, 8, 24);
        const lMesh = new THREE.Mesh(lGeom, matMetal);
        lMesh.position.set(i*0.32*tamano, 0, 0);
        lMesh.rotation.y = i%2===0 ? 0 : Math.PI/2;
        group.add(lMesh);
      }
    }

    group.castShadow = true;
    scene.add(group);
    meshRef.current = group;
  }

  // Reconstruir cuando cambian parámetros
  useEffect(()=>{
    const THREE = window.THREE;
    if (!THREE||!sceneRef.current||!loaded) return;
    buildMesh(THREE, sceneRef.current, forma, metal, piedra, acabado, tamano, grosor);
  }, [forma, metal, piedra, acabado, tamano, grosor, loaded]);

  const S = d3dStyles;

  return (
    <div style={{display:'flex',height:'100%',overflow:'hidden'}}>
      {/* Panel config */}
      <div style={S.panel}>
        <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,
          color:'var(--cream)',marginBottom:'4px'}}>Diseño 3D</div>
        <div style={{color:'var(--cream-3)',fontSize:'11px',marginBottom:'16px'}}>
          Visualiza la joya en tiempo real · Arrastra para girar
        </div>

        {/* Forma */}
        <div style={S.grupo}>
          <div style={S.label}>Tipo de Joya</div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'4px'}}>
            {FORMAS.map(f=>(
              <button key={f.id} onClick={()=>setForma(f.id)}
                style={{...S.fBtn,...(forma===f.id?S.fBtnAct:{})}}>
                <span style={{fontSize:'16px'}}>{f.icon}</span>
                <span style={{fontSize:'11px'}}>{f.label}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Metal */}
        <div style={S.grupo}>
          <div style={S.label}>Metal</div>
          <div style={{display:'flex',flexDirection:'column',gap:'3px'}}>
            {Object.entries(METALES_3D).map(([k,v])=>(
              <button key={k} onClick={()=>setMetal(k)}
                style={{...S.mBtn,...(metal===k?S.mBtnAct:{})}}>
                <div style={{width:'10px',height:'10px',borderRadius:'50%',flexShrink:0,
                  background:`#${v.color.toString(16).padStart(6,'0')}`}}/>
                <span style={{fontSize:'11px'}}>{v.label}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Piedra */}
        <div style={S.grupo}>
          <div style={S.label}>Piedra / Gema</div>
          <div style={{display:'flex',flexDirection:'column',gap:'3px'}}>
            {Object.entries(PIEDRAS_3D).map(([k,v])=>(
              <button key={k} onClick={()=>setPiedra(k)}
                style={{...S.mBtn,...(piedra===k?S.mBtnAct:{})}}>
                {v&&<div style={{width:'10px',height:'10px',borderRadius:'50%',flexShrink:0,
                  background:`#${v.color.toString(16).padStart(6,'0')}`}}/>}
                {!v&&<div style={{width:'10px',height:'10px',borderRadius:'50%',flexShrink:0,
                  background:'var(--surface)',border:'1px solid var(--border)'}}/>}
                <span style={{fontSize:'11px'}}>{v?v.label:'Sin piedra'}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Acabado */}
        <div style={S.grupo}>
          <div style={S.label}>Acabado</div>
          <div style={{display:'flex',gap:'4px',flexWrap:'wrap'}}>
            {['pulido','mate','satinado','martillado'].map(a=>(
              <button key={a} onClick={()=>setAcabado(a)}
                style={{...calcStyles.chip,...(acabado===a?calcStyles.chipAct:{}),
                  textTransform:'capitalize',fontSize:'10px'}}>
                {a}
              </button>
            ))}
          </div>
        </div>

        {/* Sliders */}
        {[
          {l:'Tamaño',k:tamano,set:setTamano,min:0.5,max:2,step:0.05},
          {l:'Grosor', k:grosor,set:setGrosor,min:0.05,max:0.4,step:0.01},
        ].map(sl=>(
          <div key={sl.l} style={S.grupo}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:'4px'}}>
              <div style={S.label}>{sl.l}</div>
              <span style={{color:'var(--gold)',fontSize:'11px',fontWeight:600}}>{sl.k.toFixed(2)}</span>
            </div>
            <input type="range" min={sl.min} max={sl.max} step={sl.step} value={sl.k}
              onChange={e=>sl.set(parseFloat(e.target.value))}
              style={{width:'100%',accentColor:'var(--gold)'}}/>
          </div>
        ))}

        {/* Giro auto */}
        <div style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'10px'}}>
          <input type="checkbox" checked={giro} onChange={e=>setGiro(e.target.checked)}
            style={{accentColor:'var(--gold)',width:'14px',height:'14px'}}/>
          <span style={{color:'var(--cream-2)',fontSize:'12px'}}>Rotación automática</span>
        </div>

        {/* Grabado */}
        <div style={S.grupo}>
          <div style={S.label}>Texto grabado (referencial)</div>
          <input style={{...calcStyles.input,fontSize:'12px'}} placeholder="Ej: Para siempre"
            value={grabado} onChange={e=>setGrabado(e.target.value)} maxLength={20}/>
        </div>

        {/* Cotizar */}
        <div style={{background:'var(--surface)',borderRadius:'10px',padding:'12px',marginTop:'8px'}}>
          <div style={{color:'var(--gold)',fontWeight:600,fontSize:'12px',marginBottom:'8px'}}>
            Resumen del diseño
          </div>
          {[
            {l:'Tipo', v: FORMAS.find(f=>f.id===forma)?.label},
            {l:'Metal',v: METALES_3D[metal]?.label},
            {l:'Piedra',v:piedra==='ninguna'?'Sin piedra':PIEDRAS_3D[piedra]?.label},
            {l:'Acabado',v:acabado.charAt(0).toUpperCase()+acabado.slice(1)},
          ].map(r=>(
            <div key={r.l} style={{display:'flex',justifyContent:'space-between',
              fontSize:'11px',marginBottom:'3px'}}>
              <span style={{color:'var(--cream-3)'}}>{r.l}</span>
              <span style={{color:'var(--cream)'}}>{r.v}</span>
            </div>
          ))}
          {grabado&&<div style={{marginTop:'6px',fontFamily:'Cormorant Garamond,serif',
            fontStyle:'italic',color:'var(--gold)',fontSize:'12px',textAlign:'center'}}>
            "{grabado}"
          </div>}
        </div>
      </div>

      {/* Viewport 3D */}
      <div style={{flex:1,display:'flex',flexDirection:'column',overflow:'hidden'}}>
        <div ref={mountRef} style={{flex:1,position:'relative',overflow:'hidden',
          background:'#0e0b08',cursor:'grab'}}>
          {error3d && (
            <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',
              justifyContent:'center',flexDirection:'column',gap:'12px',color:'var(--cream-3)'}}>
              <div style={{fontSize:'40px'}}>💍</div>
              <div style={{fontSize:'13px'}}>No se pudo cargar Three.js</div>
              <div style={{fontSize:'11px'}}>Verifica la conexión a internet</div>
            </div>
          )}
          {!loaded&&!error3d&&(
            <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',
              justifyContent:'center',flexDirection:'column',gap:'12px',color:'var(--cream-3)'}}>
              <div style={{fontSize:'32px',animation:'pulse 1.5s infinite'}}>✦</div>
              <div>Cargando motor 3D…</div>
            </div>
          )}
          {/* Overlay info */}
          {loaded&&(
            <div style={{position:'absolute',bottom:'12px',left:'50%',transform:'translateX(-50%)',
              background:'rgba(0,0,0,0.6)',backdropFilter:'blur(4px)',
              padding:'6px 14px',borderRadius:'20px',
              fontSize:'11px',color:'var(--cream-3)',whiteSpace:'nowrap'}}>
              🖱 Arrastra para girar · Scroll para zoom
            </div>
          )}
          {/* Watermark */}
          {loaded&&(
            <div style={{position:'absolute',top:'12px',left:'12px',
              fontFamily:'Cormorant Garamond,serif',fontSize:'12px',
              color:'rgba(201,168,76,0.5)',letterSpacing:'2px'}}>
              NAVARRO ✦ 3D
            </div>
          )}
        </div>

        {/* Barra inferior acciones */}
        <div style={{display:'flex',gap:'8px',padding:'12px 16px',
          borderTop:'1px solid var(--border)',background:'var(--bg-card)',flexShrink:0}}>
          <button onClick={()=>{if(meshRef.current){meshRef.current.rotation.set(0,0,0);}}}
            style={inv2Styles.btnSec}>
            ↺ Resetear vista
          </button>
          <button onClick={()=>{ if(rendRef.current&&mountRef.current){
            const link=document.createElement('a');
            link.download='navarro-diseno-3d.png';
            link.href=rendRef.current.domElement.toDataURL();
            link.click();
          }}} style={inv2Styles.btnSec}>
            📷 Capturar imagen
          </button>
          <div style={{flex:1}}/>
          <div style={{display:'flex',gap:'4px',alignItems:'center'}}>
            <span style={{color:'var(--cream-3)',fontSize:'11px'}}>Enviar a:</span>
            <button style={inv2Styles.btnSec} onClick={()=>alert('Se crea OT de Hechura con este diseño')}>
              ⚒ Nueva Hechura
            </button>
            <button style={inv2Styles.btnSec} onClick={()=>alert('Se crea cotización de Argolla con este diseño')}>
              💍 Cotizar Argolla
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

const d3dStyles = {
  panel:{ width:'240px', overflowY:'auto', padding:'16px',
    borderRight:'1px solid var(--border)', flexShrink:0 },
  grupo:{ marginBottom:'14px' },
  label:{ fontSize:'10px', color:'var(--cream-3)', fontWeight:600,
    textTransform:'uppercase', letterSpacing:'0.5px', marginBottom:'6px' },
  fBtn:{ display:'flex', flexDirection:'column', alignItems:'center', gap:'3px',
    padding:'8px 4px', background:'var(--surface)', border:'1px solid var(--border)',
    borderRadius:'7px', cursor:'pointer', fontFamily:'Inter,sans-serif' },
  fBtnAct:{ background:'var(--gold-dim)', border:'1px solid var(--gold)' },
  mBtn:{ display:'flex', alignItems:'center', gap:'8px', padding:'5px 8px',
    background:'var(--surface)', border:'1px solid var(--border)',
    borderRadius:'6px', cursor:'pointer', fontFamily:'Inter,sans-serif' },
  mBtnAct:{ background:'var(--gold-dim)', border:'1px solid var(--gold)' },
};

Object.assign(window, { Diseno3D });
