/* ============================================================
   B1 — Màn "Tạo phiên mới" (host)
   Tab trên chuyển bước · 1 nút "Tạo phiên mới" (bật khi có nền).
   Bối cảnh: tải ảnh / chụp ngay · Vật phẩm · Thềm nhạc (optional).
   Ảnh nền + nhạc = của host. Item là vật phẩm mặc định của phiên.
   ============================================================ */
const MUSIC_LIB = [
  { id: 1, title: 'Hương trầm', mood: 'Trầm', dur: '4:32' },
  { id: 2, title: 'Mưa thềm', mood: 'Trầm', dur: '3:50' },
  { id: 3, title: 'Sớm xuân', mood: 'Vui', dur: '3:20' },
  { id: 4, title: 'Hội làng', mood: 'Vui', dur: '4:00' },
  { id: 5, title: 'Khúc giao', mood: 'Trung tính', dur: '4:15' },
];

function CreateScreen({ onCreate, bg, setBg, sessionType = 'hop', setSessionType = () => {} }) {
  const [step, setStep] = useState(1);
  const [dim, setDim] = useState(28);
  const [items, setItems] = useState([]);
  const [music, setMusic] = useState(null);
  const [custom, setCustom] = useState(null);
  const [playing, setPlaying] = useState(null);
  const fileRef = useRef(null);
  const camRef = useRef(null);
  const musicRef = useRef(null);
  const audioRef = useRef(null);
  const steps = [{ k: 1, l: 'Bối cảnh' }, { k: 2, l: 'Vật phẩm' }, { k: 3, l: 'Thềm nhạc' }];

  useEffect(() => () => { if (audioRef.current) audioRef.current.pause(); }, []);

  const onPickBg = (e) => { const f = e.target.files?.[0]; if (f) setBg(URL.createObjectURL(f)); if (e.target) e.target.value = ''; };
  const onPickMusic = (e) => { const f = e.target.files?.[0]; if (f) { setCustom({ name: f.name, url: URL.createObjectURL(f) }); setMusic('custom'); } e.target.value = ''; };
  const toggleItem = (emoji) => setItems(s => {
    const ex = s.find(i => i.emoji === emoji);
    if (ex) return s.filter(i => i.emoji !== emoji);
    if (s.length >= 5) return s;
    return [...s, { emoji, weight: 'medium' }];
  });
  const setWeight = (emoji, w) => setItems(s => s.map(i => i.emoji === emoji ? { ...i, weight: w } : i));
  const playCustom = () => {
    if (!custom) return;
    if (!audioRef.current) audioRef.current = new Audio(custom.url);
    if (playing === 'custom') { audioRef.current.pause(); setPlaying(null); }
    else { audioRef.current.currentTime = 0; audioRef.current.play().catch(() => {}); setPlaying('custom'); }
  };
  const playPreset = (id) => { if (audioRef.current) audioRef.current.pause(); setPlaying(p => p === id ? null : id); };

  return (
    <div className="b1-screen b1-scroll b1-safe-top" style={{ overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '14px 24px 0' }}>
        <div className="b1-eyebrow">Tạo phiên mới</div>

        {/* loại phiên — quyết định vật phẩm mặc định + tự điền thẻ ở Lưu phiên sau này */}
        <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
          {[{ k: 'hop', l: 'Họp', d: 'Công việc · giỗ, họp họ' }, { k: 'gap-mat', l: 'Gặp mặt', d: 'Sinh nhật · bạn bè' }].map(o => {
            const on = sessionType === o.k;
            return (
              <button key={o.k} onClick={() => { setSessionType(o.k); setItems([]); }} style={{
                flex: 1, textAlign: 'left', cursor: 'pointer', padding: '11px 13px', borderRadius: 'var(--r-md)',
                background: on ? 'rgba(184,153,104,.14)' : 'var(--ink-soft)',
                border: '1px solid ' + (on ? 'var(--gold)' : 'var(--ink-line)'),
              }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: on ? 'var(--gold)' : 'var(--cream)' }}>{o.l}</div>
                <div className="b1-mono" style={{ fontSize: 8.5, color: 'var(--cream-dim)', marginTop: 2 }}>{o.d}</div>
              </button>
            );
          })}
        </div>

        <div style={{ display: 'flex', gap: 18, marginTop: 14, borderBottom: '1px solid var(--ink-line)' }}>
          {steps.map(s => {
            const on = step === s.k;
            return (
              <button key={s.k} onClick={() => setStep(s.k)} style={{
                background: 'none', border: 'none', cursor: 'pointer', padding: '0 0 9px',
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.08em', textTransform: 'uppercase',
                color: on ? 'var(--gold)' : 'rgba(200,192,174,.5)',
                borderBottom: '2px solid ' + (on ? 'var(--gold)' : 'transparent'), marginBottom: -1,
              }}>{s.l}</button>
            );
          })}
        </div>
      </div>

      <div style={{ flex: 1 }}>
        {/* STEP 1 — Bối cảnh */}
        {step === 1 && (
          <div style={{ padding: '18px 24px 0' }}>
            <div className="b1-label" style={{ marginBottom: 9 }}>BỐI CẢNH</div>
            <div style={{ position: 'relative', width: '100%', height: 168, borderRadius: 'var(--r-md)', overflow: 'hidden', border: '1px solid var(--ink-line)', background: 'var(--ink-soft)' }}>
              {bg
                ? <img src={bg} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', filter: `brightness(${100 - dim}%)` }} />
                : <span className="b1-placeholder-label">chưa có ảnh nền</span>}
              {bg && <div style={{ position: 'absolute', inset: 0, background: `rgba(21,30,48,${dim / 160})` }} />}
              {bg && items.slice(0, 5).map((it, i) => (
                <span key={i} style={{ position: 'absolute', left: `${14 + i * 17}%`, top: `${30 + (i % 2) * 26}%`, fontSize: 22, filter: 'drop-shadow(0 1px 4px rgba(0,0,0,.6))' }}>{it.emoji}</span>
              ))}
              <span className="b1-mono" style={{ position: 'absolute', bottom: 7, left: 9, fontSize: 8.5, color: 'rgba(237,229,211,.55)', letterSpacing: '.12em' }}>PREVIEW · LIVE</span>
            </div>

            <input ref={fileRef} type="file" accept="image/*" onChange={onPickBg} style={{ display: 'none' }} />
            <input ref={camRef} type="file" accept="image/*" capture="environment" onChange={onPickBg} style={{ display: 'none' }} />
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              <button className="b1-btn b1-btn-soft" style={{ flex: 1, flexDirection: 'column', gap: 6, padding: '14px' }} onClick={() => fileRef.current?.click()}>
                <svg width="22" height="22" 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={{ fontSize: 13.5 }}>{bg ? 'Đổi ảnh nền' : 'Tải ảnh nền'}</span>
              </button>
              <button className="b1-btn b1-btn-soft" style={{ flex: 1, flexDirection: 'column', gap: 6, padding: '14px' }} onClick={() => camRef.current?.click()}>
                <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><rect x="3" y="6.5" width="16" height="11" rx="2.4" stroke="var(--gold)" strokeWidth="1.6"/><circle cx="11" cy="12" r="3" stroke="var(--gold)" strokeWidth="1.6"/><path d="M8 6.5l1.3-2h3.4L14 6.5" stroke="var(--gold-dim)" strokeWidth="1.6" strokeLinejoin="round"/></svg>
                <span style={{ fontSize: 13.5 }}>Chụp ngay</span>
              </button>
            </div>
            <p className="b1-mono" style={{ fontSize: 9, color: 'rgba(200,192,174,.45)', marginTop: 11, lineHeight: 1.6 }}>Ảnh nền là của host · jpg · png · webp · ≤ 5MB · nên dùng ảnh nét, đủ lớn nếu định dùng làm bảng trắng</p>

            {bg && (
              <div style={{ marginTop: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 9 }}>
                  <span className="b1-label">MỨC TỐI NỀN</span>
                  <span className="b1-mono" style={{ fontSize: 10, color: 'var(--gold)' }}>{dim}</span>
                </div>
                <B1Range value={dim} min={0} max={70} onChange={setDim} />
              </div>
            )}
          </div>
        )}

        {/* STEP 2 — Vật phẩm */}
        {step === 2 && (
          <div style={{ padding: '18px 24px 0' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
              {EMOJI_LIB[sessionType].map((e, i) => {
                const sel = items.find(i => i.emoji === e);
                return (
                  <button key={i} onClick={() => toggleItem(e)} style={{
                    aspectRatio: '1', fontSize: 24, cursor: 'pointer', borderRadius: 'var(--r-sm)',
                    background: sel ? 'rgba(184,153,104,.16)' : 'var(--ink-soft)',
                    border: sel ? '1px solid var(--gold)' : '1px solid var(--ink-line)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{e}</button>
                );
              })}
            </div>
            <div className="b1-label" style={{ margin: '20px 0 10px' }}>VẬT PHẨM MẶC ĐỊNH · {items.length}/5</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 7 }}>
              {Array.from({ length: 5 }).map((_, idx) => {
                const it = items[idx];
                return (
                  <div key={idx} style={{
                    aspectRatio: '1', borderRadius: 'var(--r-sm)', position: 'relative',
                    background: it ? 'rgba(184,153,104,.08)' : 'transparent',
                    border: it ? '1px solid var(--gold)' : '1px dashed rgba(138,115,80,.4)',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
                  }}>
                    {it ? (
                      <>
                        <button onClick={() => toggleItem(it.emoji)} style={{ position: 'absolute', top: 1, right: 3, background: 'none', border: 'none', color: 'var(--cream-dim)', cursor: 'pointer', fontSize: 13, lineHeight: 1 }}>×</button>
                        <span style={{ fontSize: 20 }}>{it.emoji}</span>
                        <span style={{ display: 'flex', gap: 3 }}>
                          {['low', 'medium', 'high'].map(w => (
                            <button key={w} onClick={() => setWeight(it.emoji, w)} title={w === 'low' ? 'thưa' : w === 'high' ? 'dày' : 'vừa'} style={{
                              width: 7, height: 7, padding: 0, borderRadius: '50%', cursor: 'pointer', border: 'none',
                              background: it.weight === w ? 'var(--gold)' : 'rgba(138,115,80,.35)',
                            }} />
                          ))}
                        </span>
                      </>
                    ) : <span style={{ color: 'rgba(200,192,174,.4)', fontSize: 16 }}>+</span>}
                  </div>
                );
              })}
            </div>
            <p className="b1-mono" style={{ fontSize: 9, color: 'rgba(200,192,174,.45)', marginTop: 10, lineHeight: 1.6 }}>Chấm tròn = độ dày bay · khách vẫn tự thả thêm item của họ</p>
          </div>
        )}

        {/* STEP 3 — Thềm nhạc (optional) */}
        {step === 3 && (
          <div style={{ padding: '18px 24px 0' }}>
            <div className="b1-label" style={{ marginBottom: 10 }}>THỀM NHẠC · KHÔNG BẮT BUỘC</div>
            <input ref={musicRef} type="file" accept="audio/*" onChange={onPickMusic} style={{ display: 'none' }} />
            <button onClick={() => musicRef.current?.click()} style={{
              width: '100%', padding: '14px 16px', cursor: 'pointer', borderRadius: 'var(--r-md)', marginBottom: 16,
              background: music === 'custom' ? 'rgba(184,153,104,.12)' : 'var(--ink-soft)',
              border: '1px solid ' + (music === 'custom' ? 'var(--gold)' : 'var(--ink-line)'),
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <span onClick={(e) => { e.stopPropagation(); playCustom(); }} style={{
                width: 34, height: 34, borderRadius: '50%', flexShrink: 0, border: '1px solid var(--gold-dim)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--gold)', opacity: custom ? 1 : .4,
              }}>
                {playing === 'custom'
                  ? <svg width="11" height="11" viewBox="0 0 12 12"><rect x="2.5" y="2" width="2.4" height="8" fill="var(--gold)"/><rect x="7.1" y="2" width="2.4" height="8" fill="var(--gold)"/></svg>
                  : <svg width="11" height="11" viewBox="0 0 12 12"><path d="M3 2l7 4-7 4z" fill="var(--gold)"/></svg>}
              </span>
              <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                <div style={{ fontSize: 13.5, color: 'var(--cream)', fontWeight: 500 }}>{custom ? 'Nhạc của bạn' : 'Tải nhạc nền lên'}</div>
                <div className="b1-mono" style={{ fontSize: 9.5, color: 'var(--cream-dim)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {custom ? custom.name : 'mp3 · m4a · nghe thử ngay'}
                </div>
              </div>
              <span className="b1-mono" style={{ fontSize: 9, color: 'var(--gold)', border: '1px solid var(--ink-line)', borderRadius: 4, padding: '4px 7px', flexShrink: 0 }}>{custom ? 'ĐỔI' : 'TẢI'}</span>
            </button>

            <div className="b1-label" style={{ marginBottom: 10 }}>HOẶC CHỌN NHẠC NỀN B1</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {MUSIC_LIB.map(m => {
                const sel = music === m.id;
                return (
                  <div key={m.id} onClick={() => setMusic(sel ? null : m.id)} style={{
                    display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px', cursor: 'pointer', borderRadius: 'var(--r-sm)',
                    background: sel ? 'rgba(184,153,104,.1)' : 'var(--ink-soft)', border: '1px solid ' + (sel ? 'var(--gold)' : 'var(--ink-line)'),
                  }}>
                    <button onClick={(e) => { e.stopPropagation(); playPreset(m.id); }} style={{
                      width: 30, height: 30, borderRadius: '50%', flexShrink: 0, cursor: 'pointer', background: 'transparent',
                      border: '1px solid var(--gold-dim)', color: 'var(--gold)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {playing === m.id
                        ? <svg width="10" height="10" viewBox="0 0 12 12"><rect x="2.5" y="2" width="2.4" height="8" fill="var(--gold)"/><rect x="7.1" y="2" width="2.4" height="8" fill="var(--gold)"/></svg>
                        : <svg width="10" height="10" viewBox="0 0 12 12"><path d="M3 2l7 4-7 4z" fill="var(--gold)"/></svg>}
                    </button>
                    <span style={{ flex: 1, fontSize: 13.5, color: 'var(--cream)' }}>{m.title}</span>
                    <span className="b1-mono" style={{ fontSize: 9, color: 'var(--gold-dim)' }}>{m.mood}</span>
                    <span className="b1-mono" style={{ fontSize: 10, color: 'var(--cream-dim)' }}>{m.dur}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* footer — 1 nút duy nhất, bật khi đã có nền (nhạc/item optional) */}
      <div style={{ padding: '20px 24px 36px' }}>
        <button className="b1-btn b1-btn-primary" style={{ width: '100%', padding: '17px' }} onClick={onCreate}>
          Tạo phiên & vào chủ trì
          <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>
        {!bg && <p className="b1-mono" style={{ fontSize: 9, color: 'rgba(200,192,174,.45)', textAlign: 'center', marginTop: 10 }}>Ảnh nền là tuỳ chọn · có thể tạo phiên rồi thêm sau</p>}
      </div>
    </div>
  );
}

function CtxStrip({ bg, items }) {
  return null; // bỏ dải bối cảnh lặp lại ở bước sau — đã có bối cảnh, dẹp khoảng thừa
}

Object.assign(window, { CreateScreen, MUSIC_LIB });
