// 3D / motion decorations — pure CSS 3D + SVG.
// All driven by --accent and --three-d-density vars on :root.

const { useEffect, useRef, useState } = React;

// Rotating peptide vial (capsule shape with red liquid)
function Vial({ size = 120, speed = 8, tilt = 15, fill = 0.6, style = {} }) {
  const w = size;
  const h = size * 2.2;
  return (
    <div className="vial-wrap" style={{ width: w, height: h, ...style, animationDuration: `${speed}s` }}>
      <svg viewBox="0 0 60 140" width={w} height={h} style={{ overflow: "visible" }}>
        <defs>
          <linearGradient id={`vial-glass-${size}`} x1="0" x2="1">
            <stop offset="0" stopColor="rgba(255,255,255,0.18)" />
            <stop offset="0.4" stopColor="rgba(255,255,255,0.04)" />
            <stop offset="0.7" stopColor="rgba(255,255,255,0.12)" />
            <stop offset="1" stopColor="rgba(255,255,255,0.02)" />
          </linearGradient>
          <linearGradient id={`vial-liquid-${size}`} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="var(--accent)" stopOpacity="0.95" />
            <stop offset="1" stopColor="var(--accent-deep)" stopOpacity="1" />
          </linearGradient>
        </defs>
        {/* cap */}
        <rect x="14" y="2" width="32" height="12" rx="2" fill="#1a1a1a" stroke="#2a2a2a" />
        <rect x="16" y="14" width="28" height="6" fill="#0a0a0a" />
        {/* glass body */}
        <rect x="10" y="20" width="40" height="110" rx="6" fill={`url(#vial-glass-${size})`} stroke="rgba(255,255,255,0.25)" strokeWidth="0.8" />
        {/* liquid */}
        <clipPath id={`liquid-clip-${size}`}>
          <rect x="11" y="20" width="38" height="109" rx="5" />
        </clipPath>
        <g clipPath={`url(#liquid-clip-${size})`}>
          <rect x="10" y={20 + (1 - fill) * 110} width="40" height={fill * 110} fill={`url(#vial-liquid-${size})`} />
          <ellipse cx="30" cy={20 + (1 - fill) * 110} rx="20" ry="3" fill="var(--accent)" opacity="0.6" />
        </g>
        {/* highlight */}
        <rect x="14" y="26" width="3" height="80" rx="1.5" fill="rgba(255,255,255,0.18)" />
        {/* label */}
        <rect x="14" y="68" width="32" height="22" fill="#0a0a0a" stroke="var(--accent)" strokeWidth="0.6" />
        <text x="30" y="82" fontSize="6" fill="var(--accent)" textAnchor="middle" fontFamily="monospace">CC-LAB</text>
      </svg>
    </div>
  );
}

