// Send-gift flow — two-step: Select gifts → Recipient → Toast.

function SendSelectSheet({ initialIds, gifts, onCancel, onNext }) {
  const all = gifts || [];            // реальные held-подарки (проброс из app.jsx)
  const [selected, setSelected] = React.useState(() => new Set(initialIds || []));
  const [query, setQuery] = React.useState('');
  const closeAnim = React.useContext(SheetCloseContext);

  // Snapshot the initially-selected gifts so the ordering stays stable while
  // the user toggles inside the picker — they sort to the top once, on open,
  // not jumping around with every tap.
  const initialOrder = React.useRef(new Set(initialIds || []));
  const items = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    const list = all.filter(g => !q || g.name.toLowerCase().includes(q));
    return list.slice().sort((a, b) => {
      const sa = initialOrder.current.has(a.id) ? 0 : 1;
      const sb = initialOrder.current.has(b.id) ? 0 : 1;
      return sa - sb;
    });
  }, [query, all]);
  const allSelected = items.length > 0 && items.every(g => selected.has(g.id));
  const count = selected.size;

  const toggle = (id) => setSelected(prev => {
    const s = new Set(prev);
    s.has(id) ? s.delete(id) : s.add(id);
    return s;
  });
  const toggleAll = () => setSelected(prev => {
    if (allSelected) {
      const s = new Set(prev);
      items.forEach(g => s.delete(g.id));
      return s;
    }
    const s = new Set(prev);
    items.forEach(g => s.add(g.id));
    return s;
  });

  return (
    <>
      <div className="row aic jcsb" style={{ marginBottom: 14, padding: '4px 2px 0' }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em' }}>Выберите подарок</div>
        <button onClick={onCancel} aria-label="Назад" style={{
          width: 32, height: 32, borderRadius: '50%', border: 0, padding: 0, cursor: 'pointer',
          background: 'var(--bg-input)', color: 'var(--text-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icons.close size={16}/></button>
      </div>

      <div style={{
        padding: '11px 16px', borderRadius: 999, background: 'var(--bg-input)',
        display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
      }}>
        <Icons.search size={16} style={{ color: 'var(--text-mute)' }}/>
        <input placeholder="Быстрый поиск" value={query} onChange={(e) => setQuery(e.target.value)}
               style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: 'var(--text)', fontSize: 14 }}/>
      </div>

      <div className="row aic gap-10" style={{ padding: '4px 4px 12px', cursor: 'pointer' }} onClick={toggleAll}>
        <CheckBox on={allSelected}/>
        <div style={{ fontSize: 15, fontWeight: 650 }}>Выбрать все</div>
        <div className="t-mute small">· {count}</div>
      </div>

      <div style={{ maxHeight: 360, overflowY: 'auto', margin: '-6px -4px 0', padding: '6px 4px 2px', display: 'flex', flexDirection: 'column', gap: 8, scrollbarWidth: 'none' }}>
        {items.map(g => {
          const on = selected.has(g.id);
          return (
            <div key={g.id} onClick={() => toggle(g.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: 10, borderRadius: 16,
              background: 'var(--bg-input)',
              border: on ? '0.5px solid var(--accent)' : '0.5px solid var(--border)',
              boxShadow: on ? '0 0 0 1px var(--accent), 0 4px 14px var(--accent-glow)' : 'none',
              transition: 'border-color 0.15s, box-shadow 0.15s',
              cursor: 'pointer',
            }}>
              <div style={{ position: 'relative', width: 48, height: 48, borderRadius: 12, overflow: 'hidden', flexShrink: 0 }}>
                <GiftMedia kind={g.kind} num={g.num} rounded={12}/>
              </div>
              <div className="flex1" style={{ minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{g.name}</div>
                <div className="small t-mute mono">#{g.num}</div>
              </div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, marginRight: 6 }}>{fmtRub(g.rub)}</div>
              <CheckBox on={on}/>
            </div>
          );
        })}
      </div>

      <div className="row gap-8" style={{ marginTop: 14 }}>
        <button onClick={onCancel} style={{
          flex: 1, padding: '14px', borderRadius: 999,
          background: 'var(--bg-input)', color: 'var(--text)',
          border: 0, fontSize: 15, fontWeight: 650, cursor: 'pointer',
        }}>Отмена</button>
        <button onClick={() => onNext([...selected])} disabled={count === 0} style={{
          flex: 1.4, padding: '14px', borderRadius: 999,
          background: 'var(--accent)', color: '#fff',
          border: 0, fontSize: 15, fontWeight: 700,
          cursor: count > 0 ? 'pointer' : 'not-allowed',
          opacity: count > 0 ? 1 : 0.5,
          boxShadow: count > 0 ? '0 6px 18px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,0.18)' : 'none',
        }}>Выбрать {count > 0 && `· ${count}`}</button>
      </div>
    </>
  );
}

