// bdk-apps.jsx — the "value blocks": CTA, live, leaderboard, tiers, tier match, challenges.

const BDK_CODE = 'BDKev';
const BDK_YEET_URL = 'https://yeet.com/register?aff=BDKev';
const BDK_SOCIALS = [
  { k: 'KICK', label: 'kick.com/bizdevkev', href: 'https://kick.com/bizdevkev', ic: 'bdk/icons/kick.svg' },
  { k: 'X', label: 'x.com/bizdevkevv', href: 'https://x.com/bizdevkevv', ic: 'bdk/icons/x.svg' },
  { k: 'YT', label: 'youtube.com/@bizdevkev', href: 'https://www.youtube.com/@bizdevkev', ic: 'bdk/icons/youtube.svg' },
  { k: 'DC', label: 'discord.gg/bizdevkev', href: 'https://discord.gg/bizdevkev', ic: 'bdk/icons/discord.svg' },
];

function BdkCodeChip({ small }) {
  const [copied, setCopied] = React.useState(false);
  const tm = React.useRef(null);
  React.useEffect(() => () => clearTimeout(tm.current), []);
  return (
    <button
      className={'bdk-chip' + (small ? ' small' : '')}
      onClick={() => {
        window.bdkCopy(BDK_CODE);
        window.BDKSOUND.play('pop');
        setCopied(true);
        clearTimeout(tm.current);
        tm.current = setTimeout(() => setCopied(false), 1400);
      }}
    >
      <span>CODE: {BDK_CODE}</span>
      <span className="bdk-chip-act">{copied ? 'COPIED ✓' : 'COPY'}</span>
    </button>
  );
}

function CtaApp() {
  return (
    <div>
      <p className="bdk-eyebrow">CAREER OPPORTUNITY — REMOTE, DEGEN-FRIENDLY</p>
      <h1 className="bdk-h">Lose money <em>professionally.</em></h1>
      <p className="bdk-p">Join YEET with code <b>BDKev</b> for instant access to the bi-weekly wager race, cash reward tiers and a VIP tier match. Benefits package does not include benefits.</p>
      <div className="bdk-cta-row">
        <BdkCodeChip></BdkCodeChip>
        <a className="bdk-cta" href={BDK_YEET_URL} target="_blank" rel="noreferrer" onClick={() => window.BDKSOUND.play('blip')}>JOIN YEET →</a>
      </div>
      <p className="bdk-fine">18+ only. Gambling is entertainment, not income — Kev is living proof. Play responsibly.</p>
    </div>
  );
}

function LiveApp({ live }) {
  return (
    <div>
      <div className="bdk-live-row">
        <span className={'bdk-dot' + (live ? '' : ' off')}></span>
        <span className="bdk-live-label">{live ? 'KEV IS LIVE' : 'KEV IS OFFLINE (RARE)'}</span>
        {live ? <span className="bdk-live-meta">1,485 WATCHING</span> : null}
      </div>
      <p className="bdk-live-title">{live ? '“MAX BET MONDAY — Q2 BANKROLL REVIEW”' : 'Back soon. Probably already losing.'}</p>
      <div className="bdk-screen">[ STREAM PREVIEW — DROPS IN WHEN LIVE ]</div>
      <a className="bdk-cta sub" href="https://kick.com/bizdevkev" target="_blank" rel="noreferrer" onClick={() => window.BDKSOUND.play('blip')}>
        {live ? 'WATCH ON KICK →' : 'FOLLOW ON KICK →'}
      </a>
    </div>
  );
}

const BDK_POOL = 3000;                                  // advertised prize pool
const BDK_PAYOUTS = [1000, 600, 400, 300, 250, 200, 150, 100]; // top 8 (sums to pool)
// 6:00 PM Eastern (EDT, UTC-4 in June). Ends two weeks later, same time.
const BDK_RACE_START = new Date('2026-06-15T18:00:00-04:00');
const BDK_RACE_END = new Date('2026-06-29T18:00:00-04:00');

function bdkPad(n) { return (n < 10 ? '0' : '') + n; }
function bdkCountdown(ms) {
  if (ms <= 0) return '00:00:00';
  const s = Math.floor(ms / 1000);
  const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
  return d > 0 ? d + 'd ' + bdkPad(h) + 'h ' + bdkPad(m) + 'm' : bdkPad(h) + ':' + bdkPad(m) + ':' + bdkPad(sec);
}
// privacy: reveal first 4 chars, mask the rest
function bdkMask(name) { return name.length <= 4 ? name : name.slice(0, 4) + '*'.repeat(name.length - 4); }

