// Wallet — RUB balance, deposit via CryptoBot/Platega, paginated history.

// Branded logos — drawn inline (instant, no network) to match the UI.
function CryptoBotLogo({ size = 44 }) {
  // Bitcoin ₿ — official mark drawn inline on a warm orange tile.
  return (
    <div style={{
      width: size, height: size, borderRadius: 12,
      background: 'linear-gradient(145deg, #ffb44c 0%, #f7931a 55%, #e8830f 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 4px 14px rgba(247,147,26,0.5), inset 0 1px 0 rgba(255,255,255,0.4)',
      flexShrink: 0,
    }}>
      <svg width={size * 0.62} height={size * 0.62} viewBox="0 0 64 64" aria-label="Bitcoin">
        <path fill="#fff" d="m46.1,27.44c0.64-4.26-2.6-6.55-7.04-8.07l1.44-5.77-3.51-0.88-1.4,5.62c-0.92-0.23-1.87-0.45-2.81-0.66l1.41-5.65-3.51-0.88-1.44,5.77c-0.76-0.17-1.51-0.35-2.24-0.53l0.004-0.018-4.84-1.21-0.93,3.75s2.6,0.6,2.55,0.63c1.42,0.36,1.68,1.3,1.64,2.04l-1.64,6.57c0.1,0.025,0.23,0.061,0.37,0.12-0.12-0.029-0.24-0.061-0.37-0.092l-2.3,9.2c-0.17,0.43-0.62,1.08-1.61,0.83,0.035,0.051-2.55-0.64-2.55-0.64l-1.74,4.02,4.57,1.14c0.85,0.21,1.68,0.44,2.5,0.65l-1.45,5.83,3.51,0.88,1.44-5.77c0.96,0.26,1.89,0.5,2.8,0.73l-1.43,5.75,3.51,0.88,1.45-5.82c5.99,1.13,10.49,0.68,12.38-4.74,1.53-4.36-0.076-6.88-3.23-8.52,2.29-0.53,4.02-2.04,4.48-5.16zm-8.02,11.25c-1.09,4.36-8.43,2-10.81,1.41l1.93-7.73c2.38,0.59,10.01,1.77,8.88,6.32zm1.09-11.31c-0.99,3.97-7.1,1.95-9.08,1.46l1.75-7.01c1.98,0.49,8.37,1.42,7.33,5.55z"/>
      </svg>
    </div>
  );
}

function PlategaLogo({ size = 44 }) {
  // СБП — pay by QR. Custom crisp QR glyph on a dark tile with SBP-gradient eyes.
  const u = size / 44;
  const Eye = ({ x, y }) => (
    <g transform={`translate(${x},${y})`}>
      <rect width="11" height="11" rx="2.5" fill="none" stroke="#fff" strokeWidth="2"/>
      <rect x="3.5" y="3.5" width="4" height="4" rx="1" fill="url(#sbpg)"/>
    </g>
  );
  return (
    <div style={{
      width: size, height: size, borderRadius: 12,
      background: 'linear-gradient(145deg, #1c2340 0%, #0b0f22 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 4px 14px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.12)',
      flexShrink: 0,
    }}>
      <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 34 34" aria-label="СБП QR">
        <defs>
          <linearGradient id="sbpg" x1="0" y1="0" x2="34" y2="34" gradientUnits="userSpaceOnUse">
            <stop offset="0%" stopColor="#f14635"/>
            <stop offset="50%" stopColor="#7b2ff7"/>
            <stop offset="100%" stopColor="#1aa3ff"/>
          </linearGradient>
        </defs>
        <Eye x={0} y={0}/>
        <Eye x={23} y={0}/>
        <Eye x={0} y={23}/>
        {/* scattered data modules */}
        <g fill="#fff">
          <rect x="16" y="2"  width="2.4" height="2.4" rx="0.6"/>
          <rect x="20" y="6"  width="2.4" height="2.4" rx="0.6"/>
          <rect x="16" y="10" width="2.4" height="2.4" rx="0.6"/>
          <rect x="2"  y="16" width="2.4" height="2.4" rx="0.6"/>
          <rect x="6"  y="20" width="2.4" height="2.4" rx="0.6"/>
          <rect x="10" y="16" width="2.4" height="2.4" rx="0.6"/>
        </g>
        {/* accent payment modules in SBP gradient */}
        <g fill="url(#sbpg)">
          <rect x="16" y="16" width="6" height="6" rx="1.2"/>
          <rect x="25" y="16" width="2.4" height="2.4" rx="0.6"/>
          <rect x="29" y="20" width="2.4" height="2.4" rx="0.6"/>
          <rect x="16" y="25" width="2.4" height="2.4" rx="0.6"/>
          <rect x="25" y="25" width="6" height="6" rx="1.2"/>
          <rect x="20" y="29" width="2.4" height="2.4" rx="0.6"/>
        </g>
      </svg>
    </div>
  );
}

