// terrarium.jsx — animated SVG ecosystem: the brand's centerpiece motif.
// Reusable as hero centerpiece, section background, and inline accents.

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

/* ──────────────────────────────────────────────────────────────────
   <Terrarium /> — full living-ecosystem disc.
   Used as hero centerpiece. Glass dome + soil base + breathing colonies +
   growing fronds + drifting spores. Reacts subtly to cursor.
   ────────────────────────────────────────────────────────────────── */
function Terrarium({ size = 640, intense = false, motion = true }) {
  const ref = useRef(null);
  const [tilt, setTilt] = useState({ x: 0, y: 0 });

  useEffect(() => {
    if (!motion) return;
    const onMove = (e) => {
      const el = ref.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = (e.clientX - cx) / window.innerWidth;
      const dy = (e.clientY - cy) / window.innerHeight;
      setTilt({ x: dx * 14, y: dy * 14 });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, [motion]);

  const W = 720, H = 720;

  // Generate deterministic spores
  const spores = useMemo(() => Array.from({ length: 24 }, (_, i) => ({
    x: 60 + (i * 137) % (W - 120),
    y: 200 + (i * 91) % 360,
    r: 1.2 + (i % 4) * 0.6,
    d: 6 + (i % 7),
    delay: -(i * 0.7) % 8,
  })), []);

  return (
    <div
      ref={ref}
      style={{
        position: 'relative',
        width: size, height: size, maxWidth: '92vw',
        transform: motion ? `perspective(1200px) rotateY(${tilt.x}deg) rotateX(${-tilt.y}deg)` : 'none',
        transition: 'transform 0.6s cubic-bezier(.16,.84,.32,1)',
      }}
    >
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ overflow: 'visible' }}>
        <defs>
          {/* Dome glass gradient */}
          <radialGradient id="dome" cx="38%" cy="32%" r="80%">
            <stop offset="0%"   stopColor="#FFFFFF" stopOpacity="0.85" />
            <stop offset="35%"  stopColor="#EFF7F1" stopOpacity="0.55" />
            <stop offset="75%"  stopColor="#C8E0CF" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#7FB3A0" stopOpacity="0.18" />
          </radialGradient>
          <radialGradient id="domeRim" cx="50%" cy="50%" r="50%">
            <stop offset="92%" stopColor="#7FB3A0" stopOpacity="0" />
            <stop offset="100%" stopColor="#3D6B57" stopOpacity="0.5" />
          </radialGradient>
          <linearGradient id="soil" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#5A9985" stopOpacity="0.55" />
            <stop offset="60%" stopColor="#3D6B57" stopOpacity="0.85" />
            <stop offset="100%" stopColor="#1B2823" stopOpacity="0.95" />
          </linearGradient>
          <radialGradient id="colonyA" cx="40%" cy="40%" r="60%">
            <stop offset="0%" stopColor="#E5F0E8" stopOpacity="1" />
            <stop offset="100%" stopColor="#7FB3A0" stopOpacity="0.5" />
          </radialGradient>
          <radialGradient id="colonyB" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="#F0DCD0" stopOpacity="1" />
            <stop offset="100%" stopColor="#E8B8C5" stopOpacity="0.5" />
          </radialGradient>
          <radialGradient id="colonyC" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="#FFF6E1" stopOpacity="1" />
            <stop offset="100%" stopColor="#E8C896" stopOpacity="0.5" />
          </radialGradient>
          <filter id="grain" x="0" y="0">
            <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" />
            <feColorMatrix values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.08 0" />
            <feComposite in2="SourceGraphic" operator="in" />
          </filter>
          <clipPath id="domeClip">
            <circle cx={W/2} cy={H/2} r="320" />
          </clipPath>
        </defs>

        {/* Outer aura */}
        <circle cx={W/2} cy={H/2} r="360"
          fill="none" stroke="rgba(127,179,160,0.18)" strokeWidth="1"
          style={{ transformOrigin: `${W/2}px ${H/2}px`, animation: motion ? 'breathe 8s ease-in-out infinite' : 'none' }} />
        <circle cx={W/2} cy={H/2} r="345"
          fill="none" stroke="rgba(127,179,160,0.1)" strokeWidth="1" strokeDasharray="2 6" />

        {/* DOME — glass sphere */}
        <circle cx={W/2} cy={H/2} r="320" fill="url(#dome)" />

        {/* Clipped interior: soil + flora + colonies */}
        <g clipPath="url(#domeClip)">
          {/* Soil base */}
          <path d={`M 40 ${H/2 + 120} Q ${W/2} ${H/2 + 200} ${W - 40} ${H/2 + 120} L ${W} ${H} L 0 ${H} Z`}
                fill="url(#soil)" />
          {/* Soil highlights */}
          <path d={`M 80 ${H/2 + 150} Q ${W/2} ${H/2 + 220} ${W - 80} ${H/2 + 150}`}
                fill="none" stroke="rgba(244,248,244,0.18)" strokeWidth="1.5" />

          {/* Distant haze */}
          <ellipse cx={W/2} cy={H/2 + 80} rx="240" ry="60" fill="rgba(216, 232, 222, 0.45)" filter="blur(20px)" />

          {/* COLONIES — breathing organic blobs */}
          <Colony cx={260} cy={H/2 + 60} r={56} fill="url(#colonyA)" delay={0} motion={motion} />
          <Colony cx={470} cy={H/2 + 90} r={72} fill="url(#colonyB)" delay={1.4} motion={motion} />
          <Colony cx={360} cy={H/2 + 30} r={42} fill="url(#colonyC)" delay={0.7} motion={motion} />
          <Colony cx={180} cy={H/2 + 110} r={34} fill="url(#colonyA)" delay={2.1} motion={motion} />
          <Colony cx={540} cy={H/2 + 150} r={38} fill="url(#colonyB)" delay={0.4} motion={motion} />

          {/* FRONDS — growing stems */}
          <Frond x={220} y={H/2 + 80} h={120} curl={-0.3} delay={0.5} motion={motion} />
          <Frond x={360} y={H/2 + 50} h={180} curl={0.1} delay={0.1} motion={motion} />
          <Frond x={420} y={H/2 + 70} h={140} curl={-0.2} delay={0.8} motion={motion} />
          <Frond x={500} y={H/2 + 100} h={150} curl={0.3} delay={1.1} motion={motion} />
          <Frond x={290} y={H/2 + 100} h={90}  curl={0.2} delay={1.4} motion={motion} />

          {/* SPORES drifting upward */}
          {spores.map((s, i) => (
            <circle key={i} cx={s.x} cy={s.y} r={s.r} fill="#F4F8F4" opacity="0.7"
              style={motion ? {
                animation: `float-up ${s.d}s linear ${s.delay}s infinite`,
                transformOrigin: `${s.x}px ${s.y}px`,
              } : {}}
            />
          ))}

          {/* Inner dewdrops on glass */}
          <Dew x={W/2 - 180} y={180} r={8} delay={0} motion={motion} />
          <Dew x={W/2 + 130} y={150} r={5} delay={2.4} motion={motion} />
          <Dew x={W/2 - 80}  y={120} r={3} delay={1.1} motion={motion} />
          <Dew x={W/2 + 200} y={240} r={4} delay={3.2} motion={motion} />
        </g>

        {/* DOME edge highlight */}
        <circle cx={W/2} cy={H/2} r="320" fill="none" stroke="url(#domeRim)" strokeWidth="2" />
        <circle cx={W/2} cy={H/2} r="320" fill="none" stroke="rgba(255,255,255,0.45)" strokeWidth="1" />

        {/* Specular highlight */}
        <ellipse cx={W/2 - 110} cy={H/2 - 160} rx="80" ry="46"
          fill="rgba(255,255,255,0.55)" transform={`rotate(-28 ${W/2 - 110} ${H/2 - 160})`} />
        <ellipse cx={W/2 - 140} cy={H/2 - 180} rx="22" ry="10"
          fill="rgba(255,255,255,0.9)" transform={`rotate(-28 ${W/2 - 140} ${H/2 - 180})`} />

        {/* Orbiting micro-organisms outside dome */}
        {motion && (
          <g style={{ transformOrigin: `${W/2}px ${H/2}px`, animation: 'rotate-slow 60s linear infinite' }}>
            <circle cx={W/2 + 340} cy={H/2} r="3" fill="#7FB3A0" opacity="0.6" />
            <circle cx={W/2 - 348} cy={H/2 + 8} r="2" fill="#E8B8C5" opacity="0.7" />
          </g>
        )}
        {motion && (
          <g style={{ transformOrigin: `${W/2}px ${H/2}px`, animation: 'rotate-slow 90s linear infinite reverse' }}>
            <circle cx={W/2} cy={H/2 - 352} r="2.5" fill="#E8C896" opacity="0.7" />
            <circle cx={W/2 + 12} cy={H/2 + 348} r="1.8" fill="#7FB3A0" opacity="0.5" />
          </g>
        )}
      </svg>

      {/* Label */}
      {intense && (
        <div style={{
          position: 'absolute', bottom: -14, left: '50%', transform: 'translateX(-50%)',
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'var(--moss-deep)',
          background: 'rgba(244,248,244,0.92)', padding: '5px 12px', borderRadius: 999,
          border: '0.5px solid rgba(61,107,87,0.18)',
        }}>
          live preview · skin biome model
        </div>
      )}
    </div>
  );
}

