/* Sacred geometry SVG components — animate on mount + scroll-tied morph */
const { useEffect, useRef, useState } = React;

// Utility: stroke-dash-based "draw on" animation via CSS variable
function useDrawIn(delay = 0) {
  const [drawn, setDrawn] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setDrawn(true), delay);
    return () => clearTimeout(t);
  }, [delay]);
  return drawn;
}

// === Hero geometry: triangle + circles + axes, builds line by line ===
function HeroGeometry({ progress = 0, accent = '#c9bd9b' }) {
  // progress 0..1 drives morph between triangle and hexagram
  const drawn = useDrawIn(200);
  const morph = Math.min(1, Math.max(0, progress));
  // Triangle vertices (equilateral) on a circle radius R, rotated -90°
  const cx = 200, cy = 200, R = 130;
  const angles = [-90, 30, 150].map(a => a * Math.PI / 180);
  const triPts = angles.map(a => [cx + R * Math.cos(a), cy + R * Math.sin(a)]);
  // inverted triangle for hexagram
  const angles2 = [90, 210, 330].map(a => a * Math.PI / 180);
  const tri2Pts = angles2.map(a => [cx + R * Math.cos(a), cy + R * Math.sin(a)]);
  const triPath = `M${triPts[0][0]},${triPts[0][1]} L${triPts[1][0]},${triPts[1][1]} L${triPts[2][0]},${triPts[2][1]} Z`;
  const tri2Path = `M${tri2Pts[0][0]},${tri2Pts[0][1]} L${tri2Pts[1][0]},${tri2Pts[1][1]} L${tri2Pts[2][0]},${tri2Pts[2][1]} Z`;

  return (
    <svg viewBox="0 0 400 400" className={`hero-geom ${drawn ? 'drawn' : ''}`} style={{ '--accent': accent }}>
      <defs>
        <radialGradient id="coreGrad" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor={accent} stopOpacity="0.55" />
          <stop offset="60%" stopColor={accent} stopOpacity="0.1" />
          <stop offset="100%" stopColor={accent} stopOpacity="0" />
        </radialGradient>
        <pattern id="dotPat" width="3" height="3" patternUnits="userSpaceOnUse">
          <circle cx="1.5" cy="1.5" r="0.6" fill={accent} fillOpacity="0.7"/>
        </pattern>
      </defs>

      {/* Outer ring — slow rotation */}
      <g className="orbit-slow" style={{ transformOrigin: '200px 200px' }}>
        <circle cx={cx} cy={cy} r={R} fill="none" stroke={accent} strokeWidth="0.6" className="draw" style={{ '--len': 2 * Math.PI * R, '--dur': '2.2s', '--delay': '0.1s' }} />
      </g>

      {/* Dotted inner ring */}
      <circle cx={cx} cy={cy} r={R - 32} fill="none" stroke={accent} strokeWidth="0.5" strokeDasharray="1 4" opacity="0.6" className="fade-in" style={{ '--delay': '0.6s' }} />

      {/* Triangle */}
      <path d={triPath} fill="none" stroke={accent} strokeWidth="0.7" className="draw" style={{ '--len': 1100, '--dur': '1.6s', '--delay': '0.9s', opacity: 1 - morph * 0.15 }} />
      {/* Inverted triangle — fades in with scroll progress */}
      <path d={tri2Path} fill="none" stroke={accent} strokeWidth="0.7" opacity={morph * 0.85} />

      {/* Horizontal axis */}
      <line x1={cx - R - 30} y1={cy} x2={cx + R + 30} y2={cy} stroke={accent} strokeWidth="0.5" strokeDasharray="2 3" className="draw" style={{ '--len': 320, '--dur': '1s', '--delay': '1.4s' }} />
      {/* Vertical axis */}
      <line x1={cx} y1={cy - R - 30} x2={cx} y2={cy + R + 30} stroke={accent} strokeWidth="0.5" strokeDasharray="2 3" className="draw" style={{ '--len': 320, '--dur': '1s', '--delay': '1.5s' }} />

      {/* Arrow tip */}
      <path d={`M${cx - 4},${cy - R - 26} L${cx},${cy - R - 34} L${cx + 4},${cy - R - 26}`} fill="none" stroke={accent} strokeWidth="0.6" className="fade-in" style={{ '--delay': '2s' }} />

      {/* Vertex dots */}
      {triPts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="2.6" fill={accent} className="pop" style={{ '--delay': `${1.7 + i * 0.1}s` }} />
      ))}
      {tri2Pts.map((p, i) => (
        <circle key={`b${i}`} cx={p[0]} cy={p[1]} r="2" fill={accent} opacity={morph * 0.9} />
      ))}

      {/* Mid-line bead trail (left + right) */}
      {[-1, 1].map(dir => (
        <g key={dir}>
          {[0.35, 0.5, 0.65, 0.78, 0.88, 0.95].map((t, i) => (
            <circle key={i} cx={cx + dir * (R + 30) * t} cy={cy} r={0.8 + (1 - t) * 1.2} fill={accent} opacity="0.85" className="fade-in" style={{ '--delay': `${1.6 + i * 0.05}s` }} />
          ))}
        </g>
      ))}

      {/* Inner core — dotted disc */}
      <circle cx={cx} cy={cy} r={28 + morph * 6} fill="url(#dotPat)" className="pop" style={{ '--delay': '2.1s' }} />
      <circle cx={cx} cy={cy} r={50} fill="url(#coreGrad)" className="fade-in" style={{ '--delay': '2.3s' }} />

      {/* Tiny satellite circles, orbital */}
      <g className="orbit-rev" style={{ transformOrigin: '200px 200px' }}>
        <circle cx={cx} cy={cy - R} r="6" fill="none" stroke={accent} strokeWidth="0.6" className="pop" style={{ '--delay': '1.2s' }} />
        <circle cx={cx} cy={cy - R} r="1.8" fill={accent} className="pop" style={{ '--delay': '1.3s' }} />
      </g>
      <g className="orbit-slow" style={{ transformOrigin: '200px 200px' }}>
        <circle cx={cx + R} cy={cy} r="4" fill="none" stroke={accent} strokeWidth="0.5" />
      </g>
    </svg>
  );
}

