/* global React */
const { useState, useEffect, useRef, useCallback } = React;

function Gallery({ onExit, initialId = null, soundOn = false, onToggleSound = () => {} }) {
  const photos = window.DARSHAN || [];

  // resolve initial index from id or default to 0
  const startIdx = (() => {
    if (initialId) {
      const i = photos.findIndex(p => p.id === initialId);
      if (i >= 0) return i;
    }
    return 0;
  })();

  const [idx, setIdx] = useState(startIdx);
  const [prevIdx, setPrevIdx] = useState(null);
  const [transitioning, setTransitioning] = useState(false);
  const [favs, setFavs] = useState(() => {
    try { return JSON.parse(localStorage.getItem("darshan.favs") || "[]"); } catch (e) { return []; }
  });
  const [showHelp, setShowHelp] = useState(false);
  const [shareNote, setShareNote] = useState("");
  const [showMeta, setShowMeta] = useState(false);

  const photo = photos[idx];
  const prevPhoto = prevIdx != null ? photos[prevIdx] : null;
  const isFav = favs.includes(photo?.id);

  // First-visit help overlay
  useEffect(() => {
    try {
      const seen = localStorage.getItem("darshan.gallery.helpSeen");
      if (!seen) {
        const t = setTimeout(() => { setShowHelp(true); }, 1200);
        return () => clearTimeout(t);
      }
    } catch (e) {}
  }, []);

  const dismissHelp = () => {
    setShowHelp(false);
    try { localStorage.setItem("darshan.gallery.helpSeen", "1"); } catch (e) {}
  };

  const go = useCallback((d) => {
    setIdx((cur) => {
      const next = (cur + d + photos.length) % photos.length;
      setPrevIdx(cur);
      setTransitioning(true);
      setShowMeta(false);
      setTimeout(() => { setTransitioning(false); setPrevIdx(null); }, 1400);
      return next;
    });
  }, [photos.length]);

  const jumpTo = useCallback((i) => {
    setIdx((cur) => {
      if (i === cur) return cur;
      setPrevIdx(cur);
      setTransitioning(true);
      setShowMeta(false);
      setTimeout(() => { setTransitioning(false); setPrevIdx(null); }, 1400);
      return i;
    });
  }, []);

  const toggleFav = useCallback(() => {
    setFavs(cur => {
      const next = cur.includes(photo.id) ? cur.filter(x => x !== photo.id) : [...cur, photo.id];
      try { localStorage.setItem("darshan.favs", JSON.stringify(next)); } catch (e) {}
      return next;
    });
  }, [photo]);

  const share = useCallback(() => {
    const url = `${location.origin}${location.pathname}#darshan/${photo.id}`;
    const text = `${photo.title} — ${photo.place}\n"${photo.line}"\n${url}`;
    try {
      navigator.clipboard.writeText(text);
      setShareNote("link copied · share gently");
    } catch (e) {
      setShareNote(url);
    }
    setTimeout(() => setShareNote(""), 2400);
  }, [photo]);

  // keyboard
  useEffect(() => {
    const onKey = (e) => {
      if (showHelp) {
        if (e.key === "Escape" || e.key === "Enter") { dismissHelp(); return; }
      }
      if (e.key === "ArrowRight" || e.key === " ") { e.preventDefault(); go(1); }
      else if (e.key === "ArrowLeft") { e.preventDefault(); go(-1); }
      else if (e.key === "Escape") onExit();
      else if (e.key === "f" || e.key === "F") toggleFav();
      else if (e.key === "s" || e.key === "S") share();
      else if (e.key === "i" || e.key === "I") setShowMeta(m => !m);
      else if (e.key === "?" || e.key === "/") setShowHelp(s => !s);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [go, onExit, toggleFav, share, showHelp]);

  // wheel — debounced
  useEffect(() => {
    let cooling = false;
    const onWheel = (e) => {
      if (cooling) return;
      if (Math.abs(e.deltaY) < 18) return;
      cooling = true;
      go(e.deltaY > 0 ? 1 : -1);
      setTimeout(() => { cooling = false; }, 1100);
    };
    window.addEventListener("wheel", onWheel, { passive: true });
    return () => window.removeEventListener("wheel", onWheel);
  }, [go]);

  if (!photo) return null;

  return (
    <div className="gallery-v2">
      <div className="thread">
        <div className="fill" style={{ width: `${((idx + 1) / photos.length) * 100}%` }}></div>
      </div>

      <div className="gallery-topbar">
        <button
          onClick={onExit}
          data-cursor
          className="gallery-back"
        >
          <span className="dash"></span>
          <span className="gallery-back-copy">
            <span className="gallery-back-label">return to the threshold</span>
            <span className="gallery-back-name">Rahul Malviya</span>
          </span>
        </button>

        <div className="gallery-tools">
          <button className={`gtool fav ${isFav ? "active" : ""}`} onClick={toggleFav} data-cursor title="hold close (F)">
            <svg viewBox="0 0 24 24" width="14" height="14" fill={isFav ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.4">
              <path d="M12 21s-7-4.5-9.5-9.2C0.7 8.2 2.7 4 6.7 4c2.1 0 3.6 1.1 5.3 3.1C13.7 5.1 15.2 4 17.3 4c4 0 6 4.2 4.2 7.8C19 16.5 12 21 12 21z"/>
            </svg>
            <span className="gtool-label">{isFav ? "kept close" : "hold close"}</span>
          </button>
          <button className="gtool" onClick={share} data-cursor title="share (S)">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4">
              <circle cx="6" cy="12" r="2.4"/>
              <circle cx="18" cy="6" r="2.4"/>
              <circle cx="18" cy="18" r="2.4"/>
              <path d="M8 11l8-4M8 13l8 4"/>
            </svg>
            <span className="gtool-label">share gently</span>
          </button>
          <button className={`gtool ${showMeta ? "active" : ""}`} onClick={() => setShowMeta(m => !m)} data-cursor title="exposure & coords (I)">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4">
              <circle cx="12" cy="12" r="8.5"/>
              <line x1="12" y1="11" x2="12" y2="17"/>
              <circle cx="12" cy="7.5" r="0.6" fill="currentColor"/>
            </svg>
            <span className="gtool-label">details</span>
          </button>
          <button
            className={`gtool sound-gtool ${soundOn ? "active" : ""}`}
            onClick={onToggleSound}
            data-cursor
            title={soundOn ? "silence the drone" : "let the drone enter"}
          >
            <span className="wave" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
            <span className="gtool-label">{soundOn ? "tanpura on" : "tanpura off"}</span>
          </button>
          <button className="gtool" onClick={() => setShowHelp(true)} data-cursor title="help (?)">
            <span className="qmark">?</span>
          </button>
        </div>
      </div>

      {/* Toast for share */}
      {shareNote && <div className="gallery-toast">{shareNote}</div>}

      {/* Stage */}
      <div className="stage-v2">
        {prevPhoto && (
          <div className="layer layer-out" key={`out-${prevIdx}`}>
            <img src={prevPhoto.file} alt="" />
          </div>
        )}
        <div className={`layer layer-in ${transitioning ? "" : "settled"}`} key={`in-${idx}`}>
          <img src={photo.file} alt={photo.title} />
        </div>
        <div className={`stage-flash ${transitioning ? "active" : ""}`}></div>
      </div>

      {/* Side rail · large numeral */}
      <div className="rail-num">
        <div className="rail-current">{photo.id}</div>
        <div className="rail-divider"></div>
        <div className="rail-total">{String(photos.length).padStart(2, "0")}</div>
      </div>

      {/* Devanagari watermark */}
      <div className="dev-watermark" key={`dev-${idx}`}>
        {photo.dev}
      </div>

      {/* Caption */}
      <div className={`caption-v2 ${transitioning ? "fading" : ""}`} key={`cap-${idx}`}>
        <div className="cap-place">
          <span className="rule"></span>
          <span>{photo.place} · {photo.year}</span>
        </div>
        <h2 className="cap-title">{photo.title}</h2>
        <p className="cap-line">{photo.line}</p>

        {/* Metadata panel — toggle with I or the details button */}
        <div className={`cap-meta ${showMeta ? "open" : ""}`}>
          <div className="meta-row">
            <span className="ai-bullet"></span>
            <div>
              <div className="meta-eyebrow">AI · listening</div>
              <div className="meta-text ai">{photo.aiThought}</div>
            </div>
          </div>
          <div className="meta-row meta-cols">
            <div>
              <div className="meta-eyebrow">exposure</div>
              <div className="meta-text mono">{photo.exposure}</div>
            </div>
            <div>
              <div className="meta-eyebrow">coordinates</div>
              <div className="meta-text mono">{photo.coords}</div>
            </div>
            <div>
              <div className="meta-eyebrow">whisper</div>
              <div className="meta-text ital">"{photo.whisper}"</div>
            </div>
          </div>
        </div>
      </div>

      {/* Index strip */}
      <div className="index-strip-v2">
        {photos.map((p, i) => (
          <button
            key={p.id}
            className={`${i === idx ? "active" : ""} ${favs.includes(p.id) ? "favd" : ""}`}
            onClick={() => jumpTo(i)}
            data-cursor
            aria-label={`darshan ${p.id}`}
          ></button>
        ))}
      </div>

      <div className="gallery-nav-v2">
        <button className="prev" onClick={() => go(-1)} data-cursor>
          <span className="arrow"></span>
          <span>previous</span>
        </button>
        <div className="nav-center">
          <span>{idx + 1} / {photos.length} · take your time.</span>
        </div>
        <button className="next" onClick={() => go(1)} data-cursor>
          <span>next</span>
          <span className="arrow"></span>
        </button>
      </div>

      {/* Help overlay */}
      {showHelp && (
        <div className="help-overlay" onClick={dismissHelp}>
          <div className="help-card" onClick={e => e.stopPropagation()}>
            <div className="help-eyebrow">— a small map —</div>
            <h3 className="help-title">how to walk this gallery</h3>
            <div className="help-rows">
              <div className="help-row">
                <span className="key"><kbd>←</kbd><kbd>→</kbd></span>
                <span>walk between photographs</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>scroll</kbd></span>
                <span>also works · the gallery is gentle</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>F</kbd></span>
                <span>hold a photograph close</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>S</kbd></span>
                <span>share a photograph, gently</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>I</kbd></span>
                <span>open exposure, coordinates &amp; whisper</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>?</kbd></span>
                <span>open this map again</span>
              </div>
              <div className="help-row">
                <span className="key"><kbd>esc</kbd></span>
                <span>return to the threshold</span>
              </div>
            </div>
            <button className="help-dismiss" onClick={dismissHelp} data-cursor>
              i have walked galleries before  →
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

window.Gallery = Gallery;