/* ── Colony: breathing organic blob ───────────────────────────── */
function Colony({ cx, cy, r, fill, delay = 0, motion = true }) {
  return (
    <g style={{
      transformOrigin: `${cx}px ${cy}px`,
      animation: motion ? `breathe 7s ease-in-out ${delay}s infinite` : 'none',
    }}>
      <circle cx={cx} cy={cy} r={r * 1.15} fill={fill} opacity="0.35" />
      <circle cx={cx} cy={cy} r={r} fill={fill} />
      {/* tiny inner cells */}
      <circle cx={cx - r*0.3} cy={cy - r*0.2} r={r*0.18} fill="rgba(255,255,255,0.5)" />
      <circle cx={cx + r*0.25} cy={cy + r*0.1} r={r*0.1} fill="rgba(255,255,255,0.4)" />
      <circle cx={cx - r*0.05} cy={cy + r*0.3} r={r*0.08} fill="rgba(255,255,255,0.5)" />
    </g>
  );
}

/* ── Frond: growing stem with leaves ───────────────────────────── */
function Frond({ x, y, h, curl = 0, delay = 0, motion = true }) {
  const cx = x + curl * h * 0.4;
  const tipX = x + curl * h;
  const tipY = y - h;
  const pathD = `M ${x} ${y} Q ${cx} ${y - h * 0.5} ${tipX} ${tipY}`;
  const len = h + 40;
  return (
    <g style={motion ? { animation: `grow 2.4s cubic-bezier(.4,0,.2,1) ${delay}s both`, ['--len']: len } : {}}>
      <path d={pathD} fill="none" stroke="#5A9985" strokeWidth="2.5" strokeLinecap="round"
            strokeDasharray={len} strokeDashoffset={motion ? len : 0} />
      {/* leaves */}
      <ellipse cx={x + curl * h * 0.3} cy={y - h * 0.35} rx="11" ry="4.5"
        fill="#7FB3A0" opacity="0.85"
        transform={`rotate(${-30 + curl*40} ${x + curl * h * 0.3} ${y - h * 0.35})`} />
      <ellipse cx={x + curl * h * 0.6} cy={y - h * 0.65} rx="9" ry="3.5"
        fill="#B8D4C2" opacity="0.9"
        transform={`rotate(${30 - curl*30} ${x + curl * h * 0.6} ${y - h * 0.65})`} />
      <circle cx={tipX} cy={tipY} r="3.5" fill="#D9E8C9" />
    </g>
  );
}

