/* ============================================================================
   BetPrince Sportsbook — Atoms (light/dark). Exports to window.
   ============================================================================ */
const { useState, useEffect, useRef } = React;

const SB_TEAMS = {
  CEU: { name: 'Ceuta',        short: 'CEU', c: '#111827', t: '#fff', tsdbId: 140159 },
  CAS: { name: 'Castellón',    short: 'CAS', c: '#111827', t: '#fff', tsdbId: 133860 },
  SAR: { name: 'Sarpsborg 08', short: 'SAR', c: '#1E5BBE', t: '#fff', tsdbId: 134768 },
  MOL: { name: 'Molde',        short: 'MOL', c: '#0A5BD0', t: '#fff', tsdbId: 134261 },
  HAI: { name: 'Haiti',        short: 'HAI', c: '#C8102E', t: '#fff', flag: 'ht' },
  NZL: { name: 'New Zealand',  short: 'NZL', c: '#0F172A', t: '#fff', flag: 'nz' },
  GAL: { name: 'Galatasaray',  short: 'GAL', c: '#E0571E', t: '#fff', tsdbId: 133804 },
  FEN: { name: 'Fenerbahçe',   short: 'FEN', c: '#1B2A6B', t: '#fff', tsdbId: 133807 },
  ENY: { name: 'Enyimba',      short: 'ENY', c: '#0A8F3C', t: '#fff' },
  KAN: { name: 'Kano Pillars', short: 'KAN', c: '#C8102E', t: '#fff' },
  RIV: { name: 'Rivers United',short: 'RIV', c: '#1E5BBE', t: '#fff' },
  RAN: { name: 'Rangers Intl', short: 'RAN', c: '#E0431E', t: '#fff' },
};

/* Badge cache — fetched once from TheSportsDB free API at runtime */
const _badgeCache = {};
function useBadge(id) {
  const team = SB_TEAMS[id];
  const [url, setUrl] = useState(_badgeCache[id] || null);
  useEffect(() => {
    if (_badgeCache[id]) { setUrl(_badgeCache[id]); return; }
    if (team.flag) {
      const flagUrl = `https://flagcdn.com/w80/${team.flag}.png`;
      _badgeCache[id] = flagUrl;
      setUrl(flagUrl);
      return;
    }
    if (!team.tsdbId) return;
    fetch(`https://www.thesportsdb.com/api/v1/json/3/lookupteam.php?id=${team.tsdbId}`)
      .then(r => r.json())
      .then(data => {
        const badge = data.teams && data.teams[0] && (data.teams[0].strBadge || data.teams[0].strTeamBadge);
        if (badge) {
          const small = badge + '/small';
          _badgeCache[id] = small;
          setUrl(small);
        }
      })
      .catch(() => {});
  }, [id]);
  return url;
}

// live + upcoming sample fixtures (decimal odds, 1X2)
const SB_MATCHES = [
  { id: 'g1', h: 'CEU', a: 'CAS', hs: 0, as: 0, min: 23, live: true, lg: 'La Liga 2',     o: ['2.10', '3.10', '3.40'] },
  { id: 'g2', h: 'SAR', a: 'MOL', hs: 1, as: 0, min: 56, live: true, lg: 'Eliteserien',   o: ['4.20', '3.60', '1.80'] },
  { id: 'g3', h: 'GAL', a: 'FEN', hs: 2, as: 1, min: 71, live: true, lg: 'Süper Lig',     o: ['1.95', '3.50', '3.80'] },
  { id: 'g4', h: 'HAI', a: 'NZL', hs: 0, as: 0, min: 0,  live: false, lg: 'Intl Friendly', when: '03/06 01:00', o: ['2.30', '3.20', '2.90'] },
  { id: 'g5', h: 'ENY', a: 'KAN', hs: 0, as: 0, min: 0,  live: false, scheduled: true, lg: 'NPFL', country: 'NG', time: '17:00', date: '03.06', when: '17:00 · 03.06', o: ['1.58', '3.68', '5.08'] },
  { id: 'g6', h: 'RIV', a: 'RAN', hs: 0, as: 0, min: 0,  live: false, scheduled: true, lg: 'NPFL', country: 'NG', time: '20:00', date: '03.06', when: '20:00 · 03.06', o: ['2.05', '3.10', '3.40'] },
];