function SendRecipientSheet({ gifts: initialGifts, onBack, onSend, onAddMore }) {
  const [gifts, setGifts] = React.useState(initialGifts);
  const [username, setUsername] = React.useState('');
  const [anon, setAnon] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendErr, setSendErr] = React.useState(null);
  const closeAnim = React.useContext(SheetCloseContext);
  const total = gifts.reduce((s, g) => s + g.rub, 0);

  // РЕАЛЬНАЯ отправка: POST /me/gifts/{order_id}/send по одному на подарок.
  const doSend = async () => {
    const recip = username.trim();
    if (!recip || gifts.length === 0 || sending) return;
    setSending(true); setSendErr(null);
    try {
      const DS = window.DataSource;
      if (DS && DS.sendGift) {
        for (const g of gifts) {
          await DS.sendGift(g.order_id || g.id, recip, anon);   // anonymous реально уходит на бэк
        }
      } else if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.initData) {
        throw new Error('DataSource unavailable');    // прод в Telegram: НЕ притворяемся успехом
      } else {
        await new Promise(r => setTimeout(r, 600));    // дизайн-симулятор в браузере
      }
      onSend({ username: recip, anon, count: gifts.length });
    } catch (e) {
      setSendErr(window.friendlyError ? window.friendlyError(e, 'send') : 'Не удалось отправить — попробуй через минуту');
      setSending(false);
    }
  };
  const removeGift = (id) => setGifts(prev => prev.filter(g => g.id !== id));
  // Hand the current id set up to the parent on navigation so the picker
  // shows what's still in the recipient bundle (and removals stick).
  const currentIds = gifts.map(g => g.id);

  return (
    <>
      <div className="row aic jcsb" style={{ padding: '4px 2px 0', marginBottom: 14 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em' }}>Получатель</div>
          <div className="small t-soft" style={{ marginTop: 2 }}>Введи только логин Telegram</div>
        </div>
        <button onClick={closeAnim} aria-label="Закрыть" style={{
          width: 32, height: 32, borderRadius: '50%', border: 0, padding: 0, cursor: 'pointer',
          background: 'var(--bg-input)', color: 'var(--text-soft)', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icons.close size={16}/></button>
      </div>

      <div className="row aic jcsb" style={{ marginBottom: 10 }}>
        <div className="small t-soft">Выбраны подарки</div>
        <div className="mono small" style={{ fontWeight: 600 }}>{fmtRub(total)} · {gifts.length} шт.</div>
      </div>

      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 8, marginBottom: 12, scrollbarWidth: 'none' }}>
        {gifts.map(g => (
          <div key={g.id} style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 72, height: 72, borderRadius: 16, overflow: 'hidden', position: 'relative' }}>
              <GiftMedia kind={g.kind} num={g.num} rounded={16}/>
            </div>
            <div onClick={() => removeGift(g.id)} style={{
              position: 'absolute', top: -4, right: -4,
              width: 22, height: 22, borderRadius: '50%',
              background: 'rgba(0,0,0,0.6)', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
              border: '1.5px solid var(--bg-app)',
            }}><Icons.close size={12}/></div>
            <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.85)', textAlign: 'center', marginTop: 4, fontWeight: 600 }}>
              #{g.num}
            </div>
          </div>
        ))}
        <div onClick={() => onAddMore(currentIds)} style={{
          width: 72, height: 72, borderRadius: 16,
          background: 'var(--accent-soft)', color: 'var(--accent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0,
        }}>
          <Icons.plus size={20}/>
        </div>
      </div>

      <div style={{
        padding: '12px 16px', borderRadius: 14,
        background: 'var(--bg-input)',
        display: 'flex', alignItems: 'center', gap: 6,
        marginBottom: 10,
      }}>
        <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>

      <div className="row aic gap-10" style={{ padding: '6px 4px', cursor: 'pointer' }} onClick={() => setAnon(v => !v)}>
        <CheckBox on={anon}/>
        <div style={{ fontSize: 14, fontWeight: 600 }}>Отправить анонимно</div>
      </div>

      {sendErr && (
        <div className="small" style={{ color: 'var(--red, #e25555)', textAlign: 'center', marginTop: 10 }}>{sendErr}</div>
      )}

      <div className="row gap-8" style={{ marginTop: 16 }}>
        <button onClick={closeAnim} style={{
          flex: 1, padding: '14px', borderRadius: 999,
          background: 'var(--bg-input)', color: 'var(--text)',
          border: 0, fontSize: 15, fontWeight: 650, cursor: 'pointer',
        }}>Назад</button>
        <button onClick={doSend}
                disabled={!username || gifts.length === 0 || sending}
                style={{
          flex: 1.4, padding: '14px', borderRadius: 999,
          background: 'var(--accent)', color: '#fff',
          border: 0, fontSize: 15, fontWeight: 700,
          cursor: (username && gifts.length > 0 && !sending) ? 'pointer' : 'not-allowed',
          opacity: (username && gifts.length > 0 && !sending) ? 1 : 0.5,
          boxShadow: (username && gifts.length > 0 && !sending) ? '0 6px 18px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,0.18)' : 'none',
        }}>{sending ? 'Отправляем…' : <>Отправить {gifts.length > 0 && `· ${gifts.length}`}</>}</button>
      </div>

      <div className="row aic gap-6 small t-mute" style={{ marginTop: 12, textAlign: 'center', justifyContent: 'center' }}>
        <Icons.shield size={12}/>
        <span>Внимательно проверь имя получателя</span>
      </div>
    </>
  );
}

