// ============================================================
// HUNGRY HOLE 3D — Power-ups, Loadout & Free-Rewards (ad center)
// Ad-only unlocks, level-gated. Exposes: PowerUps, AdCenter
// ============================================================
const { useState: useStateX, useEffect: useEffectX } = React;

function reachedLevel() {
  const HH = window.HH; let r = 1;
  for (const lv of HH.LEVELS.flat()) { if ((HH.STARS[lv[0]] || 0) > 0) r = Math.min(160, lv[0] + 1); }
  return r;
}

// ---------- Power-ups / Loadout ----------
function PowerUps({ go, wallet }) {
  const HH = window.HH;
  if (!HH.equipped) HH.equipped = ['magnet'];
  if (!HH.adProgress) HH.adProgress = {};
  const reached = reachedLevel();
  const [, bump] = useStateX(0); const force = () => bump(n => n + 1);
  const [ad, setAd] = useStateX(null);    // power being unlocked
  const [unlocked, setUnlocked] = useStateX(null); // celebrate
  const equipped = HH.equipped;

  const owns = (p) => p.ads === 0 ? reached >= p.unlock : (HH.adProgress[p.id] || 0) >= p.ads && reached >= p.unlock;
  const toggleEquip = (id) => {
    const i = equipped.indexOf(id);
    if (i >= 0) equipped.splice(i, 1);
    else if (equipped.length < 3) equipped.push(id);
    force();
  };

  return (
    <Sheet title="Power" sub="Loadout" onBack={() => go('home')}
      right={<CurChip kind="coin" value={wallet.coins} />}>
      {/* loadout header — frosted candy panel with equipped pips */}
      <div className="panel" style={{ borderRadius: 22, padding: 16, display: 'flex', alignItems: 'center', gap: 13, marginBottom: 16, position: 'relative', overflow: 'hidden' }}>
        <span aria-hidden style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '46%', background: 'linear-gradient(180deg, rgba(255,255,255,0.55), transparent)', pointerEvents: 'none' }} />
        <GameIcon id="bolt" size={48} tone="grape" />
        <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
          <div className="disp" style={{ fontSize: 16 }}>Equip up to 3</div>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--slate)', marginTop: 2 }}>
            <b className="num" style={{ color: 'var(--grape)' }}>{equipped.length}</b>/3 ready</div>
        </div>
        <div style={{ display: 'flex', gap: 5, flexShrink: 0, position: 'relative' }}>
          {[0, 1, 2].map(s => <span key={s} style={{ width: 12, height: 12, borderRadius: '50%',
            background: s < equipped.length ? 'var(--mint)' : 'var(--line)',
            boxShadow: s < equipped.length ? '0 0 8px rgba(34,201,160,0.6)' : 'none', transition: 'background .2s' }} />)}
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {HH.POWERUPS.map((p, i) => {
          const locked = reached < p.unlock;
          const owned = owns(p);
          const prog = HH.adProgress[p.id] || 0;
          const isEq = equipped.includes(p.id);
          return (
            <div key={p.id} className="card fadeup" style={{ animationDelay: `${i * 0.04}s`, padding: 14, background: '#fff', display: 'flex', gap: 14, alignItems: 'center',
              border: isEq ? `2px solid ${p.color}` : '1px solid var(--line)',
              boxShadow: isEq ? `0 8px 22px ${p.color}33` : 'var(--shadow)', opacity: locked ? 0.62 : 1, transition: 'box-shadow .2s, border-color .2s' }}>
              <div style={{ width: 58, height: 58, flexShrink: 0, display: 'grid', placeItems: 'center', position: 'relative' }}>
                {locked ? <span style={{ width: 54, height: 54, borderRadius: 18, display: 'grid', placeItems: 'center', background: 'linear-gradient(180deg,#F1F5FB,#DCE5F1)', color: 'var(--slate)', boxShadow: '0 5px 0 rgba(121,142,177,0.28), inset 0 1px 0 #fff' }}><I.lock /></span> : <GameIcon id={p.icon} size={54} color={p.color} />}
                {isEq && <span style={{ position: 'absolute', top: -5, right: -5, width: 20, height: 20, borderRadius: '50%', background: 'var(--mint)', border: '2px solid #fff',
                  display: 'grid', placeItems: 'center', color: '#fff', boxShadow: '0 2px 6px rgba(0,0,0,0.2)' }}><I.check width={11} /></span>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 800, fontSize: 15 }}>{p.name}</div>
                <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--slate)', marginTop: 1, lineHeight: 1.35 }}>{p.desc}</div>
                {!locked && !owned && p.ads > 0 && <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ flex: 1 }}><Bar v={prog / p.ads} color={p.color} h={7} /></div>
                  <span className="num" style={{ fontSize: 11, fontWeight: 700, color: 'var(--slate)', flexShrink: 0 }}>{prog}/{p.ads}</span></div>}
              </div>
              <div style={{ flexShrink: 0, textAlign: 'right' }}>
                {locked ? <span className="chip" style={{ padding: '6px 11px', fontSize: 11.5, background: 'var(--card)', boxShadow: 'none', border: '1px solid var(--line)', color: 'var(--slate)', gap: 4 }}><I.lock width={12} />Lv {p.unlock}</span>
                  : owned ? <button onClick={() => toggleEquip(p.id)} className={isEq ? 'btn mint sm' : 'btn ghost sm'}>{isEq ? 'Equipped' : 'Equip'}</button>
                  : <button onClick={() => setAd(p)} className="btn sun sm"><I.ad width={15} />{prog}/{p.ads}</button>}
              </div>
            </div>
          );
        })}
      </div>

      {ad && <AdModal title="Unlock power-up" rewardLabel={`${ad.name} progress`} accent={ad.color}
        onClose={() => setAd(null)} onClaim={() => {
          HH.adProgress[ad.id] = (HH.adProgress[ad.id] || 0) + 1;
          const nowOwned = HH.adProgress[ad.id] >= ad.ads;
          const left = ad.ads - HH.adProgress[ad.id];
          const justUnlocked = ad; setAd(null);
          if (nowOwned) { if (equipped.length < 3) equipped.push(justUnlocked.id); setUnlocked(justUnlocked); }
          else if (window.HHToast) window.HHToast(`${left} more to unlock ${justUnlocked.name}`);
          force();
        }} />}
      {unlocked && <UnlockBurst item={unlocked} onClose={() => setUnlocked(null)} />}
    </Sheet>
  );
}