// === Small accent: orbit/circles inset for section markers ===
function OrbitMark({ accent = '#c9bd9b', variant = 0 }) {
  const variants = [
    // Concentric
    <g key="0">
      <circle cx="40" cy="40" r="30" fill="none" stroke={accent} strokeWidth="0.6"/>
      <circle cx="40" cy="40" r="18" fill="none" stroke={accent} strokeWidth="0.5" strokeDasharray="1 2"/>
      <circle cx="40" cy="40" r="6" fill={accent} fillOpacity="0.8"/>
      <line x1="5" y1="40" x2="75" y2="40" stroke={accent} strokeWidth="0.4" strokeDasharray="1 2"/>
      <circle cx="5" cy="40" r="1.4" fill={accent}/>
      <circle cx="75" cy="40" r="1.4" fill={accent}/>
    </g>,
    // Triangle in circle
    <g key="1">
      <circle cx="40" cy="40" r="30" fill="none" stroke={accent} strokeWidth="0.6"/>
      <polygon points="40,12 65,55 15,55" fill="none" stroke={accent} strokeWidth="0.6"/>
      <circle cx="40" cy="40" r="5" fill={accent} fillOpacity="0.8"/>
      <line x1="40" y1="2" x2="40" y2="78" stroke={accent} strokeWidth="0.4" strokeDasharray="1 2"/>
    </g>,
    // Sunburst
    <g key="2">
      <circle cx="40" cy="40" r="6" fill={accent} fillOpacity="0.85"/>
      {Array.from({ length: 24 }).map((_, i) => {
        const a = (i / 24) * Math.PI * 2;
        const r1 = 10, r2 = 10 + (i % 2 === 0 ? 22 : 14);
        return <line key={i} x1={40 + Math.cos(a) * r1} y1={40 + Math.sin(a) * r1} x2={40 + Math.cos(a) * r2} y2={40 + Math.sin(a) * r2} stroke={accent} strokeWidth="0.5"/>;
      })}
    </g>,
    // Hexagram
    <g key="3">
      <circle cx="40" cy="40" r="30" fill="none" stroke={accent} strokeWidth="0.5"/>
      <polygon points="40,12 66,55 14,55" fill="none" stroke={accent} strokeWidth="0.6"/>
      <polygon points="40,68 14,25 66,25" fill="none" stroke={accent} strokeWidth="0.6"/>
      <circle cx="40" cy="40" r="4" fill={accent}/>
    </g>,
  ];
  return (
    <svg viewBox="0 0 80 80" className="orbit-mark">
      {variants[variant % variants.length]}
    </svg>
  );
}

