// ============================================================
// HUNGRY HOLE 3D — meta: Shop, Daily, Missions, Settings, WorldClear, Share
// hole.io look — frosted candy panels, big hole preview, tappable grids.
// Uses §7 handles: HoleVisual, Coin, Gem, Stars, ProgressBar, Bar, Dialog,
// GoalPill, TopBar, CurChip, AdModal, PowerIcon, I icons, .btn/.panel/.card/.chip.
// ============================================================
const { useState: useStateMe, useEffect: useEffectMe } = React;

// ---------- shared menu shell — bright hole.io sky → cloud ----------
function Sheet({ title, sub, onBack, right, children, world }) {
  const W = world || window.HH.WORLDS[0];
  const dark = window.__hhTheme === 'dark';
  const top = (W.sky && W.sky[0]) || '#8FE3FF';
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden',
      background: '#071B34' }}>
      <img className="hh-page-bg" src="assets/ui-ai/menu-bg.webp" alt="" />
      <div className="hh-page-vignette" />
      <div className="pf-scroll hh-page-content">
        <TopBar title={title} sub={sub} onBack={onBack} right={right} />
        <div style={{ padding: '0 18px' }}>{children}</div>
      </div>
    </div>
  );
}

// ---------- segmented pill tabs (frosted track, candy active pill) ----------
function Tabs({ tabs, active, onChange }) {
  return <div style={{ display: 'flex', gap: 5, padding: 5, borderRadius: 100,
    background: 'rgba(255,255,255,0.7)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
    border: '1px solid rgba(255,255,255,0.9)', boxShadow: 'var(--shadow)', margin: '6px 0 18px' }}>
    {tabs.map(t => {
      const on = active === t;
      return <button key={t} onClick={() => onChange(t)} style={{ flex: 1, padding: '11px 4px', borderRadius: 100,
        border: 'none', cursor: 'pointer', fontFamily: 'var(--disp)', fontWeight: 800, fontSize: 13.5,
        background: on ? 'linear-gradient(180deg,#3FB8FF,var(--sky))' : 'transparent',
        color: on ? '#fff' : 'var(--slate)', textShadow: on ? '0 1px 2px rgba(12,80,140,0.4)' : 'none',
        boxShadow: on ? '0 3px 0 #1481c6, 0 5px 12px rgba(34,166,242,0.35)' : 'none',
        transition: 'all .16s cubic-bezier(.34,1.56,.64,1)' }}>{t}</button>;
    })}
  </div>;
}

// ---------- springy toggle ----------
function Toggle({ on, onClick }) {
  return <button onClick={onClick} style={{ width: 52, height: 31, borderRadius: 100, border: 'none', cursor: 'pointer', position: 'relative',
    background: on ? 'linear-gradient(180deg,#46E6BF,var(--mint))' : 'var(--line)',
    boxShadow: on ? 'inset 0 1px 3px rgba(4,70,55,0.25), 0 1px 0 rgba(255,255,255,0.5)' : 'inset 0 1px 3px rgba(27,39,64,0.18)',
    transition: 'background .22s' }}>
    <span style={{ position: 'absolute', top: 3, left: on ? 24 : 3, width: 25, height: 25, borderRadius: '50%', background: '#fff',
      boxShadow: '0 2px 5px rgba(0,0,0,0.28), inset 0 1px 0 rgba(255,255,255,0.9)',
      transition: 'left .2s cubic-bezier(.34,1.56,.64,1)' }} />
  </button>;
}

