/* fungames — Advanced effects: ShinyText, DotPattern, PulseBeams, LogoMarquee, ChartCard */

function ShinyText({ children, style }) {
  return <span className="shiny-text" style={style}>{children}</span>;
}

/* Aurora — soft conic/radial light wash, light-theme tuned (warm bone palette).
   Inspired by Aceternity's aurora-background. Drop into any section with
   position: relative; overflow: hidden. Pass `intensity` 0-1, `tone` to override. */
function Aurora({ intensity = 0.55, tone = 'warm', className = '', style }) {
  const tones = {
    warm: { a: 'rgba(255,122,60,0.40)', b: 'rgba(184,69,12,0.28)', c: 'rgba(255,231,223,0.55)', d: 'rgba(184,133,60,0.22)' },
    cool: { a: 'rgba(110,154,214,0.55)', b: 'rgba(30,58,95,0.42)', c: 'rgba(219,228,237,0.70)', d: 'rgba(79,107,74,0.32)' },
    mix:  { a: 'rgba(255,122,60,0.50)', b: 'rgba(30,58,95,0.38)', c: 'rgba(184,133,60,0.36)', d: 'rgba(184,69,12,0.30)' },
  };
  const t = tones[tone] || tones.warm;
  return (
    <div
      aria-hidden="true"
      className={`aurora ${className}`}
      style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        opacity: intensity, overflow: 'hidden',
        ...style,
      }}
    >
      <div className="aurora-layer aurora-layer-1" style={{ '--c1': t.a, '--c2': t.b }} />
      <div className="aurora-layer aurora-layer-2" style={{ '--c1': t.c, '--c2': t.d }} />
      <div className="aurora-grain" />
    </div>
  );
}

function DotPattern({ className = '', style }) {
  return (
    <div
      className={`dot-pattern dot-pattern-mask ${className}`}
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none', ...style }}
    />
  );
}

/* Pulse Beams — radial nodes connected to a center hub.
   Light theme variant tuned for rust/bone palette. */
function PulseBeams({ height = 320 }) {
  const cx = 400, cy = height / 2;
  const nodes = [
    { x: 80,  y: 60,  label: 'OPERATOR' },
    { x: 80,  y: cy,  label: 'AGGREGATOR' },
    { x: 80,  y: height - 60, label: 'WALLET' },
    { x: 720, y: 60,  label: 'GLI-19' },
    { x: 720, y: cy,  label: 'AUDIT' },
    { x: 720, y: height - 60, label: 'PLAYER' },
  ];
  return (
    <div style={{ position: 'relative', width: '100%', height, overflow: 'hidden', borderRadius: 'var(--r-card)', background: 'linear-gradient(180deg, var(--chalk) 0%, var(--bone) 100%)', border: '1px solid var(--hairline)' }}>
      <div className="dot-pattern dot-pattern-mask" style={{ position: 'absolute', inset: 0, opacity: 0.55 }} />
      <svg viewBox={`0 0 800 ${height}`} preserveAspectRatio="xMidYMid meet" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <radialGradient id="pb-hub" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="var(--rust)" stopOpacity="0.9"/>
            <stop offset="100%" stopColor="var(--rust)" stopOpacity="0"/>
          </radialGradient>
        </defs>
        {nodes.map((n, i) => (
          <line key={`l${i}`} className="pulse-beam" x1={n.x} y1={n.y} x2={cx} y2={cy} stroke="var(--rust)" strokeOpacity="0.55" strokeWidth="1.4" style={{ animationDelay: `${i * 0.18}s` }}/>
        ))}
        {nodes.map((n, i) => (
          <g key={`n${i}`}>
            <circle className="pulse-node" cx={n.x} cy={n.y} r="10" fill="none" stroke="var(--rust)" strokeWidth="1.5" style={{ animationDelay: `${i * 0.3}s` }}/>
            <circle cx={n.x} cy={n.y} r="4" fill="var(--rust)"/>
            <text x={n.x} y={n.y + (n.y > cy ? 28 : -16)} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.16em" fill="var(--ink-3)">{n.label}</text>
          </g>
        ))}
        <circle cx={cx} cy={cy} r="80" fill="url(#pb-hub)" opacity="0.35"/>
        <circle cx={cx} cy={cy} r="36" fill="var(--ink)"/>
        <circle cx={cx} cy={cy} r="36" fill="none" stroke="var(--rust)" strokeOpacity="0.4" strokeWidth="1"/>
        <text x={cx} y={cy - 2} textAnchor="middle" fontFamily="var(--font-display)" fontSize="13" fontWeight="700" fill="var(--chalk)" letterSpacing="-0.01em">simplegames.fun</text>
        <text x={cx} y={cy + 14} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="rgba(255,237,231,0.55)" letterSpacing="0.18em">RNG CORE</text>
      </svg>
    </div>
  );
}

