// wci26/extras.jsx — Paul peek, soccer-ball pile-up animation, ticker tape, tweaks panel

// ───────── Soccer-ball pile-up burst ────────────────────
const BallBurst = ({ trigger, color }) => {
  // When trigger key changes, spawn a fresh wave
  const balls = React.useMemo(() => Array.from({ length: 8 }).map((_, i) => ({
    x: -20 + Math.random() * 40,
    delay: i * 0.05,
    rotate: Math.random() * 720 - 360,
    scale: 0.7 + Math.random() * 0.6,
  })), [trigger]);

  if (!trigger) return null;
  return (
    <div key={trigger} style={{
      position: 'fixed', bottom: 24, right: 360, zIndex: 60,
      pointerEvents: 'none', width: 200, height: 200,
    }}>
      {balls.map((b, i) => (
        <div key={i} style={{
          position: 'absolute', bottom: 0, left: '50%',
          width: 28, height: 28,
          transform: `translateX(${b.x}px) scale(${b.scale})`,
          animation: `ball-toss 1.2s ease-out ${b.delay}s forwards`,
        }}>
          <svg viewBox="0 0 28 28" width="28" height="28">
            <circle cx="14" cy="14" r="13" fill="#fff" stroke="#000" strokeWidth="1" />
            <polygon points="14,8 19,12 17,17 11,17 9,12" fill="#0a0615" />
          </svg>
        </div>
      ))}
    </div>
  );
};

// ───────── Paul peek tentacle (bottom right) ────────────
const PaulPeek = ({ msg, color }) => {
  const [showSpeech, setShowSpeech] = React.useState(false);
  React.useEffect(() => {
    if (!msg) return;
    setShowSpeech(true);
    const t = setTimeout(() => setShowSpeech(false), 4200);
    return () => clearTimeout(t);
  }, [msg]);

  if (!showSpeech || !msg) return null;

  return (
    <div className="paul-peek" style={{
      position: 'fixed', bottom: 0, right: 28, zIndex: 50,
      pointerEvents: 'none',
    }}>
      <div style={{
        position: 'absolute', bottom: 122, right: 0, width: 240, padding: 12,
        background: 'rgba(10,6,21,0.95)', backdropFilter: 'blur(12px)',
        border: '1px solid ' + (color || 'var(--fifa-purple)'),
        borderRadius: 14,
        boxShadow: `0 16px 40px -10px rgba(0,0,0,0.8), 0 0 32px -8px ${color || 'var(--fifa-purple)'}`,
        fontSize: 12, color: 'var(--t1)',
        animation: 'toast-in 320ms var(--ease)',
        pointerEvents: 'auto',
      }}>
        <div className="label" style={{ color: color || 'var(--fifa-purple)', marginBottom: 4 }}>PAUL ORACLE</div>
        <div>{msg}</div>
        {/* Bubble pointer */}
        <div style={{
          position: 'absolute', bottom: -8, right: 28,
          width: 14, height: 14,
          background: 'rgba(10,6,21,0.95)',
          borderRight: '1px solid ' + (color || 'var(--fifa-purple)'),
          borderBottom: '1px solid ' + (color || 'var(--fifa-purple)'),
          transform: 'rotate(45deg)',
        }} />
      </div>
      <div style={{
        width: 110, height: 110,
        transform: 'translateY(28px)',
        animation: 'tentacle-peek 4s ease-in-out infinite',
      }}>
        <img src="assets/chibi_jumping.png" width="110" height="110" />
      </div>
    </div>
  );
};

// ───────── Ticker tape (top of screen) ─────────────────
const buildMarketTickerItems = (countries = [], fallbackTicker = []) => {
  const liveCountries = (Array.isArray(countries) ? countries : [])
    .filter((country) => country?.code)
    .sort((a, b) => (Number(b.marketCapWETH || b.mcap || 0) - Number(a.marketCapWETH || a.mcap || 0)) || (a.rank || 999) - (b.rank || 999));
  if (liveCountries.length) {
    return liveCountries.map((country) => ({
      id: `mcap-${country.code}`,
      code: country.code,
      tokenSymbol: typeof wciCountryDollarTicker === 'function' ? wciCountryDollarTicker(country) : country.tokenSymbol,
      color: country.color,
      marketCapLabel: typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(country) : (typeof fmtMcap === 'function' ? fmtMcap(country.mcap || 0) : '$--'),
      volumeLabel: typeof wciFormatCountryVolume === 'function' ? wciFormatCountryVolume(country) : (typeof fmtVol === 'function' ? fmtVol(country.volume24h || 0) : '$0'),
    }));
  }
  return (fallbackTicker && fallbackTicker.length
    ? fallbackTicker
    : [{ id: 'pending', name: 'WCI26', amountLabel: 'Sync pending', color: 'var(--fifa-teal)' }]
  ).filter((item) => !/pool created|v3 pool/i.test(`${item.amountLabel || ''} ${item.message || ''} ${item.eventType || ''}`));
};