// ---------- 9 · HOLES (the flagship cosmetics screen) ----------
// CLASSIC / SPECIAL segmented tabs filter HH.SKINS by category; Trails & Effects
// live as extra tabs in the same seg-bar. Skin cards use the .hh-holecard states
// (locked / owned / selected). Tapping an owned skin equips it; a locked one opens
// the rewarded-ad flow. A big ▶ FREE rewarded button sits below the grid.
function Shop({ go, world, wallet }) {
  const HH = window.HH;
  if (!HH.adProgress) HH.adProgress = {};
  const reached = (window.reachedLevel ? window.reachedLevel() : 1);
  const [tab, setTab] = useStateMe('classic');   // 'classic' | 'special' | 'trails' | 'effects'
  const [ad, setAd] = useStateMe(null);
  const [, bump] = useStateMe(0);

  const isSkinTab = tab === 'classic' || tab === 'special';
  const list = tab === 'classic' ? HH.SKINS.filter(s => s.category === 'classic')
    : tab === 'special' ? HH.SKINS.filter(s => s.category === 'special')
    : tab === 'trails' ? HH.TRAILS : HH.EFFECTS;
  const owns = (it) => it.owned || (it.ads != null && (HH.adProgress['cos_' + it.id] || 0) >= it.ads && reached >= (it.unlock || 1));
  const ownedCount = list.filter(owns).length;

  // equip an owned cosmetic across the WHOLE category set it belongs to
  const equip = (it) => {
    const family = isSkinTab ? HH.SKINS : (tab === 'trails' ? HH.TRAILS : HH.EFFECTS);
    family.forEach(x => x.sel = false); it.sel = true; it.owned = true;
    // persist the pick so it stays equipped + active in gameplay across sessions
    try {
      const key = isSkinTab ? 'hh_skin' : (tab === 'trails' ? 'hh_trail' : 'hh_effect');
      localStorage.setItem(key, it.id);
    } catch (e) {}
    if (window.HHSound) window.HHSound.tap && window.HHSound.tap();
    if (window.HH && window.HH.haptics !== false && window.HHHaptics) window.HHHaptics.tap();
    bump(n => n + 1);
  };

  // first not-yet-owned, unlockable item — the ▶ FREE button's reward target
  const freeTarget = list.find(it => !owns(it) && reached >= (it.unlock || 1))
    || list.find(it => !owns(it));

  // a styled cosmetic icon for Trails / Effects (no HoleVisual for those)
  const cosIcon = (sz) => (
    <div className="hh-holecard-art" style={{ width: sz, height: sz, borderRadius: '50%', display: 'grid', placeItems: 'center',
      background: 'radial-gradient(120% 120% at 40% 28%, rgba(63,182,255,0.22), rgba(46,143,230,0.06))',
      border: '2px solid rgba(46,143,230,0.18)' }}>
      <PowerIcon id={tab === 'trails' ? 'magnet' : 'bolt'} size={sz * 0.52} color="var(--sky)" />
    </div>
  );

  const SEGS = [['classic', 'CLASSIC'], ['special', 'SPECIAL'], ['trails', 'TRAILS'], ['effects', 'EFFECTS']];

  return (
    <Sheet title="Holes" sub="Skins and trails" onBack={() => go('home')} world={HH.WORLDS[0]}
      right={<CurChip kind="coin" value={wallet.coins} />}>

      {/* CLASSIC / SPECIAL (+ Trails / Effects) segmented tabs with live counts */}
      <div className="fadeup" style={{ display: 'flex', justifyContent: 'center', margin: '4px 0 16px' }}>
        <div className="hh-segtabs" style={{ maxWidth: '100%', flexWrap: 'wrap', justifyContent: 'center' }}>
          {SEGS.map(([key, lbl]) => {
            const on = tab === key;
            const full = key === 'classic' ? HH.SKINS.filter(s => s.category === 'classic')
              : key === 'special' ? HH.SKINS.filter(s => s.category === 'special')
              : key === 'trails' ? HH.TRAILS : HH.EFFECTS;
            const ownN = full.filter(owns).length;
            return <button key={key} className={'hh-segtab' + (on ? ' active' : '')} onClick={() => setTab(key)}
              style={{ padding: '9px 16px', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              {lbl}
              <span style={{ fontFamily: 'var(--num)', fontWeight: 700, fontSize: 11, opacity: on ? 0.95 : 0.7,
                padding: '1px 7px', borderRadius: 100, background: on ? 'rgba(255,255,255,0.22)' : 'rgba(16,34,68,0.10)' }}>
                {ownN}/{full.length}
              </span>
            </button>;
          })}
        </div>
      </div>

      {/* the skin / cosmetic grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
        {list.map((it, i) => {
          const owned = owns(it);
          const locked = reached < (it.unlock || 1) && !owned;
          const cls = 'hh-holecard fadeup' + (owned ? ' owned' : '') + (it.sel ? ' selected' : '') + (locked ? ' locked' : '');
          return (
            <button key={it.id} className={cls} aria-label={it.name}
              style={{ animationDelay: `${0.03 + i * 0.03}s` }}
              onClick={() => { if (owned) equip(it); else setAd(it); }}>
              <div className="hh-holecard-art hh-bob" style={{ display: 'grid', placeItems: 'center', height: 62 }}>
                {isSkinTab
                  ? (it.img
                      ? <img src={it.img} alt="" style={{ width: 64, height: 64, objectFit: 'contain', display: 'block',
                          animation: 'hh-spin 9s linear infinite', filter: 'drop-shadow(0 3px 7px rgba(0,0,0,0.45))' }} />
                      : <div style={{ transform: 'perspective(360px) rotateX(46deg)' }}><HoleVisual r={24} skin={it.id} /></div>)
                  : (it.img ? <img src={it.img} alt="" style={{ width: 48, height: 48, objectFit: 'contain', display: 'block', filter: locked ? 'grayscale(0.9) opacity(0.6)' : 'drop-shadow(0 3px 6px rgba(0,0,0,0.25))' }} /> : cosIcon(48))}
              </div>
              <span className="hh-holecard-name">{it.name}</span>
              {locked && <span style={{ fontFamily: 'var(--ui)', fontWeight: 800, fontSize: 10.5, color: 'rgba(255,255,255,0.6)',
                display: 'inline-flex', alignItems: 'center', gap: 3 }}><I.lock width={10} />Lv {it.unlock}</span>}
              {!owned && !locked && it.ads > 0 && (() => {
                const prog = HH.adProgress['cos_' + it.id] || 0;
                return <span style={{ fontFamily: 'var(--ui)', fontWeight: 800, fontSize: 10.5, color: 'var(--sun)',
                  display: 'inline-flex', alignItems: 'center', gap: 3 }}><I.ad width={12} />{prog}/{it.ads}</span>;
              })()}
            </button>
          );
        })}
      </div>

      {/* big ▶ FREE rewarded button */}
      <button className="btn block" disabled={!freeTarget}
        onClick={() => freeTarget && setAd(freeTarget)}
        style={{ marginTop: 20, fontSize: 19, opacity: freeTarget ? 1 : 0.55,
          background: 'linear-gradient(180deg, var(--candy-green) 0%, var(--candy-green-dk) 100%)',
          boxShadow: '0 5px 0 #178B3E, 0 10px 22px rgba(63,208,106,0.4)' }}>
        <span className="hh-freebtn" style={{ justifyContent: 'center', width: '100%' }}>
          <I.play width={20} />{freeTarget ? <>Unlock {freeTarget.name}</> : 'Complete'}
        </span>
      </button>

      {ad && <AdModal title="Unlock cosmetic" rewardLabel={`${ad.name} progress`} accent="var(--candy-green)" onClose={() => setAd(null)}
        onClaim={() => {
          const k = 'cos_' + ad.id;
          HH.adProgress[k] = (HH.adProgress[k] || 0) + 1;
          const left = (ad.ads || 1) - HH.adProgress[k];
          if (left <= 0) {
            ad.owned = true;
            if (window.HHToast) window.HHToast(`${ad.name} unlocked`, 'linear-gradient(180deg,#34e0b6,#22C9A0)');
            if (window.HHSound) window.HHSound.star && window.HHSound.star();
          } else {
            if (window.HHToast) window.HHToast(`${left} more to unlock ${ad.name}`);
          }
          setAd(null); bump(n => n + 1);
        }} />}
    </Sheet>
  );
}

// ---------- 10 · Daily Reward (7-day calendar) ----------
function Daily({ go, world, wallet }) {
  const HH = window.HH;
  const D = HH.DAILY;
  const today = new Date().toDateString();
  const todayDef = D.find(d => d.today) || D[0];
  const streak = D.filter(d => d.got).length + (todayDef ? 1 : 0);
  const [claimed, setClaimed] = useStateMe(() => { try { return localStorage.getItem('hh_daily_claimed') === today; } catch (e) { return false; } });

  const claim = () => {
    if (claimed) return;
    wallet.coins += 150; HH.saveWallet && HH.saveWallet();
    try { localStorage.setItem('hh_daily_claimed', today); } catch (e) {}
    setClaimed(true);
    if (window.HHToast) window.HHToast('+150 coins claimed', 'linear-gradient(180deg,#ffc94f,#FFB627)');
    if (window.HHSound) window.HHSound.coin && window.HHSound.coin();
  };

  const dayIcon = (d, sz) => d.kind === 'power' ? <PowerIcon id="magnet" size={sz} color="var(--grape)" />
    : d.kind === 'chest' ? <I.gift width={sz} style={{ color: 'var(--grape)' }} />
    : d.kind === 'skin' ? <PowerIcon id="bolt" size={sz} color="var(--grape)" />
    : <Coin size={sz} />;

  return (
    <Sheet title="Daily" sub={`${streak} day streak`} onBack={() => go('home')} world={HH.WORLDS[0]}
      right={<CurChip kind="coin" value={wallet.coins} />}>

      {/* streak flame strip */}
      <div className="fadeup" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, margin: '2px 0 14px',
        fontFamily: 'var(--disp)', fontWeight: 800, fontSize: 14, color: 'var(--sun)' }}>
        <I.bolt width={16} />{streak} day streak
      </div>

      {/* today's big claim */}
      <div className={'panel' + (claimed ? '' : ' shimmer')} style={{ borderRadius: 26, padding: 24, textAlign: 'center', marginBottom: 18,
        border: claimed ? '2px solid var(--line)' : '2px solid var(--sun)' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 6 }}>
          <div style={{ animation: claimed ? 'none' : 'hh-bob 2.5s ease-in-out infinite',
            filter: claimed ? 'grayscale(0.5) opacity(0.7)' : 'drop-shadow(0 8px 16px rgba(255,182,39,0.45))' }}>
            <img src="assets/ui-ai/chest.webp?v=129" alt="" style={{ width: 88, height: 88, objectFit: 'contain', display: 'block' }} /></div>
        </div>
        <div className="eyebrow" style={{ color: claimed ? 'var(--mint)' : 'var(--sun)' }}>{claimed ? 'Claimed' : `Day ${todayDef ? todayDef.day : 4}`}</div>
        <div className="disp" style={{ fontSize: 34, margin: '2px 0 4px' }}>+150 Coins</div>
        <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--slate)', marginBottom: 16 }}>Daily streak reward</div>
        <button className={claimed ? 'btn ghost block' : 'btn sun block'} disabled={claimed} onClick={claim} style={{ opacity: claimed ? 0.6 : 1 }}>
          {claimed ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><I.check width={20} />Claimed</span> : 'Claim'}
        </button>
      </div>

      <Label>7 day track</Label>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
        {D.map((d, i) => {
          const isToday = d.today && !claimed;
          return (
            <div key={d.day} className={'card fadeup' + (isToday ? ' shimmer' : '')}
              style={{ animationDelay: `${i * 0.05}s`, padding: '13px 6px 11px', textAlign: 'center', position: 'relative', background: '#fff',
                border: isToday ? '2px solid var(--sun)' : d.grand ? '2px solid var(--grape)' : '1px solid var(--line)',
                opacity: (d.got || (d.today && claimed)) ? 0.55 : 1,
                boxShadow: isToday ? '0 8px 18px rgba(255,182,39,0.28)' : 'none' }}>
              <div className="eyebrow" style={{ fontSize: 9, color: d.grand ? 'var(--grape)' : 'var(--slate)' }}>{d.grand ? 'Day 7' : `Day ${d.day}`}</div>
              <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0 6px' }}>{dayIcon(d, d.grand ? 30 : 26)}</div>
              <div style={{ fontWeight: 800, fontSize: 11, color: isToday ? 'var(--sun)' : 'var(--ink)' }}>{d.reward}</div>
              {(d.got || (d.today && claimed)) && <div style={{ position: 'absolute', top: 6, right: 6, color: 'var(--mint)' }}><I.check width={16} /></div>}
            </div>
          );
        })}
      </div>

      <button className="btn ghost block" style={{ marginTop: 18 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><I.play width={18} />Daily level</span>
      </button>
    </Sheet>
  );
}

// ---------- 11 · Missions ----------
function Missions({ go, world, wallet }) {
  const HH = window.HH;
  const [, bump] = useStateMe(0);
  const ready = HH.MISSIONS.filter(m => m.done && !m.claimed).length;
  const claim = (m) => {
    if (!m.done || m.claimed) return;
    m.claimed = true;
    if (m.kind !== 'power') { wallet.coins += (parseInt(m.reward) || 0); HH.saveWallet && HH.saveWallet(); }
    if (window.HHToast) window.HHToast(`Claimed: ${m.reward}${m.kind === 'power' ? ' charge' : ' coins'}`, 'linear-gradient(180deg,#34e0b6,#22C9A0)');
    if (window.HHSound) window.HHSound.coin && window.HHSound.coin();
    if (window.HH && window.HH.haptics !== false && window.HHHaptics) window.HHHaptics.win();
    bump(n => n + 1);
  };
  return (
    <Sheet title="Missions" sub="Objectives" onBack={() => go('home')} world={HH.WORLDS[2]}
      right={<CurChip kind="coin" value={wallet.coins} />}>

      {/* refresh banner */}
      <div className="card" style={{ padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontWeight: 800, fontSize: 13 }}>
          <I.retry width={16} style={{ color: 'var(--slate)' }} />Refreshes in <span className="num" style={{ color: 'var(--sky)' }}>11h 04m</span>
        </span>
        <span className="chip" style={{ padding: '5px 11px', fontSize: 12, background: ready ? 'var(--mint)' : 'var(--chip-bg)', color: ready ? '#063b2e' : 'var(--slate)', border: ready ? 'none' : '1px solid var(--line)' }}>{ready} ready</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {HH.MISSIONS.map((m, i) => (
          <div key={i} className={'card fadeup' + (m.done && !m.claimed ? ' shimmer' : '')}
            style={{ animationDelay: `${i * 0.05}s`, padding: 16, opacity: m.claimed ? 0.62 : 1,
              border: m.done ? '2px solid var(--mint)' : '1px solid var(--line)',
              boxShadow: m.done && !m.claimed ? '0 6px 0 rgba(34,201,160,0.16), 0 10px 22px rgba(34,201,160,0.28), inset 0 1px 0 rgba(255,255,255,0.55)' : undefined }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
              <div style={{ flex: 1 }}>
                <div className="disp" style={{ fontSize: 18 }}>{m.title}</div>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--slate)', marginTop: 1 }}>{m.sub}</div>
              </div>
              {/* reward chip */}
              <span className="chip" style={{ padding: '6px 12px 6px 9px', fontSize: 13.5,
                background: m.kind === 'power' ? 'rgba(124,92,252,0.12)' : 'rgba(255,182,39,0.14)',
                border: `1px solid ${m.kind === 'power' ? 'rgba(124,92,252,0.35)' : 'rgba(232,165,22,0.4)'}`,
                color: m.kind === 'power' ? 'var(--grape)' : '#9a6a00' }}>
                {m.kind === 'power' ? <PowerIcon id="bolt" size={16} color="var(--grape)" /> : <Coin size={16} />}
                <span className="num">{m.reward}</span>
              </span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 13 }}>
              <div style={{ flex: 1 }}><Bar v={m.claimed ? 1 : m.prog} color={m.done ? 'var(--mint)' : 'var(--sky)'} h={9} /></div>
              {m.claimed
                ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 800, fontSize: 12.5, color: 'var(--mint)' }}><I.check width={16} />Done</span>
                : m.done
                ? <button className="btn mint sm" style={{ padding: '8px 20px' }} onClick={() => claim(m)}>Claim</button>
                : <span className="num" style={{ fontWeight: 800, fontSize: 12.5, color: 'var(--slate)', minWidth: 36, textAlign: 'right' }}>{Math.round(m.prog * 100)}%</span>}
            </div>
          </div>
        ))}
      </div>

      <Label>Milestones</Label>
      <div style={{ display: 'flex', gap: 10 }}>
        {HH.CHESTS.map(c => (
          <div key={c.at} className={'card' + (c.next ? ' shimmer' : '')} style={{ flex: 1, padding: '14px 6px 12px', textAlign: 'center',
            border: c.next ? '2px solid var(--grape)' : '1px solid var(--line)', opacity: c.open ? 0.55 : 1,
            boxShadow: c.next ? '0 6px 0 rgba(124,92,252,0.18), 0 10px 22px rgba(124,92,252,0.28), inset 0 1px 0 rgba(255,255,255,0.55)' : undefined }}>
            <I.gift width={28} style={{ color: c.open ? 'var(--mint)' : 'var(--grape)' }} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3, fontWeight: 800, fontSize: 12, marginTop: 7 }} className="num">
              <I.star width={13} style={{ color: 'var(--sun)' }} />{c.at}</div>
            {c.open && <div style={{ position: 'absolute' }} />}
          </div>
        ))}
      </div>
    </Sheet>
  );
}