// 3D rotating cube
function Cube({ size = 100, speed = 12, color = "var(--accent)", style = {} }) {
  const half = size / 2;
  const faces = [
    { transform: `translateZ(${half}px)` },
    { transform: `rotateY(180deg) translateZ(${half}px)` },
    { transform: `rotateY(90deg) translateZ(${half}px)` },
    { transform: `rotateY(-90deg) translateZ(${half}px)` },
    { transform: `rotateX(90deg) translateZ(${half}px)` },
    { transform: `rotateX(-90deg) translateZ(${half}px)` },
  ];
  return (
    <div className="cube-scene" style={{ width: size, height: size, ...style }}>
      <div className="cube-body" style={{ width: size, height: size, animationDuration: `${speed}s` }}>
        {faces.map((f, i) => (
          <div key={i} className="cube-face" style={{
            width: size, height: size,
            ...f,
            border: `1px solid ${color}`,
            background: `linear-gradient(135deg, rgba(255,255,255,0.92), rgba(238,242,248,0.55))`,
            boxShadow: `inset 0 0 30px ${color}22`
          }}>
            <div style={{ position: "absolute", inset: 8, border: `1px solid ${color}55`, opacity: 0.5 }} />
            <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", color, fontFamily: "monospace", fontSize: size / 8, letterSpacing: "0.2em" }}>
              {["X+","X-","Y+","Y-","Z+","Z-"][i]}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Wireframe torus / sphere via SVG
function Torus({ size = 180, speed = 16, style = {} }) {
  return (
    <div style={{ width: size, height: size, animation: `spin3d ${speed}s linear infinite`, transformStyle: "preserve-3d", ...style }}>
      <svg viewBox="-100 -100 200 200" width={size} height={size} style={{ overflow: "visible" }}>
        {[...Array(12)].map((_, i) => {
          const rot = (i * 180) / 12;
          return <ellipse key={`a${i}`} cx="0" cy="0" rx="80" ry="22" stroke="var(--accent)" strokeWidth="0.8" fill="none" opacity={0.5} transform={`rotate(${rot})`} />;
        })}
        {[...Array(12)].map((_, i) => {
          const a = (i * 360) / 12;
          const x = Math.cos((a * Math.PI) / 180) * 80;
          const y = Math.sin((a * Math.PI) / 180) * 80;
          return <circle key={`b${i}`} cx={x} cy={y} r="3" fill="var(--accent)" />;
        })}
      </svg>
    </div>
  );
}

// DNA double helix
function Helix({ height = 400, width = 120, speed = 10, style = {} }) {
  const rungs = 22;
  return (
    <div style={{ width, height, position: "relative", ...style }}>
      <div style={{
        position: "absolute", inset: 0,
        animation: `helixSpin ${speed}s linear infinite`,
        transformStyle: "preserve-3d",
        perspective: 800,
      }}>
        {[...Array(rungs)].map((_, i) => {
          const t = i / (rungs - 1);
          const y = t * height;
          const phase = t * Math.PI * 4;
          return (
            <div key={i} style={{
              position: "absolute", left: 0, right: 0, top: y,
              height: 2,
              transformStyle: "preserve-3d",
              animation: `rungSpin ${speed}s linear infinite`,
              animationDelay: `${-t * speed}s`,
            }}>
              <div style={{
                position: "absolute", left: "50%", top: 0, width: width * 0.8, height: 2,
                background: `linear-gradient(90deg, var(--accent), #fff2, var(--accent))`,
                transform: `translateX(-50%)`,
                opacity: 0.7,
              }} />
              <div style={{
                position: "absolute", left: "50%", top: -4, width: 10, height: 10, borderRadius: "50%",
                background: "var(--accent)",
                transform: `translateX(-50%) translateX(${Math.cos(phase) * width * 0.4}px) translateZ(${Math.sin(phase) * width * 0.4}px)`,
                boxShadow: "0 0 12px var(--accent)"
              }} />
              <div style={{
                position: "absolute", left: "50%", top: -4, width: 10, height: 10, borderRadius: "50%",
                background: "#fff",
                transform: `translateX(-50%) translateX(${-Math.cos(phase) * width * 0.4}px) translateZ(${-Math.sin(phase) * width * 0.4}px)`,
                boxShadow: "0 0 8px #fff8"
              }} />
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Floating molecule (atoms with connecting lines)
function Molecule({ size = 200, speed = 14, style = {} }) {
  const atoms = [
    { x: 0, y: 0, z: 0, r: 14 },
    { x: 60, y: -30, z: 20, r: 10 },
    { x: -50, y: -40, z: -10, r: 11 },
    { x: 40, y: 50, z: -30, r: 9 },
    { x: -40, y: 60, z: 25, r: 12 },
    { x: 0, y: -70, z: 0, r: 8 },
  ];
  const bonds = [[0,1],[0,2],[0,3],[0,4],[1,5]];
  return (
    <div style={{ width: size, height: size, perspective: 600, ...style }}>
      <div style={{
        width: "100%", height: "100%", position: "relative",
        transformStyle: "preserve-3d",
        animation: `spin3d ${speed}s linear infinite`,
      }}>
        <svg viewBox="-100 -100 200 200" width={size} height={size} style={{ position: "absolute", inset: 0, overflow: "visible" }}>
          {bonds.map(([a, b], i) => (
            <line key={i} x1={atoms[a].x} y1={atoms[a].y} x2={atoms[b].x} y2={atoms[b].y} stroke="var(--accent)" strokeWidth="1.5" opacity="0.7" />
          ))}
          {atoms.map((a, i) => (
            <g key={i} transform={`translate(${a.x},${a.y})`}>
              <circle r={a.r} fill={i === 0 ? "var(--accent-deep)" : "var(--accent)"} opacity="0.95" />
              <circle r={a.r} fill="none" stroke="var(--accent)" strokeWidth="0.6" opacity="0.6" />
            </g>
          ))}
        </svg>
      </div>
    </div>
  );
}

// Big floating background ambient — collection of shapes that drift via parallax
function AmbientField({ density = 1 }) {
  const items = [
    { Cmp: Vial, x: "8%", y: "12%", size: 90, speed: 10, depth: 0.3 },
    { Cmp: Cube, x: "82%", y: "18%", size: 110, speed: 14, depth: 0.5 },
    { Cmp: Torus, x: "75%", y: "62%", size: 200, speed: 22, depth: 0.2 },
    { Cmp: Molecule, x: "12%", y: "70%", size: 180, speed: 18, depth: 0.4 },
    { Cmp: Vial, x: "90%", y: "85%", size: 70, speed: 12, depth: 0.6 },
    { Cmp: Cube, x: "5%", y: "45%", size: 70, speed: 18, depth: 0.35 },
    { Cmp: Molecule, x: "55%", y: "8%", size: 130, speed: 20, depth: 0.25 },
    { Cmp: Torus, x: "30%", y: "92%", size: 140, speed: 26, depth: 0.45 },
  ];
  const [scrollY, setScrollY] = useState(0);
  useEffect(() => {
    const onScroll = () => setScrollY(window.scrollY);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const visible = Math.ceil(items.length * density);
  return (
    <div className="ambient-field" aria-hidden="true">
      {items.slice(0, visible).map((it, i) => (
        <div key={i} className="ambient-item" style={{
          left: it.x, top: it.y,
          transform: `translateY(${scrollY * it.depth * -0.5}px)`,
          opacity: 0.55 + it.depth * 0.2,
        }}>
          <it.Cmp size={it.size} speed={it.speed} />
        </div>
      ))}
    </div>
  );
}

// Photo-real product bottle (user-supplied shot, label text overlaid per product)
function PhotoVial({ name, mass, width = 160, style = {} }) {
  const h = width * (1048 / 610);
  const nameLen = (name || "").length;
  let nameSize = width * 0.082;
  if (nameLen > 8) nameSize = Math.max(width * 0.046, (width * 0.082 * 8) / nameLen);
  const massLen = (mass || "").length;
  let massSize = width * 0.06;
  if (massLen > 5) massSize = Math.max(width * 0.038, (width * 0.06 * 5) / massLen);
  return (
    <div className="photo-vial" style={{ width, height: h, ...style }}>
      <img src={(window.__resources && window.__resources.vialCut) || "/assets/vial-cut.png"} alt={name} draggable={false} />
      <div className="pv-name" style={{ fontSize: nameSize }}>{name}</div>
      <div className="pv-mass" style={{ fontSize: massSize }}>{mass}</div>
    </div>
  );
}

window.PhotoVial = PhotoVial;
window.Vial = Vial;
window.Cube = Cube;
window.Torus = Torus;
window.Helix = Helix;
window.Molecule = Molecule;
window.AmbientField = AmbientField;
