/* ============================================================
   B1 — Màn "Chủ trì" (Host, in-session)
   Full-screen bg + flying items + danmu + emoji tray + PTT.
   Sidebar phải (gear) · confirm "Kết thúc phiên".
   ============================================================ */
const HOST_PARTICIPANTS = [
  { name: 'Anh Dũng', color: '#C8A06A', host: true, mic: true },
  { name: 'Cô Hoa',  color: '#9FAE8C', mic: false, speaking: true },
  { name: 'Bác Tư',  color: '#CDB48A', mic: true },
  { name: 'Chị Lan', color: '#B49B86', mic: false },
  { name: 'Em Minh', color: '#A8B59A', mic: false },
  { name: 'Ông Bảy', color: '#BFA98C', mic: true },
];

function Gear({ size = 19 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none">
      <circle cx="10" cy="10" r="2.6" stroke="var(--cream)" strokeWidth="1.4"/>
      <path d="M10 1.5v2.2M10 16.3v2.2M3.5 3.5l1.6 1.6M14.9 14.9l1.6 1.6M1.5 10h2.2M16.3 10h2.2M3.5 16.5l1.6-1.6M14.9 5.1l1.6-1.6" stroke="var(--cream)" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  );
}

function HostScreen({ defaultSpeed = 'vừa', particle = 'Bụi trầm', onEnd, bg, setBg, mode = 'chat', setMode = () => {}, notes = [], setNotes = () => {}, sessionType = 'hop' }) {
  const flyRef = useRef(null);
  const danmuRef = useRef(null);
  const bgFileRef = useRef(null);
  const onPickBg = (e) => { const f = e.target.files?.[0]; if (f) setBg(URL.createObjectURL(f)); if (e.target) e.target.value = ''; };
  const [sidebar, setSidebar] = useState(false);
  const [confirm, setConfirm] = useState(false);
  const [speed, setSpeed] = useState(defaultSpeed);
  const [music, setMusic] = useState(true);
  const [vol, setVol] = useState(40);
  const [locked, setLocked] = useState(false);
  const [elapsed, setElapsed] = useState(214); // seconds
  const [queue, setQueue] = useState([{ name: 'Cô Hoa', color: '#9FAE8C' }, { name: 'Bác Tư', color: '#CDB48A' }]);
  const [live, setLive] = useState(null);
  const [fx, setFx] = useState(particle);
  const [bo, setBo] = useState(sessionType);
  const [invite, setInvite] = useState(false);
  const [clip, setClip] = useState(null);
  const [wb, setWb] = useState(false);
  const [pen, setPen] = useState('#A8413A');
  const [overlays, setOverlays] = useState([]);
  const [strokes, setStrokes] = useState([]);
  const [cohost, setCohost] = useState(null);
  const [vote, setVote] = useState(false);
  const toggleLayer = (id) => setOverlays(s => s.map(x => x.id === id ? { ...x, visible: !x.visible } : x));
  const commitOverlay = (name = 'Anh Dũng', col) => {
    setStrokes(cur => {
      if (!cur.length) return cur;
      setOverlays(o => [...o, { id: uid(), name, color: col || pen, strokes: cur, visible: true, n: o.length + 1 }]);
      return [];
    });
  };
  const cat = EMOJI_LIB[bo] ? bo : 'hop';
  const isWork = mode === 'work';
  const scrim = sessionType === 'gap-mat' ? '61,32,26' : '27,42,69';
  useEffect(() => setFx(particle), [particle]);
  useEffect(() => setBo(sessionType), [sessionType]);

  const grant = (i) => { const p = queue[i]; setLive(p); setQueue(q => q.filter((_, idx) => idx !== i)); };
  const discard = (i) => setQueue(q => q.filter((_, idx) => idx !== i));

  useEffect(() => setSpeed(defaultSpeed), [defaultSpeed]);
  useInterval(() => setElapsed(e => e + 1), 1000);
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');

  return (
    <div className="b1-screen">
      <InAppBrowserBanner />
      {/* full bg */}
      {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: isWork ? `linear-gradient(180deg, rgba(${scrim},.32) 0%, rgba(${scrim},.06) 30%, rgba(${scrim},.16) 70%, rgba(${scrim},.5) 100%)` : `linear-gradient(180deg, rgba(${scrim},.7) 0%, rgba(${scrim},.25) 30%, rgba(${scrim},.45) 70%, rgba(${scrim},.92) 100%)` }} />
      <input ref={bgFileRef} type="file" accept="image/*" onChange={onPickBg} style={{ display: 'none' }} />

      {/* engine layers — chế độ Họp tắt hết hiệu ứng xã giao */}
      {!isWork && <MoteLayer variant={fx} />}
      {wb && <DrawLayer active color={pen} overlays={overlays} liveStrokes={strokes} onChange={setStrokes} zIndex={3} />}
      {!isWork && <FlyingLayer ref={flyRef} autoEmojis={EMOJI_LIB[cat]} autoEvery={2400} zIndex={4} />}
      {!isWork && <DanmuLayer ref={danmuRef} speed={speed} zIndex={5} />}

      {/* thanh lớp nổi — lật lớp tức thì khi đang thuyết giảng (không cần mở sidebar) */}
      {wb && overlays.length > 0 && (
        <div style={{ position: 'absolute', left: 14, top: 168, zIndex: 18, display: 'flex', flexDirection: 'column', gap: 6, maxWidth: 168 }}>
          <div className="b1-mono" style={{ fontSize: 8, color: 'rgba(237,229,211,.6)', letterSpacing: '.14em', paddingLeft: 2 }}>LỚP GHI CHÚ</div>
          {overlays.map(o => (
            <button key={o.id} onClick={() => toggleLayer(o.id)} style={{
              display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', textAlign: 'left',
              padding: '7px 10px', borderRadius: 999, opacity: o.visible ? 1 : .5,
              background: 'var(--ink-glass)', backdropFilter: 'blur(10px)',
              border: '1px solid ' + (o.visible ? o.color : 'var(--ink-line)'),
            }}>
              <span style={{ width: 11, height: 11, borderRadius: '50%', background: o.color, flexShrink: 0, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.25)' }} />
              <span style={{ flex: 1, fontSize: 12, color: 'var(--cream)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{o.name}</span>
              <span style={{ flexShrink: 0, display: 'flex' }}>
                {o.visible
                  ? <svg width="14" height="14" viewBox="0 0 18 18" fill="none"><path d="M1.5 9S4.5 3.5 9 3.5 16.5 9 16.5 9 13.5 14.5 9 14.5 1.5 9 1.5 9Z" stroke="var(--cream)" strokeWidth="1.3"/><circle cx="9" cy="9" r="2.2" stroke="var(--cream)" strokeWidth="1.3"/></svg>
                  : <svg width="14" height="14" viewBox="0 0 18 18" fill="none"><path d="M3 3l12 12M1.5 9S4.5 3.5 9 3.5c1.3 0 2.5.5 3.5 1" stroke="rgba(200,192,174,.6)" strokeWidth="1.3" strokeLinecap="round"/></svg>}
              </span>
            </button>
          ))}
          {cohost && (
            <div className="b1-mono" style={{ fontSize: 8, color: 'var(--gold)', letterSpacing: '.06em', paddingLeft: 2, marginTop: 2 }}>+ {cohost} cùng lật được</div>
          )}
        </div>
      )}

      {/* 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>
        <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={() => setSidebar(true)} style={{
          width: 38, height: 38, borderRadius: '50%', cursor: 'pointer',
          background: 'var(--ink-glass)', backdropFilter: 'blur(10px)',
          border: '1px solid var(--ink-line)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Gear /></button>
      </div>

      {/* chế độ: Chat (xã giao) ↔ Họp (xem/góp ý bản vẽ, vẽ layer) · nút đổi ảnh nền luôn cạnh đó */}
      <div style={{ position: 'absolute', top: 96, left: 0, right: 0, zIndex: 20, display: 'flex', alignItems: 'center', gap: 10, padding: '0 18px' }}>
        <button onClick={() => bgFileRef.current?.click()} title={bg ? 'Đổi ảnh nền' : 'Tải ảnh nền'} style={{
          width: 34, height: 34, borderRadius: '50%', flexShrink: 0, cursor: 'pointer',
          background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', border: '1px solid var(--ink-line)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="15" height="15" viewBox="0 0 22 22" fill="none"><path d="M11 3v11m0-11L7 7m4-4l4 4" stroke="var(--gold)" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/><path d="M4 16v3h14v-3" stroke="var(--gold-dim)" strokeWidth="1.7" strokeLinecap="round"/></svg>
        </button>
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
          <div style={{ display: 'flex', gap: 2, padding: 3, background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', borderRadius: 999, border: '1px solid var(--ink-line)' }}>
            {[{ k: 'chat', l: 'Chat' }, { k: 'work', l: 'Họp' }].map(o => {
              const on = mode === o.k;
              return (
                <button key={o.k} onClick={() => setMode(o.k)} className="b1-mono" style={{
                  padding: '6px 14px', borderRadius: 999, cursor: 'pointer', border: 'none', fontSize: 10, letterSpacing: '.06em',
                  background: on ? 'var(--gold)' : 'transparent', color: on ? '#15100A' : 'var(--cream-dim)',
                  fontWeight: on ? 600 : 400, transition: 'all .15s ease',
                }}>{o.l}</button>
              );
            })}
          </div>
        </div>
        <div style={{ width: 34, flexShrink: 0 }} />
      </div>

      {/* title centerpiece — ẩn ở chế độ Họp để nhường tối đa diện tích cho bản vẽ */}
      {!isWork && (
        <div style={{ position: 'absolute', top: 140, left: 0, right: 0, textAlign: 'center', zIndex: 3, pointerEvents: 'none' }}>
          <div className="b1-eyebrow" style={{ color: 'var(--cream-dim)' }}>CHỦ TRÌ</div>
          <h1 className="b1-display" style={{ fontSize: 30, margin: '4px 0 0', color: 'var(--cream)', textShadow: '0 2px 14px rgba(0,0,0,.5)' }}>Lễ giỗ ông nội</h1>
        </div>
      )}

      {/* bottom controls */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 30, zIndex: 20, padding: '0 18px' }}>
        {isWork && <NotesList notes={notes} selfName="Anh Dũng" />}
        <DanmuCompose placeholder={isWork ? 'Ghi chú góp ý…' : undefined}
          onPublish={(t) => isWork ? setNotes(n => [...n, { a: 'Anh Dũng', t, color: '#C8A06A' }]) : (danmuRef.current && danmuRef.current.push({ a: 'Anh Dũng', t }))} />
        <VotePill onClick={() => setVote(true)} />
        {wb
          ? <PenBar pen={pen} setPen={setPen} liveCount={strokes.length} onUndo={() => setStrokes(s => s.slice(0, -1))} onCommit={() => commitOverlay()} />
          : isWork
            ? <button onClick={() => setWb(true)} className="b1-btn b1-btn-soft" style={{ width: '100%', gap: 9, marginBottom: 11 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--gold)', flexShrink: 0 }} />
                <span style={{ fontWeight: 500 }}>Bật bảng trắng để vẽ ghi chú</span>
              </button>
            : <SessionTray flyRef={flyRef} emojis={EMOJI_LIB[cat]} />}
        {clip && <VoiceClip clip={clip} onClose={() => setClip(null)} />}
        <PushToTalk
          onEnd={(c) => {
            setClip(c);
            if (wb) commitOverlay('Anh Dũng', pen); // hết lượt nói → chốt overlay
            const t = `đã gửi tin thoại · ${c.duration.toFixed(1)}s 🎙️`;
            if (isWork) setNotes(n => [...n, { a: 'Anh Dũng', t, color: '#C8A06A' }]);
            else danmuRef.current && danmuRef.current.push({ a: 'Anh Dũng', t });
          }} />
      </div>

      {/* dim scrim when sidebar open */}
      {sidebar && <div onClick={() => setSidebar(false)} style={{ position: 'absolute', inset: 0, zIndex: 40, background: 'rgba(13,19,31,.5)' }} />}

      {/* right sidebar */}
      <div style={{
        position: 'absolute', top: 0, bottom: 0, right: 0, width: 'min(296px, 86%)', zIndex: 50,
        background: 'var(--ink-soft)', borderLeft: '1px solid var(--ink-line)',
        boxShadow: '-20px 0 50px -20px rgba(0,0,0,.6)',
        transform: sidebar ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform .26s cubic-bezier(.2,.8,.2,1)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '58px 20px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <span className="b1-display" style={{ fontSize: 22, color: 'var(--cream)', whiteSpace: 'nowrap' }}>Điều khiển phiên</span>
          <button onClick={() => setSidebar(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--cream-dim)', fontSize: 22, lineHeight: 1, flexShrink: 0 }}>×</button>
        </div>
        <div className="b1-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 20px 20px' }}>
          {/* participants */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span className="b1-label">NGƯỜI THAM GIA · 6</span>
            <button onClick={() => setInvite(true)} className="b1-mono" style={{
              display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer', padding: '5px 10px', borderRadius: 999,
              background: 'rgba(184,153,104,.12)', border: '1px solid var(--gold-dim)', color: 'var(--gold)', fontSize: 10, letterSpacing: '.04em',
            }}>
              <svg width="11" height="11" viewBox="0 0 12 12"><path d="M6 2.5v7M2.5 6h7" stroke="var(--gold)" strokeWidth="1.5" strokeLinecap="round"/></svg>
              CHIA SẺ LINK
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginBottom: 22 }}>
            {HOST_PARTICIPANTS.map((p, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0' }}>
                <div style={{ position: 'relative' }}>
                  <Avatar name={p.name} color={p.color} size={30} ring={p.host} />
                  {p.speaking && <span style={{ position: 'absolute', inset: -3, borderRadius: '50%', border: '1.5px solid var(--gold)', animation: 'b1-glow 1.4s ease-out infinite' }} />}
                </div>
                <span style={{ flex: 1, fontSize: 13.5, color: 'var(--cream)' }}>
                  {p.name}
                  {p.host && <span className="b1-mono" style={{ fontSize: 9, color: 'var(--gold)', marginLeft: 7 }}>CHỦ TRÌ</span>}
                  {!p.host && cohost === p.name && <span className="b1-mono" style={{ fontSize: 9, color: 'var(--vermilion)', marginLeft: 7 }}>ĐỒNG CHỦ TRÌ</span>}
                </span>
                {!p.host && (
                  <button onClick={() => setCohost(c => c === p.name ? null : p.name)}
                    title={cohost === p.name ? 'Thu quyền' : 'Trao quyền lật lớp'} style={{
                    background: 'none', border: '1px solid ' + (cohost === p.name ? 'var(--vermilion)' : 'var(--ink-line)'),
                    cursor: 'pointer', borderRadius: 6, padding: '4px 7px', marginRight: 4, flexShrink: 0,
                    fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '.04em',
                    color: cohost === p.name ? 'var(--vermilion)' : 'var(--cream-dim)',
                  }}>{cohost === p.name ? 'THU' : 'TRAO'}</button>
                )}
                <MicBars active={p.mic} />
              </div>
            ))}
          </div>

          {/* speak queue */}
          <div className="b1-label" style={{ marginBottom: 10 }}>HÀNG CHỜ NÓI · {queue.length}</div>
          {live && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 11px', marginBottom: 8, borderRadius: 'var(--r-sm)', background: 'rgba(168,65,58,.14)', border: '1px solid rgba(168,65,58,.4)' }}>
              <Avatar name={live.name} color={live.color} size={28} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: 'var(--cream)' }}>{live.name}</div>
                <div className="b1-mono" style={{ fontSize: 9, color: 'var(--vermilion)', letterSpacing: '.06em' }}>● ĐANG NÓI · MIC MỞ</div>
              </div>
              <MicBars active color="var(--vermilion)" />
              <button onClick={() => setLive(null)} className="b1-mono" style={{ fontSize: 9, cursor: 'pointer', border: '1px solid var(--ink-line)', background: 'none', color: 'var(--cream-dim)', borderRadius: 4, padding: '5px 7px' }}>KẾT THÚC</button>
            </div>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginBottom: 8 }}>
            {queue.length === 0 && !live && <div className="b1-mono" style={{ fontSize: 10, color: 'rgba(200,192,174,.45)', padding: '4px 0' }}>Chưa ai xin nói</div>}
            {queue.map((p, i) => (
              <div key={p.name} onClick={() => grant(i)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', cursor: 'pointer', borderRadius: 'var(--r-sm)', background: i === 0 ? 'rgba(184,153,104,.08)' : 'transparent', border: '1px solid ' + (i === 0 ? 'rgba(184,153,104,.3)' : 'transparent') }}>
                <div style={{ position: 'relative' }}>
                  <Avatar name={p.name} color={p.color} size={28} />
                  {i === 0 && <span style={{ position: 'absolute', inset: -3, borderRadius: '50%', border: '1.5px solid var(--gold)', animation: 'b1-blink 1.3s ease-in-out infinite' }} />}
                </div>
                <span style={{ flex: 1, fontSize: 13, color: 'var(--cream)' }}>{p.name}</span>
                {i === 0 && <span className="b1-mono" style={{ fontSize: 8.5, color: 'var(--gold)', letterSpacing: '.06em', animation: 'b1-blink 1.3s ease-in-out infinite' }}>CHẠM ĐỂ MỞ MIC</span>}
                <button onClick={(e) => { e.stopPropagation(); discard(i); }} title="Bỏ qua" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--cream-dim)', fontSize: 16, lineHeight: 1, padding: '0 2px' }}>×</button>
              </div>
            ))}
          </div>
          <p className="b1-mono" style={{ fontSize: 8.5, color: 'rgba(200,192,174,.4)', margin: '0 0 22px', lineHeight: 1.6 }}>Chạm thẳng vào tên để mở mic cho người đó · một người nói, cả nhà nghe</p>

          {/* audio */}
          <div className="b1-label" style={{ marginBottom: 12 }}>ÂM THANH</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 13 }}>
            <div>
              <div style={{ fontSize: 13.5, color: 'var(--cream)' }}>Nhạc nền</div>
              <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--gold)', marginTop: 2 }}>Hương trầm · 4:32</div>
            </div>
            <B1Toggle on={music} onChange={setMusic} />
          </div>
          <div style={{ opacity: music ? 1 : .4, transition: 'opacity .2s', marginBottom: 22, pointerEvents: music ? 'auto' : 'none' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 9 }}>
              <span className="b1-mono" style={{ fontSize: 10, color: 'var(--cream-dim)' }}>ÂM LƯỢNG</span>
              <span className="b1-mono" style={{ fontSize: 10, color: 'var(--gold)' }}>{vol}%</span>
            </div>
            <B1Range value={vol} onChange={setVol} />
          </div>

          {/* bảng trắng — host bật/tắt · nét cố định · mỗi lượt nói = 1 lớp */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
            <div>
              <div style={{ fontSize: 13.5, color: 'var(--cream)' }}>Bảng trắng</div>
              <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', marginTop: 2 }}>{wb ? 'Vẽ lên ảnh nền · nét cố định' : 'Tắt · ảnh nền sạch'}</div>
            </div>
            <B1Toggle on={wb} onChange={(v) => { setWb(v); if (v) setMode('work'); }} />
          </div>
          {wb && (
            <div style={{ marginBottom: 8 }}>
              {(overlays.length === 0 && strokes.length === 0) && <div className="b1-mono" style={{ fontSize: 10, color: 'rgba(200,192,174,.45)', padding: '4px 0' }}>Chưa có lớp ghi chú nào</div>}
              {strokes.length > 0 && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '7px 9px', borderRadius: 'var(--r-sm)', background: 'rgba(184,153,104,.08)', border: '1px dashed var(--gold-dim)', marginBottom: 4 }}>
                  <span style={{ width: 12, height: 12, borderRadius: '50%', background: pen, flexShrink: 0, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.25)' }} />
                  <span style={{ flex: 1, fontSize: 12.5, color: 'var(--cream)' }}>Đang vẽ… <span className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)' }}>{strokes.length} nét</span></span>
                  <button onClick={() => commitOverlay()} className="b1-mono" style={{ fontSize: 9, cursor: 'pointer', border: 'none', background: 'var(--gold)', color: '#15100A', borderRadius: 5, padding: '5px 8px', fontWeight: 600 }}>CHỐT LỚP</button>
                </div>
              )}
              {overlays.map(o => (
                <div key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '7px 9px', borderRadius: 'var(--r-sm)', opacity: o.visible ? 1 : .5 }}>
                  <span style={{ width: 12, height: 12, borderRadius: '50%', background: o.color, flexShrink: 0, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.25)' }} />
                  <span style={{ flex: 1, fontSize: 12.5, color: 'var(--cream)' }}>{o.name} <span className="b1-mono" style={{ fontSize: 9, color: 'var(--gold)' }}>LỚP {o.n}</span></span>
                  <button onClick={() => setOverlays(s => s.map(x => x.id === o.id ? { ...x, visible: !x.visible } : x))} title={o.visible ? 'Ẩn lớp' : 'Hiện lớp'} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 2, display: 'flex' }}>                    {o.visible
                      ? <svg width="16" height="16" viewBox="0 0 18 18" fill="none"><path d="M1.5 9S4.5 3.5 9 3.5 16.5 9 16.5 9 13.5 14.5 9 14.5 1.5 9 1.5 9Z" stroke="var(--cream-dim)" strokeWidth="1.3"/><circle cx="9" cy="9" r="2.2" stroke="var(--cream-dim)" strokeWidth="1.3"/></svg>
                      : <svg width="16" height="16" viewBox="0 0 18 18" fill="none"><path d="M1.5 9S4.5 3.5 9 3.5c1.3 0 2.5.5 3.5 1M16.5 9S13.5 14.5 9 14.5c-1.3 0-2.5-.5-3.5-1M3 3l12 12" stroke="rgba(200,192,174,.5)" strokeWidth="1.3" strokeLinecap="round"/></svg>}
                  </button>
                  <button onClick={() => setOverlays(s => s.filter(x => x.id !== o.id))} title="Xoá lớp" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--cream-dim)', fontSize: 16, lineHeight: 1, padding: '0 2px' }}>×</button>
                </div>
              ))}
            </div>
          )}
          <p className="b1-mono" style={{ fontSize: 8.5, color: 'rgba(200,192,174,.4)', margin: '0 0 22px', lineHeight: 1.6 }}>{wb ? 'Ai tới lượt nói thì vẽ được · hết lượt → nét đông thành 1 lớp' : 'Bật để vẽ ghi chú lên ảnh nền'}</p>

          {/* ảnh nền — host đổi bất cứ lúc nào, không phụ thuộc chế độ */}
          <div className="b1-label" style={{ marginBottom: 12 }}>ẢNH NỀN</div>
          <button onClick={() => bgFileRef.current?.click()} className="b1-btn b1-btn-soft" style={{ width: '100%', gap: 10, marginBottom: 22 }}>
            <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={{ flex: 1, textAlign: 'left', fontSize: 13.5 }}>{bg ? 'Đổi ảnh nền' : 'Tải ảnh nền'}</span>
            <span className="b1-mono" style={{ fontSize: 9, color: 'var(--cream-dim)' }}>JPG · PNG · WEBP</span>
          </button>

          {isWork && <p className="b1-mono" style={{ fontSize: 8.5, color: 'var(--gold-dim)', margin: '0 0 14px', lineHeight: 1.6 }}>ĐANG Ở CHẾ ĐỘ HỌP · các mục dưới chỉ phát khi chuyển lại Chat</p>}
          <div style={{ opacity: isWork ? .4 : 1, pointerEvents: isWork ? 'none' : 'auto', transition: 'opacity .2s' }}>
          {/* bộ vật phẩm — host đổi giữa phiên */}
          <div className="b1-label" style={{ marginBottom: 12 }}>BỘ VẬT PHẨM</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 22 }}>
            {Object.keys(EMOJI_LIB).map(k => (
              <button key={k} onClick={() => setBo(k)} className={'b1-chip' + (bo === k ? ' is-on' : '')}>{TYPE_LABEL[k] || k}</button>
            ))}
          </div>

          {/* hiệu ứng nền — host chọn */}
          <div className="b1-label" style={{ marginBottom: 12 }}>HIỆU ỨNG NỀN</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 22 }}>
            {['Tắt', 'Bụi trầm', 'Tuyết', 'Mưa', 'Khói hương', 'Cánh hoa'].map(k => (
              <button key={k} onClick={() => setFx(k)} className={'b1-chip' + (fx === k ? ' is-on' : '')}>{k}</button>
            ))}
          </div>

          {/* bình luận */}
          <div className="b1-label" style={{ marginBottom: 12 }}>BÌNH LUẬN BAY</div>
          <div style={{ marginBottom: 22 }}>
            <B1Segment small options={[{k:'tắt',label:'Tắt'},{k:'chậm',label:'Chậm'},{k:'vừa',label:'Vừa'},{k:'nhanh',label:'Nhanh'}]}
                       value={speed} onChange={setSpeed} />
          </div>
          </div>

          {/* permission */}
          <div className="b1-label" style={{ marginBottom: 12 }}>QUYỀN</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
            <div>
              <div style={{ fontSize: 13.5, color: 'var(--cream)' }}>Khóa lối vào</div>
              <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', marginTop: 2 }}>{locked ? 'Khách mới không vào được' : 'Đang nhận khách mới'}</div>
            </div>
            <B1Toggle on={locked} onChange={setLocked} accent="var(--moss)" />
          </div>
        </div>
        {/* end session */}
        <div style={{ padding: '14px 20px 24px', borderTop: '1px solid var(--ink-line)' }}>
          <button className="b1-btn b1-btn-vermilion" style={{ width: '100%' }} onClick={() => setConfirm(true)}>
            Kết thúc phiên
          </button>
        </div>
      </div>

      <ConfirmDialog open={confirm}
        title="Kết thúc phiên?"
        body="Mọi người sẽ rời phiên. Bạn có thể lưu lại thành capsule để xem lại sau."
        confirmLabel="Kết thúc & lưu lại"
        cancelLabel="Tiếp tục phiên"
        onCancel={() => setConfirm(false)}
        onConfirm={() => { setConfirm(false); setSidebar(false); onEnd && onEnd(); }} />

      <InviteSheet open={invite} onClose={() => setInvite(false)} />
      {vote && <VoteSheet mode="host" onClose={() => setVote(false)} />}
    </div>
  );
}