function Icon({ name, size = 18, color, style }) {
  // Wrap the lucide placeholder in a display:contents span. lucide.createIcons()
  // replaces the inner <i> with an <svg>; React only ever owns/removes the wrapper,
  // which avoids the "removeChild: node is not a child" crash when an icon unmounts.
  return (
    <span style={{ display: 'contents' }}>
      <i data-lucide={name} style={{ width: size, height: size, color: color || 'currentColor', ...style }}></i>
    </span>
  );
}

function CrestFallback({ t, size }) {
  return (
    <span style={{ width: size, height: size, borderRadius: 9, background: t.c, color: t.t,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size * 0.32,
      letterSpacing: '-0.02em', flexShrink: 0 }}>{t.short}</span>
  );
}

function Crest({ id, size = 30 }) {
  const t = SB_TEAMS[id];
  const badge = useBadge(id);
  const [failed, setFailed] = useState(false);
  if (badge && !failed) {
    return (
      <span style={{ width: size, height: size, borderRadius: t.flag ? 999 : 9,
        overflow: 'hidden', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0, background: t.flag ? '#eee' : 'transparent' }}>
        <img src={badge} alt={t.short} style={{ width: '100%', height: '100%',
          objectFit: t.flag ? 'cover' : 'contain' }}
          onError={() => setFailed(true)} />
      </span>
    );
  }
  return <CrestFallback t={t} size={size} />;
}

function fmtNGN(n) {
  return 'NGN ' + Number(n).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/* number only, no currency prefix — for stacked balance displays */
function fmtBal(n) {
  return Number(n).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/* Wordmark — crown + Bet/Prince, inherits header ink */
function Wordmark({ size = 21 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
      <Icon name="crown" size={size} color="var(--gold)" />
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size,
        letterSpacing: '-0.01em', color: 'var(--header-ink)' }}>
        Bet<span style={{ color: 'var(--gold)' }}>Prince</span>
      </span>
    </span>
  );
}

