/* ============================================================
   B1 — Màn "Vào phiên" (Join)
   Hero ảnh nền blurred + host info + counter + input + CTA.
   Edge states: mở · đã kết thúc · đã khóa.
   ============================================================ */
function Avatar({ name, color, size = 30, ring = false }) {
  const initial = name.trim().split(' ').pop()[0];
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: color, color: '#1B2420',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: size * 0.4,
      boxShadow: ring ? '0 0 0 2px var(--ink), 0 0 0 3px var(--gold-dim)' : '0 0 0 2px var(--ink)',
    }}>{initial}</div>
  );
}

const WAITING = [
  { name: 'Cô Hoa', color: '#C8A06A' },
  { name: 'Bác Tư', color: '#9FAE8C' },
  { name: 'Chị Lan', color: '#CDB48A' },
  { name: 'Em Minh', color: '#B49B86' },
  { name: 'Ông Bảy', color: '#A8B59A' },
];

function JoinScreen({ onEnter, onReview }) {
  const [state, setState] = useState('open'); // open | ended | locked
  const [name, setName] = useState('');
  const [auth, setAuth] = useState(false); // đã dùng Zalo Login lấy tên
  const [left, setLeft] = useState(118);
  useInterval(() => setLeft(s => (s > 0 ? s - 1 : 0)), state === 'open' ? 1000 : null);
  const cmm = String(Math.floor(left / 60)).padStart(2, '0');
  const css = String(left % 60).padStart(2, '0');
  const states = [
    { k: 'open', label: 'Mở' },
    { k: 'ended', label: 'Đã kết thúc' },
    { k: 'locked', label: 'Đã khóa' },
  ];

  return (
    <div className="b1-screen b1-scroll">
      {/* demo state switcher */}
      <div style={{
        position: 'absolute', top: 52, left: 0, right: 0, zIndex: 30,
        display: 'flex', justifyContent: 'center', pointerEvents: 'none',
      }}>
        <div style={{
          display: 'flex', gap: 2, padding: 3, borderRadius: 999,
          background: 'rgba(21,30,48,.6)', backdropFilter: 'blur(10px)',
          border: '1px solid var(--ink-line)', pointerEvents: 'auto',
        }}>
          {states.map(s => (
            <button key={s.k} onClick={() => setState(s.k)} className="b1-mono" style={{
              border: 'none', cursor: 'pointer', borderRadius: 999, padding: '5px 11px',
              fontSize: 9.5, letterSpacing: '.1em',
              background: state === s.k ? 'var(--gold)' : 'transparent',
              color: state === s.k ? '#1B1408' : 'var(--cream-dim)',
            }}>{s.label}</button>
          ))}
        </div>
      </div>

      {/* hero — blurred uploaded background */}
      <div style={{ position: 'relative', height: 372 }}>
        <StripedImg label="ẢNH NỀN · LA KINH PHONG THỦY" style={{
          position: 'absolute', inset: 0, filter: 'blur(3px)', transform: 'scale(1.06)',
        }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(27,42,69,.35) 0%, rgba(27,42,69,.1) 38%, rgba(27,42,69,.86) 82%, var(--ink) 100%)',
        }} />
        {/* signature seal floating on hero */}
        <div style={{ position: 'absolute', top: 92, left: 26, display: 'flex', alignItems: 'center', gap: 13 }}>
          <B1Wordmark size={44} title="Be One" />
          <div>
            <div className="b1-eyebrow" style={{ color: 'var(--cream-dim)' }}>B1</div>
            <div className="b1-mono" style={{ fontSize: 10.5, color: 'var(--cream-dim)', marginTop: 3 }}>
              {state === 'open' ? 'phiên đang mở' : state === 'ended' ? 'phiên đã đóng' : 'phiên đã khóa'}
            </div>
          </div>
        </div>
      </div>

      {/* body */}
      <div style={{ padding: '0 26px 40px', marginTop: -38, position: 'relative', zIndex: 5 }}>
        {/* chuông báo app — người đã cài app nhận thông báo + đếm ngược */}
        {state === 'open' && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 11, marginBottom: 18,
            padding: '11px 14px', borderRadius: 'var(--r-md)',
            background: 'rgba(184,153,104,.1)', border: '1px solid var(--gold-dim)',
          }}>
            <span style={{ position: 'relative', display: 'flex', flexShrink: 0 }}>
              <svg width="17" height="17" viewBox="0 0 18 18" fill="none"><path d="M9 2.2a4.4 4.4 0 0 0-4.4 4.4c0 4-1.6 5.2-1.6 5.2h12s-1.6-1.2-1.6-5.2A4.4 4.4 0 0 0 9 2.2ZM7.3 14.4a1.8 1.8 0 0 0 3.4 0" stroke="var(--gold)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <span style={{ position: 'absolute', top: -1, right: -1, width: 6, height: 6, borderRadius: '50%', background: 'var(--vermilion)', animation: 'b1-blink 1.3s ease-in-out infinite' }} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, color: 'var(--cream)' }}>B1 nhắc bạn · <b style={{ fontWeight: 600 }}>Anh Dũng</b> sắp mở phiên</div>
              <div className="b1-mono" style={{ fontSize: 9, color: 'var(--cream-dim)', letterSpacing: '.06em', marginTop: 2 }}>NHẮC LỊCH · PWA ĐÃ CÀI</div>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0 }}>
              <div className="b1-display" style={{ fontSize: 22, lineHeight: 1, color: 'var(--gold)' }}>{left > 0 ? `${cmm}:${css}` : 'LIVE'}</div>
              <div className="b1-mono" style={{ fontSize: 8, color: 'var(--cream-dim)', letterSpacing: '.1em', marginTop: 2 }}>{left > 0 ? 'CÒN LẠI' : 'ĐANG MỞ'}</div>
            </div>
          </div>
        )}
        <div className="b1-eyebrow">Mời bạn vào phiên</div>
        <h1 className="b1-display" style={{ fontSize: 40, margin: '7px 0 0', color: 'var(--cream)' }}>
          Lễ giỗ ông nội
        </h1>
        <div className="b1-mono" style={{ fontSize: 11, color: 'var(--cream-dim)', marginTop: 9 }}>
          CHỦ NHẬT · 13.06 · 19:00
        </div>

        {/* host + counter */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, marginTop: 22,
          padding: '14px 16px', background: 'var(--ink-soft)', borderRadius: 'var(--r-md)',
          border: '1px solid var(--ink-line)',
        }}>
          <Avatar name="Anh Dũng" color="#C8A06A" size={40} ring />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--cream)' }}>Anh Dũng</div>
            <div className="b1-label" style={{ marginTop: 2 }}>Chủ trì phiên</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ display: 'flex', marginBottom: 4, justifyContent: 'flex-end' }}>
              {WAITING.slice(0, 4).map((p, i) => (
                <div key={i} style={{ marginLeft: i ? -9 : 0 }}><Avatar name={p.name} color={p.color} size={24} /></div>
              ))}
            </div>
            <div className="b1-label" style={{ color: 'var(--gold)' }}>
              {state === 'ended' ? '6 người đã dự' : '6 người đang trong phiên'}
            </div>
          </div>
        </div>

        {/* state-specific footer */}
        {state === 'open' && (
          <div style={{ marginTop: 22 }}>
            <label className="b1-label" style={{ display: 'block', marginBottom: 8 }}>Tên hiển thị trong phiên</label>
            {auth ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 'var(--r-md)', background: 'var(--ink-soft)', border: '1px solid var(--ink-line)' }}>
                <Avatar name={name} color="#B49B86" size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--cream)' }}>{name}</div>
                  <div className="b1-mono" style={{ fontSize: 9, color: 'var(--moss)', letterSpacing: '.06em', marginTop: 2 }}>● LẤY TỪ ZALO LOGIN</div>
                </div>
                <button onClick={() => { setAuth(false); setName(''); }} className="b1-mono" style={{ flexShrink: 0, fontSize: 9.5, cursor: 'pointer', background: 'none', border: '1px solid var(--ink-line)', color: 'var(--cream-dim)', borderRadius: 6, padding: '6px 10px' }}>BỌF</button>
              </div>
            ) : (
              <>
                <input className="b1-input" value={name} onChange={e => setName(e.target.value)} placeholder="Ví dụ: Minh" />
                <button onClick={() => { setAuth(true); setName(name.trim() || 'Minh Nguyễn'); }} className="b1-btn b1-btn-soft" style={{ width: '100%', marginTop: 8, padding: '12px', gap: 8 }}>
                  <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="6" r="2.6" stroke="var(--gold)" strokeWidth="1.4"/><path d="M3 13.5c.6-2.4 2.6-3.8 5-3.8s4.4 1.4 5 3.8" stroke="var(--gold)" strokeWidth="1.4" strokeLinecap="round"/></svg>
                  <span style={{ fontSize: 13, color: 'var(--cream)' }}>Hoặc lấy tên từ Zalo</span>
                  <span className="b1-mono" style={{ fontSize: 8.5, color: 'var(--cream-dim)', letterSpacing: '.06em' }}>· KHÔNG BẮT BUỘC</span>
                </button>
              </>
            )}
            <button className="b1-btn b1-btn-primary" style={{ width: '100%', marginTop: 14, padding: '17px' }}
                    disabled={!name.trim()} onClick={onEnter}>
              Tham gia
              <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3 8h9m0 0L8.5 4.5M12 8l-3.5 3.5" stroke="#15100A" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <p className="b1-mono" style={{ fontSize: 10, color: 'rgba(200,192,174,.5)', textAlign: 'center', marginTop: 12, lineHeight: 1.6 }}>
              Phiên kín · chỉ ai có link của host mới vào được
            </p>
          </div>
        )}

        {state === 'ended' && (
          <div style={{ marginTop: 22 }}>
            <div style={{
              padding: '13px 16px', borderRadius: 'var(--r-md)', marginBottom: 14,
              background: 'rgba(92,110,84,.12)', border: '1px solid rgba(92,110,84,.3)',
              display: 'flex', alignItems: 'center', gap: 11,
            }}>
              <span style={{ fontSize: 16 }}>🪷</span>
              <span style={{ fontSize: 13, color: 'var(--cream-dim)' }}>
                Phiên đã kết thúc lúc <b style={{ color: 'var(--cream)' }}>21:40</b> · đã lưu capsule
              </span>
            </div>
            <button className="b1-btn b1-btn-primary" style={{ width: '100%', padding: '17px' }} onClick={onReview}>
              Xem lại capsule
              <svg width="16" height="16" viewBox="0 0 16 16"><path d="M5 3.5l7 4.5-7 4.5z" fill="#1B1408"/></svg>
            </button>
          </div>
        )}

        {state === 'locked' && (
          <div style={{ marginTop: 22 }}>
            <button className="b1-btn b1-btn-soft" style={{ width: '100%', padding: '17px' }} disabled>
              <svg width="15" height="15" viewBox="0 0 15 15"><rect x="3" y="6.5" width="9" height="6.5" rx="1.4" fill="none" stroke="var(--cream-dim)" strokeWidth="1.3"/><path d="M5 6.5V5a2.5 2.5 0 0 1 5 0v1.5" fill="none" stroke="var(--cream-dim)" strokeWidth="1.3"/></svg>
              Phiên đang khóa
            </button>
            <p className="b1-mono" style={{ fontSize: 10.5, color: 'var(--cream-dim)', textAlign: 'center', marginTop: 12, lineHeight: 1.7 }}>
              Chủ phiên đã tạm khóa lối vào.<br />Bạn sẽ vào được khi mở lại — vui lòng chờ.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { JoinScreen, Avatar, WAITING });
