// My Gifts — collection of owned NFT gifts + action sheet (Send / Withdraw / Sell).

function MyGiftActions({ gift, onClose, onWithdraw, onView, onSend }) {
  if (!gift) return null;
  const target = typeof document !== 'undefined' && document.querySelector('.app-view') || typeof document !== 'undefined' && document.body;
  if (!target) return null;
  return ReactDOM.createPortal(
    <SheetShell onClose={onClose}>

        <div className="col aic" style={{ alignItems: 'center', padding: '8px 0 16px' }}>
          <Gift kind={gift.kind} num={gift.num} size="2xl" animated clean float
        glow={gift.tier === 'epic' || gift.tier === 'legendary'} />
          <div className="row aic gap-8" style={{ marginTop: 14 }}>
            <div className="mono small t-mute">#{gift.num}</div>
          </div>
          <div className="h2" style={{ marginTop: 4 }}>{gift.name}</div>
        </div>

        <div style={{
          padding: '14px 16px', borderRadius: 16,
          background: 'var(--bg-input)',
          border: '0.5px solid var(--border)',
        }}>
          <div className="row aic jcsb">
            <div className="lbl">Куплен за</div>
            <div className="row aic gap-6 small t-soft">
              <Icons.history size={12}/>
              {(() => {
                // Реальная дата покупки из заказа; фоллбэк — сегодня.
                const d = gift.created_at ? new Date(gift.created_at) : new Date();
                return isNaN(d) ? '—' : d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
              })()}
            </div>
          </div>
          <div className="mono" style={{ fontSize: 24, fontWeight: 700, marginTop: 6, letterSpacing: '-0.01em' }}>
            {fmtRub(gift.rub)}
          </div>
        </div>

        <div className="col gap-8" style={{ marginTop: 14 }}>
          <button className="btn btn-primary center" onClick={() => onWithdraw(gift)}
        style={{ justifyContent: 'center', padding: '14px', fontSize: 15, fontWeight: 650 }}>
            <Icons.download size={16} /> Забрать в Telegram
          </button>
          <div className="row gap-8">
            <button className="btn flex1 center" onClick={() => onView && onView(gift)} style={{ justifyContent: 'center', padding: '13px' }}>
              <Icons.eye size={15} /> Посмотреть
            </button>
            <button className="btn flex1 center" onClick={() => onSend(gift)} style={{ justifyContent: 'center', padding: '13px' }}>
              <Icons.send size={15} /> Отправить
            </button>
          </div>
        </div>

        <div className="small t-mute center" style={{ marginTop: 12, textAlign: 'center', padding: '0 12px' }}>
          Забрать в Telegram → подарок появится на твоём профиле, его смогут увидеть друзья
        </div>
    </SheetShell>,
    target
  );
}

