/* media.jsx — Video Wishes + Gallery (upload, masonry, slideshow) */
const { useState: useStateMed, useRef: useRefMed } = React;

function MediaUploader({ kind, accept, cta, hint }) {
  const [file, setFile] = useStateMed(null);
  const [preview, setPreview] = useStateMed(null);
  const [name, setName] = useStateMed('');
  const [caption, setCaption] = useStateMed('');
  const [busy, setBusy] = useStateMed(false);
  const [drag, setDrag] = useStateMed(false);
  const inputRef = useRefMed(null);

  const take = (f) => {
    if (!f) return;
    if (!f.type.startsWith('image/')) { window.R50UI && window.R50UI.toast('Please choose a photo file.'); return; }
    if (f.size > 2 * 1024 * 1024) { window.R50UI && window.R50UI.toast('That photo is over 2MB — please choose a smaller one.'); return; }
    setFile(f); setPreview(URL.createObjectURL(f));
  };

  const post = async () => {
    if (!file) return;
    setBusy(true);
    await R50.addMedia({ kind, name: name.trim(), file, caption: caption.trim() });
    bumpMedia();
    setBusy(false); setFile(null); setPreview(null); setName(''); setCaption('');
    window.R50UI && window.R50UI.toast(kind === 'wish' ? 'Your video wish is posted 💛' : 'Added to the gallery 💛');
  };

  return (
    <div className="panel">
      {!file ? (
        <div
          className={`dropzone ${drag ? 'drag' : ''}`}
          onClick={() => inputRef.current.click()}
          onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
          onDragLeave={() => setDrag(false)}
          onDrop={(e) => { e.preventDefault(); setDrag(false); take(e.dataTransfer.files[0]); }}
        >
          <div className="dz-ic">{kind === 'wish' ? '🎬' : '📷'}</div>
          <div className="dz-main">{cta}</div>
          <div className="dz-sub">{hint}</div>
          <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => take(e.target.files[0])} />
        </div>
      ) : (
        <div style={{ animation: 'popIn .35s both' }}>
          <div style={{ borderRadius: 10, overflow: 'hidden', marginBottom: 18, boxShadow: '0 12px 30px rgba(0,0,0,.35)' }}>
            <img src={preview} alt="preview" style={{ width: '100%', display: 'block', maxHeight: 360, objectFit: 'cover' }} />
          </div>
          <div className="field">
            <label>Your name</label>
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Who's this from?" />
          </div>
          <div className="field">
            <label>{kind === 'wish' ? 'A line to go with it' : 'Caption'} <span style={{ textTransform: 'none', letterSpacing: 0 }}>(optional)</span></label>
            <input value={caption} onChange={(e) => setCaption(e.target.value)} placeholder={kind === 'wish' ? 'Happy 50th, Rajshree!' : 'Say something about this moment…'} />
          </div>
          <div className="center" style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
            <button className="btn btn-ghost" onClick={() => { setFile(null); setPreview(null); }}>Choose another</button>
            <button className="btn" disabled={busy} onClick={post}>{busy ? 'Posting…' : 'Post it'}</button>
          </div>
        </div>
      )}
    </div>
  );
}

function Gallery() {
  const media = useMediaList();
  const photos = media.filter((m) => m.type === 'image' && m.src);

  return (
    <section className="dark section-pad" id="gallery">
      <div className="wrap">
        <Reveal className="section-head center">
          <span className="kicker">The Gallery</span>
          <h2 style={{ color: 'var(--paper)' }}>Share the <em>memories</em></h2>
          <p className="lead" style={{ color: '#cdbfa6' }}>Add your favorite photos — before, during, and after the party. One shared album for everyone.</p>
        </Reveal>

        <Reveal style={{ marginBottom: 44 }}>
          <MediaUploader kind="photo" accept="image/*" cta="Add photos" hint="Drag & drop, or tap to choose · they appear instantly below" />
        </Reveal>

        {photos.length > 0 && (
          <Reveal className="tabs">
            <button className="tab" onClick={() => window.R50UI.slideshow(photos)}>▶ Play slideshow</button>
          </Reveal>
        )}

        {photos.length === 0 ? (
          <Reveal className="empty-note">No photos yet — be the first to add one.</Reveal>
        ) : (
          <div className="masonry">
            {photos.map((m) => (
              <div className="m-item" key={m.id} onClick={() => m.src && window.R50UI.lightbox(m)}>
                <span className="m-badge">Photo</span>
                <img src={m.src} alt={m.caption || 'memory'} loading="lazy" />
                {(m.name || m.caption) && <div className="cap"><b>{m.name}</b>{m.caption}</div>}
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { Gallery });