/* ── Dewdrop: shimmering droplet ──────────────────────────────── */
function Dew({ x, y, r, delay = 0, motion = true }) {
  return (
    <g style={motion ? { animation: `shimmer 4s ease-in-out ${delay}s infinite` } : {}}>
      <ellipse cx={x} cy={y} rx={r} ry={r * 1.15} fill="rgba(255,255,255,0.7)" />
      <circle cx={x - r*0.3} cy={y - r*0.4} r={r*0.3} fill="rgba(255,255,255,0.95)" />
    </g>
  );
}

/* ──────────────────────────────────────────────────────────────────
   <PetriOrnament /> — small decorative petri dish for grid layouts.
   ────────────────────────────────────────────────────────────────── */
function PetriOrnament({ size = 120, hue = 'sage' }) {
  const palettes = {
    sage:  ['#E5F0E8', '#7FB3A0', '#5A9985'],
    petal: ['#FBEFEA', '#E8B8C5', '#E8A89C'],
    honey: ['#FFF6E1', '#E8C896', '#C9A66B'],
    mint:  ['#EAF7E8', '#B8D4C2', '#7FB3A0'],
  };
  const [bg, mid, deep] = palettes[hue] || palettes.sage;
  return (
    <svg viewBox="0 0 120 120" width={size} height={size}>
      <defs>
        <radialGradient id={`pg-${hue}`} cx="38%" cy="34%" r="70%">
          <stop offset="0%" stopColor="#FFF" stopOpacity="0.95" />
          <stop offset="60%" stopColor={bg} stopOpacity="0.7" />
          <stop offset="100%" stopColor={mid} stopOpacity="0.3" />
        </radialGradient>
      </defs>
      <circle cx="60" cy="60" r="55" fill={`url(#pg-${hue})`} stroke={mid} strokeWidth="0.5" opacity="0.85" />
      <circle cx="48" cy="55" r="9"  fill={mid} opacity="0.6" />
      <circle cx="68" cy="65" r="14" fill={deep} opacity="0.45" />
      <circle cx="75" cy="48" r="5"  fill={mid} opacity="0.55" />
      <circle cx="40" cy="72" r="6"  fill={deep} opacity="0.4" />
      <ellipse cx="42" cy="42" rx="14" ry="6" fill="rgba(255,255,255,0.55)" transform="rotate(-30 42 42)" />
    </svg>
  );
}

Object.assign(window, { Terrarium, Colony, Frond, Dew, PetriOrnament });
