// Gift Detail bottom-sheet — Portals-style.

function AttrRow({ label, name, rarity, isLast }) {
  return (
    <>
      <div className="row aic" style={{ padding: '13px 16px', gap: 12 }}>
        <div className="t-soft" style={{ fontSize: 14, fontWeight: 500, width: 80 }}>{label}</div>
        <div className="row aic gap-6" style={{ flex: 1, minWidth: 0, justifyContent: 'flex-end' }}>
          <span style={{
            fontSize: 14, fontWeight: 650, color: 'var(--accent)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{name || '—'}</span>
          {rarity != null && (
            <span style={{
              fontSize: 10.5, padding: '1.5px 7px', borderRadius: 999,
              background: 'var(--accent-soft)', color: 'var(--accent)',
              fontWeight: 700, flexShrink: 0,
            }}>{rarity}%</span>
          )}
        </div>
      </div>
      {!isLast && <div style={{ height: 0.5, background: 'var(--border)', margin: '0 16px' }}/>}
    </>
  );
}

function HeroIconBtn({ children, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 32, height: 32, borderRadius: '50%',
      border: 0, padding: 0, cursor: 'pointer',
      background: 'rgba(0,0,0,0.32)',
      WebkitBackdropFilter: 'blur(12px) saturate(160%)',
      backdropFilter: 'blur(12px) saturate(160%)',
      color: 'rgba(255,255,255,0.92)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: 'inset 0 0.5px 0 rgba(255,255,255,0.18)',
    }}>
      {children}
    </button>
  );
}

