// src/viewer3d.jsx — drag-to-rotate 3D plate viewer using CSS 3D transforms.
// The placa is a thin slab; front face holds <PlacaArt>, back is white, edges are colored.

const { useState, useRef, useEffect, useCallback } = React;

function Viewer3D({ width = 320, autoSpin = false }) {
  const [rot, setRot] = useState({ x: -8, y: -22 });
  const [dragging, setDragging] = useState(false);
  const drag = useRef(null);
  const containerRef = useRef(null);
  const dragAreaRef = useRef(null);
  const rotRef = useRef(rot);
  rotRef.current = rot;

  // Auto-spin opcional. Sem dragging e sem autoSpin: mantém a posição que o usuário deixou.
  useEffect(() => {
    if (dragging || !autoSpin) return;
    let raf;
    const tick = () => {
      if (dragging) return;
      setRot(prev => ({ x: prev.x, y: prev.y + 0.25 }));
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [dragging, autoSpin]);

  const beginDrag = (clientX, clientY) => {
    drag.current = { x: clientX, y: clientY, startRot: { ...rotRef.current } };
    setDragging(true);
  };

  // Mouse: pode usar handler React normal (sem preventDefault necessário)
  const onMouseDown = (e) => {
    beginDrag(e.clientX, e.clientY);
  };

  // Touch: registrado manualmente como non-passive pra permitir preventDefault
  // (evita scroll da página enquanto arrasta o viewer 3D).
  useEffect(() => {
    const el = dragAreaRef.current;
    if (!el) return;
    const onTouchStart = (e) => {
      const t = e.touches[0];
      beginDrag(t.clientX, t.clientY);
      e.preventDefault();
    };
    el.addEventListener('touchstart', onTouchStart, { passive: false });
    return () => el.removeEventListener('touchstart', onTouchStart);
  }, []);

  useEffect(() => {
    if (!dragging) return;
    const onMove = (e) => {
      if (!drag.current) return;
      const p = 'touches' in e ? e.touches[0] : e;
      const dx = p.clientX - drag.current.x;
      const dy = p.clientY - drag.current.y;
      setRot({
        x: Math.max(-75, Math.min(75, drag.current.startRot.x - dy * 0.5)),
        y: drag.current.startRot.y + dx * 0.5,
      });
    };
    const onUp = () => { setDragging(false); drag.current = null; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove, { passive: false });
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, [dragging]);

  const reset = () => setRot({ x: -8, y: -22 });

  // placa dimensions (160x140 cm) -> 1000x875 art canvas. Slab depth ~16
  const w = width;
  const h = width * (875 / 1000);
  const depth = 14;

  return (
    <div ref={containerRef}
         className={dragging ? 'no-select' : ''}
         style={{
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 14,
         }}>
      <div
        ref={dragAreaRef}
        style={{
          width: w,
          maxWidth: '100%',
          height: h + 60,
          perspective: '1400px',
          perspectiveOrigin: '50% 50%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: dragging ? 'grabbing' : 'grab',
          position: 'relative',
          touchAction: 'none',
        }}
        onMouseDown={onMouseDown}
      >
        {/* floor shadow */}
        <div style={{
          position: 'absolute',
          bottom: 18,
          width: w * 0.8,
          height: 22,
          borderRadius: '50%',
          background: 'radial-gradient(ellipse at center, rgba(0,0,0,0.25), transparent 70%)',
          filter: 'blur(6px)',
          transform: `scaleX(${Math.max(0.4, Math.cos(rot.y * Math.PI/180))})`,
          opacity: 0.6,
        }}/>

        <div style={{
          width: w, height: h,
          position: 'relative',
          transformStyle: 'preserve-3d',
          transform: `rotateX(${rot.x}deg) rotateY(${rot.y}deg)`,
          transition: dragging ? 'none' : 'transform 0.18s cubic-bezier(.2,.7,.2,1)',
        }}>
          {/* Front face */}
          <div style={{
            position: 'absolute', inset: 0,
            transform: `translateZ(${depth/2}px)`,
            backfaceVisibility: 'hidden',
            boxShadow: '0 30px 60px -30px rgba(0,0,0,0.5)',
          }}>
            <PlacaArt size={w} />
          </div>

          {/* Back face */}
          <div style={{
            position: 'absolute', inset: 0,
            transform: `translateZ(-${depth/2}px) rotateY(180deg)`,
            background: 'linear-gradient(135deg, #f4f4f4, #d9d9d9)',
            backfaceVisibility: 'hidden',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#999',
            fontFamily: 'var(--font-mono)',
            fontSize: 11,
            letterSpacing: '0.1em',
            textTransform: 'uppercase',
          }}>
            QGV-016 · Verso
          </div>

          {/* Top edge */}
          <div style={{
            position: 'absolute',
            top: 0, left: 0, right: 0,
            height: depth,
            background: 'linear-gradient(#e5e5e5, #b8b8b8)',
            transform: `rotateX(90deg) translateZ(${depth/2}px) translateY(-${depth/2}px)`,
            transformOrigin: 'top',
          }}/>
          {/* Bottom edge */}
          <div style={{
            position: 'absolute',
            bottom: 0, left: 0, right: 0,
            height: depth,
            background: 'linear-gradient(#b8b8b8, #e5e5e5)',
            transform: `rotateX(-90deg) translateZ(${depth/2}px) translateY(${depth/2}px)`,
            transformOrigin: 'bottom',
          }}/>
          {/* Left edge */}
          <div style={{
            position: 'absolute',
            top: 0, bottom: 0, left: 0,
            width: depth,
            background: 'linear-gradient(90deg, #b8b8b8, #e5e5e5)',
            transform: `rotateY(-90deg) translateZ(${depth/2}px) translateX(-${depth/2}px)`,
            transformOrigin: 'left',
          }}/>
          {/* Right edge */}
          <div style={{
            position: 'absolute',
            top: 0, bottom: 0, right: 0,
            width: depth,
            background: 'linear-gradient(-90deg, #b8b8b8, #e5e5e5)',
            transform: `rotateY(90deg) translateZ(${depth/2}px) translateX(${depth/2}px)`,
            transformOrigin: 'right',
          }}/>
        </div>
      </div>

      {/* Controls */}
      <div style={{
        display: 'flex',
        gap: 10,
        alignItems: 'center',
        fontSize: 12,
        color: 'var(--ink-soft)',
        fontFamily: 'var(--font-mono)',
      }}>
        <span style={{ opacity: 0.7 }}>arraste para rotacionar</span>
        <span style={{ opacity: 0.4 }}>·</span>
        <button onClick={reset}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px',
            border: '1px solid var(--line)',
            borderRadius: 999,
            background: 'var(--bg-elev)',
            fontSize: 11,
            letterSpacing: '0.08em',
            textTransform: 'uppercase',
            color: 'var(--ink-soft)',
          }}>
          <IconRotate size={13}/> Reset
        </button>
        <span style={{ opacity: 0.4 }}>·</span>
        <span style={{ opacity: 0.5 }}>{Math.round(rot.y)}° / {Math.round(rot.x)}°</span>
      </div>
    </div>
  );
}

window.Viewer3D = Viewer3D;
