// svg-symbols.jsx
// Symbol SVG components for The Living Mark
// React available globally via CDN, no imports needed

// ---------------------------------------------------------------------------
// Shared utility
// ---------------------------------------------------------------------------

function seededRandom(seed) {
  const x = Math.sin(seed * 9301 + 49297) * 49297;
  return x - Math.floor(x);
}

// ---------------------------------------------------------------------------
// 1. OuroborosSVG
//    A serpent consuming its own tail.
//    The visible segment moves endlessly around the circle.
//    Speed changes on each scroll re-entry (seed prop).
// ---------------------------------------------------------------------------

function OuroborosSVG({ seed = 0, className = '' }) {
  const id = React.useId ? React.useId() : `ouroboros-${seed}`;
  const safeId = id.replace(/:/g, '');

  // Animation speed varies with seed — 8s to 12s per revolution
  const duration = (8 + seededRandom(seed) * 4).toFixed(2);

  // Circle geometry
  const R = 80;           // serpent body radius
  const cx = 0;
  const cy = 0;
  const circumference = 2 * Math.PI * R; // ≈ 502.65

  // Dash segment: 70% visible, 30% gap
  const visibleLen = Math.round(circumference * 0.70); // ≈ 352
  const gapLen     = Math.round(circumference * 0.30); // ≈ 151

  // Trailing-fade path uses a shorter, more transparent segment
  // to simulate the gradient "dissolving tail" effect without rotating gradients
  const trailLen = Math.round(circumference * 0.25);
  const trailGap = circumference - trailLen;

  // Head detail — small jaws at the "bite" point.
  // The bite occurs at the top of the circle (12 o'clock = -π/2 radians).
  // We draw two small lines opening like jaws; they are fixed in space
  // because the dashoffset animation moves the *pattern*, not the geometry.
  // The head sits just inside the visible segment's leading edge.
  const jawLen = 9;
  const jawSpread = 14; // degrees between upper and lower jaw

  // Jaw anchor: top of circle
  const jawX = cx + R * Math.cos(-Math.PI / 2);
  const jawY = cy + R * Math.sin(-Math.PI / 2);

  // Upper jaw line: slightly above the circle tangent
  const upperAngle = (-Math.PI / 2) + (jawSpread * Math.PI / 180);
  const lowerAngle = (-Math.PI / 2) - (jawSpread * Math.PI / 180);

  const upperJawX2 = jawX + jawLen * Math.cos(upperAngle - Math.PI / 2);
  const upperJawY2 = jawY + jawLen * Math.sin(upperAngle - Math.PI / 2);
  const lowerJawX2 = jawX + jawLen * Math.cos(lowerAngle + Math.PI / 2);
  const lowerJawY2 = jawY + jawLen * Math.sin(lowerAngle + Math.PI / 2);

  // Tail tip: a fading dot at the tail end of the visible segment
  // Positioned slightly before the leading edge, along the circle
  const tailAngle = -Math.PI / 2 + (visibleLen / R); // arc length → angle
  const tailX = cx + R * Math.cos(tailAngle);
  const tailY = cy + R * Math.sin(tailAngle);

  const animId = `ouroboros-consume-${safeId}`;
  const gradId = `ouroboros-trail-${safeId}`;

  const styleBlock = `
    @keyframes ${animId} {
      from { stroke-dashoffset: 0; }
      to   { stroke-dashoffset: ${-circumference.toFixed(2)}; }
    }
    @media (prefers-reduced-motion: reduce) {
      .ouroboros-moving-${safeId} {
        animation: none !important;
        stroke-dasharray: none !important;
        stroke-dashoffset: 0 !important;
        opacity: 1 !important;
      }
      .ouroboros-trail-${safeId} { display: none; }
      .ouroboros-jaw-${safeId}   { opacity: 0.9; }
    }
  `;

  return (
    <svg
      viewBox="-110 -110 220 220"
      role="img"
      aria-label="Ouroboros: a serpent consuming its own tail, symbol of eternal return and the self-sustaining loop"
      className={className}
      style={{
        width: '100%',
        height: '100%',
        overflow: 'visible',
      }}
    >
      <defs>
        <style>{styleBlock}</style>
        {/* Radial gradient for the dot/scale texture on the body */}
        <radialGradient id={`${gradId}-body`} cx="50%" cy="50%" r="50%">
          <stop offset="0%"   stopColor="#c9a84c" stopOpacity="0.15" />
          <stop offset="100%" stopColor="#c9a84c" stopOpacity="0" />
        </radialGradient>
      </defs>

      {/* Ambient glow ring — very subtle, behind everything */}
      <circle
        cx={cx} cy={cy} r={R}
        fill="none"
        stroke="#c9a84c"
        strokeWidth="12"
        strokeOpacity="0.04"
      />

      {/* Trail layer: shorter, dimmer segment running behind the main body.
          Creates illusion of the tail dissolving as it is consumed. */}
      <circle
        cx={cx} cy={cy} r={R}
        fill="none"
        stroke="#8b4513"
        strokeWidth="3.5"
        strokeLinecap="round"
        strokeDasharray={`${trailLen} ${trailGap.toFixed(2)}`}
        className={`ouroboros-moving-${safeId} ouroboros-trail-${safeId}`}
        style={{
          animation: `${animId} ${duration}s linear infinite`,
          opacity: 0.45,
          willChange: 'stroke-dashoffset',
          transformOrigin: 'center',
        }}
      />

      {/* Main body: gold segment cycling around the circle */}
      <circle
        cx={cx} cy={cy} r={R}
        fill="none"
        stroke="#c9a84c"
        strokeWidth="3.5"
        strokeLinecap="round"
        strokeDasharray={`${visibleLen} ${gapLen}`}
        className={`ouroboros-moving-${safeId}`}
        style={{
          animation: `${animId} ${duration}s linear infinite`,
          willChange: 'stroke-dashoffset',
          transformOrigin: 'center',
        }}
      />

      {/* Scale texture: a slightly brighter narrow strip on the body's spine */}
      <circle
        cx={cx} cy={cy} r={R}
        fill="none"
        stroke="#d4a017"
        strokeWidth="1"
        strokeLinecap="round"
        strokeDasharray={`${visibleLen} ${gapLen}`}
        className={`ouroboros-moving-${safeId}`}
        style={{
          animation: `${animId} ${duration}s linear infinite`,
          opacity: 0.5,
          willChange: 'stroke-dashoffset',
          transformOrigin: 'center',
        }}
      />

      {/* Head / jaw detail — fixed at the bite point (top of circle).
          Because the dashoffset moves the visible segment past this point,
          the jaws appear at the leading edge of the segment. */}
      <g className={`ouroboros-jaw-${safeId}`} opacity="0.85">
        {/* Upper jaw */}
        <line
          x1={jawX} y1={jawY}
          x2={upperJawX2} y2={upperJawY2}
          stroke="#d4a017"
          strokeWidth="2"
          strokeLinecap="round"
        />
        {/* Lower jaw */}
        <line
          x1={jawX} y1={jawY}
          x2={lowerJawX2} y2={lowerJawY2}
          stroke="#d4a017"
          strokeWidth="2"
          strokeLinecap="round"
        />
        {/* Eye — a tiny glinting dot just back from the bite point */}
        <circle
          cx={jawX + 5 * Math.cos(-Math.PI / 2 + 0.3)}
          cy={jawY + 5 * Math.sin(-Math.PI / 2 + 0.3)}
          r="1.5"
          fill="#f5f0e8"
          opacity="0.9"
        />
      </g>

      {/* Subtle scale marks — small tick marks along the body path suggesting scales.
          Static; they exist independently of the animation. */}
      {Array.from({ length: 24 }, (_, i) => {
        const angle = (i / 24) * 2 * Math.PI - Math.PI / 2;
        const innerR = R - 5;
        const outerR = R + 5;
        const x1 = cx + innerR * Math.cos(angle);
        const y1 = cy + innerR * Math.sin(angle);
        const x2 = cx + outerR * Math.cos(angle);
        const y2 = cy + outerR * Math.sin(angle);
        return (
          <line
            key={i}
            x1={x1} y1={y1} x2={x2} y2={y2}
            stroke="#c9a84c"
            strokeWidth="0.5"
            strokeOpacity="0.12"
          />
        );
      })}
    </svg>
  );
}

