/* ============================================================
   B1 — Màn "Lưu phiên" (gộp quyết định lưu + xem lại capsule)
   Header đổi theo trạng thái + reel + stats + tên/thẻ +
   action bar (Lưu về máy / Lưu tại B1 / Xoá / Chia sẻ) +
   PaymentSheet mock + theater xem lại (CapsuleScreen nhúng).
   ============================================================ */
const SNAPSHOTS = [
  { t: '19:04', cap: 'Khai phiên', emoji: '🪷', reacts: 12 },
  { t: '19:18', cap: 'Cô Hoa dâng hương', emoji: '🕯️', reacts: 23 },
  { t: '19:33', cap: 'Cả nhà cùng khấn', emoji: '🙏', reacts: 31 },
  { t: '19:47', cap: 'Lời ông Bảy', emoji: '🧧', reacts: 18 },
  { t: '19:41', cap: 'Khoảnh khắc cuối', emoji: '🌕', reacts: 27 },
];
const WRAP_TAGS = ['Giỗ', 'Broker', 'Sinh nhật', 'Lễ', 'Khác'];
const PAY_PRICE = { server: 29000, device: 15000 };
const PAY_LABEL = { server: 'Lưu tại B1 · 13 tháng', device: 'Tải bản gốc về máy' };

function StatCell({ value, label, accent }) {
  return (
    <div style={{ flex: 1, textAlign: 'center' }}>
      <div className="b1-display" style={{ fontSize: 30, color: accent || 'var(--cream)', lineHeight: 1 }}>{value}</div>
      <div className="b1-label" style={{ marginTop: 6 }}>{label}</div>
    </div>
  );
}

function PaymentSheet({ method, onClose, onConfirm }) {
  const [via, setVia] = useState('momo');
  if (!method) return null;
  const price = PAY_PRICE[method];
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 95, background: 'rgba(13,19,31,.78)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', background: 'var(--ink-soft)', borderTopLeftRadius: 22, borderTopRightRadius: 22, border: '1px solid var(--ink-line)', borderBottom: 'none', padding: '14px 22px 30px', animation: 'b1-rise-in .28s ease both' }}>
        <div style={{ width: 38, height: 4, borderRadius: 4, background: 'var(--ink-line)', margin: '0 auto 16px' }} />
        <div className="b1-eyebrow">Xác nhận thanh toán</div>
        <h3 className="b1-display" style={{ fontSize: 23, margin: '6px 0 16px', color: 'var(--cream)' }}>{PAY_LABEL[method]}</h3>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {['momo', 'zalopay', 'thẻ'].map(k => (
            <button key={k} onClick={() => setVia(k)} className={'b1-chip' + (via === k ? ' is-on' : '')} style={{ flex: 1, textAlign: 'center', textTransform: 'capitalize' }}>{k === 'thẻ' ? 'Thẻ NH' : k}</button>
          ))}
        </div>
        <button onClick={() => onConfirm(method)} className="b1-btn b1-btn-primary" style={{ width: '100%', padding: '15px', justifyContent: 'center', fontWeight: 600 }}>
          Xác nhận · {price.toLocaleString('vi-VN')}đ
        </button>
        <p className="b1-mono" style={{ fontSize: 9, color: 'rgba(200,192,174,.45)', textAlign: 'center', marginTop: 12 }}>Demo — chưa nối cổng thanh toán thật</p>
      </div>
    </div>
  );
}