/* ---- chia sẻ phiên: Web Share API native + copy link fallback + Zalo trực tiếp ---- */
function InviteSheet({ open, onClose, variant = 'invite' }) {
  const isCapsule = variant === 'capsule';
  const url = isCapsule ? 'https://b1b.vercel.app/?mode=capsule&id=lgxn0613' : 'https://b1b.vercel.app/?mode=member';
  const text = isCapsule ? 'Anh Dũng chia sẻ capsule “Lễ giỗ ông nội” trên B1' : 'Anh Dũng mời bạn vào phiên “Lễ giỗ ông nội” trên B1';
  const [copied, setCopied] = useState(false);
  const [shared, setShared] = useState(false);
  useEffect(() => { if (open) { setCopied(false); setShared(false); } }, [open]);
  if (!open) return null;
  const canShare = typeof navigator !== 'undefined' && !!navigator.share;
  const share = async () => {
    if (canShare) {
      try {
        await navigator.share({ title: isCapsule ? 'B1 · Capsule' : 'B1 · Lễ giỗ ông nội', text, url });
        setShared(true);
      } catch (_) {}
    } else {
      copy();
    }
  };
  const copy = async () => {
    try { await navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 1800); } catch (_) {}
  };
  const openZalo = () => window.open('https://zalo.me/share?u=' + encodeURIComponent(url) + '&d=' + encodeURIComponent(text), '_blank');
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 90, background: 'rgba(13,19,31,.72)', 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">{isCapsule ? 'Chia sẻ capsule' : 'Mời vào phiên'}</div>
        <h3 className="b1-display" style={{ fontSize: 25, margin: '6px 0 3px', color: 'var(--cream)' }}>{isCapsule ? 'Gửi link xem lại' : 'Chia sẻ đường dẫn phiên'}</h3>
        <p className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', margin: '0 0 16px', letterSpacing: '.04em' }}>{isCapsule ? 'CHỈ NGƯỜI CÓ LINK MỚI XEM ĐƯỢC · RIÊNG TƯ' : 'AI CÓ LINK ĐỀU VÀO ĐƯỢC · PHIÊN KHÓA ĐỂ HẠN LẠI'}</p>

        {/* url card */}
        <div onClick={copy} style={{
          display: 'flex', alignItems: 'center', gap: 11, padding: '12px 14px', cursor: 'pointer',
          borderRadius: 'var(--r-md)', background: 'var(--ink)', border: '1px solid var(--ink-line)', marginBottom: 14,
        }}>
          <svg width="18" height="18" viewBox="0 0 20 20" fill="none" style={{ flexShrink: 0 }}><path d="M8.5 11.5l-2 2a3 3 0 1 1-4.3-4.3l2.3-2.3a3 3 0 0 1 4.3 0M11.5 8.5l2-2a3 3 0 1 1 4.3 4.3l-2.3 2.3a3 3 0 0 1-4.3 0M7.5 12.5l5-5" stroke="var(--gold)" strokeWidth="1.4" strokeLinecap="round"/></svg>
          <span style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--cream)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{url}</span>
          <span className="b1-mono" style={{ flexShrink: 0, fontSize: 9, color: copied ? 'var(--moss)' : 'var(--gold)', letterSpacing: '.06em' }}>{copied ? 'ĐÃ CHÉP ✓' : 'CHÉP'}</span>
        </div>

        {/* primary: native share — user tự chọn Zalo / SMS / Messenger / Copy */}
        <button onClick={share} className="b1-btn b1-btn-primary" style={{ width: '100%', padding: '15px', justifyContent: 'space-between' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <svg width="16" height="16" viewBox="0 0 18 18" fill="none"><circle cx="4.5" cy="9" r="2" stroke="#15100A" strokeWidth="1.5"/><circle cx="13.5" cy="4" r="2" stroke="#15100A" strokeWidth="1.5"/><circle cx="13.5" cy="14" r="2" stroke="#15100A" strokeWidth="1.5"/><path d="M6.3 8l5.4-3M6.3 10l5.4 3" stroke="#15100A" strokeWidth="1.5"/></svg>
            <span style={{ fontWeight: 600 }}>{shared ? 'Đã chia sẻ ✓' : 'Chia sẻ phiên'}</span>
          </span>
          <span className="b1-mono" style={{ fontSize: 9, opacity: .65, letterSpacing: '.06em' }}>{canShare ? 'ZALO · SMS · MESS · …' : 'CHÉP LINK'}</span>
        </button>
        <button onClick={openZalo} className="b1-btn b1-btn-soft" style={{ width: '100%', marginTop: 10, padding: '13px 15px', justifyContent: 'center', gap: 9 }}>
          <svg width="15" height="15" viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="6" fill="#0068FF"/><text x="12" y="16" textAnchor="middle" fontSize="10" fontWeight="700" fill="#fff" fontFamily="sans-serif">Za</text></svg>
          <span style={{ fontSize: 13.5, fontWeight: 500 }}>Gửi thẳng qua Zalo</span>
        </button>
        <p className="b1-mono" style={{ fontSize: 9, color: 'rgba(200,192,174,.45)', textAlign: 'center', marginTop: 12, lineHeight: 1.6 }}>
          {isCapsule ? 'Người xem không cần cài app' : 'Ông chọn nơi gửi ở bước sau · B1 không đọc danh bạ'}
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { HostScreen, InviteSheet });
