/* ============================================================
   FreeM0ney views — Smart Bets, Analytics, Profile, Tips,
   Calculator, About, Contact, Admin.
   ============================================================ */
const { useState: useStateV, useEffect: useEffectV, useMemo: useMemoV, useRef: useRefV } = React;

function apiFetch(path, opts = {}) {
  const token = window.__fm_adminToken || localStorage.getItem('fm_token') || '';
  return fetch(path, { ...opts, headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token, ...(opts.headers || {}) } }).then(r => r.json());
}

function ViewShell({ title, subtitle, tag, children }) {
  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '24px 22px 60px', width: '100%' }}>
      {(tag || title || subtitle) && (
        <div style={{ marginBottom: 26 }}>
          {tag && <div className="mono" style={{ display: 'inline-block', padding: '6px 14px', borderRadius: 999, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.14em', color: 'var(--acc)', border: '1px solid color-mix(in srgb, var(--acc) 40%, transparent)', background: 'color-mix(in srgb, var(--acc) 8%, rgba(8,13,24,0.55))', textTransform: 'uppercase', marginBottom: 12 }}>{tag}</div>}
          {title && <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(24px, 4vw, 36px)', fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 6px', background: 'linear-gradient(180deg, #ffffff 0%, #b9c6db 100%)', WebkitBackgroundClip: 'text', backgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>{title}</h1>}
          {subtitle && <p style={{ color: 'var(--fg-muted)', fontSize: 14, margin: 0 }}>{subtitle}</p>}
        </div>
      )}
      {children}
    </div>
  );
}

function GlassCard({ children, style = {}, accent }) {
  return (
    <div style={{
      position: 'relative', borderRadius: 18, padding: 20,
      background: 'linear-gradient(165deg, rgba(56,76,120,0.22) 0%, rgba(20,28,48,0.40) 50%, rgba(12,18,34,0.62) 100%)',
      backdropFilter: 'blur(24px) saturate(1.5)', WebkitBackdropFilter: 'blur(24px) saturate(1.5)',
      border: '1px solid ' + (accent ? `color-mix(in srgb, ${accent} 35%, transparent)` : 'var(--bd)'),
      boxShadow: '0 18px 48px -22px rgba(0,0,0,0.85), inset 0 1.2px 0 rgba(255,255,255,0.22)',
      ...style,
    }}>{children}</div>
  );
}

function MetaTag({ children, accent = 'var(--acc)' }) {
  return (
    <span className="mono" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      fontSize: 10.5, fontWeight: 700, letterSpacing: '0.10em',
      padding: '4px 10px', borderRadius: 999,
      color: accent,
      border: `1px solid color-mix(in srgb, ${accent} 42%, transparent)`,
      background: `color-mix(in srgb, ${accent} 10%, rgba(8,13,24,0.55))`,
      textTransform: 'uppercase',
    }}>{children}</span>
  );
}

const inputStyle = {
  padding: '8px 12px', borderRadius: 9,
  background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)',
  color: 'var(--fg)', fontFamily: 'var(--font-mono)', fontSize: 12, outline: 'none',
};

function Field({ id, label, def = '', readOnly = false, type = 'text' }) {
  return (
    <label style={{ display: 'block' }}>
      <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>{label}</span>
      <input id={id} type={type} defaultValue={def} readOnly={readOnly} style={{
        width: '100%', padding: '11px 13px', borderRadius: 10,
        background: readOnly ? 'rgba(8,13,24,0.30)' : 'rgba(8,13,24,0.55)',
        border: '1px solid var(--bd)',
        color: readOnly ? 'var(--fg-muted)' : 'var(--fg)',
        fontSize: 13, outline: 'none',
        boxShadow: 'inset 0 1px 0 rgba(0,0,0,0.20)',
      }} />
    </label>
  );
}

const primaryBtn = {
  marginTop: 18, padding: '12px 22px',
  border: '1px solid color-mix(in srgb, var(--acc) 70%, white)',
  borderRadius: 11,
  background: 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 92%, white), var(--acc))',
  color: '#052816',
  fontFamily: 'var(--font-mono)', fontSize: 11.5, fontWeight: 800, letterSpacing: '0.14em', textTransform: 'uppercase',
  cursor: 'pointer',
  boxShadow: '0 10px 24px -8px color-mix(in srgb, var(--acc) 55%, transparent), inset 0 1px 0 rgba(255,255,255,0.40)',
};