const TickerTape = ({ ticker, countries = [] }) => {
  const tickerItems = buildMarketTickerItems(countries, ticker);
  const renderedItems = [...tickerItems, ...tickerItems];
  return (
  <div className="ticker-tape" style={{
    height: 32, overflow: 'hidden', position: 'relative',
    background: 'linear-gradient(90deg, rgba(10,6,21,0.95), rgba(20,16,40,0.95), rgba(10,6,21,0.95))',
    borderBottom: '1px solid var(--hair)',
    display: 'flex', alignItems: 'center',
  }}>
    <div style={{
      padding: '0 14px', height: '100%', display: 'flex', alignItems: 'center',
      background: 'rgba(232,57,44,0.15)', borderRight: '1px solid rgba(232,57,44,0.3)',
      gap: 8,
    }}>
      <span className="chip-live" style={{
        width: 6, height: 6, borderRadius: '50%',
        background: '#FF5040', boxShadow: '0 0 10px #FF5040',
        animation: 'live-pulse 1.5s ease-in-out infinite',
      }} />
      <span className="label" style={{ color: '#FF7060', fontSize: 9 }}>SEPOLIA LIVE</span>
    </div>
    <div style={{ flex: 1, overflow: 'hidden', maskImage: 'linear-gradient(90deg, transparent, black 4%, black 96%, transparent)' }}>
      <div className="marquee" style={{ animationDuration: '120s', display: 'flex' }}>
        {renderedItems.map((t, i) => (
          <span key={i} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '0 16px', whiteSpace: 'nowrap',
            borderRight: '1px solid var(--hair)',
          }}>
            {t.code ? <FlagRect code={t.code} w={16} h={11} /> : <span className="chip-live" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--fifa-teal)', boxShadow: '0 0 10px var(--fifa-teal)' }} />}
            <span className="mono" style={{ fontSize: 11, color: 'var(--t2)', fontWeight: 600 }}>
              {t.tokenSymbol || (typeof wciCountryDollarTicker === 'function' && t.code ? wciCountryDollarTicker(t) : t.name)}
            </span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--lime)', fontWeight: 800 }}>
              {t.marketCapLabel ? `MCAP ${t.marketCapLabel}` : (t.amountLabel || `${Number(t.amount || 0).toFixed(4)} WETH`)}
            </span>
            {t.volumeLabel && <span className="mono" style={{ fontSize: 10, color: 'var(--t3)', fontWeight: 700 }}>VOL {t.volumeLabel}</span>}
            {t.marketCapLabel && <span style={{
              width: 5, height: 5, borderRadius: 999,
              background: t.color || 'var(--fifa-teal)',
              boxShadow: `0 0 10px ${t.color || 'var(--fifa-teal)'}`,
            }} />}
          </span>
        ))}
      </div>
    </div>
  </div>
  );
};

// ───────── Tweaks panel ────────────────────────────────
const TweaksPanel = ({ tweaks, updateTweak }) => (
  <div style={{
    position: 'fixed', bottom: 20, right: 20, zIndex: 70,
    width: 280, padding: 18,
    background: 'rgba(10,6,21,0.92)', backdropFilter: 'blur(16px)',
    border: '1px solid var(--hair-strong)', borderRadius: 16,
    boxShadow: '0 20px 60px -12px rgba(0,0,0,0.8)',
  }}>
    <div className="display" style={{ fontSize: 14, marginBottom: 14 }}>Tweaks</div>

    <div style={{ marginBottom: 14 }}>
      <div className="label" style={{ marginBottom: 6 }}>Globe size · {(tweaks.globeSize * 100).toFixed(0)}%</div>
      <input type="range" min="0.7" max="1.4" step="0.02" value={tweaks.globeSize}
             onChange={e => updateTweak('globeSize', parseFloat(e.target.value))}
             style={{ width: '100%' }} />
    </div>

    <div style={{ marginBottom: 14 }}>
      <div className="label" style={{ marginBottom: 6 }}>Rotation · {tweaks.rotationSpeed.toFixed(2)} rad/s</div>
      <input type="range" min="0" max="0.3" step="0.005" value={tweaks.rotationSpeed}
             onChange={e => updateTweak('rotationSpeed', parseFloat(e.target.value))}
             style={{ width: '100%' }} />
    </div>

    <div>
      <div className="label" style={{ marginBottom: 6 }}>Market state</div>
      <div style={{ display: 'flex', gap: 4 }}>
        {[['calm','Calm'], ['live','Live'], ['euphoric','Euphoric']].map(([k,l]) => (
          <button key={k} onClick={() => updateTweak('marketState', k)}
                  style={{
                    flex: 1, padding: '8px 4px', borderRadius: 8,
                    border: '1px solid ' + (tweaks.marketState === k ? 'var(--gold)' : 'var(--hair)'),
                    background: tweaks.marketState === k ? 'rgba(245,208,32,0.12)' : 'transparent',
                    color: tweaks.marketState === k ? 'var(--gold)' : 'var(--t2)',
                    cursor: 'pointer', fontSize: 11, fontWeight: 700,
                    fontFamily: 'Bricolage Grotesque, sans-serif',
                    letterSpacing: '0.04em', textTransform: 'uppercase',
                  }}>{l}</button>
        ))}
      </div>
    </div>
  </div>
);

window.BallBurst = BallBurst;
window.PaulPeek = PaulPeek;
window.TickerTape = TickerTape;
window.TweaksPanel = TweaksPanel;