const DEPOSIT_METHODS = [
  {
    id: 'cryptobot',
    name: 'CryptoBot',
    sub: 'Биткоин, USDT, TON',
    badge: 'Крипта',
    Logo: CryptoBotLogo,
  },
  {
    id: 'platega',
    name: 'СБП',
    sub: 'QR-код или карта РФ',
    badge: 'Мгновенно',
    Logo: PlategaLogo,
  },
];

const QUICK_AMOUNTS = [500, 1000, 2500, 5000, 10000, 25000];

// Format integer with non-breaking thin spaces: 1234567 → "1 234 567"
function fmtAmount(n) {
  if (!n && n !== 0) return '';
  return Math.abs(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '\u202F');
}

function DepositSheet({ open, onClose, onConfirm }) {
  const [method, setMethod] = React.useState('cryptobot');
  const [amount, setAmount] = React.useState(1000);
  if (!open) return null;

  const onAmountChange = (e) => {
    const digits = e.target.value.replace(/\D/g, '');
    const n = digits ? parseInt(digits, 10) : 0;
    setAmount(Math.min(n, 9_999_999));
  };

  return (
    <SheetShell onClose={onClose}>
      <div className="row aic jcsb" style={{ marginBottom: 12 }}>
        <div className="h2">Пополнить баланс</div>
        <SheetCloseX/>
      </div>

      <div className="lbl" style={{ marginBottom: 8 }}>Способ пополнения</div>
      <div className="col gap-8">
        {DEPOSIT_METHODS.map(d => {
          const Logo = d.Logo;
          return (
            <div key={d.id}
                 onClick={() => setMethod(d.id)}
                 className={'pay-method' + (method === d.id ? ' active' : '')}>
              <Logo size={44}/>
              <div className="flex1">
                <div className="row aic gap-6">
                  <div style={{ fontSize: 14, fontWeight: 650 }}>{d.name}</div>
                  <div className="chip chip-green" style={{ padding: '1px 7px', fontSize: 9 }}>{d.badge}</div>
                </div>
                <div className="small t-soft" style={{ marginTop: 2 }}>{d.sub}</div>
              </div>
              <div className={'radio' + (method === d.id ? ' on' : '')}/>
            </div>
          );
        })}
      </div>

      <div className="lbl" style={{ marginTop: 16, marginBottom: 8 }}>Сумма</div>
      <div style={{
        padding: '12px 14px', borderRadius: 14,
        background: 'var(--bg-input)',
        border: '0.5px solid var(--border)',
      }}>
        <div className="row aic gap-8" style={{ marginBottom: 4 }}>
          <input type="text" inputMode="numeric"
                 className="input"
                 value={fmtAmount(amount)}
                 onChange={onAmountChange}
                 style={{
                   background: 'transparent', padding: 0,
                   fontFamily: 'inherit',
                   fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em',
                   fontVariantNumeric: 'tabular-nums',
                 }}/>
          <span style={{ fontSize: 24, fontWeight: 700, color: 'var(--text-soft)', letterSpacing: '-0.02em' }}>₽</span>
        </div>
        <div className="small t-mute">Без комиссии — на баланс зачислится вся сумма</div>
      </div>

      <div className="row gap-6" style={{ marginTop: 10, flexWrap: 'wrap' }}>
        {QUICK_AMOUNTS.map(a => (
          <div key={a} className={'chip ' + (amount === a ? '' : 'chip-mute')}
               style={{ padding: '6px 12px', cursor: 'pointer' }}
               onClick={() => setAmount(a)}>
            {fmtRubShort(a)}
          </div>
        ))}
      </div>

      <button className="btn btn-primary center" style={{
        justifyContent: 'center', padding: '15px',
        marginTop: 16, fontSize: 15, fontWeight: 650,
      }} onClick={() => onConfirm(amount, method)}>
        <Icons.arrowR size={16}/> Перейти к оплате
      </button>
      <div className="small t-mute" style={{ marginTop: 8, textAlign: 'center' }}>
        Открыть в Telegram · оплата займёт ~30 секунд
      </div>
    </SheetShell>
  );
}