// SMART BETS
function SmartBetsView() {
  const [tab, setTab] = useStateV('smart');
  const [bets, setBets] = useStateV(window.SMART_BETS || []);
  const [hrBets, setHrBets] = useStateV(window.HR_BETS || []);
  const [connected, setConnected] = useStateV(false);
  const [stats, setStats] = useStateV({ received: 0, smart: 0, users: 0, uptime: '0m' });
  useEffectV(() => {
    window.__fm_updateSmartBets = setBets;
    window.__fm_updateHrBets = setHrBets;
    window.__fm_setConnectionStatus = setConnected;
    if (window.__fm_socket) setConnected(window.__fm_socket.connected);
    apiFetch('/api/smart-bets/status').then(d => { if (d && !d.error) setStats(d); }).catch(() => {});
    return () => {
      delete window.__fm_updateSmartBets;
      delete window.__fm_updateHrBets;
      delete window.__fm_setConnectionStatus;
    };
  }, []);
  const list = tab === 'smart' ? bets : hrBets;

  return (
    <ViewShell tag="Live Feed · Tracked Bettors" title="Smart Bets" subtitle="Theo dõi cược của các bettor xếp hạng cao đang thắng đều.">
      <GlassCard style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span id="statusDot" style={{ width: 9, height: 9, borderRadius: '50%', background: connected ? 'var(--acc)' : '#ff4d8d', boxShadow: connected ? '0 0 10px var(--acc)' : '0 0 10px #ff4d8d', animation: connected ? 'pulse-dot 1.5s infinite' : 'none' }} />
            <span id="statusText" className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', color: connected ? 'var(--acc)' : '#ff4d8d' }}>{connected ? 'CONNECTED' : 'RECONNECTING…'}</span>
          </div>
          <span style={{ flex: 1 }} />
          {[
            { id: 'statBetsReceived', label: 'Bets received', v: (stats.received || 0).toLocaleString() },
            { id: 'statSmartBets',    label: 'Smart bets',    v: stats.smart || 0 },
            { id: 'statUsersChecked', label: 'Users checked', v: stats.users || 0 },
            { id: 'statUptime',       label: 'Uptime',        v: stats.uptime || '0m' },
          ].map(s => (
            <div key={s.id} style={{ minWidth: 100 }}>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{s.label}</div>
              <div className="mono" id={s.id} style={{ fontSize: 17, fontWeight: 800, color: 'var(--fg)' }}>{s.v}</div>
            </div>
          ))}
        </div>
      </GlassCard>

      <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
        {[
          { id: 'smart', label: 'Smart Bets', acc: 'var(--acc)' },
          { id: 'hr',    label: 'Big Bet (High Rollers)', acc: 'var(--acc-warn, #ffb648)' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} className="mono" style={{
            padding: '10px 18px', borderRadius: 11,
            fontSize: 11.5, fontWeight: 800, letterSpacing: '0.10em', textTransform: 'uppercase',
            border: tab === t.id ? `1px solid ${t.acc}` : '1px solid var(--bd)',
            background: tab === t.id ? `color-mix(in srgb, ${t.acc} 16%, rgba(8,13,24,0.55))` : 'rgba(8,13,24,0.55)',
            color: tab === t.id ? t.acc : 'var(--fg-muted)',
            cursor: 'pointer',
            boxShadow: tab === t.id ? `0 0 22px -6px ${t.acc}, inset 0 1px 0 rgba(255,255,255,0.18)` : 'none',
            textShadow: tab === t.id ? `0 0 10px color-mix(in srgb, ${t.acc} 60%, transparent)` : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      <div id="smartBetList" style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))' }}>
        {list.map(b => <SmartBetCard key={b.id} bet={b} />)}
      </div>
      <div id="hrBetList" style={{ display: 'none' }} />
      <div id="toastContainer" style={{ position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', zIndex: 200 }} />
    </ViewShell>
  );
}

function SmartBetCard({ bet }) {
  if (!bet) return null;
  const accent = bet.isDiamond ? '#7ad8ff' : 'var(--acc)';
  const rank = bet.rank || '';
  const name = bet.name || bet.bettor || 'Unknown';
  const rankAccent = rank.startsWith('Diamond') ? '#7ad8ff' : rank.startsWith('Platinum') ? '#c0c4d6' : rank.startsWith('Gold') ? '#d4af37' : 'var(--fg-muted)';
  const outcomes = Array.isArray(bet.outcomes) ? bet.outcomes : [];
  return (
    <div style={{
      position: 'relative', borderRadius: 20, padding: 18,
      background: 'linear-gradient(165deg, rgba(56,76,120,0.32) 0%, rgba(20,28,48,0.45) 50%, rgba(12,18,34,0.7) 100%)',
      backdropFilter: 'blur(24px) saturate(1.6)', WebkitBackdropFilter: 'blur(24px) saturate(1.6)',
      border: `1px solid color-mix(in srgb, ${accent} 25%, var(--bd))`,
      boxShadow: bet.isDiamond
        ? `0 22px 50px -22px rgba(0,0,0,0.85), 0 0 36px -10px ${accent}, inset 0 1.4px 0 rgba(255,255,255,0.30)`
        : '0 18px 48px -22px rgba(0,0,0,0.85), inset 0 1.2px 0 rgba(255,255,255,0.22)',
    }}>
      {bet.isDiamond && (
        <span className="mono" style={{ position: 'absolute', top: 12, right: 14, fontSize: 9.5, fontWeight: 800, letterSpacing: '0.14em', color: accent, textShadow: `0 0 12px ${accent}` }}>♦ DIAMOND</span>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 38, height: 38, borderRadius: 10, display: 'grid', placeItems: 'center', background: `linear-gradient(135deg, color-mix(in srgb, ${rankAccent} 30%, transparent), rgba(12,18,32,0.6))`, border: `1px solid color-mix(in srgb, ${rankAccent} 40%, transparent)`, color: rankAccent, fontWeight: 800, fontSize: 13 }}>
          {name.split(' ').map(p => p[0]).join('')}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.1 }}>{name}</div>
          <div className="mono" style={{ fontSize: 10, color: rankAccent, marginTop: 3, fontWeight: 600, letterSpacing: '0.06em' }}>{rank}{bet.wr != null ? ` · ${bet.wr}% WR` : ''}</div>
        </div>
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.06em' }}>{bet.time}</span>
      </div>

      <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--bd)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          {bet.sport && <MetaTag accent={accent}>{(bet.sport || '').toUpperCase()}</MetaTag>}
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)' }}>{bet.tournament}</span>
          {bet.live && <MetaTag accent="#ff4d8d">LIVE</MetaTag>}
        </div>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{bet.match}</div>
      </div>

      <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {outcomes.map((o, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
            <span style={{ fontSize: 12.5, color: 'var(--fg)' }}>{o.name}</span>
            <span className="mono" style={{ fontSize: 14, fontWeight: 800, color: accent, textShadow: `0 0 12px color-mix(in srgb, ${accent} 50%, transparent)` }}>{(o.odds || 0).toFixed(2)}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-muted)', letterSpacing: '0.10em' }}>STAKE</div>
          <div className="mono" style={{ fontSize: 17, fontWeight: 800, color: 'var(--fg)' }}>${(bet.stake || 0).toLocaleString()}</div>
        </div>
        <button className="mono" style={{
          padding: '9px 16px', borderRadius: 10,
          fontSize: 11, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase',
          background: `linear-gradient(135deg, color-mix(in srgb, ${accent} 90%, white), ${accent})`,
          color: '#052816',
          border: `1px solid color-mix(in srgb, ${accent} 70%, white)`,
          boxShadow: `0 8px 22px -6px color-mix(in srgb, ${accent} 60%, transparent), inset 0 1px 0 rgba(255,255,255,0.45)`,
          cursor: 'pointer',
        }}>Stake →</button>
      </div>
    </div>
  );
}

// ANALYTICS
function AnalyticsView() {
  const [tab, setTab] = useStateV('7d');
  const [profitData, setProfitData] = useStateV(null);
  useEffectV(() => {
    window.__fm_updateAnalytics = (d) => { if (d && d.stats) setProfitData(d.stats); else if (d) setProfitData(d); };
    apiFetch('/api/profits/stats').then(d => { if (d && d.stats) setProfitData(d.stats); }).catch(() => {});
    return () => { delete window.__fm_updateAnalytics; };
  }, []);
  const pd = profitData || {};
  const today = pd.today || {};
  const total = pd.total || {};
  const kpis = [
    { id: 'kpiTodayProfit', label: "Today's Profit", v: '+$' + (today.profit || 0).toFixed(2), acc: 'var(--acc)' },
    { id: 'kpiTotalProfit', label: 'Total Profit',   v: '+$' + (total.profit || 0).toLocaleString(), acc: 'var(--acc)' },
    { id: 'kpiWinRate',     label: 'Win Rate',       v: (total.winRate || 0).toFixed(1) + '%', acc: 'var(--acc-2)' },
    { id: 'kpiRoi',         label: 'ROI',            v: '+' + (total.bets > 0 && total.totalStake > 0 ? (total.profit / total.totalStake * 100).toFixed(2) : '0.00') + '%', acc: 'var(--acc-warn, #ffb648)' },
    { id: 'kpiTotalStake',  label: 'Total Stake',    v: '$' + (total.totalStake || 0).toLocaleString(), acc: 'var(--fg)' },
    { id: 'kpiAvgProfit',   label: 'Avg / Bet',      v: '$' + (total.avgProfit || 0).toFixed(2), acc: 'var(--fg)' },
  ];
  const days = tab === '7d' ? 7 : 30;
  const bars = useMemoV(() => {
    const arr = tab === '7d' ? (pd.last7Days || []) : (pd.last30Days || []);
    if (arr.length) return arr.slice(-days).map((v, i) => ({ d: i + 1, v: Math.max(0, typeof v === 'object' ? (v.profit || 0) : v) }));
    return Array.from({ length: days }, (_, i) => ({ d: i + 1, v: 0 }));
  }, [days, profitData]);
  const maxV = Math.max(...bars.map(b => b.v), 1);

  const history = pd.history || [];

  return (
    <ViewShell tag="Profit Insights" title="Analytics" subtitle="Theo dõi KPI thực thắng/lỗ, ROI, win rate và lịch sử bet.">
      <div id="kpiGrid" style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', marginBottom: 22 }}>
        {kpis.map(k => (
          <GlassCard key={k.id} style={{ padding: 16 }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{k.label}</div>
            <div id={k.id} className="mono" style={{ fontSize: 24, fontWeight: 800, color: k.acc, marginTop: 6, textShadow: `0 0 16px color-mix(in srgb, ${k.acc} 35%, transparent)` }}>{k.v}</div>
          </GlassCard>
        ))}
      </div>

      <GlassCard style={{ marginBottom: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, margin: 0 }}>Profit Trend</h3>
          <div style={{ display: 'flex', gap: 6, padding: 4, borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
            {['7d', '30d'].map(t => (
              <button key={t} id={'tab' + t} onClick={() => setTab(t)} className="mono" style={{
                padding: '6px 12px', borderRadius: 7,
                fontSize: 10.5, fontWeight: 800, letterSpacing: '0.10em',
                background: tab === t ? 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), transparent)' : 'transparent',
                color: tab === t ? 'var(--acc)' : 'var(--fg-muted)',
                border: 'none', cursor: 'pointer',
                textShadow: tab === t ? '0 0 10px color-mix(in srgb, var(--acc) 50%, transparent)' : 'none',
              }}>{t.toUpperCase()}</button>
            ))}
          </div>
        </div>
        <div id="profitChart" style={{ display: 'flex', alignItems: 'flex-end', gap: tab === '7d' ? 18 : 6, height: 200, padding: '8px 0', borderBottom: '1px solid var(--bd)' }}>
          {bars.map(b => (
            <div key={b.d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{
                width: '100%', height: (b.v / maxV * 100) + '%',
                background: `linear-gradient(180deg, var(--acc), color-mix(in srgb, var(--acc) 25%, transparent))`,
                borderRadius: '6px 6px 2px 2px',
                boxShadow: '0 0 14px -4px color-mix(in srgb, var(--acc) 55%, transparent), inset 0 1px 0 rgba(255,255,255,0.30)',
              }} />
              {tab === '7d' && <span className="mono" style={{ fontSize: 9, color: 'var(--fg-dim)' }}>D{b.d}</span>}
            </div>
          ))}
        </div>
      </GlassCard>

      <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', marginBottom: 22 }}>
        <GlassCard>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 14px' }}>Bookmaker Breakdown</h3>
          <div id="bookmakerBreakdown" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { name: '1xBet', pct: 38, v: 4870 },
              { name: 'Parimatch', pct: 24, v: 3080 },
              { name: 'Stake', pct: 18, v: 2310 },
              { name: 'Polymarket', pct: 12, v: 1540 },
              { name: 'BC Game', pct: 8, v: 1040 },
            ].map((b, i) => (
              <div key={i}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                  <span style={{ color: 'var(--fg)' }}>{b.name}</span>
                  <span className="mono" style={{ color: 'var(--fg-muted)' }}>${b.v.toLocaleString()} · {b.pct}%</span>
                </div>
                <div style={{ height: 6, borderRadius: 999, background: 'rgba(8,13,24,0.55)', overflow: 'hidden' }}>
                  <div style={{ width: b.pct + '%', height: '100%', background: 'linear-gradient(90deg, var(--acc), var(--acc-2))', boxShadow: '0 0 10px -2px var(--acc)' }} />
                </div>
              </div>
            ))}
          </div>
        </GlassCard>
        <GlassCard>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 14px' }}>Streak</h3>
          <div id="streakGrid" style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(2, 1fr)' }}>
            {[
              { id: 'streakCurrentWin',  label: 'Current Win',  v: 12, acc: 'var(--acc)' },
              { id: 'streakBestWin',     label: 'Best Win',     v: 28, acc: 'var(--acc)' },
              { id: 'streakCurrentLose', label: 'Current Lose', v: 0,  acc: 'var(--fg-muted)' },
              { id: 'streakWorstLose',   label: 'Worst Lose',   v: 5,  acc: '#ff4d8d' },
            ].map(s => (
              <div key={s.id} style={{ padding: 12, borderRadius: 11, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
                <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{s.label}</div>
                <div id={s.id} className="mono" style={{ fontSize: 22, fontWeight: 800, color: s.acc, marginTop: 4 }}>{s.v}</div>
              </div>
            ))}
          </div>
        </GlassCard>
      </div>

      <GlassCard>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: 0, flex: 1 }}>Transaction History</h3>
          <input id="historyFrom" type="date" defaultValue="2026-05-10" style={inputStyle} />
          <input id="historyTo" type="date" defaultValue="2026-05-18" style={inputStyle} />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table id="historyTable" style={{ width: '100%', borderCollapse: 'collapse', minWidth: 600 }}>
            <thead>
              <tr style={{ fontSize: 10.5, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>
                {['Date', 'Match', 'Bet', 'Bookmaker', 'Stake', 'Profit', ''].map(h => (
                  <th key={h} style={{ textAlign: h === 'Stake' || h === 'Profit' ? 'right' : 'left', padding: '8px 10px', borderBottom: '1px solid var(--bd)', fontWeight: 700 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody id="historyBody">
              {history.map(h => (
                <tr key={h.id} style={{ fontSize: 13 }}>
                  <td style={{ padding: '10px', color: 'var(--fg-muted)' }} className="mono">{h.date}</td>
                  <td style={{ padding: '10px' }}>{h.match}</td>
                  <td style={{ padding: '10px', color: 'var(--fg-muted)' }}>{h.bet}</td>
                  <td style={{ padding: '10px' }}>{h.book}</td>
                  <td style={{ padding: '10px', textAlign: 'right' }} className="mono">${h.stake}</td>
                  <td style={{ padding: '10px', textAlign: 'right', color: h.profit >= 0 ? 'var(--acc)' : '#ff4d8d', fontWeight: 700 }} className="mono">
                    {h.profit >= 0 ? '+' : ''}${h.profit.toFixed(2)}
                  </td>
                  <td style={{ padding: '10px', textAlign: 'right' }}>
                    <button style={{ width: 26, height: 26, borderRadius: 7, background: 'transparent', border: '1px solid var(--bd)', color: 'var(--fg-dim)', cursor: 'pointer', fontSize: 13 }}>×</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </GlassCard>
    </ViewShell>
  );
}

// PROFILE
function ProfileView() {
  const [u, setU] = useStateV({});
  const [firstName, setFirstName] = useStateV('');
  const [lastName,  setLastName]  = useStateV('');
  const [profileMsg, setProfileMsg] = useStateV('');
  const [pwMsg, setPwMsg] = useStateV('');
  const [oldPw, setOldPw] = useStateV('');
  const [newPw, setNewPw] = useStateV('');
  const [confPw, setConfPw] = useStateV('');

  // Load user data on mount; re-sync when api-connector pushes fresh data
  useEffectV(() => {
    const sync = (fresh) => {
      if (!fresh) fresh = window.__fm_currentUser || window.__fm_user;
      if (!fresh || !fresh.id) return;
      setU(fresh);
      setFirstName(fresh.firstName || '');
      setLastName(fresh.lastName || '');
    };
    sync();
    window.__fm_setProfileUser = sync;
    return () => { delete window.__fm_setProfileUser; };
  }, []);

  const handleSaveProfile = async (e) => {
    e.preventDefault();
    try {
      const d = await apiFetch('/api/auth/profile', { method: 'PUT', body: JSON.stringify({ firstName, lastName }) });
      if (d.success) {
        const updated = { ...u, firstName, lastName };
        setU(updated);
        window.__fm_currentUser = updated;
        setProfileMsg('✓ Saved');
      } else {
        setProfileMsg(d.error || 'Error');
      }
      setTimeout(() => setProfileMsg(''), 3000);
    } catch (_) { setProfileMsg('Connection error'); }
  };

  const handleChangePassword = async (e) => {
    e.preventDefault();
    if (newPw !== confPw) { setPwMsg('Passwords do not match'); return; }
    try {
      const d = await apiFetch('/api/auth/change-password', { method: 'POST', body: JSON.stringify({ currentPassword: oldPw, newPassword: newPw }) });
      setPwMsg(d.success ? '✓ Password updated' : (d.error || 'Error'));
      if (d.success) { setOldPw(''); setNewPw(''); setConfPw(''); }
    } catch (_) { setPwMsg('Connection error'); }
    setTimeout(() => setPwMsg(''), 4000);
  };

  // All derived from u state — never from stale snapshots
  const expiry = u.subscriptionExpiresAt || u.subscriptionExpiry || null;
  const expMs = expiry ? new Date(expiry).getTime() : 0;
  const daysLeft = expiry ? Math.max(0, Math.ceil((expMs - Date.now()) / 86400000)) : 0;
  const isPaid = u.role === 'paid';
  const isAdmin = u.role === 'admin';
  const roleLabel = isAdmin ? '★ ADMIN' : isPaid ? '★ PAID' : u.id ? '○ FREE' : '…';
  const roleColor = isAdmin ? '#ffd700' : isPaid ? 'var(--acc)' : 'var(--fg-muted)';

  const inputStyle = {
    width: '100%', padding: '11px 13px', borderRadius: 10,
    background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)',
    color: 'var(--fg)', fontSize: 13, outline: 'none',
    boxShadow: 'inset 0 1px 0 rgba(0,0,0,0.20)',
  };
  const inputReadOnly = { ...inputStyle, background: 'rgba(8,13,24,0.30)', color: 'var(--fg-muted)' };

  return (
    <ViewShell tag="Account" title="Profile" subtitle="Quản lý hồ sơ, mật khẩu và gói đăng ký của bạn.">
      <div style={{ display: 'grid', gap: 18, gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 280px), 1fr))' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Identity card */}
          <GlassCard style={{ textAlign: 'center', padding: 26 }}>
            <div style={{
              width: 88, height: 88, borderRadius: '50%', margin: '0 auto 14px',
              display: 'grid', placeItems: 'center',
              background: 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), rgba(12,18,32,0.6))',
              border: '1px solid color-mix(in srgb, var(--acc) 45%, transparent)',
              boxShadow: '0 0 28px -4px color-mix(in srgb, var(--acc) 55%, transparent), inset 0 1px 0 rgba(255,255,255,0.30)',
              fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700, color: 'var(--acc)',
            }}>{((u.username || 'U')[0]).toUpperCase()}</div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>{u.username || '—'}</div>
            <div className="mono" style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 4 }}>{u.email || '—'}</div>
            <div style={{ marginTop: 14, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span className="mono" style={{
                padding: '3px 10px', borderRadius: 99, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.10em',
                border: `1px solid color-mix(in srgb, ${roleColor} 50%, transparent)`,
                background: `color-mix(in srgb, ${roleColor} 12%, transparent)`,
                color: roleColor,
              }}>{roleLabel}</span>
            </div>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-dim)', marginTop: 18, lineHeight: 1.8 }}>
              <div><span style={{ color: 'var(--fg-muted)' }}>Member Since:</span> {u.createdAt ? u.createdAt.slice(0, 10) : '—'}</div>
              <div><span style={{ color: 'var(--fg-muted)' }}>Last Login:</span> {u.lastLogin ? u.lastLogin.slice(0, 16).replace('T', ' ') : '—'}</div>
            </div>
            <button
              onClick={() => { localStorage.removeItem('fm_token'); localStorage.removeItem('fm_settings'); window.location.href = '/login.html'; }}
              style={{
                width: '100%', marginTop: 18, padding: '10px 14px',
                borderRadius: 10, border: '1px solid color-mix(in srgb, #ff4d8d 40%, transparent)',
                background: 'color-mix(in srgb, #ff4d8d 10%, transparent)',
                color: '#ff4d8d', fontFamily: 'var(--font-mono)', fontSize: 11.5, fontWeight: 800, letterSpacing: '0.10em', textTransform: 'uppercase',
                cursor: 'pointer',
              }}>Sign Out</button>
          </GlassCard>

          {/* Subscription card */}
          <GlassCard id="subscriptionCard" accent="var(--acc)">
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 10px' }}>Subscription</h3>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-muted)', letterSpacing: '0.10em' }}>TIME REMAINING</div>
            <div className="mono" style={{ fontSize: 28, fontWeight: 800, color: 'var(--acc)', textShadow: '0 0 20px color-mix(in srgb, var(--acc) 50%, transparent)' }}>
              {isAdmin ? 'Unlimited' : isPaid && expiry ? daysLeft + ' days' : 'Free plan'}
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4 }}>
              {isAdmin ? 'Admin account' : isPaid && expiry ? 'expires ' + expiry.slice(0, 10) : 'Upgrade to access full feed'}
            </div>
            {!isAdmin && (
              <button
                onClick={() => { if (window.__fm_nav) window.__fm_nav('payment'); }}
                style={{
                  width: '100%', marginTop: 14, padding: '10px 14px',
                  borderRadius: 10, border: '1px solid color-mix(in srgb, var(--acc) 60%, white)',
                  background: 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 90%, white), var(--acc))',
                  color: '#052816', fontFamily: 'var(--font-mono)', fontSize: 11.5, fontWeight: 800, letterSpacing: '0.10em', textTransform: 'uppercase',
                  cursor: 'pointer',
                  boxShadow: '0 8px 20px -6px color-mix(in srgb, var(--acc) 60%, transparent), inset 0 1px 0 rgba(255,255,255,0.45)',
                }}>{isPaid ? 'Renew →' : 'Upgrade →'}</button>
            )}
          </GlassCard>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Edit Profile */}
          <GlassCard>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, margin: '0 0 16px' }}>Edit Profile</h3>
            <form onSubmit={handleSaveProfile}>
              <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(2, 1fr)' }}>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>First Name</span>
                  <input value={firstName} onChange={e => setFirstName(e.target.value)} style={inputStyle} />
                </label>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Last Name</span>
                  <input value={lastName} onChange={e => setLastName(e.target.value)} style={inputStyle} />
                </label>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Username</span>
                  <input value={u.username || ''} readOnly style={inputReadOnly} />
                </label>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Email</span>
                  <input value={u.email || ''} readOnly style={inputReadOnly} />
                </label>
              </div>
              <button type="submit" style={primaryBtn}>Save Changes</button>
              {profileMsg && <div style={{ marginTop: 8, fontSize: 13, color: profileMsg.startsWith('✓') ? 'var(--acc)' : '#ff4d8d' }}>{profileMsg}</div>}
            </form>
          </GlassCard>

          {/* Change Password */}
          <GlassCard>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, margin: '0 0 16px' }}>Change Password</h3>
            <form onSubmit={handleChangePassword}>
              <div style={{ display: 'grid', gap: 14 }}>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Current Password</span>
                  <input type="password" value={oldPw} onChange={e => setOldPw(e.target.value)} style={inputStyle} />
                </label>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>New Password</span>
                  <input type="password" value={newPw} onChange={e => setNewPw(e.target.value)} style={inputStyle} />
                </label>
                <label style={{ display: 'block' }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Confirm Password</span>
                  <input type="password" value={confPw} onChange={e => setConfPw(e.target.value)} style={inputStyle} />
                </label>
              </div>
              <button type="submit" style={primaryBtn}>Update Password</button>
              {pwMsg && <div style={{ marginTop: 8, fontSize: 13, color: pwMsg.startsWith('✓') ? 'var(--acc)' : '#ff4d8d' }}>{pwMsg}</div>}
            </form>
          </GlassCard>

          {/* hidden compat divs kept for api-connector DOM queries */}
          <div id="message" style={{ display: 'none' }} />
        </div>
      </div>
    </ViewShell>
  );
}

