/* global React, firebase */
/* ============================================
   EAImageSlot — single image (backward compat)
   EAImageGallery — multiple images per EA
   Both read/write Firestore /eas/{eaId}
   - imageUrl    : main image (legacy + card preview)
   - images[]    : full gallery (new)
   ============================================ */

function EAImageSlot({ eaId, name = '', fit = 'cover' }) {
  const [url, setUrl] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [dragOver, setDragOver] = React.useState(false);
  const [, setTick] = React.useState(0);
  const fileRef = React.useRef(null);
  const isAdmin = window.__effAdminMode;

  React.useEffect(() => {
    if (!window.fb || !eaId) return;
    const unsub = window.fb.db.collection('eas').doc(eaId).onSnapshot(
      doc => {
        const data = doc.exists ? doc.data() : null;
        // Prefer first image from gallery, fall back to legacy imageUrl
        const first = data?.images?.[0] || data?.imageUrl || null;
        setUrl(first);
      },
      () => setUrl(null)
    );
    return () => unsub();
  }, [eaId]);

  React.useEffect(() => {
    const handler = () => setTick(t => t + 1);
    window.addEventListener('eff_admin_changed', handler);
    return () => window.removeEventListener('eff_admin_changed', handler);
  }, []);

  async function handleFile(file) {
    if (!isAdmin || !window.fb) return;
    if (!file.type?.startsWith('image/')) { setError('Please drop an image file'); return; }
    setError(''); setUploading(true);
    try {
      const newUrl = await window.Cloudinary.uploadToCloudinary(file, `eas/${eaId}`);
      // Read existing images, prepend new one
      const doc = await window.fb.db.collection('eas').doc(eaId).get();
      const existing = (doc.data()?.images) || [];
      const newImages = [newUrl, ...existing.filter(u => u !== newUrl)];
      await window.fb.db.collection('eas').doc(eaId).set({
        imageUrl: newUrl,   // keep legacy field in sync
        images: newImages,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      }, { merge: true });
    } catch (e) {
      setError(e.message || 'Upload failed');
      console.error('Cloudinary upload error:', e);
    } finally {
      setUploading(false);
    }
  }

  async function clear(ev) {
    ev?.stopPropagation();
    if (!isAdmin || !window.fb) return;
    try {
      await window.fb.db.collection('eas').doc(eaId).set({ imageUrl: null, images: [] }, { merge: true });
    } catch (e) { setError(e.message); }
  }

  const canEdit = !!isAdmin;
  return (
    <div
      onDragOver={canEdit ? (e) => { e.preventDefault(); setDragOver(true); } : undefined}
      onDragLeave={canEdit ? () => setDragOver(false) : undefined}
      onDrop={canEdit ? (e) => {
        e.preventDefault(); setDragOver(false);
        if (e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
      } : undefined}
      onClick={canEdit && !url ? () => fileRef.current?.click() : undefined}
      style={{
        position: 'relative', width: '100%', height: '100%',
        backgroundImage: url ? `url(${url})` : 'none',
        backgroundSize: fit, backgroundPosition: 'center', backgroundRepeat: 'no-repeat',
        backgroundColor: 'rgba(0,0,0,0.3)',
        cursor: canEdit && !url ? 'pointer' : 'default',
        border: canEdit ? `1px dashed ${dragOver ? 'var(--cyan)' : 'rgba(255,45,170,0.35)'}` : 'none',
        transition: 'all 0.2s',
        display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
      }}>
      {canEdit && (
        <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }}
          onChange={(e) => e.target.files[0] && handleFile(e.target.files[0])}/>
      )}
      {!url && canEdit && !uploading && (
        <div className="text-center" style={{ pointerEvents: 'none' }}>
          <div style={{ fontSize: 28, color: 'var(--cyan)', lineHeight: 1 }}>↗</div>
          <div className="font-mono text-xs text-muted mt-2" style={{ letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 10 }}>
            {dragOver ? 'DROP TO UPLOAD' : `${name || 'EA'} IMAGE`}
          </div>
        </div>
      )}
      {canEdit && url && (
        <div style={{ position: 'absolute', top: 8, right: 8, display: 'flex', gap: 6, zIndex: 2 }}>
          <button onClick={(e) => { e.stopPropagation(); fileRef.current?.click(); }}
            style={{ padding: '6px 10px', fontSize: 10, fontFamily: 'var(--font-mono)', background: 'rgba(5,6,13,0.85)', backdropFilter: 'blur(8px)', border: '1px solid var(--line-strong)', borderRadius: 4, color: 'var(--cyan)', cursor: 'pointer', letterSpacing: '0.1em' }}>↻ REPLACE</button>
          <button onClick={clear}
            style={{ padding: '6px 10px', fontSize: 10, fontFamily: 'var(--font-mono)', background: 'rgba(5,6,13,0.85)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,59,92,0.4)', borderRadius: 4, color: 'var(--red)', cursor: 'pointer', letterSpacing: '0.1em' }}>× CLEAR</button>
        </div>
      )}
      {uploading && (
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(5,6,13,0.88)', display: 'grid', placeItems: 'center', backdropFilter: 'blur(4px)', zIndex: 3 }}>
          <div className="text-center">
            <span className="typing"><span/><span/><span/></span>
            <div className="font-mono text-xs text-cyan mt-2" style={{ letterSpacing: '0.15em' }}>UPLOADING...</div>
          </div>
        </div>
      )}
      {error && (
        <div style={{ position: 'absolute', bottom: 8, left: 8, right: 8, padding: '8px 12px', background: 'rgba(255,59,92,0.15)', border: '1px solid rgba(255,59,92,0.4)', borderRadius: 4, zIndex: 3 }}>
          <span className="text-red font-mono text-xs">⚠ {error}</span>
        </div>
      )}
    </div>
  );
}