// celebration overlay when a power-up/skin is unlocked
function UnlockBurst({ item, onClose }) {
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 130, background: 'rgba(8,10,22,0.8)', backdropFilter: 'blur(8px)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 26 }}>
      {Array.from({ length: 22 }).map((_, i) => <span key={i} style={{ position: 'absolute', left: '50%', top: '42%', width: 8, height: 8, borderRadius: 2,
        background: [window.HH.C.sun, window.HH.C.coral, window.HH.C.mint, window.HH.C.sky, window.HH.C.grape][i % 5],
        animation: `hh-firework 1s ${(i % 6) * 0.06}s ease-out forwards`, transform: `rotate(${i * 16}deg) translateY(-10px)`, transformOrigin: 'center' }} />)}
      <div className="pop" style={{ width: 100, height: 100, borderRadius: 28, background: item.color || 'var(--grape)', display: 'grid', placeItems: 'center', boxShadow: 'var(--shadow-lg)', marginBottom: 18 }}>
        {item.icon ? <PowerIcon id={item.icon} size={52} color="#fff" /> : <HoleVisual r={36} skin={item.id} />}</div>
      <div className="eyebrow fadeup" style={{ color: '#fff' }}>Unlocked</div>
      <h2 className="disp fadeup" style={{ animationDelay: '.05s', color: '#fff', fontSize: 34, margin: '4px 0 6px' }}>{item.name}</h2>
      <p className="fadeup" style={{ animationDelay: '.1s', color: 'rgba(255,255,255,0.75)', fontWeight: 700, textAlign: 'center', maxWidth: 260, margin: '0 0 22px' }}>{item.desc || 'Ready for the next run.'}</p>
      <button className="btn sun" onClick={onClose} style={{ minWidth: 200 }}>Continue</button>
    </div>
  );
}

