/* ============================================================
   B1 — Biểu quyết (vote / xác nhận việc chung)
   Host mở câu hỏi → mọi người bỏ phiếu Đồng ý / Chưa →
   kiểm phiếu trực tiếp → host chốt kết quả.
   Prototype 1 máy: phiếu người khác trickle vào giả lập.
   ============================================================ */
const VOTE_PRESETS = ['Đồng ý hướng này?', 'Chốt phương án này?', 'Chọn ngày này?', 'Đồng ý mức giá?'];
const VOTE_TOTAL = 6;

function TallyBar({ yes, no, total }) {
  const yp = (yes / total) * 100, np = (no / total) * 100;
  return (
    <div style={{ display: 'flex', height: 10, borderRadius: 999, overflow: 'hidden', background: 'var(--ink)', border: '1px solid var(--ink-line)' }}>
      <span style={{ width: yp + '%', background: 'var(--moss)', transition: 'width .4s ease' }} />
      <span style={{ width: np + '%', background: 'var(--vermilion)', transition: 'width .4s ease' }} />
    </div>
  );
}

function VoteSheet({ mode = 'host', presetQuestion, onClose }) {
  const [q, setQ] = useState(presetQuestion || '');
  const [phase, setPhase] = useState(mode === 'host' ? 'raise' : 'vote'); // raise | vote | live | done
  const [yes, setYes] = useState(0);
  const [no, setNo] = useState(0);
  const [mine, setMine] = useState(null);
  const voted = yes + no;
  const votedRef = useRef(0); votedRef.current = voted;

  // phiếu người khác trickle vào (giả lập)
  useInterval(() => {
    if (votedRef.current >= VOTE_TOTAL) return;
    if (Math.random() < 0.72) setYes(v => v + 1); else setNo(v => v + 1);
  }, phase === 'live' && voted < VOTE_TOTAL ? 800 : null);

  useEffect(() => { if (phase === 'live' && voted >= VOTE_TOTAL) setPhase('done'); }, [phase, voted]);

  const castMine = (v) => {
    setMine(v);
    if (v === 'yes') setYes(1); else setNo(1);
    setPhase('live');
  };
  const raise = () => { if (!q.trim()) return; setYes(0); setNo(0); setPhase('live'); };

  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 92, 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' }} />

        {/* HOST · soạn câu hỏi */}
        {phase === 'raise' && (
          <>
            <div className="b1-eyebrow">Biểu quyết</div>
            <h3 className="b1-display" style={{ fontSize: 25, margin: '6px 0 14px', color: 'var(--cream)' }}>Mở một biểu quyết</h3>
            <input className="b1-input" value={q} onChange={e => setQ(e.target.value)} placeholder="Câu hỏi cho cả phiên…" style={{ marginBottom: 12 }} />
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 18 }}>
              {VOTE_PRESETS.map(p => (
                <button key={p} onClick={() => setQ(p)} className={'b1-chip' + (q === p ? ' is-on' : '')}>{p}</button>
              ))}
            </div>
            <button className="b1-btn b1-btn-primary" style={{ width: '100%' }} disabled={!q.trim()} onClick={raise}>Mở biểu quyết</button>
          </>
        )}

        {/* PARTICIPANT · bỏ phiếu */}
        {phase === 'vote' && (
          <>
            <div className="b1-eyebrow">Chủ trì mở biểu quyết</div>
            <h3 className="b1-display" style={{ fontSize: 27, margin: '7px 0 18px', color: 'var(--cream)', lineHeight: 1.1 }}>{presetQuestion || 'Đồng ý hướng này?'}</h3>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="b1-btn" style={{ flex: 1, padding: '16px', background: 'var(--moss)', color: '#F2F4EE', border: 'none' }} onClick={() => castMine('yes')}>
                <svg width="17" height="17" viewBox="0 0 18 18" fill="none"><path d="M4 9.5l3.5 3.5L14 6" stroke="#F2F4EE" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Đồng ý
              </button>
              <button className="b1-btn b1-btn-ghost" style={{ flex: 1, padding: '16px' }} onClick={() => castMine('no')}>Chưa</button>
            </div>
          </>
        )}

        {/* live tally + done */}
        {(phase === 'live' || phase === 'done') && (
          <>
            <div className="b1-eyebrow" style={{ color: phase === 'done' ? 'var(--moss)' : 'var(--gold)' }}>{phase === 'done' ? 'Kết quả' : 'Đang kiểm phiếu'}</div>
            <h3 className="b1-display" style={{ fontSize: 24, margin: '6px 0 16px', color: 'var(--cream)', lineHeight: 1.12 }}>{presetQuestion || q || 'Đồng ý hướng này?'}</h3>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 9 }}>
              <span><span className="b1-display" style={{ fontSize: 34, color: 'var(--moss)' }}>{yes}</span><span className="b1-mono" style={{ fontSize: 11, color: 'var(--cream-dim)' }}> / {VOTE_TOTAL} đồng ý</span></span>
              {no > 0 && <span className="b1-mono" style={{ fontSize: 11, color: 'var(--vermilion)' }}>{no} chưa</span>}
              {voted < VOTE_TOTAL && <span className="b1-mono" style={{ fontSize: 10, color: 'rgba(200,192,174,.5)' }}>{VOTE_TOTAL - voted} chưa bỏ</span>}
            </div>
            <TallyBar yes={yes} no={no} total={VOTE_TOTAL} />
            {mine && <p className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', marginTop: 10 }}>Bạn đã chọn · {mine === 'yes' ? 'Đồng ý' : 'Chưa'}</p>}
            {phase === 'done'
              ? <button className="b1-btn b1-btn-primary" style={{ width: '100%', marginTop: 18 }} onClick={onClose}>{mode === 'host' ? `Chốt · ${yes}/${VOTE_TOTAL} đồng ý` : 'Xong'}</button>
              : mode === 'host'
                ? <button className="b1-btn b1-btn-soft" style={{ width: '100%', marginTop: 18 }} onClick={() => setPhase('done')}>Chốt kết quả sớm</button>
                : <p className="b1-mono" style={{ fontSize: 9.5, color: 'rgba(200,192,174,.45)', textAlign: 'center', marginTop: 16 }}>Đang chờ mọi người bỏ phiếu…</p>}
          </>
        )}
      </div>
    </div>
  );
}

/* ---- pill mở biểu quyết (đặt trong cụm nút) ---- */
function VotePill({ label = 'Biểu quyết', live = false, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, width: '100%', cursor: 'pointer',
      padding: '11px', marginBottom: 11, borderRadius: 12,
      background: 'var(--ink-glass)', backdropFilter: 'blur(10px)', border: '1px solid var(--gold-dim)',
    }}>
      {live && <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--gold)', animation: 'b1-blink 1.2s ease-in-out infinite' }} />}
      <svg width="15" height="15" viewBox="0 0 18 18" fill="none"><path d="M4 9.5l3 3L14 6" stroke="var(--gold)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 500, color: 'var(--cream)' }}>{label}</span>
    </button>
  );
}

Object.assign(window, { VoteSheet, VotePill, VOTE_PRESETS });