// ─── Transaction history — РЕАЛЬНЫЕ заказы из GET /me (последние 20) ───
// Заказ → строка истории: покупка (минус ₽), отправка/вывод (движение подарка).
function _adaptOrderTx(o) {
  const kind = o.kind || '';
  const slug = String(o.gift_name || '').replace(/[^A-Za-z0-9]/g, '');
  // Реальная миниатюра купленного NFT: строим фото по gift_slug (напр.
  // 'InstantRamen-10462'). GiftMedia отдаёт приоритет photo и мягко откатывается
  // на градиент, если Fragment вернёт 404. Номер — суффикс слага.
  const gslug = o.gift_slug || '';
  const photo = gslug ? `https://nft.fragment.com/gift/${gslug}.small.jpg` : null;
  const numMatch = gslug.match(/-(\d+)$/);
  const num = numMatch ? Number(numMatch[1]) : 1;
  const t = o.created_at ? Date.parse(o.created_at) : Date.now();
  const rub = Number(o.amount_rub) || 0;
  const failed = o.status === 'failed';
  const inflight = o.status === 'awaiting_payment' || o.status === 'processing' || o.status === 'pending';
  let type, title, sub;
  if (kind === 'purchase' || kind === 'buy') {
    type = 'buy';
    title = `Покупка ${o.gift_name || 'подарка'}`;
    sub = failed ? 'отменён' : inflight ? 'в обработке' : 'успешно';
  } else if (kind === 'withdraw' || kind === 'tg_transfer') {
    type = 'withdraw';
    title = `Вывод ${o.gift_name || 'подарка'} в Telegram`;
    sub = failed ? 'не удался' : 'успешно';
  } else if (kind === 'transfer') {
    type = 'send';
    title = `Отправка ${o.gift_name || 'подарка'}`;
    sub = o.recipient ? '@' + String(o.recipient).replace(/^@/, '') : 'другу';
  } else {
    type = 'other';
    title = kind || 'Операция';
    sub = o.status || '';
  }
  return { type, title, sub, slug, photo, num, t, rub, failed, inflight, id: o.id };
}

function TxRow({ tx }) {
  const showAmount = tx.type === 'buy' && tx.rub > 0;
  const icon = tx.type === 'withdraw' ? <Icons.download/>
    : tx.type === 'send' ? <Icons.send/>
    : <Icons.cart/>;
  return (
    <div className="row-item" style={{ padding: '12px 14px', gap: 12 }}>
      {tx.slug ? (
        <div style={{
          position: 'relative', width: 36, height: 36,
          borderRadius: 10, overflow: 'hidden', flexShrink: 0,
          boxShadow: 'inset 0 0 0 1px var(--border)',
        }}>
          <GiftMedia kind={tx.slug} num={tx.num || 1} photo={tx.photo} rounded={10}/>
        </div>
      ) : (
        <div className="tile" style={{
          background: 'var(--bg-input)', color: 'var(--text-soft)',
        }}>{React.cloneElement(icon, { size: 18 })}</div>
      )}
      <div className="flex1" style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tx.title}</div>
        <div className="small" style={{ color: tx.failed ? 'var(--red, #e25555)' : 'var(--text-mute)' }}>
          {tx.sub} · {fmtRel(tx.t)}
        </div>
      </div>
      {showAmount && (
        <div style={{
          fontSize: 14, fontWeight: 700, fontVariantNumeric: 'tabular-nums',
          textDecoration: tx.failed ? 'line-through' : 'none',
          opacity: tx.failed ? 0.5 : 1,
        }}>
          −{fmtAmount(Math.round(tx.rub))} ₽
        </div>
      )}
    </div>
  );
}