/* Header — blue (light) / dark (dark). Balance + Deposit + theme toggle. */
/* step the balance font down as the number gets longer so big sums never wrap/clip */
function balanceFontSize(n) {
  const digits = Math.round(Number(n)).toString().length; // integer part length
  if (digits >= 9) return 12;   // 100,000,000+
  if (digits >= 7) return 13.5; // 1,000,000+
  return 15;
}
function Header({ balance, theme, onToggleTheme, onDeposit, user, onLogin, onSignup }) {
  return (
    <div style={{ background: 'var(--header-bg)', padding: '8px 14px 14px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
      <span style={{ flexShrink: 0 }}><Wordmark /></span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        {user ? (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,0.12)',
            borderRadius: 999, padding: '5px 6px 5px 13px', minWidth: 0 }}>
            <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', lineHeight: 1, minWidth: 0 }}>
              <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 9, letterSpacing: '0.08em',
                color: 'var(--header-ink)', opacity: 0.55, marginBottom: 2 }}>NGN</span>
              <span className="sb-num" style={{ display: 'block', fontWeight: 700, fontSize: balanceFontSize(balance),
                color: 'var(--header-ink)', whiteSpace: 'nowrap', letterSpacing: '-0.01em' }}>{fmtBal(balance)}</span>
            </span>
            <button onClick={onDeposit} style={{ background: 'var(--gold)', color: 'var(--gold-ink)', border: 'none',
              borderRadius: 999, padding: '8px 13px', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
              cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0, whiteSpace: 'nowrap' }}>
              <Icon name="plus" size={14} style={{ strokeWidth: 2.5 }} />Deposit
            </button>
          </span>
        ) : (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <button onClick={onLogin} style={{ background: 'rgba(255,255,255,0.14)', color: 'var(--header-ink)',
              border: 'none', borderRadius: 999, padding: '8px 15px', fontFamily: 'var(--font-text)', fontWeight: 700,
              fontSize: 13, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>Log in</button>
            <button onClick={onSignup} style={{ background: 'var(--gold)', color: 'var(--gold-ink)', border: 'none',
              borderRadius: 999, padding: '8px 15px', fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
              cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>Sign up</button>
          </span>
        )}
      </div>
    </div>
  );
}

/* Quick actions — 3 round tiles with dividers (Football / Live / Load Code) */
function QuickActions({ onPick }) {
  const items = [
    { key: 'football', label: 'Football', icon: 'volleyball', bg: 'var(--blue-tint)', fg: 'var(--blue)' },
    { key: 'live', label: 'Live', icon: 'radio', bg: 'var(--live-bg)', fg: 'var(--live)', dot: true },
    { key: 'code', label: 'Load Code', icon: 'list', bg: 'rgba(247,197,61,0.16)', fg: 'var(--gold-strong)' },
  ];
  return (
    <div style={{ display: 'flex', background: 'var(--card)', borderRadius: 16, overflow: 'hidden',
      border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)', margin: '0 14px 4px' }}>
      {items.map((it, i) => (
        <button key={it.key} onClick={() => onPick && onPick(it.key)} style={{ flex: 1, background: 'transparent',
          border: 'none', borderLeft: i ? '1px solid var(--line)' : 'none', cursor: 'pointer',
          padding: '16px 6px 14px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9 }}>
          <span style={{ position: 'relative', width: 46, height: 46, borderRadius: 999, background: it.bg,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: it.fg }}>
            <Icon name={it.icon} size={20} />
            {it.dot && <span style={{ position: 'absolute', top: 8, right: 9, width: 7, height: 7, borderRadius: 999,
              background: 'var(--live)', boxShadow: '0 0 0 2px var(--card)' }} />}
          </span>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13.5, color: 'var(--ink)', whiteSpace: 'nowrap' }}>{it.label}</span>
        </button>
      ))}
    </div>
  );
}

/* Pill / chip */
function Chip({ children, on, onClick }) {
  return (
    <button onClick={onClick} style={{ padding: '8px 14px', borderRadius: 999, whiteSpace: 'nowrap',
      fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13, cursor: 'pointer', transition: 'box-shadow 140ms',
      background: on ? 'var(--blue)' : 'var(--card-2)', color: on ? 'var(--blue-ink)' : 'var(--ink-2)',
      border: '1px solid ' + (on ? 'var(--blue)' : 'var(--line)') }}>{children}</button>
  );
}

/* Odds button */
function OddsBtn({ label, value, picked, onClick }) {
  return (
    <button onClick={onClick} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 6, padding: '9px 11px', borderRadius: 10, cursor: 'pointer', transition: 'box-shadow 140ms',
      background: picked ? 'var(--blue)' : 'var(--card-2)',
      border: '1px solid ' + (picked ? 'var(--blue)' : 'var(--line)') }}>
      <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12,
        color: picked ? 'rgba(255,255,255,0.8)' : 'var(--ink-3)' }}>{label}</span>
      <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: picked ? '#fff' : 'var(--ink)' }}>{value}</span>
    </button>
  );
}

/* Primary (gold) + green buttons */
function GoldBtn({ children, onClick, full, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{ width: full ? '100%' : undefined, background: 'var(--gold)',
      color: 'var(--gold-ink)', border: 'none', borderRadius: 12, padding: '14px 20px', cursor: disabled ? 'default' : 'pointer',
      fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15, opacity: disabled ? 0.5 : 1,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>{children}</button>
  );
}
function GreenBtn({ children, onClick, full }) {
  return (
    <button onClick={onClick} style={{ width: full ? '100%' : undefined, background: 'var(--green)',
      color: 'var(--green-ink)', border: 'none', borderRadius: 12, padding: '14px 20px', cursor: 'pointer',
      fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15 }}>{children}</button>
  );
}

Object.assign(window, { SB_TEAMS, SB_MATCHES, Icon, Crest, fmtNGN, fmtBal, Wordmark, Header, QuickActions, Chip, OddsBtn, GoldBtn, GreenBtn });