function WithdrawConfirm({ gift, onClose, onDone }) {
  const [stage, setStage] = React.useState('confirm');
  const [err, setErr] = React.useState(null);
  const [username, setUsername] = React.useState('');
  const uname = username.trim().replace(/^@/, '');
  const unameOk = /^[A-Za-z0-9_]{5,32}$/.test(uname);
  React.useEffect(() => {
    if (stage !== 'progress') return;
    let cancel = false;
    (async () => {
      try {
        // РЕАЛЬНЫЙ вывод: POST /me/gifts/{order_id}/withdraw {recipient} —
        // маркет выводит NFT на основной аккаунт, оттуда за ⭐ отправляет @username.
        const DS = window.DataSource;
        if (DS && DS.withdrawGift) {
          await DS.withdrawGift(gift.order_id || gift.id, uname);
        } else if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.initData) {
          throw new Error('DataSource unavailable');     // прод в Telegram: НЕ притворяемся успехом
        } else {
          await new Promise(r => setTimeout(r, 1500));    // дизайн-симулятор в браузере
        }
        if (!cancel) setStage('done');
      } catch (e) {
        if (!cancel) {
          setErr(window.friendlyError ? window.friendlyError(e, 'withdraw') : 'Не удалось запустить вывод — попробуй через минуту');
          setStage('confirm');
        }
      }
    })();
    return () => { cancel = true; };
  }, [stage]);

  if (!gift) return null;
  const target = typeof document !== 'undefined' && document.querySelector('.app-view') || typeof document !== 'undefined' && document.body;
  if (!target) return null;
  return ReactDOM.createPortal(
    <SheetShell onClose={onClose} dismissable={stage !== 'progress'}>

        {stage === 'confirm' &&
      <div className="col aic" style={{ alignItems: 'center', textAlign: 'center', padding: '8px 16px' }}>
            <Gift kind={gift.kind} num={gift.num} size="xl" />
            <div className="h2" style={{ marginTop: 14 }}>Забрать {gift.name}?</div>
            <div className="t-soft body" style={{ marginTop: 6, maxWidth: 280 }}>
              Укажи Telegram-получателя — подарок появится на его профиле в течение
              пары минут. Можно указать свой @username.
            </div>
            <div style={{
              padding: '12px 16px', borderRadius: 14,
              background: 'var(--bg-input)', alignSelf: 'stretch',
              display: 'flex', alignItems: 'center', gap: 6,
              marginTop: 14,
            }}>
              <span style={{ color: 'var(--text-mute)', fontSize: 16, lineHeight: 1, fontWeight: 600 }}>@</span>
              <input placeholder="Telegram username" value={username}
                     onChange={(e) => setUsername(e.target.value.replace(/^@/, ''))}
                     style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: 'var(--text)', fontSize: 16, fontWeight: 600, lineHeight: 1, padding: 0, marginLeft: -2 }}/>
            </div>
            {err && (
              <div className="small" style={{ color: 'var(--red, #e25555)', marginTop: 10, maxWidth: 280 }}>{err}</div>
            )}
            <button className="btn btn-primary center"
              disabled={!unameOk}
              style={{
          justifyContent: 'center', padding: '14px',
          alignSelf: 'stretch', marginTop: 14, fontSize: 15, fontWeight: 650,
          opacity: unameOk ? 1 : 0.5,
        }} onClick={() => unameOk && setStage('progress')}>
              <Icons.check size={16} /> Забрать сейчас
            </button>
            <WithSheetClose>{close => (
              <button className="btn-ghost" onClick={close} style={{
                border: 0, background: 'transparent', color: 'var(--text-soft)',
                padding: '10px', marginTop: 4, fontSize: 14, cursor: 'pointer'
              }}>Отмена</button>
            )}</WithSheetClose>
          </div>
      }

        {stage === 'progress' &&
      <div className="col aic" style={{ alignItems: 'center', textAlign: 'center', padding: '24px 16px' }}>
            <div className="anim-hero-float">
              <Gift kind={gift.kind} num={gift.num} size="2xl" animated clean glow />
            </div>
            <div className="h2" style={{ marginTop: 22 }}>Передаём в Telegram…</div>
            <div className="t-soft body" style={{ marginTop: 6 }}>Подключаемся к API Portals</div>
            <div className="bar" style={{ alignSelf: 'stretch', marginTop: 20 }}>
              <div style={{ width: '100%', animation: 'fillBar 2.2s cubic-bezier(0.4, 0, 0.2, 1) forwards' }} />
            </div>
          </div>
      }

        {stage === 'done' &&
      <div className="col aic" style={{ alignItems: 'center', textAlign: 'center', padding: '24px 16px', position: 'relative' }}>
            <Confetti />
            <Gift kind={gift.kind} num={gift.num} size="2xl" animated clean glow />
            <div className="h2" style={{ marginTop: 22 }}>Готово! 🎉</div>
            <div className="t-soft body" style={{ marginTop: 6 }}>
              {gift.name}{gift.num != null ? ` #${gift.num}` : ''} уже летит к{' '}
              <span style={{ color: 'var(--text)', fontWeight: 700 }}>@{uname}</span> — придёт в течение пары минут
            </div>
            <WithSheetClose>{close => (
              <button className="btn btn-primary center" style={{
                justifyContent: 'center', padding: '14px',
                alignSelf: 'stretch', marginTop: 22, fontSize: 15, fontWeight: 650
              }} onClick={() => {
                // Кнопка обещает открыть Telegram — открываем чат получателя.
                try {
                  const tg = window.Telegram && window.Telegram.WebApp;
                  if (tg && tg.openTelegramLink && unameOk) tg.openTelegramLink('https://t.me/' + uname);
                } catch (_) {}
                close(); setTimeout(onDone, 320);
              }}>
                Открыть в Telegram <Icons.arrowR size={16} />
              </button>
            )}</WithSheetClose>
          </div>
      }
    </SheetShell>,
    target
  );
}

