/* Web4 Cube Catcher — interactive dummy game for hero slide 4 */
const Web4Game = () => {
  const [score, setScore] = React.useState(0);
  const [combo, setCombo] = React.useState(0);
  const [tokens, setTokens] = React.useState(0);
  const [level, setLevel] = React.useState(1);
  const [energy, setEnergy] = React.useState(80);
  const [running, setRunning] = React.useState(true);
  const [floaters, setFloaters] = React.useState(() => seedFloaters());
  const [pops, setPops] = React.useState([]); // floating +score chips
  const [wallet, setWallet] = React.useState(false);
  const [highlight, setHighlight] = React.useState(null);
  const arenaRef = React.useRef(null);
  const popId = React.useRef(0);

  function seedFloaters() {
    return Array.from({ length: 6 }, (_, i) => ({
      id: 'f' + Date.now() + '-' + i,
      x: 10 + Math.random() * 80,
      y: 15 + Math.random() * 70,
      kind: pickKind(),
      birth: Date.now() + i * 100,
    }));
  }

  function pickKind() {
    const r = Math.random();
    if (r < 0.6) return 'cube';
    if (r < 0.85) return 'gem';
    if (r < 0.95) return 'token';
    return 'bomb';
  }

  // Spawn loop
  React.useEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      setFloaters(prev => {
        // remove old + add new
        const now = Date.now();
        const alive = prev.filter(f => now - f.birth < 4200);
        if (alive.length < 7) {
          alive.push({
            id: 'f' + now + '-' + Math.random().toString(36).slice(2, 6),
            x: 8 + Math.random() * 84,
            y: 12 + Math.random() * 72,
            kind: pickKind(),
            birth: now,
          });
        }
        return alive;
      });
    }, 900);
    return () => clearInterval(id);
  }, [running]);

  // Energy regen
  React.useEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      setEnergy(e => Math.min(100, e + 1.5));
    }, 700);
    return () => clearInterval(id);
  }, [running]);

  // Auto-level up
  React.useEffect(() => {
    setLevel(Math.floor(score / 250) + 1);
  }, [score]);

  const grab = (f) => {
    setFloaters(prev => prev.filter(x => x.id !== f.id));
    const delta = f.kind === 'cube' ? 10
                : f.kind === 'gem'  ? 25
                : f.kind === 'token'? 50
                : -20;
    setScore(s => Math.max(0, s + delta + combo * 2));
    if (f.kind === 'bomb') {
      setCombo(0);
      setEnergy(e => Math.max(0, e - 12));
    } else {
      setCombo(c => c + 1);
      if (f.kind === 'token') setTokens(t => t + 1);
    }
    // floating pop label
    const id = ++popId.current;
    setPops(p => [...p, { id, x: f.x, y: f.y, text: f.kind === 'bomb' ? '−20 ⚡' : `+${delta}`, tone: f.kind === 'bomb' ? 'bad' : 'good' }]);
    setTimeout(() => setPops(p => p.filter(pp => pp.id !== id)), 800);
  };

  const reset = () => {
    setScore(0); setCombo(0); setTokens(0); setLevel(1); setEnergy(80);
    setFloaters(seedFloaters());
    setRunning(true);
  };

  return (
    <div className="game-stage">
      <div className="game-screen">
        {/* HUD */}
        <div className="game-hud">
          <div className="game-hud-l">
            <span className="game-hud-label">SCORE</span>
            <span className="game-hud-val game-hud-score">{score.toLocaleString()}</span>
          </div>
          <div className="game-hud-c">
            <span className="game-hud-label">LEVEL · {level}</span>
            <span className="game-hud-val game-hud-combo">×{combo} combo</span>
          </div>
          <div className="game-hud-r">
            <span className="game-hud-label">TOKENS</span>
            <span className="game-hud-val">
              <span className="game-tok-ico">◆</span> {tokens.toLocaleString()}
            </span>
          </div>
        </div>

        {/* Arena */}
        <div className="game-arena" ref={arenaRef}>
          {/* hex grid background */}
          <svg className="game-hex" viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice">
            <defs>
              <pattern id="hexp" width="40" height="35" patternUnits="userSpaceOnUse">
                <path d="M20 0 L40 11 L40 23 L20 35 L0 23 L0 11 Z" fill="none" stroke="rgba(34, 211, 238, 0.08)" strokeWidth="0.6"/>
              </pattern>
              <radialGradient id="hex-glow" cx="0.5" cy="0.5" r="0.55">
                <stop offset="0" stopColor="rgba(34, 211, 238, 0.18)"/>
                <stop offset="1" stopColor="rgba(34, 211, 238, 0)"/>
              </radialGradient>
            </defs>
            <rect width="600" height="400" fill="url(#hexp)"/>
            <circle cx="300" cy="200" r="220" fill="url(#hex-glow)"/>
          </svg>

          {/* Drifting bgline */}
          <div className="game-scanline"/>

          {/* Floaters */}
          {floaters.map(f => (
            <button
              key={f.id}
              className={"game-floater game-f-" + f.kind}
              style={{ left: f.x + '%', top: f.y + '%' }}
              onClick={() => grab(f)}
              aria-label={f.kind}
            >
              <span className="game-floater-glow"/>
              <span className="game-floater-mark">
                {f.kind === 'cube'  && <CubeIcon/>}
                {f.kind === 'gem'   && <GemIcon/>}
                {f.kind === 'token' && <TokIcon/>}
                {f.kind === 'bomb'  && <BombIcon/>}
              </span>
            </button>
          ))}

          {/* Floating score pops */}
          {pops.map(p => (
            <div key={p.id} className={"game-pop game-pop-" + p.tone}
              style={{ left: p.x + '%', top: p.y + '%' }}>
              {p.text}
            </div>
          ))}

          {/* Event banner */}
          {combo >= 5 && (
            <div className="game-event">
              <IconSparkle size={11}/> ×{combo} STREAK ACTIVE
            </div>
          )}
        </div>

        {/* Controls */}
        <div className="game-controls">
          <button className="game-btn" onClick={() => setRunning(r => !r)}>
            {running ? <React.Fragment>⏸ Pause</React.Fragment> : <React.Fragment><IconPlay size={12}/> Play</React.Fragment>}
          </button>
          <button className="game-btn" onClick={reset}>
            ↻ Reset
          </button>
          <div className="game-energy">
            <span className="game-energy-label">ENERGY</span>
            <div className="game-energy-bar"><i style={{ width: energy + '%' }}/></div>
            <span className="game-energy-val">{Math.round(energy)}%</span>
          </div>
          <button className={"game-btn " + (wallet ? 'game-btn-primary' : '')}
            onClick={() => setWallet(w => !w)}>
            {wallet ? <React.Fragment>✓ 0x4f…ab9c</React.Fragment> : <React.Fragment>◆ Connect Wallet</React.Fragment>}
          </button>
          <button className="game-btn game-btn-primary" onClick={() => {
            if (tokens > 0) {
              setTokens(0);
              setScore(s => s + 100);
            }
          }}>
            <IconSparkle size={11}/> Claim Rewards
          </button>
        </div>
      </div>
    </div>
  );
};