// ---------------------------------------------------------------------------
// 2. ChaosStarSVG
//    Eight radiating lines from center, angles perturbed by seed.
//    Lines pulse with staggered timing; particles drift along each line.
// ---------------------------------------------------------------------------

function ChaosStarSVG({ seed = 0, className = '' }) {
  const id = React.useId ? React.useId() : `chaos-${seed}`;
  const safeId = id.replace(/:/g, '');

  const BASE_ANGLES = [0, 45, 90, 135, 180, 225, 270, 315];
  const LINE_LENGTH = 70;

  // Perturb each base angle by ±5° using the seed
  const angles = BASE_ANGLES.map((a, i) =>
    a + (seededRandom(seed + i * 7) * 10 - 5)
  );

  // Compute line endpoints in Cartesian coords (SVG, y-down)
  const lines = angles.map((deg) => {
    const rad = (deg * Math.PI) / 180;
    return {
      x2: LINE_LENGTH * Math.cos(rad),
      y2: LINE_LENGTH * Math.sin(rad),
      deg,
      rad,
    };
  });

  // Particle positions: each line gets 2 particles at different positions
  const particles = lines.flatMap(({ x2, y2, deg }, li) => {
    const count = 2;
    return Array.from({ length: count }, (_, pi) => {
      const t = 0.3 + pi * 0.35; // normalized position along line
      return {
        cx: x2 * t,
        cy: y2 * t,
        deg,
        lineIdx: li,
        particleIdx: pi,
        delay: li * 0.3 + pi * 0.7,
      };
    });
  });

  // Build keyframe + style block
  const pulseId = `chaos-pulse-${safeId}`;
  const driftId = `particle-drift-${safeId}`;

  const styleBlock = `
    @keyframes ${pulseId} {
      0%, 100% { stroke-dasharray: 70 0;  opacity: 0.65; }
      50%       { stroke-dasharray: 52 18; opacity: 1; }
    }
    @keyframes ${driftId} {
      0%, 100% { opacity: 0.3; transform: scale(0.7); }
      50%       { opacity: 0.85; transform: scale(1.3); }
    }
    @media (prefers-reduced-motion: reduce) {
      .chaos-line-${safeId} {
        animation: none !important;
        stroke-dasharray: 70 0 !important;
        opacity: 1 !important;
      }
      .chaos-particle-${safeId} {
        animation: none !important;
        opacity: 0.6 !important;
        transform: none !important;
      }
    }
  `;

  return (
    <svg
      viewBox="-90 -90 180 180"
      role="img"
      aria-label="Chaos star: eight radiating lines from a center point, symbol of infinite possibility and divergent paths"
      className={className}
      style={{ width: '100%', height: '100%', overflow: 'visible' }}
    >
      <defs>
        <style>{styleBlock}</style>
      </defs>

      {/* Center glow */}
      <circle cx="0" cy="0" r="4" fill="#c9a84c" opacity="0.18" />
      <circle cx="0" cy="0" r="2" fill="#d4a017" opacity="0.5" />

      {/* Eight radiating lines */}
      {lines.map(({ x2, y2 }, i) => (
        <line
          key={i}
          x1="0" y1="0"
          x2={x2.toFixed(3)}
          y2={y2.toFixed(3)}
          stroke="#c9a84c"
          strokeWidth="1.5"
          strokeLinecap="round"
          className={`chaos-line-${safeId}`}
          style={{
            animation: `${pulseId} ${3.2 + seededRandom(seed + i * 13) * 1.6}s ease-in-out infinite`,
            animationDelay: `${(i * 0.3).toFixed(2)}s`,
            willChange: 'stroke-dasharray, opacity',
          }}
        />
      ))}

      {/* Particles drifting outward along each line */}
      {particles.map(({ cx, cy, deg, lineIdx, particleIdx, delay }) => (
        <circle
          key={`${lineIdx}-${particleIdx}`}
          cx={cx.toFixed(3)}
          cy={cy.toFixed(3)}
          r="1.5"
          fill="#c9a84c"
          className={`chaos-particle-${safeId}`}
          style={{
            animation: `${driftId} ${2.4 + seededRandom(seed + lineIdx * 3 + particleIdx) * 1.2}s ease-in-out infinite`,
            animationDelay: `${delay.toFixed(2)}s`,
            transformOrigin: `${cx.toFixed(3)}px ${cy.toFixed(3)}px`,
            willChange: 'opacity, transform',
          }}
        />
      ))}

      {/* Fine secondary lines at half-length — subtler, gold at lower opacity.
          These do NOT vary with seed; they anchor the visual against the
          randomized outer lines. */}
      {BASE_ANGLES.map((deg, i) => {
        const rad = (deg * Math.PI) / 180;
        const halfLen = 38;
        return (
          <line
            key={`inner-${i}`}
            x1="0" y1="0"
            x2={(halfLen * Math.cos(rad)).toFixed(3)}
            y2={(halfLen * Math.sin(rad)).toFixed(3)}
            stroke="#c9a84c"
            strokeWidth="0.5"
            strokeOpacity="0.2"
            strokeLinecap="round"
          />
        );
      })}

      {/* Outer ring — very faint, grounds the composition */}
      <circle
        cx="0" cy="0" r="72"
        fill="none"
        stroke="#c9a84c"
        strokeWidth="0.5"
        strokeOpacity="0.1"
        strokeDasharray="3 6"
      />
    </svg>
  );
}