function LeaderApp() {
  const [now, setNow] = React.useState(() => Date.now());
  const [race, setRace] = React.useState([]); // real entries from Supabase: [{name, wager}]
  React.useEffect(() => {
    const iv = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(iv);
  }, []);
  React.useEffect(() => {
    if (window.bdkLoadRace) window.bdkLoadRace().then((r) => { if (Array.isArray(r)) setRace(r); }).catch(() => {});
  }, []);

  const start = BDK_RACE_START.getTime(), end = BDK_RACE_END.getTime();
  let timerVal, timerLbl, statusTxt, statusCls, pct;
  if (now < start) { timerVal = bdkCountdown(start - now); timerLbl = 'UNTIL START'; statusTxt = 'UPCOMING'; statusCls = 'up'; pct = 0; }
  else if (now < end) { timerVal = bdkCountdown(end - now); timerLbl = 'TIME REMAINING'; statusTxt = '● LIVE'; statusCls = 'live'; pct = ((now - start) / (end - start)) * 100; }
  else { timerVal = 'CLOSED'; timerLbl = 'RACE ENDED'; statusTxt = 'ENDED'; statusCls = 'ended'; pct = 100; }

  const ranked = race.slice().sort((a, b) => (b.wager || 0) - (a.wager || 0))
    .map((r, i) => ({ name: r.name, wager: r.wager || 0, prize: BDK_PAYOUTS[i] || 0, rank: i + 1 }));
  const totalWagered = ranked.reduce((a, r) => a + r.wager, 0);

  return (
    <div>
      <div className="bdk-lb-head">
        <div className="bdk-lb-pool">
          <span className="bdk-lb-pool-amt">{window.bdkFmt(BDK_POOL)}</span>
          <span className="bdk-lb-pool-lbl">PRIZE POOL · BI-WEEKLY</span>
        </div>
        <div className="bdk-lb-timer">
          <span className={'bdk-lb-status ' + statusCls}>{statusTxt}</span>
          <span className="bdk-lb-timer-val">{timerVal}</span>
          <span className="bdk-lb-timer-lbl">{timerLbl}</span>
        </div>
      </div>

      <div className="bdk-lb-sched">
        <div className="bdk-lb-sched-col">
          <span className="bdk-lb-sched-lbl">STARTS</span>
          <span className="bdk-lb-sched-val">JUN 15 · 6:00 PM ET</span>
        </div>
        <span className="bdk-lb-sched-arrow">→</span>
        <div className="bdk-lb-sched-col end">
          <span className="bdk-lb-sched-lbl">ENDS</span>
          <span className="bdk-lb-sched-val">JUN 29 · 6:00 PM ET</span>
        </div>
      </div>
      <div className="bdk-lb-progress"><span style={{ width: pct + '%' }}></span></div>
      <div className="bdk-lb-stats">
        <span><b>{ranked.length}</b> RACERS</span>
        <span><b>{window.bdkFmt(totalWagered)}</b> TOTAL WAGERED</span>
      </div>

      {ranked.length === 0 ? (
        <div className="bdk-lb-empty">No racers on the board yet. Wager on YEET with code <b>BDKev</b> to claim your spot — standings update through the race.</div>
      ) : ranked.length < 3 ? (
        <div className="bdk-lb-rest">
          {ranked.map((r) => (
            <div key={r.name} className="bdk-row">
              <span className="bdk-rank">{String(r.rank).padStart(2, '0')}</span>
              <span className="bdk-name">{bdkMask(r.name)}</span>
              <span className="bdk-wager">{window.bdkFmt(r.wager)}</span>
              <span className="bdk-prize">{window.bdkFmt(r.prize)}</span>
            </div>
          ))}
        </div>
      ) : (
        <div>
          <div className="bdk-lb-podium">
            {[1, 0, 2].map((idx) => {
              const r = ranked[idx]; const place = idx + 1;
              return (
                <div key={r.name} className={'bdk-pod bdk-pod-' + place}>
                  <span className="bdk-pod-name">{place === 1 ? <span className="bdk-pod-crown">♛</span> : null}{bdkMask(r.name)}</span>
                  <span className="bdk-pod-prize">{window.bdkFmt(r.prize)}</span>
                  <div className="bdk-pod-bar">
                    <span className="bdk-pod-num">{place}</span>
                    <span className="bdk-pod-wager">{window.bdkFmt(r.wager)}</span>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="bdk-lb-rest">
            {ranked.slice(3).map((r) => (
              <div key={r.name} className="bdk-row">
                <span className="bdk-rank">{String(r.rank).padStart(2, '0')}</span>
                <span className="bdk-name">{bdkMask(r.name)}</span>
                <span className="bdk-wager">{window.bdkFmt(r.wager)}</span>
                <span className={'bdk-prize' + (r.prize ? '' : ' unpaid')}>{r.prize ? window.bdkFmt(r.prize) : '—'}</span>
              </div>
            ))}
          </div>
        </div>
      )}
      <p className="bdk-fine">Wager with code BDKev to climb · top 8 paid · payouts within 48h of close</p>
    </div>
  );
}

const BDK_TIERS = [
  ['Bronze', '5K', 5, '#b9784a'],
  ['Silver', '10K', 10, '#c9ccd4'],
  ['Steel', '25K', 25, '#8fa3b8'],
  ['Gold', '50K', 50, '#e8b54b'],
  ['Platinum', '100K', 75, '#dde7ee'],
  ['Jade', '250K', 125, '#58c98f'],
  ['Diamond', '500K', 250, '#7fd6ff'],
  ['Aether', '1M', 500, '#b08cff'],
  ['Void', '2.5M', 800, '#7a68e8'],
  ['Eternal', '5M', 1000, '#ff5d8a'],
];

function TiersApp() {
  return (
    <div>
      <p className="bdk-eyebrow">WAGER TIERS — BRONZE → ETERNAL</p>
      <div className="bdk-tiers">
        {BDK_TIERS.map(([name, vol, cash, color]) => (
          <div key={name} className="bdk-tier">
            <span className="bdk-tier-d" style={{ color: color }}>◆</span>
            <b>{name}</b>
            <i>{vol}</i>
            <em>{window.bdkFmt(cash)}</em>
          </div>
        ))}
      </div>
      <p className="bdk-fine">Cash claims at every tier. Climbing is mandatory* (*not mandatory)</p>
    </div>
  );
}

// YEET VIP Tier Match — bring your VIP status from another casino to YEET.
const BDK_TIERMATCH_URL = 'https://yeet.com/landing/tier-match';
const BDK_TM_CASINOS = ['Stake', 'Roobet', 'Rollbit', 'Shuffle', 'BC.Game', 'Gamdom'];
const BDK_TM_STEPS = [
  ['Show proof', 'Screenshots of your VIP tier, wager history + transaction records from a supported casino.'],
  ['Verify', 'Submit your proof and complete Level 1 KYC on YEET.'],
  ['Get matched', 'Drop in at your tier — instant, daily, weekly + monthly rakeback, climbing as you go.'],
];

function TierMatchApp() {
  return (
    <div>
      <p className="bdk-eyebrow">YEET VIP — TIER MATCH</p>
      <h1 className="bdk-h">Bring your <em>status.</em></h1>
      <p className="bdk-p">Already a VIP somewhere else? YEET will <b>match your tier</b> — start at the same level and keep your rakeback. No grinding back from zero.</p>
      <div className="bdk-tm-steps">
        {BDK_TM_STEPS.map(([h, d], i) => (
          <div key={h} className="bdk-tm-step">
            <span className="bdk-tm-num">{i + 1}</span>
            <div><b>{h}</b><span>{d}</span></div>
          </div>
        ))}
      </div>
      <div className="bdk-tm-elig">
        <span className="bdk-tm-elig-lbl">ELIGIBLE — $1M+ WAGERED ON</span>
        <span className="bdk-tm-elig-list">{BDK_TM_CASINOS.join(' · ')}</span>
      </div>
      <div className="bdk-cta-row">
        <BdkCodeChip></BdkCodeChip>
        <a className="bdk-cta" href={BDK_TIERMATCH_URL} target="_blank" rel="noreferrer" onClick={() => window.BDKSOUND.play('blip')}>MATCH MY TIER →</a>
      </div>
      <p className="bdk-fine">Tier match is run by YEET · subject to YEET approval & terms · 18+ — play responsibly.</p>
    </div>
  );
}

function ChallengeApp() {
  const [bounties, setBounties] = React.useState([]);
  React.useEffect(() => {
    if (window.bdkLoadBounties) window.bdkLoadBounties().then((b) => { if (Array.isArray(b)) setBounties(b); }).catch(() => {});
  }, []);
  return (
    <div>
      <p className="bdk-eyebrow">BOUNTY BOARD — SLOT CHALLENGES</p>
      {bounties.length === 0 ? (
        <div className="bdk-lb-empty">No active bounties right now — check back soon.</div>
      ) : bounties.map((b, i) => (
        <div key={i} className="bdk-give">
          <div className="bdk-give-info">
            <div>{b.title}</div>
            {b.reward ? <div className="bdk-give-meta">REWARD: <span style={{ color: 'var(--accent2)' }}>{b.reward}</span></div> : null}
          </div>
          <span className="bdk-tag">{b.tag}</span>
        </div>
      ))}
      <p className="bdk-fine">Screenshot + bet slip required · code BDKev accounts only</p>
    </div>
  );
}

Object.assign(window, {
  BDK_CODE, BDK_YEET_URL, BDK_SOCIALS,
  BdkCodeChip, CtaApp, LiveApp, LeaderApp, TiersApp, TierMatchApp, ChallengeApp,
});
