/* ============================================================
   B1 — Màn "Khách trong phiên" (Guest / participant)
   Mọi khách host mời đều BÌNH ĐẲNG: thả vật phẩm + bình luận +
   xin phép nói (host mở mic). KHÔNG cần cài app.
   ============================================================ */
function GuestScreen({ particle = 'Bụi trầm', bg, setBg, mode = 'chat', notes = [], setNotes = () => {}, sessionType = 'hop' }) {
  const flyRef = useRef(null);
  const danmuRef = useRef(null);
  const guestBgRef = useRef(null);
  const [confirm, setConfirm] = useState(false);
  const [left, setLeft] = useState(false);
  const [speak, setSpeak] = useState('idle');
  const [elapsed, setElapsed] = useState(132);
  const [clip, setClip] = useState(null);
  const [vote, setVote] = useState(false);
  const [imgReq, setImgReq] = useState('idle'); // idle | pending | approved
  const cat = EMOJI_LIB[sessionType] ? sessionType : 'hop';
  const isWork = mode === 'work';
  const scrim = sessionType === 'gap-mat' ? '61,32,26' : '27,42,69';
  const onGuestBg = (e) => { const f = e.target.files?.[0]; if (f) setBg(URL.createObjectURL(f)); if (e.target) e.target.value = ''; setImgReq('idle'); };
  useInterval(() => setElapsed(e => e + 1), 1000);
  useEffect(() => {
    if (speak !== 'waiting') return;
    const t = setTimeout(() => setSpeak('live'), 4500); // giả lập host mở mic
    return () => clearTimeout(t);
  }, [speak]);
  useEffect(() => {
    if (imgReq !== 'pending') return;
    const t = setTimeout(() => setImgReq('approved'), 3000); // giả lập host chấp thuận
    return () => clearTimeout(t);
  }, [imgReq]);
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');

  if (left) {
    return (
      <div className="b1-screen" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 30px' }}>
        <div>
          <div className="b1-eyebrow" style={{ marginBottom: 10 }}>ĐÃ RỜI PHIÊN</div>
          <h1 className="b1-display" style={{ fontSize: 26, color: 'var(--cream)', margin: 0 }}>Hẹn gặp lại</h1>
          <p style={{ fontSize: 13, color: 'var(--cream-dim)', marginTop: 10, lineHeight: 1.6 }}>Bạn vào lại phiên bất cứ lúc nào bằng lời mời của host.</p>
          <button className="b1-btn b1-btn-soft" style={{ marginTop: 18 }} onClick={() => setLeft(false)}>Quay lại phiên</button>
        </div>
      </div>
    );
  }

  return (
    <div className="b1-screen">
      <InAppBrowserBanner />
      {bg
        ? <img src={bg} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        : <StripedImg label="ẢNH NỀN PHIÊN · FULL-BLEED" style={{ position: 'absolute', inset: 0 }} />}
      <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, rgba(${scrim},.7) 0%, rgba(${scrim},.25) 30%, rgba(${scrim},.45) 70%, rgba(${scrim},.92) 100%)` }} />
      <input ref={guestBgRef} type="file" accept="image/*" onChange={onGuestBg} style={{ display: 'none' }} />

      {!isWork && <MoteLayer variant={particle} />}
      {!isWork && <FlyingLayer ref={flyRef} autoEmojis={EMOJI_LIB[cat]} autoEvery={2400} zIndex={4} />}
      {!isWork && <DanmuLayer ref={danmuRef} speed="vừa" zIndex={5} />}

      {/* top bar */}
      <div style={{ position: 'absolute', top: 52, left: 0, right: 0, zIndex: 20, display: 'flex', alignItems: 'center', gap: 10, padding: '0 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '7px 12px', background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', borderRadius: 999, border: '1px solid var(--ink-line)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--vermilion)', animation: 'b1-glow 1.6s ease-out infinite' }} />
          {!isWork && <span className="b1-mono" style={{ fontSize: 10, color: 'var(--cream)' }}>ĐANG DIỄN RA</span>}
          <span className="b1-mono" style={{ fontSize: 10, color: 'var(--cream-dim)' }}>{mm}:{ss}</span>
        </div>
        {isWork && <span className="b1-mono" style={{ fontSize: 9.5, letterSpacing: '.06em', fontWeight: 600, padding: '6px 12px', borderRadius: 999, background: 'var(--gold)', color: '#15100A' }}>ĐANG HỌP</span>}
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 11px', background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', borderRadius: 999, border: '1px solid var(--ink-line)' }}>
          <Avatar name="Cô Hoa" color="#9FAE8C" size={18} />
          <span className="b1-mono" style={{ fontSize: 10.5, color: 'var(--cream)' }}>6</span>
        </div>
        <button onClick={() => setConfirm(true)} className="b1-mono" style={{
          padding: '8px 13px', borderRadius: 999, cursor: 'pointer', fontSize: 10, letterSpacing: '.08em',
          background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', border: '1px solid var(--ink-line)', color: 'var(--cream)',
        }}>RỜI PHIÊN</button>
      </div>

      {/* title centerpiece — ẩn ở chế độ Họp để nhường diện tích cho bản vẽ */}
      {!isWork && (
        <div style={{ position: 'absolute', top: 120, left: 0, right: 0, textAlign: 'center', zIndex: 3, pointerEvents: 'none' }}>
          <div className="b1-eyebrow" style={{ color: 'var(--cream-dim)' }}>BẠN ĐANG DỰ</div>
          <h1 className="b1-display" style={{ fontSize: 32, margin: '5px 0 0', color: 'var(--cream)', textShadow: '0 2px 14px rgba(0,0,0,.5)' }}>Lễ giỗ ông nội</h1>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 11, padding: '4px 11px 4px 5px', borderRadius: 999, background: 'var(--ink-glass)', border: '1px solid var(--ink-line)' }}>
            <Avatar name="Minh" color="#B49B86" size={18} />
            <span className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', letterSpacing: '.06em' }}>MINH · THÀNH VIÊN</span>
          </div>
        </div>
      )}

      {/* bottom controls */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 30, zIndex: 20, padding: '0 18px' }}>
        {isWork && <NotesList notes={notes} selfName="Bạn" />}
        {/* bình luận: gõ → xác nhận → xuất bản (Họp: vào list tĩnh, không bay) */}
        <DanmuCompose placeholder={isWork ? 'Ghi chú góp ý…' : undefined}
          onPublish={(t) => isWork ? setNotes(n => [...n, { a: 'Bạn', t, color: '#B49B86' }]) : (danmuRef.current && danmuRef.current.push({ a: 'Bạn', t }))} />

        <VotePill live label="Chủ trì mở biểu quyết · bỏ phiếu" onClick={() => setVote(true)} />

        {/* xin gửi ảnh nền */}
        {imgReq === 'idle' && (
          <button onClick={() => setImgReq('pending')} className="b1-btn b1-btn-soft" style={{ width: '100%', gap: 9, marginBottom: 8 }}>
            <svg width="18" height="18" viewBox="0 0 22 22" fill="none"><path d="M11 3v11m0-11L7 7m4-4l4 4" stroke="var(--gold)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/><path d="M4 16v3h14v-3" stroke="var(--gold-dim)" strokeWidth="1.6" strokeLinecap="round"/></svg>
            <span style={{ fontWeight: 500 }}>Xin gửi ảnh nền</span>
            <span className="b1-mono" style={{ fontSize: 9, color: 'var(--cream-dim)' }}>· CHờ HOST CHẤP THUẬN</span>
          </button>
        )}
        {imgReq === 'pending' && (
          <div className="b1-btn" style={{ width: '100%', padding: '13px 18px', background: 'var(--ink-soft)', border: '1px solid var(--gold-dim)', justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)', animation: 'b1-blink 1.2s ease-in-out infinite' }} />
              <span style={{ fontSize: 13.5, color: 'var(--cream)' }}>Chờ host chấp thuận…</span>
            </span>
            <button onClick={() => setImgReq('idle')} className="b1-mono" style={{ fontSize: 9.5, cursor: 'pointer', background: 'none', border: '1px solid var(--ink-line)', color: 'var(--cream-dim)', borderRadius: 5, padding: '5px 9px' }}>HỦY</button>
          </div>
        )}
        {imgReq === 'approved' && (
          <button onClick={() => guestBgRef.current?.click()} className="b1-btn b1-btn-primary" style={{ width: '100%', gap: 9, marginBottom: 8 }}>
            <svg width="18" height="18" viewBox="0 0 22 22" fill="none"><path d="M11 3v11m0-11L7 7m4-4l4 4" stroke="#15100A" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/><path d="M4 16v3h14v-3" stroke="#15100A" strokeWidth="1.6" strokeLinecap="round"/></svg>
            <span style={{ fontWeight: 600 }}>Host đồng ý · Tải ảnh lên</span>
          </button>
        )}

        {/* vật phẩm — mở cho mọi người · nút + dán ảnh/sticker của bạn (ẩn khi Họp) */}
        {!isWork && <SessionTray flyRef={flyRef} emojis={EMOJI_LIB[cat]} />}

        {/* nói — xin phép → hàng chờ → host mở mic (một người nói, cả nhà nghe) */}
        {speak === 'idle' ? (
          <button onClick={() => setSpeak('waiting')} className="b1-btn b1-btn-soft" style={{ width: '100%', gap: 9 }}>
            <MicBars active={false} />
            <span style={{ fontWeight: 500 }}>Xin phép nói</span>
            <span className="b1-mono" style={{ fontSize: 9, color: 'var(--cream-dim)', letterSpacing: '.06em' }}>· VÀO HÀNG CHỜ</span>
          </button>
        ) : speak === 'waiting' ? (
          <div className="b1-btn" style={{ width: '100%', padding: '13px 18px', background: 'var(--ink-soft)', border: '1px solid var(--gold-dim)', justifyContent: 'space-between' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)', animation: 'b1-blink 1.2s ease-in-out infinite' }} />
              <span style={{ fontSize: 13.5, color: 'var(--cream)' }}>Đang chờ tới lượt…</span>
            </span>
            <button onClick={() => setSpeak('idle')} className="b1-mono" style={{ fontSize: 9.5, cursor: 'pointer', background: 'none', border: '1px solid var(--ink-line)', color: 'var(--cream-dim)', borderRadius: 5, padding: '5px 9px' }}>HỦY</button>
          </div>
        ) : (
          <div>
            <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--gold)', letterSpacing: '.1em', textAlign: 'center', marginBottom: 8, animation: 'b1-blink 1.4s ease-in-out infinite' }}>● TỚI LƯỢT BẠN · MIC ĐÃ MỞ</div>
            {clip && <VoiceClip clip={clip} onClose={() => setClip(null)} />}
            <PushToTalk onEnd={(c) => {
              setClip(c);
              const t = `đã gửi tin thoại · ${c.duration.toFixed(1)}s 🎙️`;
              if (isWork) setNotes(n => [...n, { a: 'Bạn', t, color: '#B49B86' }]);
              else danmuRef.current && danmuRef.current.push({ a: 'Bạn', t });
              setSpeak('idle');
            }} />
          </div>
        )}
      </div>

      <ConfirmDialog open={confirm}
        title="Rời phiên?"
        body="Bạn có thể vào lại bất cứ lúc nào bằng lời mời của host."
        confirmLabel="Rời phiên" cancelLabel="Ở lại" danger={false}
        onCancel={() => setConfirm(false)}
        onConfirm={() => { setConfirm(false); setLeft(true); }} />
      {vote && <VoteSheet mode="participant" presetQuestion="Đồng ý hướng này?" onClose={() => setVote(false)} />}
    </div>
  );
}

Object.assign(window, { GuestScreen });