function GiftDetailSheet({ listing, balance, inCart, onClose, onBuy, onAddToCart }) {
  if (!listing) return null;
  const g = GIFT_KINDS[listing.kind];
  // Покупка идёт с внутреннего баланса кошелька — гейтим по нему.
  const canAfford = balance >= listing.rub;
  // Открыт СВОЙ купленный подарок из «Мои» (есть order_id) → режим просмотра,
  // без кнопок покупки/корзины (нельзя «купить» подарок, который уже твой).
  const owned = listing.order_id != null;

  const [realAttrs, setRealAttrs] = React.useState(null);
  React.useEffect(() => {
    // У реальных листингов атрибуты уже в listing.attrs (с бэка) — fragment-фетч
    // не нужен (и блокируется CORS). Пробуем только для мок-листингов с номером.
    if (listing._raw || listing.num == null) return;
    let cancel = false;
    fetch(`https://nft.fragment.com/gift/${listing.kind}-${listing.num}.json`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (cancel || !d?.attributes) return;
        const get = (t) => d.attributes.find(a => a.trait_type === t)?.value;
        setRealAttrs({
          model:    get('Model'),
          backdrop: get('Backdrop'),
          symbol:   get('Symbol'),
        });
      })
      .catch(() => {});
    return () => { cancel = true; };
  }, [listing.kind, listing.num]);

  const attrs = {
    model:    { name: realAttrs?.model    ?? listing.attrs.model.name,    rarity: listing.attrs.model.rarity },
    backdrop: { name: realAttrs?.backdrop ?? listing.attrs.backdrop.name, rarity: listing.attrs.backdrop.rarity },
    symbol:   { name: realAttrs?.symbol   ?? listing.attrs.symbol.name,   rarity: listing.attrs.symbol.rarity },
  };

  return (
    <SheetShell onClose={onClose}>

      {/* Hero card — the gift's Lottie fills the card; its own backdrop colors it. */}
      <div style={{
        position: 'relative',
        aspectRatio: '1 / 1',
        borderRadius: 28,
        overflow: 'hidden',
        margin: '4px 0 14px',
        background: 'var(--bg-input)',
      }}>
        <div style={{
          position: 'absolute', top: 12, right: 12, zIndex: 3,
          display: 'flex', gap: 8,
        }}>
          <HeroIconBtn><Icons.eye size={15}/></HeroIconBtn>
          <HeroIconBtn><Icons.send size={15}/></HeroIconBtn>
        </div>

        {/* Lottie fills the card */}
        <div style={{ position: 'absolute', inset: 0 }}>
          <GiftLottie kind={listing.kind} num={listing.num} clean/>
        </div>

        {/* Title overlay at bottom */}
        <div style={{
          position: 'absolute', bottom: 16, left: 0, right: 0, zIndex: 2,
          textAlign: 'center', color: '#fff',
          textShadow: '0 1px 8px rgba(0,0,0,0.4)',
          pointerEvents: 'none',
        }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 24, fontWeight: 700, letterSpacing: '-0.015em',
          }}>
            {listing.name}
            <Icons.chevR size={18} style={{ opacity: 0.85 }}/>
          </div>
          {listing.num != null && (
            <div style={{ fontSize: 13, fontWeight: 600, opacity: 0.85, marginTop: 1 }}>
              #{listing.num.toLocaleString('ru-RU')}
            </div>
          )}
        </div>
      </div>

      {/* Attribute table */}
      <div style={{
        borderRadius: 16,
        background: 'var(--bg-input)',
        border: '0.5px solid var(--border)',
        overflow: 'hidden',
      }}>
        <AttrRow label="Model"    name={attrs.model.name}    rarity={attrs.model.rarity}/>
        <AttrRow label="Symbol"   name={attrs.symbol.name}   rarity={attrs.symbol.rarity}/>
        <AttrRow label="Backdrop" name={attrs.backdrop.name} rarity={attrs.backdrop.rarity} isLast/>
      </div>

      {/* View-only для своего подарка; иначе — покупка. */}
      {owned ? (
        <WithSheetClose>{close => (
          <button className="btn center" onClick={close} style={{
            justifyContent: 'center', padding: '14px', marginTop: 16,
            fontSize: 15, fontWeight: 650, width: '100%',
          }}>Закрыть</button>
        )}</WithSheetClose>
      ) : (
      <>
      {/* Buy button — pill with title + price stacked, like Portals */}
      <div className="row gap-8" style={{ marginTop: 16 }}>
        <button
          disabled={!canAfford}
          onClick={() => onBuy(listing)}
          style={{
            flex: 1, border: 0, cursor: canAfford ? 'pointer' : 'not-allowed',
            borderRadius: 999,
            padding: '12px 22px',
            background: 'var(--accent)',
            color: '#fff',
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            gap: 2,
            opacity: canAfford ? 1 : 0.5,
            boxShadow: '0 6px 18px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,0.18)',
            transition: 'transform 0.12s, filter 0.15s',
          }}
          onMouseDown={(e) => canAfford && (e.currentTarget.style.transform = 'scale(0.97)')}
          onMouseUp={(e) => (e.currentTarget.style.transform = 'scale(1)')}
          onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}>
          <span style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.005em' }}>
            {canAfford ? 'Купить подарок' : 'Недостаточно средств'}
          </span>
          {canAfford && (
            <span style={{ fontSize: 13, fontWeight: 500, opacity: 0.85 }}>
              {fmtRub(listing.rub)}
            </span>
          )}
        </button>
        {onAddToCart && (
          <button onClick={() => onAddToCart(listing)} disabled={inCart}
            aria-label={inCart ? 'В корзине' : 'Добавить в корзину'}
            style={{
              width: 60, height: 60, borderRadius: '50%',
              border: 0, padding: 0, flexShrink: 0,
              cursor: inCart ? 'default' : 'pointer',
              background: inCart ? 'var(--green-soft)' : 'var(--bg-input)',
              color: inCart ? 'var(--green)' : 'var(--text)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'background 0.2s, color 0.2s, transform 0.15s',
            }}
            onMouseDown={(e) => !inCart && (e.currentTarget.style.transform = 'scale(0.94)')}
            onMouseUp={(e) => (e.currentTarget.style.transform = 'scale(1)')}
            onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}>
            {inCart ? <Icons.check size={22}/> : <Icons.cart size={22}/>}
          </button>
        )}
      </div>
      {!canAfford && (
        <div className="small t-mute" style={{ textAlign: 'center', lineHeight: 1.5, marginTop: 10 }}>
          Пополните баланс ещё на{' '}
          <span style={{ color: 'var(--text)', fontWeight: 700 }}>
            {fmtRub(listing.rub - balance)}
          </span>
          {' '}в разделе Кошелёк
        </div>
      )}
      </>
      )}
    </SheetShell>
  );
}

window.GiftDetailSheet = GiftDetailSheet;