// ---------- Free Rewards (ad center) ----------
function AdCenter({ go, wallet }) {
  const HH = window.HH;
  const [, bump] = useStateX(0);
  const [ad, setAd] = useStateX(null);
  const [toast, setToast] = useStateX(null);
  const offers = [
    { id: 'coins', icon: 'ad', color: 'var(--sun)', title: '+250 Coins', sub: 'Coin top-up', reward: '250 coins', act: () => { wallet.coins += 250; window.HH.saveWallet && window.HH.saveWallet(); } },
    { id: 'charge', icon: 'bolt', color: 'var(--grape)', title: 'Power charge', sub: 'Equipped power +1', reward: 'power-up x1' },
    { id: 'spin', icon: 'grow', color: 'var(--mint)', title: 'Mystery prize', sub: 'Coins, charge or a cosmetic shard', reward: 'mystery' },
    { id: 'dbl', icon: 'clock', color: 'var(--sky)', title: 'Double next reward', sub: "2× coins on your next level", reward: '2× boost' },
  ];
  return (
    <Sheet title="Rewards" sub="Boosts" onBack={() => go('home')}
      right={<CurChip kind="coin" value={wallet.coins} />}>
      <div className="panel" style={{ borderRadius: 22, padding: 18, marginBottom: 16, display: 'flex', gap: 14, alignItems: 'center', position: 'relative', overflow: 'hidden', background: 'linear-gradient(120deg,#11152b,#2a3568)' }}>
        {/* glossy sheen + glow blob */}
        <span aria-hidden style={{ position: 'absolute', top: -60, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,182,39,0.32), transparent 70%)', filter: 'blur(6px)' }} />
        <span aria-hidden style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '42%', background: 'linear-gradient(180deg, rgba(255,255,255,0.12), transparent)', pointerEvents: 'none' }} />
        <div style={{ width: 50, height: 50, borderRadius: 16, background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.18)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0, position: 'relative', boxShadow: '0 4px 12px rgba(0,0,0,0.25)' }}><I.ad /></div>
        <div style={{ flex: 1, position: 'relative' }}><div className="disp" style={{ fontSize: 18, color: '#fff' }}>Reward boosts</div>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.7)' }}>Claim coins, charges, and run bonuses.</div></div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {offers.map((o, i) => (
          <div key={o.id} className="card fadeup" style={{ animationDelay: `${i * 0.05}s`, padding: 14, background: '#fff', display: 'flex', gap: 14, alignItems: 'center', position: 'relative', overflow: 'hidden', boxShadow: 'var(--shadow)' }}>
            <span aria-hidden style={{ position: 'absolute', top: -30, left: -20, width: 90, height: 90, borderRadius: '50%', background: `radial-gradient(circle, ${o.color}1f, transparent 70%)`, pointerEvents: 'none' }} />
            <div style={{ width: 52, height: 52, borderRadius: 16, background: `linear-gradient(160deg, ${o.color}, ${o.color}cc)`, display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0, position: 'relative',
              boxShadow: `inset 0 -4px 0 rgba(0,0,0,0.16), 0 6px 14px ${o.color}40` }}><PowerIcon id={o.icon} size={26} color="#fff" /></div>
            <div style={{ flex: 1, minWidth: 0, position: 'relative' }}><div style={{ fontWeight: 800, fontSize: 15 }}>{o.title}</div><div style={{ fontSize: 12, fontWeight: 700, color: 'var(--slate)', marginTop: 1 }}>{o.sub}</div></div>
            <button className="btn sun sm" onClick={() => setAd(o)}><I.ad width={15} />Watch</button>
          </div>
        ))}
      </div>
      <p style={{ textAlign: 'center', fontSize: 11.5, fontWeight: 700, color: 'var(--slate)', margin: '18px auto 0', maxWidth: 280, lineHeight: 1.5 }}>Optional ads unlock rewards.</p>

      {ad && <AdModal rewardLabel={ad.reward} accent={ad.color} onClose={() => setAd(null)}
        onClaim={() => { if (ad.act) ad.act(); setToast(ad.title + ' claimed!'); setAd(null); bump(n => n + 1); setTimeout(() => setToast(null), 1800); }} />}
      {toast && <div className="chip" style={{ position: 'absolute', bottom: 80, left: '50%', transform: 'translateX(-50%)', zIndex: 100, background: 'linear-gradient(180deg,#243758,#16223C)', color: '#fff', border: 'none', padding: '12px 22px', fontWeight: 800, fontSize: 14, gap: 8, boxShadow: 'var(--shadow-lg)', animation: 'hh-pop .4s cubic-bezier(.34,1.56,.64,1)' }}><span style={{ color: 'var(--mint)' }}><I.check width={16} /></span>{toast}</div>}
    </Sheet>
  );
}

Object.assign(window, { PowerUps, AdCenter, UnlockBurst, reachedLevel });