// TIPS
function TipsView() {
  const cats = ['All', 'General', 'Strategy', 'Guide', 'Analysis', 'News'];
  const [cat, setCat] = useStateV('All');
  const [adding, setAdding] = useStateV(false);
  const [tips, setTips] = useStateV([]);
  const [msg, setMsg] = useStateV('');
  useEffectV(() => {
    window.__fm_updateTips = setTips;
    // request current tips via api-connector if already loaded
    if (window.__fm_loadTips) window.__fm_loadTips();
    return () => { delete window.__fm_updateTips; };
  }, []);
  const list = cat === 'All' ? tips : tips.filter(t => t.cat === cat);

  async function handleTipSubmit(e) {
    e.preventDefault();
    const title = document.getElementById('tipTitle')?.value?.trim();
    const category = document.getElementById('tipCategory')?.value;
    const content = document.getElementById('tipContent')?.value?.trim();
    if (!title || !content) { setMsg('Title và content không được để trống.'); return; }
    const res = await (window.__fm_submitTip ? window.__fm_submitTip(title, category, content) : Promise.resolve({ success: false, error: 'Not connected' }));
    if (res.success) { setAdding(false); setMsg(''); }
    else setMsg(res.error || 'Lỗi khi đăng tip.');
  }

  return (
    <ViewShell tag="Community" title="Tips & Hướng dẫn" subtitle="Chiến lược, hướng dẫn và phân tích từ admin và bettor.">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)} className="mono" style={{
            padding: '7px 14px', borderRadius: 999,
            fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
            background: cat === c ? 'color-mix(in srgb, var(--acc) 18%, rgba(8,13,24,0.55))' : 'rgba(8,13,24,0.55)',
            border: cat === c ? '1px solid color-mix(in srgb, var(--acc) 50%, transparent)' : '1px solid var(--bd)',
            color: cat === c ? 'var(--acc)' : 'var(--fg-muted)',
            cursor: 'pointer',
            boxShadow: cat === c ? '0 0 16px -4px color-mix(in srgb, var(--acc) 60%, transparent)' : 'none',
          }}>{c}</button>
        ))}
        <span style={{ flex: 1 }} />
        <button id="tipAddBtn" onClick={() => setAdding(v => !v)} className="mono" style={{ ...primaryBtn, marginTop: 0 }}>+ Add Tip</button>
      </div>

      {adding && (
        <form id="tipForm" onSubmit={handleTipSubmit} style={{ marginBottom: 18 }}>
          <GlassCard>
            <div style={{ display: 'grid', gap: 12 }}>
              <Field id="tipTitle" label="Title" />
              <label>
                <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Category</span>
                <select id="tipCategory" style={{ width: '100%', padding: '11px 13px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none' }}>
                  {cats.filter(c => c !== 'All').map(c => <option key={c}>{c}</option>)}
                </select>
              </label>
              <label>
                <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Content</span>
                <textarea id="tipContent" rows={4} style={{ width: '100%', padding: '11px 13px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none', resize: 'vertical', fontFamily: 'inherit' }} />
              </label>
              {msg && <div style={{ color: '#ff4d8d', fontSize: 12, fontFamily: 'var(--font-mono)' }}>{msg}</div>}
              <button id="tipSubmitBtn" style={{ ...primaryBtn, marginTop: 0 }}>Publish Tip</button>
            </div>
          </GlassCard>
        </form>
      )}

      <div id="tipsList" style={{ display: 'grid', gap: 14 }}>
        {list.map(t => (
          <GlassCard key={t.id}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
              <MetaTag>{t.cat}</MetaTag>
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>by <b style={{ color: 'var(--fg)' }}>{t.author}</b></span>
              {t.role === 'admin' && <MetaTag accent="var(--acc-warn, #ffb648)">★ ADMIN</MetaTag>}
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--fg-dim)' }}>· {t.ago} ago</span>
              <span style={{ flex: 1 }} />
              <button onClick={() => window.__fm_likeTip && window.__fm_likeTip(t.id)} className="mono" style={{ padding: '6px 10px', borderRadius: 9, background: t.hasLiked ? 'color-mix(in srgb, var(--acc) 14%, rgba(8,13,24,0.55))' : 'rgba(8,13,24,0.55)', border: t.hasLiked ? '1px solid color-mix(in srgb, var(--acc) 50%, transparent)' : '1px solid var(--bd)', color: t.hasLiked ? 'var(--acc)' : 'var(--fg)', cursor: 'pointer', fontSize: 11.5 }}>{t.hasLiked ? '♥' : '♡'} {t.likes}</button>
              {window.__fm_user && (window.__fm_user.role === 'admin' || window.__fm_user.id === t.authorId) && (
                <button onClick={() => window.__fm_deleteTip && window.__fm_deleteTip(t.id)} className="mono" style={{ padding: '6px 10px', borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid color-mix(in srgb, #ff4d8d 30%, var(--bd))', color: '#ff4d8d', cursor: 'pointer', fontSize: 11.5 }}>× Del</button>
              )}
            </div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 8px' }}>{t.title}</h3>
            <p style={{ color: 'var(--fg-muted)', fontSize: 13.5, lineHeight: 1.6, margin: 0, whiteSpace: 'pre-wrap' }}>{t.content}</p>
          </GlassCard>
        ))}
      </div>
    </ViewShell>
  );
}