// ---------- 12 · Settings (cream POP-CARD — the target look) ----------
// Wires Sound/Music to HHSound, Vibration to a localStorage-backed flag that
// HHHaptics can read (window.HH.haptics). Falls back to local state otherwise.
function Settings({ go }) {
  const back = () => go('home');
  const readHaptics = () => { try { return localStorage.getItem('hh_vibe') !== '0'; } catch (e) { return true; } };
  const [s, setS] = useStateMe({
    sound: window.HHSound ? window.HHSound.isSound() : true,
    music: window.HHSound ? window.HHSound.isMusic() : true,
    vibe: readHaptics(),
    dark: (window.__hhTheme === 'dark') });

  const t = (k) => setS(v => {
    const nv = { ...v, [k]: !v[k] };
    if (window.HHSound) {
      if (k === 'sound') window.HHSound.setSound(nv.sound);
      if (k === 'music') window.HHSound.setMusic(nv.music);
    }
    if (k === 'vibe') {
      try { localStorage.setItem('hh_vibe', nv.vibe ? '1' : '0'); } catch (e) {}
      if (window.HH) window.HH.haptics = nv.vibe;          // HHHaptics can gate on this
      if (nv.vibe && window.HHHaptics) window.HHHaptics.tap();
    }
    if (k === 'dark') { if (window.__hhApplyTheme) window.__hhApplyTheme(nv.dark ? 'dark' : 'light'); }
    if (window.HHSound && k !== 'vibe') window.HHSound.tap && window.HHSound.tap();
    return nv;
  });

  // plain cream action button used for Restore / Help (matches the candy-cream language)
  const ActBtn = ({ icon, label, onClick, primary }) => (
    <button onClick={onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      padding: '13px 16px', marginTop: 10, borderRadius: 18, fontFamily: 'var(--ui)', fontWeight: 800, fontSize: 15.5,
      color: primary ? '#5435c4' : 'var(--pc-title)', textAlign: 'left',
      background: primary ? 'linear-gradient(180deg,#EDE6FF,#DFD3FF)' : 'var(--tg-row-bg)',
      border: primary ? '2px solid #CDBBFA' : '2px solid var(--line)',
      boxShadow: primary ? '0 3px 0 #C3AEF5' : '0 2px 0 rgba(22,34,60,0.06)' }}>
      <span style={{ width: 32, height: 32, borderRadius: 11, flexShrink: 0, display: 'grid', placeItems: 'center',
        background: primary ? 'rgba(124,92,252,0.16)' : 'var(--card)', color: primary ? '#7C5CFC' : 'var(--slate)' }}>{icon}</span>
      <span style={{ flex: 1 }}>{label}</span>
      <I.back width={17} style={{ transform: 'rotate(180deg)', color: primary ? '#9C82FF' : '#C9A86E' }} />
    </button>
  );

  return (
    <PopCard title="Settings" accent="var(--candy-green)" onClose={back}>
      {/* green pill toggle rows — Sound & Vibration are the two the target shows */}
      <Toggle2 on={s.sound} onClick={() => t('sound')} label="Sound" icon={<I.sound width={20} />} />
      <Toggle2 on={s.music} onClick={() => t('music')} label="Music" icon={<I.sound width={20} />} />
      <Toggle2 on={s.vibe}  onClick={() => t('vibe')}  label="Vibration" icon={<I.phone width={20} />} />
      <Toggle2 on={s.dark}  onClick={() => t('dark')}  label="Dark Mode" icon={<I.bolt width={18} />} />

      <div style={{ height: 6 }} />
      <ActBtn primary icon={<I.target width={18} />} label="Profile" onClick={() => go('profile')} />
      <ActBtn icon={<I.flag width={18} />} label="Support" onClick={() => {
        const url = 'mailto:Ameeen.login@gmail.com?subject=Hungry%20Hole%203D%20—%20Help';
        try { window.open(url, '_blank'); } catch (e) { location.href = url; }
      }} />

      {/* legal / info page links (Firebase-hosted) */}
      <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center', gap: '6px 8px', margin: '18px auto 4px' }}>
        {[['Privacy Policy', 'privacy-policy.html'], ['Terms of Service', 'terms.html'], ['Roadmap', 'roadmap.html']].map(([label, page], i, arr) => (
          <React.Fragment key={page}>
            <button onClick={() => { const url = 'https://hungry-hole-3d-2026.web.app/' + page; try { window.open(url, '_blank'); } catch (e) { location.href = url; } if (window.HHSound) window.HHSound.tap && window.HHSound.tap(); }}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                fontFamily: 'var(--ui)', fontWeight: 800, fontSize: 13, color: '#A8763A', textDecoration: 'underline', textUnderlineOffset: 3 }}>
              {label}
            </button>
            {i < arr.length - 1 && <span style={{ color: '#C9A86E', fontWeight: 800 }}>·</span>}
          </React.Fragment>
        ))}
      </div>
      <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 11.5, color: 'var(--brown-soft)', opacity: 0.85, marginTop: 4 }}>
        Hungry Hole 3D · v7.2.2 · com.hungryhole3d.game
      </div>
    </PopCard>
  );
}