// === Background dust / stars ===
function StarField({ count = 80 }) {
  const stars = useRef(null);
  if (!stars.current) {
    stars.current = Array.from({ length: count }).map(() => ({
      x: Math.random() * 100,
      y: Math.random() * 100,
      r: Math.random() * 1.1 + 0.2,
      d: Math.random() * 4 + 2,
      o: Math.random() * 0.6 + 0.2,
    }));
  }
  return (
    <svg className="starfield" viewBox="0 0 100 100" preserveAspectRatio="none">
      {stars.current.map((s, i) => (
        <circle key={i} cx={s.x} cy={s.y} r={s.r * 0.15} fill="#c9bd9b" opacity={s.o}>
          <animate attributeName="opacity" values={`${s.o};${s.o * 0.2};${s.o}`} dur={`${s.d}s`} repeatCount="indefinite" />
        </circle>
      ))}
    </svg>
  );
}

function EarthBg({ accent = '#c9bd9b' }) {
  return (
    <svg className="earth-bg" viewBox="0 0 600 600" aria-hidden="true">
      <defs>
        <radialGradient id="earthGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor={accent} stopOpacity="0.18"/>
          <stop offset="60%" stopColor={accent} stopOpacity="0.04"/>
          <stop offset="100%" stopColor={accent} stopOpacity="0"/>
        </radialGradient>
        <clipPath id="earthClip"><circle cx="300" cy="300" r="240"/></clipPath>
      </defs>
      <circle cx="300" cy="300" r="280" fill="url(#earthGlow)"/>
      <circle cx="300" cy="300" r="240" fill="none" stroke={accent} strokeWidth="0.8" opacity="0.55"/>
      <circle cx="300" cy="300" r="240" fill="none" stroke={accent} strokeWidth="0.4" strokeDasharray="1 4" opacity="0.4"/>
      <g clipPath="url(#earthClip)" stroke={accent} fill="none" strokeWidth="0.5" opacity="0.5">
        {[-60,-30,0,30,60].map(lat => {
          const ry = Math.cos(lat * Math.PI/180) * 240 * 0.18;
          const cy = 300 + Math.sin(lat * Math.PI/180) * 240;
          return <ellipse key={`la${lat}`} cx="300" cy={cy} rx={Math.cos(lat*Math.PI/180)*240} ry={ry}/>;
        })}
        {[-75,-45,-15,15,45,75].map(lon => {
          const rx = Math.abs(Math.sin(lon * Math.PI/180)) * 240;
          return <ellipse key={`lo${lon}`} cx="300" cy="300" rx={rx} ry="240"/>;
        })}
      </g>
      <g clipPath="url(#earthClip)" fill={accent} opacity="0.35">
        {Array.from({length: 220}).map((_, i) => {
          const a = (i * 137.5) % 360 * Math.PI / 180;
          const r = ((i * 53) % 240);
          const x = 300 + Math.cos(a) * r;
          const y = 300 + Math.sin(a) * r * 0.95;
          return <circle key={i} cx={x} cy={y} r={0.5 + (i % 3) * 0.3}/>;
        })}
      </g>
    </svg>
  );
}

Object.assign(window, { HeroGeometry, OrbitMark, StarField, EarthBg });