/* ============================================
   EAImageGallery — main image + thumbnail strip + lightbox
   Used on EA detail pages.
   ============================================ */
function EAImageGallery({ eaId, name = '', height = 360 }) {
  const [images, setImages] = React.useState([]);
  const [active, setActive] = React.useState(0);
  const [uploading, setUploading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [dragOver, setDragOver] = React.useState(false);
  const [lightboxIdx, setLightboxIdx] = React.useState(-1);
  const [, setTick] = React.useState(0);
  const fileRef = React.useRef(null);
  const isAdmin = window.__effAdminMode;

  React.useEffect(() => {
    if (!window.fb || !eaId) return;
    const unsub = window.fb.db.collection('eas').doc(eaId).onSnapshot(
      doc => {
        const data = doc.exists ? doc.data() : null;
        let list = data?.images || [];
        // Back-compat: if no images[] but legacy imageUrl exists, use it
        if (!list.length && data?.imageUrl) list = [data.imageUrl];
        setImages(list);
        setActive(prev => Math.min(prev, Math.max(0, list.length - 1)));
      },
      () => setImages([])
    );
    return () => unsub();
  }, [eaId]);

  React.useEffect(() => {
    const handler = () => setTick(t => t + 1);
    window.addEventListener('eff_admin_changed', handler);
    return () => window.removeEventListener('eff_admin_changed', handler);
  }, []);

  // Keyboard navigation in lightbox
  React.useEffect(() => {
    if (lightboxIdx < 0) return;
    function onKey(e) {
      if (e.key === 'Escape') setLightboxIdx(-1);
      if (e.key === 'ArrowRight') setLightboxIdx(i => Math.min(i + 1, images.length - 1));
      if (e.key === 'ArrowLeft') setLightboxIdx(i => Math.max(i - 1, 0));
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightboxIdx, images.length]);

  async function handleFiles(files) {
    if (!isAdmin || !window.fb || !files?.length) return;
    setError(''); setUploading(true);
    try {
      const uploaded = [];
      for (const file of Array.from(files)) {
        if (!file.type?.startsWith('image/')) continue;
        const url = await window.Cloudinary.uploadToCloudinary(file, `eas/${eaId}`);
        uploaded.push(url);
      }
      if (!uploaded.length) return;
      const doc = await window.fb.db.collection('eas').doc(eaId).get();
      const existing = doc.data()?.images || [];
      const merged = [...existing, ...uploaded.filter(u => !existing.includes(u))];
      await window.fb.db.collection('eas').doc(eaId).set({
        images: merged,
        imageUrl: merged[0],
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      }, { merge: true });
    } catch (e) {
      setError(e.message || 'Upload failed');
    } finally {
      setUploading(false);
    }
  }

  async function removeImage(idx) {
    if (!isAdmin || !window.fb) return;
    if (!confirm('Remove this image?')) return;
    const next = images.filter((_, i) => i !== idx);
    try {
      await window.fb.db.collection('eas').doc(eaId).set({
        images: next,
        imageUrl: next[0] || null,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      }, { merge: true });
      setActive(prev => Math.min(prev, Math.max(0, next.length - 1)));
    } catch (e) { setError(e.message); }
  }

  async function moveImage(idx, dir) {
    if (!isAdmin || !window.fb) return;
    const j = idx + dir;
    if (j < 0 || j >= images.length) return;
    const next = [...images];
    [next[idx], next[j]] = [next[j], next[idx]];
    try {
      await window.fb.db.collection('eas').doc(eaId).set({
        images: next,
        imageUrl: next[0],
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      }, { merge: true });
      setActive(j);
    } catch (e) { setError(e.message); }
  }

  const canEdit = !!isAdmin;
  const hasImages = images.length > 0;
  const mainUrl = images[active];

  return (
    <div>
      {/* Main image */}
      <div
        onDragOver={canEdit ? (e) => { e.preventDefault(); setDragOver(true); } : undefined}
        onDragLeave={canEdit ? () => setDragOver(false) : undefined}
        onDrop={canEdit ? (e) => {
          e.preventDefault(); setDragOver(false);
          handleFiles(e.dataTransfer.files);
        } : undefined}
        className="panel"
        style={{
          position: 'relative',
          height,
          overflow: 'hidden',
          padding: 0,
          backgroundImage: mainUrl ? `url(${mainUrl})` : 'none',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundColor: 'rgba(0,0,0,0.3)',
          cursor: hasImages ? 'zoom-in' : (canEdit ? 'pointer' : 'default'),
          border: canEdit && !hasImages ? '1px dashed rgba(255,45,170,0.35)' : undefined,
        }}
        onClick={() => {
          if (hasImages) setLightboxIdx(active);
          else if (canEdit) fileRef.current?.click();
        }}>
        {canEdit && (
          <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }}
            onChange={(e) => handleFiles(e.target.files)}/>
        )}

        {!hasImages && canEdit && !uploading && (
          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', pointerEvents: 'none' }}>
            <div className="text-center">
              <div style={{ fontSize: 36, color: 'var(--cyan)', lineHeight: 1 }}>↗</div>
              <div className="font-mono text-xs text-muted mt-2" style={{ letterSpacing: '0.15em', textTransform: 'uppercase' }}>
                {dragOver ? 'Drop multiple images' : `Drop ${name || 'EA'} images`}
              </div>
              <div className="text-xs text-muted mt-1">You can drop multiple at once</div>
            </div>
          </div>
        )}

        {/* Admin upload + image counter */}
        {hasImages && (
          <div style={{ position: 'absolute', top: 12, left: 12, padding: '4px 10px', background: 'rgba(5,6,13,0.75)', backdropFilter: 'blur(8px)', borderRadius: 4, fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-2)' }}>
            {active + 1} / {images.length}
          </div>
        )}

        {canEdit && (
          <div style={{ position: 'absolute', top: 12, right: 12, display: 'flex', gap: 6, zIndex: 2 }}>
            <button onClick={(e) => { e.stopPropagation(); fileRef.current?.click(); }}
              style={{ padding: '6px 12px', fontSize: 10, fontFamily: 'var(--font-mono)', background: 'rgba(5,6,13,0.85)', backdropFilter: 'blur(8px)', border: '1px solid var(--line-strong)', borderRadius: 4, color: 'var(--cyan)', cursor: 'pointer', letterSpacing: '0.1em' }}>+ ADD IMAGE</button>
            {hasImages && (
              <button onClick={(e) => { e.stopPropagation(); removeImage(active); }}
                style={{ padding: '6px 10px', fontSize: 10, fontFamily: 'var(--font-mono)', background: 'rgba(5,6,13,0.85)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,59,92,0.4)', borderRadius: 4, color: 'var(--red)', cursor: 'pointer', letterSpacing: '0.1em' }}>× DELETE</button>
            )}
          </div>
        )}

        {/* Prev/Next arrows on main image */}
        {hasImages && images.length > 1 && (
          <>
            {active > 0 && (
              <button onClick={(e) => { e.stopPropagation(); setActive(active - 1); }}
                style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: '50%', background: 'rgba(5,6,13,0.75)', backdropFilter: 'blur(8px)', border: '1px solid var(--line-strong)', color: 'var(--cyan)', cursor: 'pointer', fontSize: 16, zIndex: 2 }}>‹</button>
            )}
            {active < images.length - 1 && (
              <button onClick={(e) => { e.stopPropagation(); setActive(active + 1); }}
                style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', width: 40, height: 40, borderRadius: '50%', background: 'rgba(5,6,13,0.75)', backdropFilter: 'blur(8px)', border: '1px solid var(--line-strong)', color: 'var(--cyan)', cursor: 'pointer', fontSize: 16, zIndex: 2 }}>›</button>
            )}
          </>
        )}

        {uploading && (
          <div style={{ position: 'absolute', inset: 0, background: 'rgba(5,6,13,0.88)', display: 'grid', placeItems: 'center', backdropFilter: 'blur(4px)' }}>
            <div className="text-center">
              <span className="typing"><span/><span/><span/></span>
              <div className="font-mono text-xs text-cyan mt-2" style={{ letterSpacing: '0.15em' }}>UPLOADING...</div>
            </div>
          </div>
        )}

        {error && (
          <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, padding: '8px 12px', background: 'rgba(255,59,92,0.15)', border: '1px solid rgba(255,59,92,0.4)', borderRadius: 4 }}>
            <span className="text-red font-mono text-xs">⚠ {error}</span>
          </div>
        )}
      </div>

      {/* Thumbnail strip */}
      {hasImages && (images.length > 1 || canEdit) && (
        <div className="flex gap-2 mt-3" style={{ overflowX: 'auto', paddingBottom: 4 }}>
          {images.map((src, i) => (
            <div key={src} style={{ position: 'relative', flexShrink: 0 }}>
              <div
                onClick={() => setActive(i)}
                style={{
                  width: 72, height: 56, borderRadius: 6, cursor: 'pointer',
                  backgroundImage: `url(${src})`, backgroundSize: 'cover', backgroundPosition: 'center',
                  border: i === active ? '2px solid var(--cyan)' : '1px solid var(--line)',
                  boxShadow: i === active ? '0 0 0 1px var(--cyan), 0 0 12px rgba(0,229,255,0.3)' : 'none',
                  transition: 'all 0.15s',
                }}/>
              {canEdit && (
                <div style={{ position: 'absolute', top: -6, right: -6, display: 'flex', gap: 2 }}>
                  {i > 0 && (
                    <button onClick={(e) => { e.stopPropagation(); moveImage(i, -1); }}
                      title="Move left"
                      style={{ width: 18, height: 18, borderRadius: '50%', background: 'rgba(5,6,13,0.95)', border: '1px solid var(--line-strong)', color: 'var(--cyan)', cursor: 'pointer', fontSize: 9, padding: 0, lineHeight: 1 }}>‹</button>
                  )}
                </div>
              )}
            </div>
          ))}
          {canEdit && (
            <div
              onClick={() => fileRef.current?.click()}
              style={{
                width: 72, height: 56, borderRadius: 6, cursor: 'pointer',
                border: '1px dashed rgba(255,45,170,0.4)',
                display: 'grid', placeItems: 'center', flexShrink: 0,
                color: 'var(--magenta)', fontSize: 20,
              }}>+</div>
          )}
        </div>
      )}

      {/* Lightbox */}
      {lightboxIdx >= 0 && images[lightboxIdx] && (
        <div
          onClick={() => setLightboxIdx(-1)}
          style={{
            position: 'fixed', inset: 0, zIndex: 200,
            background: 'rgba(5,6,13,0.95)', backdropFilter: 'blur(8px)',
            display: 'grid', placeItems: 'center', padding: 24,
          }}>
          <img src={images[lightboxIdx]} alt="" style={{ maxWidth: '92vw', maxHeight: '88vh', objectFit: 'contain', borderRadius: 8, boxShadow: '0 24px 80px rgba(0,0,0,0.8)' }}/>

          <button onClick={(e) => { e.stopPropagation(); setLightboxIdx(-1); }}
            style={{ position: 'absolute', top: 20, right: 20, width: 44, height: 44, borderRadius: '50%', background: 'rgba(5,6,13,0.8)', border: '1px solid var(--line-strong)', color: 'var(--text)', cursor: 'pointer', fontSize: 20, fontFamily: 'var(--font-mono)' }}>×</button>

          {lightboxIdx > 0 && (
            <button onClick={(e) => { e.stopPropagation(); setLightboxIdx(lightboxIdx - 1); }}
              style={{ position: 'absolute', left: 24, top: '50%', transform: 'translateY(-50%)', width: 48, height: 48, borderRadius: '50%', background: 'rgba(5,6,13,0.8)', border: '1px solid var(--line-strong)', color: 'var(--cyan)', cursor: 'pointer', fontSize: 22 }}>‹</button>
          )}
          {lightboxIdx < images.length - 1 && (
            <button onClick={(e) => { e.stopPropagation(); setLightboxIdx(lightboxIdx + 1); }}
              style={{ position: 'absolute', right: 24, top: '50%', transform: 'translateY(-50%)', width: 48, height: 48, borderRadius: '50%', background: 'rgba(5,6,13,0.8)', border: '1px solid var(--line-strong)', color: 'var(--cyan)', cursor: 'pointer', fontSize: 22 }}>›</button>
          )}

          <div style={{ position: 'absolute', bottom: 24, left: 0, right: 0, textAlign: 'center', color: 'var(--text-2)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
            {lightboxIdx + 1} / {images.length}
          </div>
        </div>
      )}
    </div>
  );
}

window.EAImageSlot = EAImageSlot;
window.EAImageGallery = EAImageGallery;