// CALCULATOR
function CalcView() {
  const [stake, setStake] = useStateV(100);
  const [bets, setBets] = useStateV([
    { odds: 2.05 },
    { odds: 2.15 },
  ]);
  const fairStakes = useMemoV(() => {
    const inv = bets.map(b => 1 / b.odds);
    const sumInv = inv.reduce((a, b) => a + b, 0);
    return bets.map((b, i) => ({
      odds: b.odds,
      stake: (stake * inv[i] / sumInv).toFixed(2),
      payout: (stake * inv[i] / sumInv * b.odds).toFixed(2),
    }));
  }, [bets, stake]);
  const minPayout = Math.min(...fairStakes.map(f => parseFloat(f.payout)));
  const profit = (minPayout - stake).toFixed(2);
  const roi = stake > 0 ? ((minPayout - stake) / stake * 100).toFixed(2) : '0.00';

  return (
    <ViewShell tag="Tools" title="Arbitrage Calculator" subtitle="Tự động tính stake tối ưu cho mỗi outcome để guarantee profit.">
      <div style={{ display: 'grid', gap: 18, gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 1fr)' }}>
        <GlassCard>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 16px' }}>Setup</h3>
          <div style={{ display: 'grid', gap: 14 }}>
            <label>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Total Stake (USD)</span>
              <input type="number" value={stake} onChange={e => setStake(parseFloat(e.target.value) || 0)} style={{ width: '100%', padding: '13px 14px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid color-mix(in srgb, var(--acc) 30%, var(--bd))', color: 'var(--acc)', fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 800, outline: 'none', textShadow: '0 0 14px color-mix(in srgb, var(--acc) 40%, transparent)' }} />
            </label>
            {bets.map((b, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-end', padding: 12, borderRadius: 11, background: 'rgba(8,13,24,0.45)', border: '1px solid var(--bd)' }}>
                <label style={{ flex: 1 }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Outcome {i + 1} · Odds</span>
                  <input type="number" step="0.01" value={b.odds} onChange={e => { const nv = [...bets]; nv[i].odds = parseFloat(e.target.value) || 0; setBets(nv); }} style={{ width: '100%', padding: '10px 12px', borderRadius: 9, background: 'rgba(8,13,24,0.65)', border: '1px solid var(--bd)', color: 'var(--fg)', fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, outline: 'none' }} />
                </label>
                <div style={{ minWidth: 120 }}>
                  <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Stake</span>
                  <div className="mono" style={{ padding: '10px 12px', borderRadius: 9, background: 'color-mix(in srgb, var(--acc) 8%, rgba(8,13,24,0.65))', border: '1px solid color-mix(in srgb, var(--acc) 30%, var(--bd))', color: 'var(--acc)', fontSize: 14, fontWeight: 800, textAlign: 'right' }}>${fairStakes[i].stake}</div>
                </div>
                <button onClick={() => setBets(bets.filter((_, j) => j !== i))} style={{ width: 36, height: 36, borderRadius: 9, background: 'transparent', border: '1px solid var(--bd)', color: 'var(--fg-dim)', cursor: 'pointer', fontSize: 16 }}>×</button>
              </div>
            ))}
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={() => setBets([...bets, { odds: 2.00 }])} className="mono" style={{ flex: 1, padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px dashed var(--bd)', color: 'var(--fg-muted)', cursor: 'pointer', fontSize: 11.5, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase' }}>+ Add Outcome</button>
              <button onClick={() => setBets([{ odds: 2.05 }, { odds: 2.15 }])} className="mono" style={{ flex: 1, padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)', cursor: 'pointer', fontSize: 11.5, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase' }}>Reset</button>
            </div>
          </div>
        </GlassCard>

        <GlassCard accent={parseFloat(profit) > 0 ? 'var(--acc)' : '#ff4d8d'}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 16px' }}>Outcome</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>Guaranteed Profit</div>
              <div className="mono" style={{ fontSize: 38, fontWeight: 800, color: parseFloat(profit) >= 0 ? 'var(--acc)' : '#ff4d8d', textShadow: `0 0 26px color-mix(in srgb, ${parseFloat(profit) >= 0 ? 'var(--acc)' : '#ff4d8d'} 55%, transparent)`, letterSpacing: '-0.02em', lineHeight: 1 }}>
                {parseFloat(profit) >= 0 ? '+' : ''}${profit}
              </div>
            </div>
            <div>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>ROI</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: parseFloat(roi) >= 0 ? 'var(--acc-2)' : '#ff4d8d' }}>{parseFloat(roi) >= 0 ? '+' : ''}{roi}%</div>
            </div>
            <div style={{ borderTop: '1px solid var(--bd)', paddingTop: 14 }}>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', marginBottom: 8 }}>Payouts per outcome</div>
              {fairStakes.map((f, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--bd)', fontSize: 13 }}>
                  <span style={{ color: 'var(--fg-muted)' }}>Outcome {i + 1} @ {f.odds.toFixed(2)}</span>
                  <span className="mono" style={{ color: 'var(--fg)', fontWeight: 700 }}>${f.payout}</span>
                </div>
              ))}
            </div>
          </div>
        </GlassCard>
      </div>
    </ViewShell>
  );
}

// ABOUT
function AboutView() {
  return (
    <ViewShell tag="About" title="The arbitrage engine for sharp bettors" subtitle="FreeM0ney quét odds từ hàng chục bookmaker mỗi giây, tìm surebet và alert real-time.">
      <div style={{ display: 'grid', gap: 18, gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', marginBottom: 28 }}>
        {[
          { t: 'Real-time scanning', d: 'Quét odds liên tục từ 30+ bookmaker. Detect surebet ngay khi xuất hiện, độ trễ < 2s.', acc: 'var(--acc)' },
          { t: 'Matched pairs view', d: 'Map team name từ nhiều bookmaker về cùng entity, tránh false-positive.', acc: 'var(--acc-2)' },
          { t: 'ROI Calculator', d: 'Tính stake tối ưu cho mỗi outcome — guaranteed profit.', acc: 'var(--acc-warn, #ffb648)' },
          { t: 'Smart Bets alerts', d: 'Theo dõi cược của bettor Diamond rank, gửi alert khi họ stake lớn.', acc: '#ff4d8d' },
        ].map((f, i) => (
          <GlassCard key={i} accent={f.acc}>
            <div style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', background: `color-mix(in srgb, ${f.acc} 16%, transparent)`, border: `1px solid color-mix(in srgb, ${f.acc} 40%, transparent)`, color: f.acc, marginBottom: 12 }}>★</div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 6px' }}>{f.t}</h3>
            <p style={{ color: 'var(--fg-muted)', fontSize: 13, margin: 0, lineHeight: 1.6 }}>{f.d}</p>
          </GlassCard>
        ))}
      </div>

      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, margin: '0 0 12px' }}>Supported Bookmakers</h3>
        <p style={{ color: 'var(--fg-muted)', fontSize: 13, marginBottom: 14 }}>1xBet · Parimatch · Pinnacle · BetMGM · DraftKings · FanDuel · Stake · Polymarket · Betano · Unibet · bwin · BC Game · Sbobet · Raybet · SABA và nhiều hơn nữa.</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['1xbet', 'parimatch', 'polymarket', 'stake', 'sbobet', 'bc-game', 'raybet', 'saba'].map(id => (
            <span key={id} style={{ padding: '6px 12px', borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-muted)' }}>{id}</span>
          ))}
        </div>
      </GlassCard>
    </ViewShell>
  );
}