// Success screen shown after the gift is sent — the gift "flies off" into
// Telegram with expanding rings, then a confetti + check celebration. The
// sheet auto-dismisses (slides down) once the celebration has played.
function SendSuccessSheet({ gifts, recipient }) {
  const closeAnim = React.useContext(SheetCloseContext);
  const [done, setDone] = React.useState(false);
  React.useEffect(() => {
    const t1 = setTimeout(() => setDone(true), 1000);
    const t2 = setTimeout(() => closeAnim(), 3000);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  const g = gifts[0] || {};
  const n = gifts.length;
  const name = recipient?.anon ? 'анонимно' : ('@' + (recipient?.username || 'recipient'));
  const giftWord = n === 1 ? 'подарок' : n < 5 ? 'подарка' : 'подарков';
  return (
    <div className="col aic" style={{ alignItems: 'center', textAlign: 'center', padding: '30px 16px 16px', position: 'relative' }}>
      {done && <Confetti/>}
      <div style={{
        position: 'relative', width: 150, height: 150,
        display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1,
      }}>
        {!done && <><div className="send-ring"/><div className="send-ring r2"/></>}
        {!done ? (
          <div className="send-gift-fly">
            <div style={{
              position: 'relative', width: 96, height: 96,
              borderRadius: 24, overflow: 'hidden',
              boxShadow: '0 14px 34px rgba(0,0,0,0.45)',
            }}>
              <GiftMedia kind={g.kind} num={g.num} rounded={24}/>
              {n > 1 && (
                <div style={{
                  position: 'absolute', top: 6, right: 6,
                  minWidth: 22, height: 22, padding: '0 6px', borderRadius: 999,
                  background: 'var(--accent)', color: '#fff',
                  fontSize: 12, fontWeight: 800,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.4)',
                }}>{n}</div>
              )}
            </div>
          </div>
        ) : (
          <div className="send-check" style={{
            width: 96, height: 96, borderRadius: '50%',
            background: 'var(--green)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 12px 34px var(--green-soft), inset 0 1px 0 rgba(255,255,255,0.3)',
          }}>
            <Icons.check size={46}/>
          </div>
        )}
      </div>
      <div className="h2" style={{ marginTop: 16, color: done ? 'var(--green)' : 'var(--text)' }}>
        {done ? 'Отправлено! 🎉' : 'Отправляем…'}
      </div>
      <div className="t-soft body" style={{ marginTop: 6, maxWidth: 290, lineHeight: 1.45 }}>
        {done ? (
          <>
            {n > 1 ? `${n} ${giftWord}` : g.name} {n > 1 ? 'улетели' : 'улетел'} к{' '}
            <span style={{ color: 'var(--text)', fontWeight: 700 }}>{name}</span>
          </>
        ) : (
          'Подарок летит в Telegram'
        )}
      </div>
    </div>
  );
}

window.SendSelectSheet  = SendSelectSheet;
window.SendSuccessSheet = SendSuccessSheet;
window.SendRecipientSheet = SendRecipientSheet;