// ---------------------------------------------------------------------------
// 3. OmStrokeSVG
//    The ॐ symbol drawn via animated stroke as scroll progresses.
//    A subtle face-in-profile fades in over the symbol in the final 30%.
// ---------------------------------------------------------------------------

function OmStrokeSVG({ progress = 0, className = '' }) {
  const id = React.useId ? React.useId() : 'om-stroke';
  const safeId = id.replace(/:/g, '');

  // -------------------------------------------------------------------------
  // Om path — hand-crafted SVG path for the ॐ symbol.
  //
  // The symbol consists of:
  //   A. Lower body: a deep reversed-C curve (like the numeral 3) suggesting
  //      the waking, dreaming, and dreamless-sleep states.
  //   B. Upper hook: a small hook curving right from the top of A.
  //   C. Virama tail: a curving flourish arcing up and left.
  //   D. Bindu (dot): a small circle above.
  //   E. Chandrabindu crescent: a short arc below the dot.
  //
  // Coordinates are in a local coordinate system; viewBox is set below.
  // The path is drawn as a single continuous stroke so stroke-dashoffset
  // animation traces the whole symbol in one sweep.
  // -------------------------------------------------------------------------

  // Main Om path — one continuous compound path
  // Built from cubic Béziers approximating the classical OM glyph form
  const omPath = [
    // ---- Part A: Lower body (large curve like a '3' / ३) ----
    // Start at upper-left of the lower body
    'M -18 10',
    // Curve rightward and down, forming the upper lobe of the '3'
    'C -18 -2, 10 -8, 12 2',
    // Middle pinch — the waist between upper and lower lobes
    'C 14 8, 6 14, 0 14',
    // Lower lobe curves right and down, ending lower-right
    'C -6 14, 12 20, 14 30',
    // Bottom of lower lobe sweeps left and back up
    'C 16 42, -2 48, -14 40',
    // End of lower body — the tail hooks slightly left
    'C -22 36, -20 28, -14 26',

    // ---- Part B: Upper hook ----
    // From the midpoint of the '3' body, a hook arcs upward and right
    'M 12 2',
    'C 22 -4, 26 -18, 16 -22',
    'C 8 -26, -2 -18, 2 -10',

    // ---- Part C: Virama / tail flourish ----
    // From near the upper hook, a sweeping line arcs up and to the left
    'M 16 -22',
    'C 22 -34, 14 -52, 0 -52',

    // ---- Part E: Chandrabindu crescent ----
    // A short arc below the bindu dot
    // (Bindu dot is handled as a separate <circle> element for easier timing)
    'M -8 -64',
    'C -10 -60, -2 -56, 4 -60',
  ].join(' ');

  // -------------------------------------------------------------------------
  // Estimated path length for stroke-dasharray.
  // The total is approximated by measuring each segment's approximate arc.
  // A real implementation would use pathRef.getTotalLength() after mount;
  // we use a close estimate here (≈ 310 units) so the animation completes cleanly.
  // -------------------------------------------------------------------------
  const PATH_LENGTH = 310;

  // Draw progress: first 67% of scroll draws the stroke
  const drawProgress = Math.min(progress * 1.5, 1);
  const strokeOffset = PATH_LENGTH * (1 - drawProgress);

  // Bindu appears when stroke is > 50% drawn
  const binduOpacity = progress > 0.5
    ? Math.min((progress - 0.5) / 0.2, 1)
    : 0;

  // Crescent timing matches bindu
  const crescentOpacity = binduOpacity;

  // Face overlay: fades in from 0 to 0.2 opacity in the last 30% of scroll
  const faceOpacity = progress > 0.7
    ? Math.min(((progress - 0.7) / 0.3) * 0.22, 0.22)
    : 0;

  // Very subtle fill after stroke is fully drawn
  const fillOpacity = drawProgress >= 1 ? 0.04 : 0;

  // -------------------------------------------------------------------------
  // Face-in-profile overlay path.
  // A simplified side-profile of a human face, aligned to the Om symbol:
  //   — Brow ridge follows the upper hook of Om
  //   — Nose bridge echoes the central vertical of the '3' body
  //   — Lips rest near the Om's lower waist
  //   — Chin aligns with the lower lobe's base
  // -------------------------------------------------------------------------
  const facePath = [
    // Brow — follows the arc of Om's upper hook
    'M -6 -30',
    'C 4 -36, 16 -32, 18 -24',
    // Nose bridge descending
    'C 20 -18, 18 -8, 16 -2',
    // Nose tip — small outward bump
    'C 18 2, 20 6, 16 8',
    // Upper lip
    'C 12 10, 8 12, 4 12',
    // Lower lip
    'C 2 14, 4 18, 8 20',
    // Chin sweep down and back
    'C 12 24, 6 32, -4 34',
  ].join(' ');

  const styleBlock = `
    @media (prefers-reduced-motion: reduce) {
      .om-path-${safeId} {
        stroke-dashoffset: 0 !important;
        transition: none !important;
      }
      .om-fill-${safeId} {
        opacity: 0.04 !important;
      }
      .om-face-${safeId} {
        opacity: 0.2 !important;
      }
      .om-bindu-${safeId} {
        opacity: 1 !important;
      }
      .om-crescent-${safeId} {
        opacity: 1 !important;
      }
    }
  `;

  return (
    <svg
      viewBox="-40 -80 80 120"
      role="img"
      aria-label="Om (ॐ): the primordial symbol being inscribed by fire, its stroke drawing the waking, dreaming, and deep-sleep states into form"
      className={className}
      style={{ width: '100%', height: '100%', overflow: 'visible' }}
    >
      <defs>
        <style>{styleBlock}</style>
        {/* Glow filter for the Om stroke */}
        <filter id={`om-glow-${safeId}`} x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="1.5" result="blur" />
          <feMerge>
            <feMergeNode in="blur" />
            <feMergeNode in="SourceGraphic" />
          </feMerge>
        </filter>
      </defs>

      {/* Glow halo behind the Om — very subtle depth */}
      <path
        d={omPath}
        fill="none"
        stroke="#c9a84c"
        strokeWidth="6"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeOpacity="0.06"
        style={{ filter: `url(#om-glow-${safeId})` }}
      />

      {/* Fill — appears only when fully drawn, barely visible */}
      <path
        d={omPath}
        fill="#c9a84c"
        className={`om-fill-${safeId}`}
        style={{ opacity: fillOpacity, transition: 'opacity 0.8s ease' }}
      />

      {/* Face overlay — very subtle, blends into the Om's curves */}
      <path
        d={facePath}
        fill="none"
        stroke="#c9a84c"
        strokeWidth="0.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={`om-face-${safeId}`}
        style={{
          opacity: faceOpacity,
          transition: 'opacity 0.6s ease',
          willChange: 'opacity',
        }}
      />

      {/* Main Om stroke — drawn via stroke-dashoffset */}
      <path
        d={omPath}
        fill="none"
        stroke="#c9a84c"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeDasharray={PATH_LENGTH}
        className={`om-path-${safeId}`}
        style={{
          strokeDashoffset: strokeOffset,
          transition: 'stroke-dashoffset 0.05s linear',
          willChange: 'stroke-dashoffset',
          filter: `url(#om-glow-${safeId})`,
        }}
      />

      {/* Bindu — the dot above the Om */}
      <circle
        cx="2"
        cy="-70"
        r="3"
        fill="#c9a84c"
        className={`om-bindu-${safeId}`}
        style={{
          opacity: binduOpacity,
          transition: 'opacity 0.5s ease',
          willChange: 'opacity',
        }}
      />

      {/* Bindu inner spark — a bright center for the dot */}
      <circle
        cx="2"
        cy="-70"
        r="1.2"
        fill="#f5f0e8"
        className={`om-bindu-${safeId}`}
        style={{
          opacity: binduOpacity * 0.8,
          transition: 'opacity 0.5s ease',
        }}
      />

      {/* Chandrabindu crescent — arc below the bindu */}
      <path
        d="M -5 -64 C -6 -60, -1 -57, 4 -60"
        fill="none"
        stroke="#c9a84c"
        strokeWidth="1.5"
        strokeLinecap="round"
        className={`om-crescent-${safeId}`}
        style={{
          opacity: crescentOpacity,
          transition: 'opacity 0.5s ease',
          willChange: 'opacity',
        }}
      />
    </svg>
  );
}