function WalletScreen({ balance, onDeposit }) {
  const [page, setPage] = React.useState(1);
  const [refreshing, setRefreshing] = React.useState(false);
  const [histKey, setHistKey]   = React.useState(0);
  const PAGE_SIZE = 6;

  // РЕАЛЬНЫЕ данные из GET /me: потрачено всего + история заказов.
  const meState = (window.DataSource && window.DataSource.useMe)
    ? window.DataSource.useMe(histKey)
    : { data: null, loading: false };
  const me = meState.data || null;
  const spent = me ? Math.round(me.total_spent_rub || 0) : 0;
  const txAll = React.useMemo(
    () => ((me && me.orders) || []).map(_adaptOrderTx).sort((a, b) => b.t - a.t),
    [me]
  );
  const totalPages = Math.max(1, Math.ceil(txAll.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const pageItems = txAll.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE);

  // Refresh: реальный рефетч /me (bump histKey) + shimmer, пока летит запрос.
  const refTimer = React.useRef(0);
  const doRefresh = () => {
    if (refreshing) return;
    setRefreshing(true);
    setPage(1);
    setHistKey(k => k + 1);
    clearTimeout(refTimer.current);
    refTimer.current = setTimeout(() => setRefreshing(false), 850);
  };
  React.useEffect(() => () => clearTimeout(refTimer.current), []);

  return (
    <ScreenWrap>
      <GlassCard strong style={{
        padding: 22, overflow: 'hidden', position: 'relative',
        background: 'linear-gradient(135deg, var(--accent-soft) 0%, transparent 60%), var(--glass-bg-strong)',
      }}>
        <div className="lbl" style={{ marginBottom: 6 }}>Баланс кошелька</div>
        <div style={{ fontSize: 38, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1, fontVariantNumeric: 'tabular-nums', minHeight: 38 }}>
          {refreshing ? (
            <SkBlock w={172} h={36} r={10} style={{ display: 'inline-block', verticalAlign: 'middle' }}/>
          ) : (
            <span key={histKey} className="bal-pop">
              <CountUp value={balance} trigger={histKey} fmt={(v) => fmtAmount(Math.round(v))}/>
              <span style={{ fontSize: 22, fontWeight: 600, color: 'var(--text-soft)', marginLeft: 6 }}>₽</span>
            </span>
          )}
        </div>
        <div className="small t-mute" style={{ marginTop: 6 }}>
          {refreshing || meState.loading ? 'Синхронизируем с Portals…' : `потрачено ${fmtAmount(spent)} ₽ · ${me ? (me.orders_total || 0) : 0} заказов`}
        </div>

        <div className="row gap-8" style={{ marginTop: 16 }}>
          <button className="btn btn-primary flex1 center" onClick={onDeposit}
                  style={{ justifyContent: 'center', padding: '13px' }}>
            <Icons.plus size={16}/> Пополнить
          </button>
          <button className="btn flex1 center" onClick={doRefresh}
                  disabled={refreshing}
                  style={{ justifyContent: 'center', padding: '13px' }}>
            <Icons.refresh size={15}
                           style={{ animation: refreshing ? 'spinSlow 0.7s linear infinite' : 'none' }}/>
            {refreshing ? 'Обновляем…' : 'Обновить'}
          </button>
        </div>

        <div style={{
          position: 'absolute', top: -40, right: -30,
          width: 140, height: 140, borderRadius: '50%',
          background: 'radial-gradient(circle, var(--accent-glow), transparent 60%)',
          pointerEvents: 'none', opacity: 0.6,
        }}/>
      </GlassCard>

      <SectionHeader title="Способы пополнения"/>
      <div className="col gap-8">
        {DEPOSIT_METHODS.map(d => {
          const Logo = d.Logo;
          return (
            <div key={d.id} className="glass card-press" style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 16,
            }} onClick={onDeposit}>
              <Logo size={44}/>
              <div className="flex1">
                <div className="row aic gap-6">
                  <div style={{ fontSize: 14, fontWeight: 650 }}>{d.name}</div>
                  <div className="chip chip-green" style={{ padding: '1px 7px', fontSize: 9 }}>{d.badge}</div>
                </div>
                <div className="small t-soft" style={{ marginTop: 2 }}>{d.sub}</div>
              </div>
              <Icons.chevR size={16} style={{ color: 'var(--text-mute)' }}/>
            </div>
          );
        })}
      </div>

      <SectionHeader title="История операций"/>
      <GlassCard style={{ padding: 0, overflow: 'hidden' }}>
        {refreshing || meState.loading ? (
          <div className="col" style={{ padding: '6px 0' }}>
            {Array.from({ length: PAGE_SIZE }).map((_, i) => (
              <div key={i} className="row aic gap-12" style={{ padding: '12px 14px' }}>
                <SkBlock w={36} h={36} r={10}/>
                <div className="flex1 col gap-6" style={{ minWidth: 0 }}>
                  <SkBlock w="58%" h={11} r={5}/>
                  <SkBlock w="34%" h={9} r={5}/>
                </div>
                <SkBlock w={62} h={13} r={5}/>
              </div>
            ))}
          </div>
        ) : pageItems.length === 0 ? (
          <div className="t-mute small" style={{ textAlign: 'center', padding: '26px 16px' }}>
            Пока пусто — купи первый подарок в маркете
          </div>
        ) : (
          <div key={safePage + '-' + histKey}>
            {pageItems.map((tx, i) => (
              <React.Fragment key={tx.id || i}>
                <div style={{ animation: `fadeUp 0.4s ${Math.min(i * 0.06, 0.4)}s both` }}>
                  <TxRow tx={tx}/>
                </div>
                {i < pageItems.length - 1 && <div style={{ height: 0.5, background: 'var(--border)', margin: '0 14px' }}/>}
              </React.Fragment>
            ))}
          </div>
        )}
      </GlassCard>

      {totalPages > 1 && (
        <div className="row aic" style={{ justifyContent: 'space-between', gap: 16, marginTop: 10, padding: '0 4px' }}>
          <button onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={safePage <= 1}
                  aria-label="Предыдущая страница"
                  style={{
                    width: 52, height: 52, borderRadius: '50%',
                    border: '1px solid var(--border)', padding: 0,
                    background: 'var(--bg-input)', color: 'var(--text)',
                    cursor: safePage <= 1 ? 'default' : 'pointer',
                    opacity: safePage <= 1 ? 0.3 : 1,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'transform 0.15s ease, background 0.2s',
                    flexShrink: 0,
                  }}
                  onMouseDown={(e) => { if (safePage > 1) e.currentTarget.style.transform = 'scale(0.94)'; }}
                  onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}>
            <Icons.chevL size={24}/>
          </button>

          <div className="row aic" style={{ gap: 8, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
            <span key={safePage} className="anim-fade-up" style={{ fontSize: 28, fontWeight: 700, color: 'var(--text)', letterSpacing: '-0.02em' }}>{safePage}</span>
            <span style={{ fontSize: 18, color: 'var(--text-mute)', opacity: 0.4, fontWeight: 300 }}>/</span>
            <span style={{ fontSize: 16, color: 'var(--text-mute)', opacity: 0.6, fontWeight: 500 }}>{totalPages}</span>
          </div>

          <button onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                  disabled={safePage >= totalPages}
                  aria-label="Следующая страница"
                  style={{
                    width: 52, height: 52, borderRadius: '50%',
                    border: '1px solid var(--border)', padding: 0,
                    background: 'var(--bg-input)', color: 'var(--text)',
                    cursor: safePage >= totalPages ? 'default' : 'pointer',
                    opacity: safePage >= totalPages ? 0.3 : 1,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'transform 0.15s ease, background 0.2s',
                    flexShrink: 0,
                  }}
                  onMouseDown={(e) => { if (safePage < totalPages) e.currentTarget.style.transform = 'scale(0.94)'; }}
                  onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}>
            <Icons.chevR size={24}/>
          </button>
        </div>
      )}
      <div className="small t-mute" style={{ textAlign: 'center', marginTop: 8, lineHeight: 1.5 }}>
        Всего <span style={{ margin: '0 2px' }}>{txAll.length}</span> операций
      </div>
    </ScreenWrap>
  );
}

window.WalletScreen = WalletScreen;
window.DepositSheet = DepositSheet;