const CubeIcon = () => (
  <svg viewBox="0 0 24 24" width="22" height="22" fill="none">
    <defs>
      <linearGradient id="cube-t" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#a5f3fc"/><stop offset="1" stopColor="#22d3ee"/></linearGradient>
    </defs>
    <path d="M12 3 L21 8 L12 13 L3 8 Z" fill="url(#cube-t)"/>
    <path d="M3 8 L12 13 L12 21 L3 16 Z" fill="#0e7a73"/>
    <path d="M21 8 L12 13 L12 21 L21 16 Z" fill="#14b8a6"/>
  </svg>
);
const GemIcon = () => (
  <svg viewBox="0 0 24 24" width="22" height="22" fill="none">
    <defs>
      <linearGradient id="gem-g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#a78bfa"/><stop offset="1" stopColor="#7c5cff"/></linearGradient>
    </defs>
    <path d="M12 3 L20 10 L12 22 L4 10 Z" fill="url(#gem-g)" stroke="#fff" strokeOpacity="0.3"/>
    <path d="M12 3 L12 22 M4 10 L20 10" stroke="#fff" strokeOpacity="0.3"/>
  </svg>
);
const TokIcon = () => (
  <svg viewBox="0 0 24 24" width="22" height="22">
    <defs>
      <linearGradient id="tok-g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#fde68a"/><stop offset="1" stopColor="#fbbf24"/></linearGradient>
    </defs>
    <circle cx="12" cy="12" r="9" fill="url(#tok-g)" stroke="#92400e" strokeWidth="1"/>
    <text x="12" y="16" textAnchor="middle" fill="#451a03" fontSize="11" fontFamily="Space Grotesk" fontWeight="700">$</text>
  </svg>
);
const BombIcon = () => (
  <svg viewBox="0 0 24 24" width="22" height="22" fill="none">
    <circle cx="12" cy="14" r="8" fill="#1a2230" stroke="#fb7185" strokeWidth="1.4"/>
    <path d="M16 6 L18 4 M14 4 L18 4 L18 8" stroke="#fb7185" strokeWidth="1.6" strokeLinecap="round"/>
    <circle cx="9" cy="12" r="1" fill="#fb7185"/>
  </svg>
);

Object.assign(window, { Web4Game });