function MyGiftsScreen({ onStartSend, onGiftClick, gifts, onChanged }) {
  const held = gifts || [];           // реальные held-подарки из /me/gifts (проброс из app.jsx)
  const [selected, setSelected] = React.useState(null);
  const [withdrawing, setWithdrawing] = React.useState(null);
  const [myFilter, setMyFilter] = React.useState('vault');
  const [page, setPage] = React.useState(1);
  // «Выведенные» — реальный /me/gifts?released=1; рефетч, когда меняется held
  // (после вывода/отправки подарок переезжает из хранилища в выведенные).
  const _rel = (window.DataSource && window.DataSource.useReleasedGifts)
    ? window.DataSource.useReleasedGifts('rel-' + held.length)
    : { data: null };
  const releasedItems = (_rel.data && _rel.data.items) || [];
  const items = myFilter === 'withdrawn' ? releasedItems : held;
  React.useEffect(() => { setPage(1); }, [myFilter]);
  const PAGE_SIZE = 6;
  const totalPages = Math.max(1, Math.ceil(items.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const pageItems = items.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE);

  const totalRub = items.reduce((s, i) => s + i.rub, 0);
  const totalTon = items.reduce((s, i) => s + i.ton, 0);

  return (
    <>
      <ScreenWrap>
        <GlassCard strong style={{ padding: 18 }}>
          <div className="lbl" style={{ marginBottom: 4 }}>Коллекция</div>
          <div className="row aic gap-8">
            <div className="mono" style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>
              {items.length}
            </div>
            <div className="t-soft" style={{ fontSize: 15, marginTop: 4 }}>подарков</div>
            <div className="flex1" />
            <div className="col" style={{ alignItems: 'flex-end' }}>
              <div className="lbl" style={{ fontSize: 9 }}>Стоимость</div>
              <div className="mono" style={{ fontSize: 16, fontWeight: 700 }}>{fmtRub(totalRub)}</div>
            </div>
          </div>
        </GlassCard>

        <div style={{
          display: 'flex', padding: 4, gap: 4,
          background: 'var(--bg-input)',
          borderRadius: 14,
          border: '0.5px solid var(--border)',
          alignSelf: 'stretch'
        }}>
          {[
          ['vault', 'В хранилище'],
          ['withdrawn', 'Выведенные']].
          map(([k, l]) => {
            const on = (myFilter || 'vault') === k;
            return (
              <button key={k} onClick={() => setMyFilter(k)} style={{
                flex: 1, border: 0, cursor: 'pointer',
                padding: '9px 8px',
                borderRadius: 10,
                background: on ? 'var(--accent)' : 'transparent',
                color: on ? '#fff' : 'var(--text-soft)',
                fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em',
                transition: 'background 0.2s, color 0.2s, transform 0.15s',
                boxShadow: on ? '0 4px 14px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,0.18)' : 'none'
              }}>{l}</button>);

          })}
        </div>

        <div key={safePage} className="anim-fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          {pageItems.map((g) => {
            return (
            <div key={g.id} className="card-press gift-card"
          onClick={() => { if (myFilter === 'vault') setSelected(g); }}
          style={{ display: 'flex', flexDirection: 'column', gap: 8,
                   cursor: myFilter === 'vault' ? 'pointer' : 'default',
                   opacity: myFilter === 'withdrawn' ? 0.75 : 1 }}>
              <div className="gift-card-media" style={{ boxShadow: 'inset 0 0 0 1px var(--border)' }}>
                <GiftMedia kind={g.kind} num={g.num} rounded={22} />
                <div style={{
                  position: 'absolute', bottom: 8, right: 10, zIndex: 2,
                  fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.96)',
                  letterSpacing: '-0.005em', textShadow: '0 1px 3px rgba(0,0,0,0.6)',
                }}>#{g.num}</div>
              </div>
              <div className="col gap-2" style={{ padding: '0 4px' }}>
                <div style={{ fontSize: 13, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{g.name}</div>
                <div className="mono" style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>{fmtRub(g.rub)}</div>
              </div>
            </div>
            );
          })}
        </div>

        {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, letterSpacing: '0.01em' }}>
          Всего <span style={{ margin: '0 2px' }}>{items.length}</span> {items.length === 1 ? 'подарок' : items.length < 5 ? 'подарка' : 'подарков'}
        </div>
      </ScreenWrap>

      {selected && !withdrawing &&
      <MyGiftActions gift={selected}
      onClose={() => setSelected(null)}
      onWithdraw={(g) => {setWithdrawing(g);}}
      onSell={() => setSelected(null)}
      onView={(g) => { setSelected(null); onGiftClick && onGiftClick(g); }}
      onSend={(g) => { setSelected(null); onStartSend && onStartSend(g.id); }} />
      }
      {withdrawing &&
      <WithdrawConfirm gift={withdrawing}
      onClose={() => {setWithdrawing(null);setSelected(null);}}
      onDone={() => {setWithdrawing(null);setSelected(null); onChanged && onChanged();}} />
      }
    </>);

}

window.MyGiftsScreen = MyGiftsScreen;