// ---------- 13 · World Clear (celebratory) ----------
function WorldClear({ go, world, wallet }) {
  const HH = window.HH;
  const W = HH.WORLDS[world] || HH.WORLDS[0];
  const nextW = HH.WORLDS[Math.min(HH.WORLDS.length - 1, (world || 0) + 1)];
  const top = (W.sky && W.sky[0]) || '#8FE3FF';
  const bot = (W.sky && W.sky[1]) || '#CFF3FF';
  // credit the world-chest coins once, and play the win sting on arrival
  useEffectMe(() => {
    const key = 'hh_worldchest_' + (W.id || world || 0);
    let got = false; try { got = localStorage.getItem(key) === '1'; } catch (e) {}
    if (!got) {
      wallet.coins += 500; HH.saveWallet && HH.saveWallet();
      try { localStorage.setItem(key, '1'); } catch (e) {}
    }
    if (window.HHSound) window.HHSound.win && window.HHSound.win();
    if (window.HH && window.HH.haptics !== false && window.HHHaptics) window.HHHaptics.win();
  }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, ${top}, ${bot})`, overflow: 'hidden' }}>
      <StatusBar />
      {/* confetti rain */}
      {Array.from({ length: 18 }).map((_, i) => <div key={i} style={{ position: 'absolute', left: `${(i * 37) % 100}%`, top: -12, width: 9, height: 14, borderRadius: 2,
        background: [HH.C.sun, HH.C.coral, HH.C.mint, HH.C.sky, HH.C.grape][i % 5],
        animation: `hh-confetti ${1.8 + (i % 4) * 0.3}s ${(i % 6) * 0.16}s ease-in forwards`, opacity: 0 }} />)}

      <div className="pf-scroll" style={{ position: 'absolute', inset: 0 }}>
        <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '70px 26px 30px' }}>
          <div className="eyebrow fadeup" style={{ color: W.night ? 'rgba(255,255,255,0.8)' : 'var(--slate)' }}>World Complete</div>
          <h2 className="disp fadeup" style={{ animationDelay: '.05s', fontSize: 40, margin: '4px 0', color: W.night ? '#fff' : 'var(--ink)', textAlign: 'center', lineHeight: 1.02 }}>
            {W.name}<br />cleared!
          </h2>
          <div className="pop" style={{ margin: '14px 0 22px', animationDelay: '.1s' }}><Stars n={3} size={34} gap={12} stamp /></div>

          {/* chest reward */}
          <div className="panel pop" style={{ width: '100%', maxWidth: 320, padding: 24, textAlign: 'center', marginBottom: 22, animationDelay: '.16s' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}>
              <div style={{ animation: 'hh-bob 2.4s ease-in-out infinite' }}><I.gift width={58} style={{ color: 'var(--grape)' }} /></div>
            </div>
            <div className="eyebrow" style={{ color: 'var(--grape)' }}>World chest</div>
            <div className="disp" style={{ fontSize: 22, margin: '4px 0 16px' }}>Big rewards unlocked!</div>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 12 }}>
              <span className="chip" style={{ padding: '8px 14px 8px 10px', background: 'rgba(255,182,39,0.14)', border: '1px solid rgba(232,165,22,0.4)' }}>
                <Coin size={22} /><span className="num disp" style={{ fontSize: 20, color: '#9a6a00' }}>+500</span>
              </span>
              <span className="chip" style={{ padding: '6px 14px 6px 8px', background: 'rgba(124,92,252,0.1)', border: '1px solid rgba(124,92,252,0.32)' }}>
                <HoleVisual r={15} skin="galaxy" /><span className="disp" style={{ fontSize: 15, color: 'var(--grape)' }}>Galaxy Skin</span>
              </span>
            </div>
          </div>

          <button className="btn block" onClick={() => { if (window.HHSound) window.HHSound.tap && window.HHSound.tap(); go('map'); }} style={{ maxWidth: 320, fontSize: 19 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>Onward to {nextW.name}<I.back width={20} style={{ transform: 'rotate(180deg)' }} /></span>
          </button>
          <button className="btn ghost block" onClick={() => go('home')} style={{ maxWidth: 320, marginTop: 12 }}>Back to home</button>
        </div>
      </div>
    </div>
  );
}

// ---------- 14 · Share Card ----------
function ShareCard({ go, world }) {
  const HH = window.HH;
  const W = HH.WORLDS[0];
  return (
    <Sheet title="Share your run" sub="Score card" onBack={() => go('map')}>
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 8 }}>
        {/* the shareable card (1:1 vibe) */}
        <div style={{ width: 300, borderRadius: 28, overflow: 'hidden', boxShadow: 'var(--shadow-lg)', background: `linear-gradient(180deg, ${W.sky[0]}, ${W.sky[1]})`, border: '4px solid #fff' }}>
          <div style={{ padding: '20px 20px 0', textAlign: 'center' }}>
            <div className="disp" style={{ fontSize: 24, color: 'var(--ink)' }}>HUNGRY HOLE <span style={{ color: 'var(--sun)' }}>3D</span></div>
            <div style={{ fontWeight: 800, fontSize: 12, color: 'rgba(27,39,64,0.6)' }}>Bus Muncher · Level 9</div>
          </div>
          <div style={{ position: 'relative', height: 150 }}>
            <div style={{ position: 'absolute', left: '50%', top: '54%', transform: 'translate(-50%,-50%) perspective(500px) rotateX(52deg)' }}>
              <div style={{ width: 170, height: 170, borderRadius: '50%', background: W.ground, border: `7px solid ${W.ring}`, position: 'relative' }}>
                <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)' }}><HoleVisual r={32} skin="lava" /></div>
              </div>
            </div>
          </div>
          <div style={{ background: '#fff', padding: 18, textAlign: 'center' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 8 }}><Stars n={3} size={26} gap={8} /></div>
            <div className="num disp" style={{ fontSize: 40, color: 'var(--ink)', lineHeight: 1 }}>2,480</div>
            <div className="eyebrow" style={{ marginTop: 2 }}>Final score · New best!</div>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
        <button className="btn ghost" onClick={() => go('map')} style={{ flex: 1, fontSize: 15 }}>Close</button>
        <button className="btn" style={{ flex: 1.6, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}><I.share /> Share</button>
      </div>
      {/* leaderboard peek */}
      <Label>Rivals</Label>
      <div className="card" style={{ padding: '4px 14px', background: '#fff' }}>
        {HH.LEADERS.map((p, i, a) => (
          <div key={p.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 2px', borderBottom: i < a.length - 1 ? '1px solid var(--line)' : 'none' }}>
            <span className="num disp" style={{ width: 22, fontSize: 17, color: p.you ? 'var(--sky)' : 'var(--slate)' }}>{p.rank}</span>
            <span style={{ flex: 1, fontWeight: 800, fontSize: 14, color: p.you ? 'var(--sky)' : 'var(--ink)' }}>{p.name}</span>
            <span className="num" style={{ fontWeight: 800, fontSize: 14 }}>{p.score.toLocaleString()}</span>
          </div>
        ))}
      </div>
    </Sheet>
  );
}

Object.assign(window, { Shop, Daily, Missions, Settings, WorldClear, ShareCard, Sheet, Tabs, Toggle });