/* Logo marquee — partner / certifier wordmarks scrolling.
   Each "logo" is a small SVG glyph + wordmark. */
function LogoMarquee() {
  const logos = [
    { mark: <Mk1/>, name: 'MGA Malta' },
    { mark: <Mk2/>, name: 'UKGC' },
    { mark: <Mk3/>, name: 'GLI-19' },
    { mark: <Mk4/>, name: 'iTechLabs' },
    { mark: <Mk5/>, name: 'BMM Testlabs' },
    { mark: <Mk6/>, name: 'AGCO Ontario' },
    { mark: <Mk7/>, name: 'ONJN Romania' },
    { mark: <Mk1/>, name: 'Spelinspektionen' },
    { mark: <Mk2/>, name: 'IBIA Member' },
    { mark: <Mk3/>, name: 'SiGMA Eurasia' },
  ];
  const list = [...logos, ...logos];
  return (
    <div className="logo-row">
      <div className="logo-row-track">
        {list.map((l, i) => (
          <span key={i} className="logo-mark">{l.mark}<span>{l.name}</span></span>
        ))}
      </div>
    </div>
  );
}
function Mk1(){return(<svg width="22" height="22" viewBox="0 0 22 22"><circle cx="11" cy="11" r="9" fill="none" stroke="currentColor" strokeWidth="1.5"/><path d="M5 11 L9 15 L17 7" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>);}
function Mk2(){return(<svg width="22" height="22" viewBox="0 0 22 22"><rect x="3" y="3" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"/><rect x="7" y="7" width="8" height="8" fill="currentColor" opacity="0.4"/></svg>);}
function Mk3(){return(<svg width="22" height="22" viewBox="0 0 22 22"><polygon points="11,2 20,8 17,19 5,19 2,8" fill="none" stroke="currentColor" strokeWidth="1.5"/><circle cx="11" cy="11" r="3" fill="currentColor"/></svg>);}
function Mk4(){return(<svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 11 H19 M11 3 V19" stroke="currentColor" strokeWidth="1.5"/><circle cx="11" cy="11" r="5" fill="none" stroke="currentColor" strokeWidth="1.5"/></svg>);}
function Mk5(){return(<svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 18 L8 8 L13 14 L19 4" stroke="currentColor" strokeWidth="1.6" fill="none"/></svg>);}
function Mk6(){return(<svg width="22" height="22" viewBox="0 0 22 22"><circle cx="11" cy="11" r="8" fill="none" stroke="currentColor" strokeWidth="1.5"/><circle cx="11" cy="11" r="3" fill="currentColor"/></svg>);}
function Mk7(){return(<svg width="22" height="22" viewBox="0 0 22 22"><path d="M4 4 L18 18 M18 4 L4 18" stroke="currentColor" strokeWidth="1.5"/><rect x="2" y="2" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5"/></svg>);}

/* Animated chart card — line + bars draw in on mount, refreshes every 8s */
function ChartCard() {
  const [seed, setSeed] = React.useState(0);
  React.useEffect(() => { const i = setInterval(() => setSeed(s => s+1), 8000); return () => clearInterval(i); }, []);
  const points = React.useMemo(() => {
    const pts = []; let v = 60;
    for (let i = 0; i < 24; i++) { v += (Math.random() - 0.45) * 18; v = Math.max(20, Math.min(120, v)); pts.push(v); }
    return pts;
  }, [seed]);
  const W = 360, H = 180, P = 16;
  const stepX = (W - P*2) / (points.length - 1);
  const path = points.map((p,i) => `${i===0?'M':'L'} ${P + i*stepX} ${H - P - p}`).join(' ');
  const area = `${path} L ${P + (points.length-1)*stepX} ${H - P} L ${P} ${H - P} Z`;
  const last = points[points.length-1].toFixed(1);
  const delta = (points[points.length-1] - points[points.length-6]).toFixed(1);
  const positive = parseFloat(delta) >= 0;

  return (
    <div className="card card-pad" style={{ position: 'relative', overflow: 'hidden' }}>
      <div className="row justify-between items-start mb-md">
        <div>
          <span className="t-label">// Network throughput</span>
          <div className="row items-baseline gap-sm" style={{ marginTop: 8 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)' }}>{last}<span style={{ fontSize: 16, color: 'var(--ink-3)', marginLeft: 4 }}>k rps</span></span>
            <span className="t-mono" style={{ fontSize: 11.5, color: positive ? 'var(--moss)' : 'var(--rust)', fontWeight: 600 }}>{positive ? '▲' : '▼'} {Math.abs(parseFloat(delta)).toFixed(1)}</span>
          </div>
        </div>
        <span className="chip chip-rust"><span className="dot dot-live"></span>LIVE</span>
      </div>
      <svg key={seed} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: '100%', height: 180, display: 'block' }}>
        <defs>
          <linearGradient id="cc-fill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--rust)" stopOpacity="0.22"/>
            <stop offset="100%" stopColor="var(--rust)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[40,80,120,160].map((x,i) => <line key={i} x1="0" y1={x*0.85+10} x2={W} y2={x*0.85+10} stroke="var(--hairline)" strokeWidth="0.5" strokeDasharray="2 4"/>)}
        <path className="chart-line" d={area} fill="url(#cc-fill)" stroke="none"/>
        <path className="chart-line" d={path} fill="none" stroke="var(--rust)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round"/>
        {points.map((p, i) => i % 4 === 3 && (
          <circle key={i} cx={P + i*stepX} cy={H - P - p} r="3" fill="var(--chalk)" stroke="var(--rust)" strokeWidth="1.5"/>
        ))}
      </svg>
      <div className="row justify-between mt-sm" style={{ paddingTop: 12, borderTop: '1px solid var(--hairline)' }}>
        {[
          { k: 'p50', v: '38ms' },
          { k: 'p99', v: '142ms' },
          { k: 'errors', v: '0.002%' },
          { k: 'sessions', v: '94.3k' },
        ].map((s, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <span className="t-mono" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{s.k}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>{s.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* PillarCard — image-driven auto-cycling visual card.
   Each card has 3 visual frames that rotate every 3.2s. */
function PillarCard({ p, index }) {
  const [frame, setFrame] = React.useState(0);
  const FM = window.Motion || window.FramerMotion || {};
  const motion = FM.motion;
  const AnimatePresence = FM.AnimatePresence;
  React.useEffect(() => {
    const i = setInterval(() => setFrame(f => (f + 1) % 3), 3200 + index * 600);
    return () => clearInterval(i);
  }, [index]);

  const accentMap = {
    rust:   { bg: 'linear-gradient(160deg, #2a1208 0%, #1a0a04 100%)', accent: '#ff7a3c', soft: 'rgba(255,122,60,0.15)' },
    indigo: { bg: 'linear-gradient(160deg, #14233a 0%, #0a1422 100%)', accent: '#6e9ad6', soft: 'rgba(110,154,214,0.15)' },
    moss:   { bg: 'linear-gradient(160deg, #1f2e1c 0%, #0e1a0c 100%)', accent: '#8eb585', soft: 'rgba(142,181,133,0.15)' },
  };
  const a = accentMap[p.color];

  return (
    <div className="card card-hover" style={{ minHeight: 420, display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: 0 }}>
      <div style={{ height: 200, position: 'relative', overflow: 'hidden', background: a.bg }}>
        {/* dot grid bg inside frame */}
        <div style={{ position: 'absolute', inset: 0, opacity: 0.25,
          backgroundImage: `radial-gradient(${a.accent}33 1px, transparent 1px)`,
          backgroundSize: '14px 14px' }} />

        {motion && AnimatePresence ? (
          <AnimatePresence mode="wait">
            <motion.div key={frame}
              initial={{ opacity: 0, scale: 1.06 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.96 }}
              transition={{ duration: 0.7, ease: [0.2,0.8,0.2,1] }}
              style={{ position: 'absolute', inset: 0 }}>
              <PillarVisual visual={p.visual} frame={frame} accent={a.accent} />
            </motion.div>
          </AnimatePresence>
        ) : (
          <div style={{ position: 'absolute', inset: 0 }}>
            <PillarVisual visual={p.visual} frame={frame} accent={a.accent} />
          </div>
        )}

        {/* frame indicators */}
        <div style={{ position: 'absolute', bottom: 14, left: 18, display: 'flex', gap: 6 }}>
          {[0,1,2].map(i => (
            <div key={i} style={{ width: i === frame ? 18 : 6, height: 3, borderRadius: 2, background: i === frame ? a.accent : 'rgba(255,255,255,0.25)', transition: 'all 400ms ease' }} />
          ))}
        </div>
        <span style={{ position: 'absolute', top: 14, left: 18, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.5)' }}>{p.n} · FIG.{frame+1}</span>
        <span style={{ position: 'absolute', top: 14, right: 18, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: a.accent }}>{p.tag.toUpperCase()}</span>
      </div>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', flex: 1 }}>
        <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--ink)' }}>{p.tag}</h3>
        <p className="t-body" style={{ marginTop: 10, marginBottom: 0 }}>{p.body}</p>
        <a className="btn btn-ghost btn-arrow" href="#about" onClick={(e)=>{e.preventDefault(); window.fgNavigate('about');}} style={{ marginTop: 'auto', alignSelf: 'flex-start' }}>Read more</a>
      </div>
    </div>
  );
}

function PillarVisual({ visual, frame, accent }) {
  // RNG: hashed seed visualization
  if (visual === 'rng') {
    const frames = [
      // hash grid
      <svg key="rng0" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        {[...Array(8)].flatMap((_,r) => [...Array(16)].map((_,c) => (
          <rect key={`${r}-${c}`} x={40+c*20} y={40+r*16} width="14" height="10" fill={accent} opacity={Math.random()*0.7+0.1} />
        )))}
        <text x="200" y="180" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">SEED PAIR · 8c4f...a319</text>
      </svg>,
      // verification check
      <svg key="rng1" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        <circle cx="200" cy="100" r="58" fill="none" stroke={accent} strokeWidth="2"/>
        <circle cx="200" cy="100" r="58" fill="none" stroke={accent} strokeOpacity="0.3" strokeWidth="14"/>
        <path d="M178 100 L195 117 L225 85" fill="none" stroke={accent} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
        <text x="200" y="180" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">VERIFIED · ROUND #2841</text>
      </svg>,
      // round stream
      <svg key="rng2" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        {[...Array(12)].map((_,i) => (
          <g key={i} transform={`translate(${30+i*30} 100)`}>
            <rect x="-9" y="-30" width="18" height="60" rx="2" fill="none" stroke={accent} strokeOpacity={0.3+i*0.05}/>
            <text textAnchor="middle" y="4" fill={accent} fontFamily="Space Grotesk" fontSize="11" opacity={0.5+i*0.04}>{(Math.random()*16).toString(16).slice(0,1).toUpperCase()}</text>
          </g>
        ))}
        <text x="200" y="180" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">PRE-COMMIT STREAM</text>
      </svg>,
    ];
    return frames[frame];
  }
  // MATH: payout curves
  if (visual === 'math') {
    const frames = [
      <svg key="m0" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        <path d="M30 170 Q 150 165 220 120 T 380 30" fill="none" stroke={accent} strokeWidth="2"/>
        <path d="M30 170 Q 150 165 220 120 T 380 30 L 380 170 Z" fill={accent} opacity="0.18"/>
        {[1,2,3,4,5].map(i => <circle key={i} cx={30+i*70} cy={170-i*22} r="3" fill={accent}/>)}
        <text x="200" y="190" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">PAYOUT CURVE · σ 0.42</text>
      </svg>,
      <svg key="m1" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        {[80,60,90,140,110,75,130,95,55,120,85,100].map((h,i) => (
          <rect key={i} x={20+i*30} y={180-h} width="20" height={h} fill={accent} opacity={0.4+(h/200)*0.6}/>
        ))}
        <text x="200" y="195" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">10⁹ SIMULATIONS · μ 1.94</text>
      </svg>,
      <svg key="m2" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
        <g transform="translate(200 100)">
          {[...Array(8)].map((_,i) => {
            const a = (i*45)*Math.PI/180;
            return <line key={i} x1="0" y1="0" x2={Math.cos(a)*70} y2={Math.sin(a)*70} stroke={accent} strokeOpacity="0.4"/>;
          })}
          <polygon points={[...Array(8)].map((_,i)=>{const a=(i*45)*Math.PI/180;const r=30+Math.random()*40;return `${Math.cos(a)*r},${Math.sin(a)*r}`}).join(' ')} fill={accent} fillOpacity="0.25" stroke={accent} strokeWidth="1.5"/>
        </g>
        <text x="200" y="190" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">VARIANCE PROFILE</text>
      </svg>,
    ];
    return frames[frame];
  }
  // OPS: engagement layer
  const frames = [
    <svg key="o0" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
      {[1,2,3,4,5].map(i => (
        <g key={i}>
          <rect x="30" y={20+i*28} width={60+i*40} height="14" rx="2" fill={accent} opacity={0.7-i*0.1}/>
          <text x={100+i*40} y={31+i*28} fill="white" fontFamily="Space Grotesk" fontSize="9" opacity="0.6">PLR_{i*2841}</text>
        </g>
      ))}
      <text x="200" y="190" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">TOURNAMENT LEADERBOARD</text>
    </svg>,
    <svg key="o1" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
      {[0,1,2,3,4].map(i => (
        <g key={i}>
          <circle cx={50+i*75} cy="80" r="14" fill="none" stroke={accent} strokeWidth="1.5" opacity={i<3?1:0.3}/>
          {i<3 && <path d={`M${44+i*75} 80 L${49+i*75} 85 L${56+i*75} 76`} fill="none" stroke={accent} strokeWidth="2"/>}
          {i<4 && <line x1={64+i*75} y1="80" x2={86+i*75} y2="80" stroke={accent} strokeOpacity="0.4" strokeDasharray="3 3"/>}
        </g>
      ))}
      <text x="200" y="190" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">MISSION · 3 OF 5 COMPLETE</text>
    </svg>,
    <svg key="o2" viewBox="0 0 400 200" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
      <g transform="translate(200 90)">
        <circle r="60" fill="none" stroke={accent} strokeWidth="1" strokeDasharray="2 4"/>
        <circle r="40" fill={accent} fillOpacity="0.18"/>
        <text textAnchor="middle" y="-2" fill="white" fontFamily="Inter" fontSize="22" fontWeight="700">€48,210</text>
        <text textAnchor="middle" y="14" fill={accent} fontFamily="Space Grotesk" fontSize="9" letterSpacing="0.18em">JACKPOT POOL</text>
      </g>
      <text x="200" y="190" textAnchor="middle" fill="rgba(255,255,255,0.4)" fontFamily="Space Grotesk" fontSize="10" letterSpacing="0.2em">POOLED · 12 OPERATORS</text>
    </svg>,
  ];
  return frames[frame];
}

Object.assign(window, { ShinyText, DotPattern, PulseBeams, LogoMarquee, ChartCard, PillarCard, PillarVisual, Aurora });