// CONTACT
function ContactView() {
  const [msgStatus, setMsgStatus] = useStateV('');
  const handleSend = async (e) => {
    e.preventDefault();
    const category = document.getElementById('msgCategory')?.value || '';
    const subject  = document.getElementById('msgSubject')?.value  || '';
    const body     = document.getElementById('msgBody')?.value     || '';
    if (!subject || !body) { setMsgStatus('Please fill in subject and message.'); return; }
    try {
      const d = await apiFetch('/api/admin/contact', { method: 'POST', body: JSON.stringify({ category, subject, message: body }) });
      setMsgStatus(d.success ? '✓ Message sent!' : (d.error || 'Error sending'));
    } catch (_) { setMsgStatus('Connection error'); }
    setTimeout(() => setMsgStatus(''), 4000);
  };
  return (
    <ViewShell tag="Support" title="Contact Support" subtitle="Nhắn cho admin trong group Telegram, hoặc gửi form tại đây.">
      <div style={{ display: 'grid', gap: 18, gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.4fr)' }}>
        <GlassCard>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 14px' }}>Direct Channels</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Channel icon="✈" name="Telegram Group" v="@freem0ney" acc="var(--acc-2)" />
            <Channel icon="✉" name="Email"          v="support@freem0ney.com" acc="var(--acc)" />
            <Channel icon="◉" name="Discord"        v="discord.gg/freem0ney" acc="#7c5cff" />
          </div>
          <div style={{ marginTop: 18, padding: 14, borderRadius: 11, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', marginBottom: 4 }}>Availability</div>
            <div style={{ fontSize: 13, color: 'var(--fg)' }}>24/7 monitoring · Avg response ~ 15 minutes</div>
          </div>
        </GlassCard>
        <GlassCard>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, margin: '0 0 14px' }}>Send a Message</h3>
          <form onSubmit={handleSend} style={{ display: 'grid', gap: 12 }}>
            <label>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Category</span>
              <select id="msgCategory" style={{ width: '100%', padding: '11px 13px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none' }}>
                <option>General</option><option>Billing</option><option>Bug Report</option><option>Feature Request</option>
              </select>
            </label>
            <Field id="msgSubject" label="Subject" />
            <label>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Message</span>
              <textarea id="msgBody" rows={6} style={{ width: '100%', padding: '11px 13px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none', resize: 'vertical', fontFamily: 'inherit' }} />
            </label>
            <button type="submit" style={primaryBtn}>Send Message</button>
            {msgStatus && <div style={{ fontSize: 13, color: msgStatus.startsWith('✓') ? 'var(--acc)' : '#ff4d8d' }}>{msgStatus}</div>}
          </form>
        </GlassCard>
      </div>
    </ViewShell>
  );
}

function Channel({ icon, name, v, acc }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, borderRadius: 11, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
      <div style={{ width: 36, height: 36, borderRadius: 9, display: 'grid', placeItems: 'center', background: `color-mix(in srgb, ${acc} 16%, transparent)`, border: `1px solid color-mix(in srgb, ${acc} 40%, transparent)`, color: acc, fontSize: 16 }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{name}</div>
        <div className="mono" style={{ fontSize: 11.5, color: acc }}>{v}</div>
      </div>
    </div>
  );
}

// ADMIN
class AdminErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null, info: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { this.setState({ info }); console.error('AdminView error:', error, info); }
  render() {
    if (this.state.error) {
      return React.createElement('div', { style: { padding: 30, color: '#ff4d8d', fontFamily: 'var(--font-mono)', fontSize: 13 } },
        React.createElement('h3', { style: { color: '#ff4d8d', margin: '0 0 12px' } }, '⚠ Admin Panel Error'),
        React.createElement('pre', { style: { whiteSpace: 'pre-wrap', background: 'rgba(255,77,141,0.1)', padding: 16, borderRadius: 10, border: '1px solid rgba(255,77,141,0.3)' } },
          String(this.state.error?.message || this.state.error) + '\n\n' + (this.state.info?.componentStack || '')
        ),
        React.createElement('button', {
          onClick: () => this.setState({ error: null, info: null }),
          style: { marginTop: 12, padding: '8px 16px', borderRadius: 8, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', cursor: 'pointer', fontSize: 12, fontWeight: 700 }
        }, 'Retry')
      );
    }
    return this.props.children;
  }
}

function AdminView() {
  const [tab, setTab] = useStateV('users');
  const tabs = [
    { id: 'users',     label: 'Users' },
    { id: 'payments',  label: 'Payments' },
    { id: 'settings',  label: 'Settings' },
    { id: 'aliases',   label: 'Team Aliases' },
    { id: 'leagues',   label: 'Leagues' },
    { id: 'markets',   label: 'Markets' },
    { id: 'monitor',   label: 'Match Monitor' },
  ];

  return (
    <ViewShell tag="Admin Panel" title="System Control" subtitle="Manage users, payments, settings, aliases, leagues, markets và match monitor.">
      <div style={{ display: 'flex', gap: 6, marginBottom: 18, flexWrap: 'wrap', padding: 4, borderRadius: 12, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} className="mono" style={{
            padding: '8px 14px', borderRadius: 8,
            fontSize: 11, fontWeight: 800, letterSpacing: '0.10em', textTransform: 'uppercase',
            background: tab === t.id ? 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), transparent)' : 'transparent',
            border: 'none',
            color: tab === t.id ? 'var(--acc)' : 'var(--fg-muted)',
            cursor: 'pointer',
            textShadow: tab === t.id ? '0 0 10px color-mix(in srgb, var(--acc) 50%, transparent)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      <AdminErrorBoundary>
        {tab === 'users'    && <AdminUsers />}
        {tab === 'payments' && <AdminPayments />}
        {tab === 'settings' && <AdminSettings />}
        {tab === 'aliases'  && <AdminAliases />}
        {tab === 'leagues'  && <AdminLeagues />}
        {tab === 'markets'  && <AdminMarkets />}
        {tab === 'monitor'  && <AdminMonitor />}
      </AdminErrorBoundary>
    </ViewShell>
  );
}

function AdminUsers() {
  const [filter, setFilter] = useStateV('all');
  const [users, setUsers] = useStateV([]);
  const [meta, setMeta] = useStateV({ totalRegistered: 0, uniqueUsers: 0, totalConnections: 0 });

  const loadUsers = () => {
    apiFetch('/api/admin/active-users').then(d => {
      setMeta({ totalRegistered: d.totalRegistered || 0, uniqueUsers: d.uniqueUsers || 0, totalConnections: d.totalConnections || 0 });
      const list = d.users || d.data || (Array.isArray(d) ? d : []);
      setUsers(list.map(u => ({
        id: u._id || u.id || '',
        name: u.username || u.name || '',
        email: u.email || '',
        role: u.role || 'free',
        ip: u.ip || u.lastLoginIp || '—',
        conn: u.connections || u.conn || 0,
        pages: u.pages || [],
        last: u.lastLogin ? u.lastLogin.slice(0, 16).replace('T', ' ') : '—',
        online: u.online !== undefined ? u.online : false,
      })));
    }).catch(() => {});
  };

  useEffectV(() => { loadUsers(); }, []);

  const changeRole = async (userId, newRole) => {
    await apiFetch(`/api/auth/users/${userId}/role`, { method: 'PUT', body: JSON.stringify({ role: newRole }) });
    loadUsers();
  };

  const deleteUser = async (userId, name) => {
    if (!confirm(`Delete user "${name}"? This cannot be undone.`)) return;
    await apiFetch(`/api/auth/users/${userId}`, { method: 'DELETE' });
    loadUsers();
  };
  const list = filter === 'all' ? users : users.filter(u => filter === 'online' ? u.online : !u.online);

  return (
    <div>
      <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', marginBottom: 18 }}>
        {[
          { id: 'uniqueUsers',      label: 'Online unique',     v: meta.uniqueUsers },
          { id: 'totalConnections', label: 'Total connections', v: meta.totalConnections },
          { id: 'totalRegistered',  label: 'Total registered',  v: meta.totalRegistered },
        ].map(k => (
          <GlassCard key={k.id} style={{ padding: 14 }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{k.label}</div>
            <div id={k.id} className="mono" style={{ fontSize: 22, fontWeight: 800, color: 'var(--acc)', marginTop: 6 }}>{k.v}</div>
          </GlassCard>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 6, marginBottom: 14, padding: 4, borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', width: 'fit-content' }}>
        {[
          { id: 'filterAll',     label: 'All',     v: 'all' },
          { id: 'filterOnline',  label: 'Online',  v: 'online' },
          { id: 'filterOffline', label: 'Offline', v: 'offline' },
        ].map(f => (
          <button key={f.v} id={f.id} onClick={() => setFilter(f.v)} className="mono" style={{
            padding: '6px 12px', borderRadius: 7, border: 'none',
            background: filter === f.v ? 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), transparent)' : 'transparent',
            color: filter === f.v ? 'var(--acc)' : 'var(--fg-muted)',
            fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', cursor: 'pointer',
          }}>{f.label}</button>
        ))}
      </div>

      <GlassCard style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 700 }}>
            <thead>
              <tr style={{ fontSize: 10.5, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--fg-muted)', background: 'rgba(8,13,24,0.55)' }}>
                {['', 'Username / Email', 'Role', 'IP', 'Conn', 'Pages', 'Last Login', 'Actions'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '12px 14px', borderBottom: '1px solid var(--bd)', fontWeight: 700 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody id="userTableBody">
              {list.map((u, i) => (
                <tr key={i} style={{ fontSize: 13, borderBottom: '1px solid var(--bd)' }}>
                  <td style={{ padding: 14 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: u.online ? 'var(--acc)' : 'var(--fg-dim)', boxShadow: u.online ? '0 0 8px var(--acc)' : 'none', display: 'inline-block' }} /></td>
                  <td style={{ padding: 14 }}><div style={{ fontWeight: 600 }}>{u.name}</div><div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>{u.email}</div></td>
                  <td style={{ padding: 14 }}><RoleBadge role={u.role} /></td>
                  <td style={{ padding: 14 }} className="mono">{u.ip}</td>
                  <td style={{ padding: 14 }} className="mono">{u.conn}</td>
                  <td style={{ padding: 14 }}>{u.pages.map(p => <span key={p} style={{ display: 'inline-block', marginRight: 4, padding: '2px 8px', borderRadius: 6, fontSize: 10.5, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)' }} className="mono">{p}</span>)}</td>
                  <td style={{ padding: 14 }} className="mono">{u.last}</td>
                  <td style={{ padding: '10px 14px' }}>
                    {u.id && (
                      <div style={{ display: 'flex', gap: 6 }}>
                        <select
                          value={u.role}
                          onChange={e => changeRole(u.id, e.target.value)}
                          style={{ padding: '4px 6px', borderRadius: 6, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)', fontSize: 11, cursor: 'pointer' }}
                        >
                          {['free', 'paid', 'admin'].map(r => <option key={r} value={r}>{r}</option>)}
                        </select>
                        <button
                          onClick={() => deleteUser(u.id, u.name)}
                          style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid color-mix(in srgb, #ff4d8d 40%, transparent)', background: 'color-mix(in srgb, #ff4d8d 8%, transparent)', color: '#ff4d8d', fontSize: 11, cursor: 'pointer', fontWeight: 700 }}
                        >✕</button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </GlassCard>
    </div>
  );
}

function RoleBadge({ role }) {
  const map = { admin: { c: '#ffb648', l: 'ADMIN' }, paid: { c: 'var(--acc)', l: 'PAID' }, free: { c: 'var(--fg-muted)', l: 'FREE' } };
  const m = map[role] || map.free;
  return <span className="mono" style={{ display: 'inline-block', padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 800, letterSpacing: '0.08em', color: m.c, border: `1px solid color-mix(in srgb, ${m.c} 40%, transparent)`, background: `color-mix(in srgb, ${m.c} 10%, transparent)` }}>{m.l}</span>;
}

function AdminPayments() {
  const [payments, setPayments] = useStateV([]);
  const [stats, setStats] = useStateV(null);
  const [search, setSearch] = useStateV('');
  useEffectV(() => {
    // Fetch payment ledger (real history with username/orderId/paidAt fields)
    apiFetch('/api/payments/history').then(d => {
      if (d.payments) setPayments(d.payments);
    }).catch(() => {});
    // Fetch real stats
    apiFetch('/api/payments/stats').then(d => {
      if (d.success && d.stats) setStats(d.stats);
    }).catch(() => {});
  }, []);

  const fmtVND = (v) => (v || 0).toLocaleString('vi-VN') + '₫';
  const fmtUSD = (v) => '$' + ((v || 0) / 1).toFixed(0);

  const kpis = stats ? [
    { label: 'Total Revenue', v: fmtVND(stats.totalRevenue), acc: 'var(--acc)' },
    { label: 'This Month', v: fmtVND(stats.thisMonthRevenue), acc: 'var(--acc-2)' },
    { label: 'Total Payments', v: String(stats.totalPayments || 0), acc: 'var(--fg)' },
    { label: 'This Month Txns', v: String(stats.thisMonthPayments || 0), acc: 'var(--fg)' },
  ] : [
    { label: 'Total Revenue', v: '—', acc: 'var(--acc)' },
    { label: 'This Month', v: '—', acc: 'var(--acc-2)' },
    { label: 'Total Payments', v: '—', acc: 'var(--fg)' },
    { label: 'This Month Txns', v: '—', acc: 'var(--fg)' },
  ];

  const filtered = payments.filter(p => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (p.username || '').toLowerCase().includes(q)
      || (p.orderId || '').toLowerCase().includes(q)
      || (p.transactionId || '').toLowerCase().includes(q)
      || (p.plan || '').toLowerCase().includes(q)
      || (p.method || '').toLowerCase().includes(q);
  });

  function exportCsv() {
    const headers = ['#', 'User', 'Plan', 'Amount (VND)', 'Amount (USD)', 'Method', 'Order ID', 'Transaction ID', 'Paid At'];
    const rows = filtered.map(p => [
      p.id, p.username, p.plan, p.amount, (p.amountUsd || '').toString(),
      p.method || 'bank', p.orderId, p.transactionId,
      p.paidAt ? new Date(p.paidAt).toLocaleString('vi-VN') : ''
    ]);
    const csv = [headers, ...rows].map(r => r.map(v => `"${String(v || '').replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `payments_${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
  }

  return (
    <div>
      <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', marginBottom: 18 }}>
        {kpis.map((k, i) => (
          <GlassCard key={i} style={{ padding: 14 }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{k.label}</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: k.acc, marginTop: 6 }}>{k.v}</div>
          </GlassCard>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
        <input
          placeholder="Search by user / order / plan / method…"
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{ ...inputStyle, flex: 1, padding: '10px 14px' }}
        />
        <button
          className="mono"
          onClick={exportCsv}
          style={{ padding: '10px 16px', borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', cursor: 'pointer', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em' }}
        >Export CSV</button>
      </div>
      <GlassCard style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 700 }}>
            <thead>
              <tr style={{ fontSize: 10.5, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--fg-muted)', background: 'rgba(8,13,24,0.55)' }}>
                {['#', 'User', 'Plan', 'Amount', 'Method', 'Order ID', 'Date'].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '12px 14px', borderBottom: '1px solid var(--bd)', fontWeight: 700 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr><td colSpan={7} style={{ padding: '28px 14px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>
                  {search ? 'No results for "' + search + '"' : 'No payment records yet'}
                </td></tr>
              )}
              {filtered.map(p => {
                const isPaid = p.status === 'paid';
                const acc = isPaid ? 'var(--acc)' : 'var(--acc-warn, #ffb648)';
                const isCrypto = (p.method || '').startsWith('crypto');
                return (
                  <tr key={p.id} style={{ fontSize: 13, borderBottom: '1px solid var(--bd)' }}>
                    <td style={{ padding: 14 }} className="mono">#{p.id}</td>
                    <td style={{ padding: 14, fontWeight: 600 }}>{p.username || p.userId}</td>
                    <td style={{ padding: 14 }}><MetaTag>{(p.plan || '').toUpperCase()}</MetaTag></td>
                    <td style={{ padding: 14 }} className="mono">
                      {(p.amount || 0).toLocaleString('vi-VN')}₫
                      {p.amountUsd ? <span style={{ color: 'var(--fg-muted)', marginLeft: 6, fontSize: 11 }}>${p.amountUsd}</span> : null}
                    </td>
                    <td style={{ padding: 14 }}>
                      <span className="mono" style={{
                        padding: '3px 9px', borderRadius: 6, fontSize: 10, fontWeight: 800, letterSpacing: '0.08em',
                        color: isCrypto ? 'var(--acc-warn, #ffb648)' : 'var(--acc-2)',
                        border: `1px solid color-mix(in srgb, ${isCrypto ? 'var(--acc-warn, #ffb648)' : 'var(--acc-2)'} 40%, transparent)`,
                        background: `color-mix(in srgb, ${isCrypto ? 'var(--acc-warn, #ffb648)' : 'var(--acc-2)'} 10%, transparent)`,
                      }}>{isCrypto ? (p.method || 'crypto').toUpperCase() : 'BANK'}</span>
                    </td>
                    <td style={{ padding: 14 }} className="mono" title={p.transactionId}>
                      {(p.orderId || '').slice(0, 16)}{p.orderId && p.orderId.length > 16 ? '…' : ''}
                    </td>
                    <td style={{ padding: 14 }} className="mono">
                      {p.paidAt ? new Date(p.paidAt).toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—'}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </GlassCard>
      {stats && (
        <div className="mono" style={{ marginTop: 10, fontSize: 11, color: 'var(--fg-muted)', textAlign: 'right' }}>
          Monthly: {stats.monthlySubscribers || 0} · Yearly: {stats.yearlySubscribers || 0}
        </div>
      )}
    </div>
  );
}

function AdminSettings() {
  const [settings, setSettings] = useStateV({});
  const [saved, setSaved] = useStateV('');
  const [pricingInputs, setPricingInputs] = useStateV({ daily: 89000, weekly: 549000, monthly: 1990000, yearly: 21900000 });
  const [popupEnabled, setPopupEnabled] = useStateV(false);
  const [popupTitle, setPopupTitle] = useStateV('Summer sale');
  const [popupContent, setPopupContent] = useStateV('Giảm 20% cho tất cả gói trong tuần này.');
  const [latency, setLatency] = useStateV({});
  const [promoEndTime, setPromoEndTime] = useStateV('');
  const [promoActive, setPromoActive] = useStateV(false);
  const [promoSaved, setPromoSaved] = useStateV('');
  const [promoFreeMaxRoi, setPromoFreeMaxRoi] = useStateV(100);

  useEffectV(() => {
    apiFetch('/api/admin/settings').then(d => {
      const s = d.settings || d.data || d;
      if (s) {
        setSettings(s);
        if (s.pricing) setPricingInputs(p => ({ ...p, ...s.pricing }));
        if (s.popup) { setPopupEnabled(!!s.popup.enabled); setPopupTitle(s.popup.title || ''); setPopupContent(s.popup.content || ''); }
      }
    }).catch(() => {});
    apiFetch('/api/admin/latency').then(d => {
      if (d.success && d.data) setLatency(d.data);
    }).catch(() => {});
    apiFetch('/api/admin/promo').then(d => {
      if (d.success && d.data) {
        setPromoActive(!!d.data.active);
        if (d.data.promoFreeMaxRoi != null) setPromoFreeMaxRoi(d.data.promoFreeMaxRoi);
        // Convert ISO → datetime-local format for input
        if (d.data.promoEndTime) {
          const local = new Date(d.data.promoEndTime);
          const pad = n => String(n).padStart(2, '0');
          setPromoEndTime(`${local.getFullYear()}-${pad(local.getMonth()+1)}-${pad(local.getDate())}T${pad(local.getHours())}:${pad(local.getMinutes())}`);
        }
      }
    }).catch(() => {});
  }, []);

  async function savePricing() {
    const d = await apiFetch('/api/admin/pricing', { method: 'PUT', body: JSON.stringify({ pricing: pricingInputs }) });
    if (d.success) { setSaved('Pricing saved!'); setTimeout(() => setSaved(''), 2000); }
  }

  async function savePopup() {
    const d = await apiFetch('/api/admin/popup', { method: 'PUT', body: JSON.stringify({ enabled: popupEnabled, title: popupTitle, content: popupContent }) });
    if (d.success) { setSaved('Popup saved!'); setTimeout(() => setSaved(''), 2000); }
  }

  async function savePromo() {
    // Convert datetime-local → ISO (treat as local time)
    let iso = null;
    if (promoEndTime) {
      const d = new Date(promoEndTime);
      if (!isNaN(d.getTime())) iso = d.toISOString();
    }
    const r = await apiFetch('/api/admin/promo', { method: 'POST', body: JSON.stringify({ promoEndTime: iso, promoFreeMaxRoi: Number(promoFreeMaxRoi) }) });
    if (r.success) {
      setPromoActive(!!r.data.active);
      setPromoSaved(r.data.active ? '✓ Promo activated!' : '✓ Promo cleared');
      setTimeout(() => setPromoSaved(''), 3000);
    }
  }

  async function clearPromo() {
    const r = await apiFetch('/api/admin/promo', { method: 'POST', body: JSON.stringify({ promoEndTime: null }) });
    if (r.success) { setPromoActive(false); setPromoEndTime(''); setPromoSaved('✓ Promo cleared'); setTimeout(() => setPromoSaved(''), 3000); }
  }

  const latencyEntries = Object.entries(latency);

  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 14px' }}>Bookmaker Latency</h3>
        {latencyEntries.length === 0 ? (
          <div style={{ color: 'var(--fg-muted)', fontSize: 13 }}>Loading latency data…</div>
        ) : (
          <div style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}>
            {latencyEntries.map(([bk, info]) => {
              const ms = info.avg || info.last || 0;
              const status = ms === 0 ? 'var(--fg-dim)' : ms < 100 ? 'var(--acc)' : ms < 250 ? 'var(--acc-2)' : ms < 500 ? 'var(--acc-warn, #ffb648)' : '#ff4d8d';
              return (
                <div key={bk} style={{ padding: 14, borderRadius: 11, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                    <span style={{ fontSize: 13, fontWeight: 600 }}>{bk}</span>
                    <span style={{ width: 8, height: 8, borderRadius: '50%', background: status, boxShadow: ms > 0 ? `0 0 8px ${status}` : 'none' }} />
                  </div>
                  <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: status }}>
                    {ms > 0 ? ms : '—'}<span style={{ fontSize: 11, color: 'var(--fg-muted)', fontWeight: 500 }}>{ms > 0 ? 'ms' : ''}</span>
                  </div>
                  <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-dim)', letterSpacing: '0.08em', marginTop: 4 }}>
                    {info.samples ? `AVG · ${info.samples} samples` : info.status || 'no data'}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </GlassCard>

      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 14px' }}>Promotion / Pricing</h3>
        <div style={{ display: 'grid', gap: 12, gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))' }}>
          {['daily', 'weekly', 'monthly', 'yearly'].map(plan => (
            <div key={plan}>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>{plan}</span>
              <input type="number" value={pricingInputs[plan]} onChange={e => setPricingInputs(p => ({ ...p, [plan]: parseFloat(e.target.value) || 0 }))} style={{ width: '100%', padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontFamily: 'var(--font-mono)', fontSize: 14, outline: 'none' }} />
            </div>
          ))}
        </div>
        <button onClick={savePricing} style={primaryBtn}>Save Pricing</button>
        {saved === 'Pricing saved!' && <span style={{ marginLeft: 12, color: 'var(--acc)', fontSize: 13 }}>✓ Saved</span>}
      </GlassCard>

      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 14px' }}>Promo Popup</h3>
        <div style={{ display: 'grid', gap: 12 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <input type="checkbox" checked={popupEnabled} onChange={e => setPopupEnabled(e.target.checked)} /> <span style={{ fontSize: 13 }}>Enable popup on payment page</span>
          </label>
          <label>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Title</span>
            <input value={popupTitle} onChange={e => setPopupTitle(e.target.value)} style={{ width: '100%', padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none' }} />
          </label>
          <label>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Content (HTML)</span>
            <textarea rows={3} value={popupContent} onChange={e => setPopupContent(e.target.value)} style={{ width: '100%', padding: '11px 13px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, fontFamily: 'inherit', outline: 'none', resize: 'vertical' }} />
          </label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={savePopup} style={{ ...primaryBtn, marginTop: 0 }}>Save Popup</button>
            {saved === 'Popup saved!' && <span style={{ color: 'var(--acc)', fontSize: 13 }}>✓ Saved</span>}
          </div>
        </div>
      </GlassCard>

      <GlassCard>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: 0 }}>Promotion Window</h3>
          {promoActive && (
            <span style={{ padding: '3px 10px', borderRadius: 99, background: 'rgba(0,230,118,0.15)', border: '1px solid var(--acc)', color: 'var(--acc)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em' }}>ACTIVE</span>
          )}
        </div>
        <p style={{ fontSize: 12.5, color: 'var(--fg-muted)', margin: '0 0 14px', lineHeight: 1.6 }}>
          Khi khoảng thời gian khuyến mãi đang chạy:<br/>
          • <b>Paid users</b> — subscription không bị trừ (đóng băng đến hết promo)<br/>
          • <b>Free users</b> — ROI cap nâng lên mức bạn cấu hình bên dưới
        </p>
        <div style={{ display: 'grid', gap: 12 }}>
          <div>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 8 }}>Duration</span>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 10 }}>
              {[1, 3, 7].map(days => (
                <button key={days} onClick={() => {
                  const end = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
                  const pad = n => String(n).padStart(2, '0');
                  setPromoEndTime(`${end.getFullYear()}-${pad(end.getMonth()+1)}-${pad(end.getDate())}T${pad(end.getHours())}:${pad(end.getMinutes())}`);
                }} style={{ ...primaryBtn, marginTop: 0, padding: '6px 14px', fontSize: 12 }}>
                  {days} ngày
                </button>
              ))}
            </div>
            <input
              type="datetime-local"
              value={promoEndTime}
              onChange={e => setPromoEndTime(e.target.value)}
              style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none', colorScheme: 'dark', width: '100%', boxSizing: 'border-box' }}
            />
          </div>
          <label>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Free User ROI Cap (%) trong promo</span>
            <input
              type="number"
              min="1" max="200"
              value={promoFreeMaxRoi}
              onChange={e => setPromoFreeMaxRoi(e.target.value)}
              style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none', width: 120 }}
            />
          </label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <button onClick={savePromo} style={{ ...primaryBtn, marginTop: 0 }}>
              {promoActive ? 'Update Promo' : 'Activate Promo'}
            </button>
            {promoActive && (
              <button onClick={clearPromo} style={{ ...primaryBtn, marginTop: 0, background: 'rgba(255,77,141,0.15)', border: '1px solid #ff4d8d', color: '#ff4d8d' }}>
                Clear / Stop
              </button>
            )}
            {promoSaved && <span style={{ color: 'var(--acc)', fontSize: 13 }}>{promoSaved}</span>}
          </div>
          {promoActive && promoEndTime && (
            <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
              Kết thúc lúc: <span style={{ color: 'var(--fg)', fontWeight: 600 }}>{new Date(promoEndTime).toLocaleString('vi-VN')}</span>
              {' · '}Free ROI cap: <span style={{ color: 'var(--acc)', fontWeight: 600 }}>{promoFreeMaxRoi}%</span>
            </div>
          )}
        </div>
      </GlassCard>
    </div>
  );
}

function AdminAliases() {
  const [allAliases, setAllAliases] = useStateV({});
  const [search, setSearch] = useStateV('');
  const [mergeForm, setMergeForm] = useStateV({ bk1: '', name1: '', bk2: '', name2: '' });
  const [mergeMsg, setMergeMsg] = useStateV('');

  const loadAliases = () => {
    apiFetch('/api/admin').then(d => {
      if (d.data) setAllAliases(d.data);
    }).catch(() => {});
  };
  useEffectV(() => { loadAliases(); }, []);

  const bookmakerList = ['1xbet', 'parimatch', 'polymarket', 'pinnacle', 'taptap', 'stake'];

  async function mergeTeams() {
    if (!mergeForm.name1 || !mergeForm.name2) return;
    const teams = [
      { bookmaker: mergeForm.bk1 || '1xbet', name: mergeForm.name1 },
      { bookmaker: mergeForm.bk2 || 'parimatch', name: mergeForm.name2 },
    ];
    const d = await apiFetch('/api/admin/group', { method: 'POST', body: JSON.stringify({ teams }) });
    if (d.success) {
      setMergeMsg(`✓ Merged as "${d.normalizedName}"`);
      setMergeForm({ bk1: '', name1: '', bk2: '', name2: '' });
      loadAliases();
      setTimeout(() => setMergeMsg(''), 3000);
    }
  }

  // Flatten alias groups for display
  const groups = Object.entries(allAliases);
  const filtered = search
    ? groups.filter(([k, v]) => k.includes(search.toLowerCase()) || JSON.stringify(v).toLowerCase().includes(search.toLowerCase()))
    : groups;

  const selectStyle = { padding: '9px 10px', borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 13, outline: 'none', cursor: 'pointer' };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 6px' }}>Merge Teams</h3>
        <p style={{ color: 'var(--fg-muted)', fontSize: 13, margin: '0 0 14px' }}>Map tên team từ nhiều bookmaker về cùng entity.</p>
        <div style={{ display: 'grid', gap: 10, gridTemplateColumns: '1fr 2fr 1fr 2fr auto', alignItems: 'end' }}>
          <select value={mergeForm.bk1} onChange={e => setMergeForm(f => ({ ...f, bk1: e.target.value }))} style={selectStyle}>
            {bookmakerList.map(b => <option key={b} value={b}>{b}</option>)}
          </select>
          <input placeholder="Team name (bk1)…" value={mergeForm.name1} onChange={e => setMergeForm(f => ({ ...f, name1: e.target.value }))} style={{ ...inputStyle, padding: '10px 12px' }} />
          <select value={mergeForm.bk2} onChange={e => setMergeForm(f => ({ ...f, bk2: e.target.value }))} style={selectStyle}>
            {bookmakerList.map(b => <option key={b} value={b}>{b}</option>)}
          </select>
          <input placeholder="Team name (bk2)…" value={mergeForm.name2} onChange={e => setMergeForm(f => ({ ...f, name2: e.target.value }))} style={{ ...inputStyle, padding: '10px 12px' }} />
          <button onClick={mergeTeams} style={{ ...primaryBtn, marginTop: 0 }}>Merge</button>
        </div>
        {mergeMsg && <div style={{ marginTop: 10, color: 'var(--acc)', fontSize: 13 }}>{mergeMsg}</div>}
      </GlassCard>

      <GlassCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: 0 }}>Alias Groups ({groups.length})</h3>
          <input placeholder="Search…" value={search} onChange={e => setSearch(e.target.value)} style={{ ...inputStyle, width: 200, padding: '7px 12px' }} />
        </div>
        {filtered.length === 0 ? (
          <div style={{ color: 'var(--fg-muted)', fontSize: 13, textAlign: 'center', padding: 20 }}>{search ? 'No matches' : 'No alias groups yet'}</div>
        ) : (
          <div style={{ display: 'grid', gap: 8, maxHeight: 400, overflowY: 'auto' }}>
            {filtered.slice(0, 50).map(([canonical, bookmakerMap]) => (
              <div key={canonical} style={{ padding: '10px 14px', borderRadius: 9, background: 'rgba(8,13,24,0.45)', border: '1px solid var(--bd)' }}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-muted)', marginBottom: 6, letterSpacing: '0.08em' }}>{canonical}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {Object.entries(bookmakerMap || {}).map(([bk, names]) =>
                    (Array.isArray(names) ? names : [names]).map((name, i) => (
                      <span key={`${bk}-${i}`} style={{ padding: '3px 9px', borderRadius: 6, fontSize: 11, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)' }}>
                        <span style={{ color: 'var(--fg-muted)', marginRight: 4 }}>{bk}:</span>{name}
                      </span>
                    ))
                  )}
                </div>
              </div>
            ))}
            {filtered.length > 50 && <div style={{ color: 'var(--fg-muted)', fontSize: 12, textAlign: 'center' }}>+{filtered.length - 50} more — refine search</div>}
          </div>
        )}
      </GlassCard>
    </div>
  );
}

function AdminLeagues() {
  const SPORTS = ['soccer', 'basketball', 'tennis', 'hockey', 'esports', 'tabletennis', 'handball', 'badminton'];
  const [leagues, setLeagues] = useStateV({});
  const [activeSport, setActiveSport] = useStateV('soccer');
  const [newName, setNewName] = useStateV('');
  const [newId, setNewId] = useStateV('');
  const [addMsg, setAddMsg] = useStateV('');

  const loadLeagues = () => {
    apiFetch('/api/leagues').then(d => {
      if (d && typeof d === 'object' && !Array.isArray(d)) setLeagues(d);
    }).catch(() => {});
  };
  useEffectV(() => { loadLeagues(); }, []);

  async function addLeague() {
    if (!newId) return;
    const d = await apiFetch('/api/leagues', {
      method: 'POST',
      body: JSON.stringify({ sport: activeSport, id: parseInt(newId), name: newName || `League ${newId}` })
    });
    if (d.success) {
      setAddMsg(`✓ Added ${d.league.name} (${d.league.id})`);
      setNewName(''); setNewId('');
      loadLeagues();
      setTimeout(() => setAddMsg(''), 3000);
    } else {
      setAddMsg(`✗ ${d.error || 'Failed'}`);
      setTimeout(() => setAddMsg(''), 3000);
    }
  }

  async function removeLeague(sport, id) {
    await apiFetch(`/api/leagues/${sport}/${id}`, { method: 'DELETE' });
    loadLeagues();
  }

  const currentList = leagues[activeSport] || [];
  const selectStyle = { padding: '7px 10px', borderRadius: 8, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg)', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', cursor: 'pointer', textTransform: 'uppercase' };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <GlassCard>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, margin: '0 0 14px' }}>League Management</h3>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 16 }}>
          {SPORTS.map(s => (
            <button key={s} onClick={() => setActiveSport(s)} className="mono" style={{
              ...selectStyle,
              background: activeSport === s ? 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), transparent)' : 'rgba(8,13,24,0.55)',
              color: activeSport === s ? 'var(--acc)' : 'var(--fg-muted)', border: 'none',
            }}>{s} <span style={{ opacity: 0.6 }}>({(leagues[s] || []).length})</span></button>
          ))}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, minHeight: 40 }}>
          {currentList.length === 0 && <span style={{ color: 'var(--fg-muted)', fontSize: 13 }}>No leagues for {activeSport} yet.</span>}
          {currentList.map(l => (
            <span key={l.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px 5px 12px', borderRadius: 999, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', fontSize: 12, color: 'var(--fg)' }}>
              <span className="mono" style={{ color: 'var(--fg-muted)', fontSize: 10 }}>{l.id}</span> {l.name}
              <button onClick={() => removeLeague(activeSport, l.id)} style={{ background: 'none', border: 'none', color: '#ff4d8d', cursor: 'pointer', padding: '0 2px', fontSize: 13, lineHeight: 1 }}>×</button>
            </span>
          ))}
        </div>
      </GlassCard>
      <GlassCard>
        <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase', marginBottom: 10 }}>Add League to {activeSport}</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input placeholder="League ID (number)" value={newId} onChange={e => setNewId(e.target.value)} onKeyDown={e => e.key === 'Enter' && addLeague()} style={{ ...inputStyle, flex: 1, padding: '10px 12px' }} type="number" />
          <input placeholder="Name (optional)" value={newName} onChange={e => setNewName(e.target.value)} onKeyDown={e => e.key === 'Enter' && addLeague()} style={{ ...inputStyle, flex: 2, padding: '10px 12px' }} />
          <button onClick={addLeague} style={{ ...primaryBtn, marginTop: 0 }}>Add</button>
        </div>
        {addMsg && <div style={{ marginTop: 8, fontSize: 13, color: addMsg.startsWith('✓') ? 'var(--acc)' : '#ff4d8d' }}>{addMsg}</div>}
      </GlassCard>
    </div>
  );
}

function AdminMarkets() {
  const [report, setReport] = useStateV([]);
  const [summary, setSummary] = useStateV(null);
  const [search, setSearch] = useStateV('');
  const [modeFilter, setModeFilter] = useStateV('all');
  const [loading, setLoading] = useStateV(true);

  const load = () => {
    setLoading(true);
    apiFetch(`/api/market-report?mode=${modeFilter}`).then(d => {
      if (d.success) { setReport(d.report || []); setSummary(d.summary || null); }
      setLoading(false);
    }).catch(() => setLoading(false));
  };
  useEffectV(() => { load(); }, [modeFilter]);

  const filtered = search
    ? report.filter(r => `${r.home} ${r.away} ${r.league} ${r.bookmaker1} ${r.bookmaker2}`.toLowerCase().includes(search.toLowerCase()))
    : report;

  const btnStyle = (active) => ({
    padding: '6px 12px', borderRadius: 7, border: 'none', cursor: 'pointer',
    background: active ? 'linear-gradient(135deg, color-mix(in srgb, var(--acc) 30%, transparent), transparent)' : 'rgba(8,13,24,0.55)',
    color: active ? 'var(--acc)' : 'var(--fg-muted)', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
  });

  return (
    <div style={{ display: 'grid', gap: 14 }}>
      {summary && (
        <div style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))' }}>
          <GlassCard style={{ padding: 14 }}>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.10em' }}>Total Pairs</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: 'var(--acc)', marginTop: 6 }}>{summary.totalPairs}</div>
          </GlassCard>
          {Object.entries(summary.marketCoverage || {}).slice(0, 6).map(([key, count]) => (
            <GlassCard key={key} style={{ padding: 14 }}>
              <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.10em' }}>{key}</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: count > 0 ? 'var(--acc-2)' : 'var(--fg-dim)', marginTop: 6 }}>{count}</div>
            </GlassCard>
          ))}
        </div>
      )}
      <GlassCard>
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 4, padding: 4, borderRadius: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)' }}>
            {['all', 'live', 'prematch'].map(m => (
              <button key={m} className="mono" onClick={() => setModeFilter(m)} style={btnStyle(modeFilter === m)}>{m}</button>
            ))}
          </div>
          <input placeholder="Search team / league…" value={search} onChange={e => setSearch(e.target.value)} style={{ ...inputStyle, flex: 1, padding: '8px 12px' }} />
          <button onClick={load} style={{ padding: '8px 14px', borderRadius: 8, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)', cursor: 'pointer', fontSize: 11, fontWeight: 700 }}>↻ Refresh</button>
        </div>
        {loading ? (
          <div style={{ textAlign: 'center', padding: 30, color: 'var(--fg-muted)' }}>Loading…</div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 30, color: 'var(--fg-muted)', fontSize: 13 }}>No matches found</div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 600 }}>
              <thead>
                <tr style={{ fontSize: 10, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--fg-muted)', background: 'rgba(8,13,24,0.55)' }}>
                  {['Mode', 'Match', 'Sport', 'BK1 Mkts', 'BK2 Mkts', 'Types'].map(h => (
                    <th key={h} style={{ textAlign: 'left', padding: '10px 12px', borderBottom: '1px solid var(--bd)', fontWeight: 700 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.slice(0, 100).map((r, i) => (
                  <tr key={i} style={{ fontSize: 12, borderBottom: '1px solid var(--bd)' }}>
                    <td style={{ padding: '10px 12px' }}>
                      <span className="mono" style={{ padding: '2px 7px', borderRadius: 5, fontSize: 10, fontWeight: 800, background: r._mode === 'live' ? 'color-mix(in srgb, var(--acc) 15%, transparent)' : 'rgba(8,13,24,0.55)', color: r._mode === 'live' ? 'var(--acc)' : 'var(--fg-muted)', border: '1px solid var(--bd)' }}>
                        {r._mode || (r.isLive ? 'live' : 'pre')}
                      </span>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <div style={{ fontWeight: 600 }}>{r.home} <span style={{ color: 'var(--fg-muted)', fontWeight: 400 }}>vs</span> {r.away}</div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--fg-muted)' }}>{r.bookmaker1} ↔ {r.bookmaker2}</div>
                    </td>
                    <td style={{ padding: '10px 12px', color: 'var(--fg-muted)' }}>{r.sport}</td>
                    <td style={{ padding: '10px 12px' }} className="mono">{r.marketCount?.bk1 || 0}</td>
                    <td style={{ padding: '10px 12px' }} className="mono">{r.marketCount?.bk2 || 0}</td>
                    <td style={{ padding: '10px 12px' }}>
                      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                        {(r.marketTypes || []).slice(0, 5).map(mt => (
                          <span key={mt.type} className="mono" style={{ padding: '2px 6px', borderRadius: 5, fontSize: 9, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)' }}>{mt.type}</span>
                        ))}
                        {(r.marketTypes || []).length > 5 && <span style={{ fontSize: 10, color: 'var(--fg-muted)' }}>+{r.marketTypes.length - 5}</span>}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filtered.length > 100 && <div style={{ padding: '10px 12px', color: 'var(--fg-muted)', fontSize: 12, textAlign: 'center' }}>Showing 100 of {filtered.length} — refine search</div>}
          </div>
        )}
      </GlassCard>
    </div>
  );
}

function AdminMonitor() {
  const [status, setStatus] = useStateV(null);
  const [accStats, setAccStats] = useStateV(null);
  const [accEntries, setAccEntries] = useStateV([]);

  const load = () => {
    apiFetch('/api/status').then(d => { if (d) setStatus(d); }).catch(() => {});
    apiFetch('/api/accumulator').then(d => {
      if (d && d.stats) { setAccStats(d.stats); setAccEntries(d.entries || []); }
    }).catch(() => {});
  };
  useEffectV(() => { load(); const t = setInterval(load, 10000); return () => clearInterval(t); }, []);

  const updatedAgo = status?.lastUpdate
    ? Math.round((Date.now() - new Date(status.lastUpdate).getTime()) / 1000) + 's ago'
    : '—';

  const kpis = [
    { label: 'Matched Pairs',    v: status?.stats?.matchedPairs ?? '—',          acc: 'var(--acc)' },
    { label: 'Surebets',         v: accStats?.confirmed ?? '—',                   acc: 'var(--acc-2)' },
    { label: 'Pending',          v: accStats != null ? (accStats.totalSeen - accStats.confirmed) : '—', acc: 'var(--acc-warn, #ffb648)' },
    { label: 'False Positives',  v: accStats?.falsePositives ?? '—',              acc: 'var(--fg-muted)' },
    { label: 'Active Entries',   v: accStats?.activeEntries ?? '—',               acc: 'var(--fg)' },
    { label: 'Updated',          v: updatedAgo,                                   acc: 'var(--fg)' },
  ];

  return (
    <div style={{ display: 'grid', gap: 14 }}>
      <div style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))' }}>
        {kpis.map((k, i) => (
          <GlassCard key={i} style={{ padding: 14 }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.10em', color: 'var(--fg-muted)', textTransform: 'uppercase' }}>{k.label}</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 800, color: k.acc, marginTop: 6 }}>{k.v}</div>
          </GlassCard>
        ))}
      </div>
      {accEntries.length > 0 && (
        <GlassCard>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 15, margin: 0 }}>Accumulator Entries ({accEntries.length})</h3>
            <button onClick={load} style={{ padding: '5px 12px', borderRadius: 7, background: 'rgba(8,13,24,0.55)', border: '1px solid var(--bd)', color: 'var(--fg-muted)', cursor: 'pointer', fontSize: 11, fontWeight: 700 }}>↻</button>
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 500 }}>
              <thead>
                <tr style={{ fontSize: 10, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--fg-muted)', background: 'rgba(8,13,24,0.55)' }}>
                  {['Match', 'BK1 ↔ BK2', 'Market', 'Ticks', 'Status'].map(h => (
                    <th key={h} style={{ textAlign: 'left', padding: '9px 12px', borderBottom: '1px solid var(--bd)', fontWeight: 700 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {accEntries.slice(0, 50).map((e, i) => (
                  <tr key={i} style={{ fontSize: 12, borderBottom: '1px solid var(--bd)' }}>
                    <td style={{ padding: '9px 12px', fontWeight: 600 }}>{e.surebet?.home} <span style={{ color: 'var(--fg-muted)' }}>vs</span> {e.surebet?.away}</td>
                    <td style={{ padding: '9px 12px', color: 'var(--fg-muted)' }} className="mono">{e.surebet?.bookmaker1} ↔ {e.surebet?.bookmaker2}</td>
                    <td style={{ padding: '9px 12px', color: 'var(--fg-muted)' }} className="mono">{e.surebet?.market || '—'}</td>
                    <td style={{ padding: '9px 12px' }} className="mono">{e.count}</td>
                    <td style={{ padding: '9px 12px' }}>
                      <span className="mono" style={{ padding: '2px 8px', borderRadius: 5, fontSize: 10, fontWeight: 800,
                        color: e.confirmed ? (e.inGrace ? 'var(--acc-warn, #ffb648)' : 'var(--acc)') : 'var(--fg-muted)',
                        background: e.confirmed ? (e.inGrace ? 'color-mix(in srgb, #ffb648 12%, transparent)' : 'color-mix(in srgb, var(--acc) 12%, transparent)') : 'rgba(8,13,24,0.55)',
                        border: '1px solid var(--bd)',
                      }}>
                        {e.confirmed ? (e.inGrace ? 'GRACE' : 'CONFIRMED') : 'PENDING'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </GlassCard>
      )}
    </div>
  );
}

Object.assign(window, {
  SmartBetsView, AnalyticsView, ProfileView, TipsView, CalcView, AboutView, ContactView, AdminView,
});