function WrapScreen({ sessionType = 'hop', particle = 'Bụi trầm' }) {
  const [tag, setTag] = useState(sessionType === 'gap-mat' ? 'Sinh nhật' : 'Giỗ');
  const [name, setName] = useState('Phiên 13.06');
  const [active, setActive] = useState(2);
  const [savedServer, setSavedServer] = useState(false);
  const [savedDevice, setSavedDevice] = useState(false);
  const [payMethod, setPayMethod] = useState(null);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [theaterOpen, setTheaterOpen] = useState(false);
  const [confirmDel, setConfirmDel] = useState(false);
  const [toast, setToast] = useState(null);

  const anySaved = savedServer || savedDevice;
  const flash = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2000); };
  const handlePay = (method) => {
    setPayMethod(null);
    if (method === 'server') { setSavedServer(true); flash('Đã lưu tại B1 ✓'); }
    else { setSavedDevice(true); flash('Đã tải về máy ✓'); }
  };
  const shareClick = () => anySaved ? setInviteOpen(true) : flash('Cần lưu phiên trước khi chia sẻ');

  return (
    <div className="b1-screen">
      <div className="b1-scroll b1-safe-top" style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}>
        <div style={{ padding: '14px 26px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div className="b1-eyebrow">{anySaved ? 'Phiên đã lưu' : 'Phiên đã khép lại'}</div>
            {anySaved && <span className="b1-mono" style={{ fontSize: 9, color: 'var(--moss)', border: '1px solid rgba(92,110,84,.4)', borderRadius: 5, padding: '2px 6px' }}>🔒 RIÊNG TƯ</span>}
          </div>
          <h1 className="b1-display" style={{ fontSize: 34, margin: '8px 0 0', color: 'var(--cream)', lineHeight: 1.08 }}>
            {anySaved ? name : <>Giữ lại phiên này<br />làm kỷ niệm?</>}
          </h1>
          <p style={{ fontSize: 13.5, color: 'var(--cream-dim)', marginTop: 11, lineHeight: 1.6 }}>
            {anySaved
              ? `Đã lưu ${savedServer ? 'tại B1 · còn 13 tháng' : ''}${savedServer && savedDevice ? ' · ' : ''}${savedDevice ? 'về máy' : ''}.`
              : 'B1 đã chọn ra những khoảnh khắc đáng nhớ nhất. Lưu thành capsule để cả nhà xem lại bất cứ lúc nào.'}
          </p>
        </div>

        <div style={{ marginTop: 22 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 26px 11px' }}>
            <span className="b1-label">KHOẢNH KHẮC ĐẸP</span>
            <span className="b1-mono" style={{ fontSize: 10, color: 'var(--gold)' }}>{active + 1} / {SNAPSHOTS.length}</span>
          </div>
          <div className="b1-scroll" style={{ display: 'flex', gap: 13, overflowX: 'auto', padding: '0 26px 4px', scrollSnapType: 'x mandatory' }}>
            {SNAPSHOTS.map((s, i) => (
              <div key={i} onClick={() => setActive(i)} style={{
                flexShrink: 0, width: 186, scrollSnapAlign: 'center', cursor: 'pointer',
                transition: 'transform .2s ease', transform: active === i ? 'translateY(-4px)' : 'none',
              }}>
                <StripedImg label={'SNAPSHOT ' + s.t} style={{
                  height: 246, borderRadius: 'var(--r-lg)', position: 'relative',
                  border: '1px solid ' + (active === i ? 'var(--gold-dim)' : 'var(--ink-line)'),
                  boxShadow: active === i ? '0 14px 34px -16px rgba(0,0,0,.7)' : 'none',
                }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 45%, rgba(21,30,48,.9) 100%)', borderRadius: 'var(--r-lg)' }} />
                  <span style={{ position: 'absolute', top: 13, left: 14, fontSize: 22 }}>{s.emoji}</span>
                  <div style={{
                    position: 'absolute', top: 13, right: 14, display: 'flex', alignItems: 'center', gap: 4,
                    background: 'rgba(21,30,48,.6)', backdropFilter: 'blur(6px)', borderRadius: 999, padding: '3px 8px',
                  }}>
                    <span style={{ fontSize: 10, color: 'var(--vermilion)' }}>❤</span>
                    <span className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream)' }}>{s.reacts}</span>
                  </div>
                  <div style={{ position: 'absolute', left: 14, right: 14, bottom: 14 }}>
                    <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--gold)', marginBottom: 3 }}>{s.t}</div>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--cream)' }}>{s.cap}</div>
                  </div>
                </StripedImg>
              </div>
            ))}
          </div>
        </div>

        {anySaved && (
          <div style={{ padding: '14px 26px 0' }}>
            <button className="b1-btn b1-btn-ghost" style={{ width: '100%' }} onClick={() => setTheaterOpen(true)}>▶ Xem lại toàn bộ · 41 phút</button>
          </div>
        )}

        <div style={{ margin: '24px 26px 0', padding: '18px 10px', background: 'var(--ink-soft)', border: '1px solid var(--ink-line)', borderRadius: 'var(--r-md)', display: 'flex', alignItems: 'center' }}>
          <StatCell value="6" label="NGƯỜI" />
          <div style={{ width: 1, height: 34, background: 'var(--ink-line)' }} />
          <StatCell value="48" label="BÌNH LUẬN" accent="var(--gold)" />
          <div style={{ width: 1, height: 34, background: 'var(--ink-line)' }} />
          <StatCell value="41" label="PHÚT" />
        </div>

        <div style={{ padding: '24px 26px 0' }}>
          <label className="b1-label" style={{ display: 'block', marginBottom: 8 }}>TÊN PHIÊN</label>
          <input className="b1-input" value={name} onChange={e => setName(e.target.value)} />
        </div>

        <div style={{ padding: '18px 26px 0' }}>
          <label className="b1-label" style={{ display: 'block', marginBottom: 10 }}>GẮN THẺ</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {WRAP_TAGS.map(t => (
              <button key={t} className={'b1-chip' + (tag === t ? ' is-on' : '')} onClick={() => setTag(t)}>{t}</button>
            ))}
          </div>
        </div>

        <div style={{ padding: '26px 26px 40px' }}>
          <button className="b1-btn b1-btn-vermilion" disabled={savedServer} style={{ width: '100%', padding: '15px 16px', justifyContent: 'space-between', opacity: savedServer ? .65 : 1, cursor: savedServer ? 'default' : 'pointer' }} onClick={() => setPayMethod('server')}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <SealStamp size={22} char="存" style={{ animation: 'none', borderRadius: 5, background: 'rgba(251,237,233,.18)', boxShadow: 'none', color: '#FBEDE9' }} />
              {savedServer ? 'Đã lưu tại B1 ✓' : 'Lưu tại B1 · 13 tháng'}
            </span>
            {!savedServer && <span className="b1-mono" style={{ fontSize: 8.5, letterSpacing: '.08em', background: 'rgba(251,237,233,.2)', padding: '3px 7px', borderRadius: 4 }}>PHÍ LƯU</span>}
          </button>
          <button className="b1-btn b1-btn-soft" disabled={savedDevice} style={{ width: '100%', marginTop: 10, padding: '15px 16px', justifyContent: 'space-between', opacity: savedDevice ? .65 : 1, cursor: savedDevice ? 'default' : 'pointer' }} onClick={() => setPayMethod('device')}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <svg width="15" height="15" viewBox="0 0 16 16"><path d="M8 2v8m0 0L4.8 6.8M8 10l3.2-3.2" stroke="var(--cream)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M3 12v2h10v-2" stroke="var(--cream)" strokeWidth="1.5" strokeLinecap="round"/></svg>
              {savedDevice ? 'Đã tải về máy ✓' : 'Lưu về máy'}
            </span>
            {!savedDevice && <span className="b1-mono" style={{ fontSize: 8.5, letterSpacing: '.08em', color: 'var(--gold)', border: '1px solid var(--gold-dim)', padding: '3px 7px', borderRadius: 4 }}>CÓ PHÍ</span>}
          </button>
          <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
            <button className="b1-btn b1-btn-ghost" style={{ flex: 1, color: 'var(--vermilion)' }} onClick={() => setConfirmDel(true)}>Xoá</button>
            <button className="b1-btn" style={{ flex: 1, justifyContent: 'center', background: anySaved ? 'var(--ink-soft)' : 'transparent', border: '1px solid var(--ink-line)', opacity: anySaved ? 1 : .55, color: 'var(--cream)' }} onClick={shareClick}>Chia sẻ</button>
          </div>
          <p className="b1-mono" style={{ fontSize: 9.5, color: 'rgba(200,192,174,.5)', textAlign: 'center', marginTop: 14, lineHeight: 1.7 }}>
            {anySaved ? 'Có thể lưu cả 2 cách nếu muốn' : 'Chưa lưu sẽ tự xoá sau 1 ngày · cả hai cách giữ đều có phí'}
          </p>
        </div>
      </div>

      {toast && (
        <div style={{ position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)', zIndex: 98, background: 'var(--ink-soft)', border: '1px solid var(--gold-dim)', borderRadius: 999, padding: '9px 16px', fontSize: 12, color: 'var(--cream)', whiteSpace: 'nowrap', animation: 'b1-rise-in .25s ease both', boxShadow: '0 10px 24px -10px rgba(0,0,0,.6)' }}>{toast}</div>
      )}

      <PaymentSheet method={payMethod} onClose={() => setPayMethod(null)} onConfirm={handlePay} />
      <InviteSheet open={inviteOpen} onClose={() => setInviteOpen(false)} variant="capsule" />
      {theaterOpen && <CapsuleScreen particle={particle} onClose={() => setTheaterOpen(false)} />}

      <ConfirmDialog open={confirmDel}
        title="Xóa phiên?"
        body="Phiên này sẽ bị xóa vĩnh viễn khỏi B1. Người được chia sẻ cũng sẽ không xem lại được."
        confirmLabel="Xóa vĩnh viễn" cancelLabel="Giữ lại"
        onCancel={() => setConfirmDel(false)}
        onConfirm={() => { setConfirmDel(false); flash('Đã xóa phiên'); }} />
    </div>
  );
}

Object.assign(window, { WrapScreen });
