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

function Portal({ onEnter }) {
  const [phraseIdx, setPhraseIdx] = useState(0);
  const [fading, setFading] = useState(false);
  const phrases = window.PORTAL_PHRASES || [""];
  const ringRef = useRef(null);
  const scrollRef = useRef(null);
  const [radius, setRadius] = useState(240);
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const measure = () => {
      const el = ringRef.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const size = Math.min(r.width, r.height);
      setRadius(Math.max(150, size * 0.5));
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setScrollY(el.scrollTop));
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => {el.removeEventListener("scroll", onScroll);cancelAnimationFrame(raf);};
  }, []);

  useEffect(() => {
    const iv = setInterval(() => {
      setFading(true);
      setTimeout(() => {
        setPhraseIdx((i) => (i + 1) % phrases.length);
        setFading(false);
      }, 1100);
    }, 4200);
    return () => clearInterval(iv);
  }, [phrases.length]);

  // scroll-reveal effect on sections
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) e.target.classList.add("revealed");});
    }, { threshold: 0.12, root: scrollRef.current });
    document.querySelectorAll('.reveal').forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  const thresholds = [
  { key: "gallery", dev: "दर्शन", en: "Gallery", meta: "the archive of glances", angle: -90 },
  { key: "themes", dev: "विषय", en: "Themes", meta: "philosophical explorations", angle: -30 },
  { key: "prints", dev: "मुद्रण", en: "Prints", meta: "owning fragments of silence", angle: 30 },
  { key: "journal", dev: "लेखन", en: "Journal", meta: "thoughts from wandering", angle: 90 },
  { key: "about", dev: "परिचय", en: "About", meta: "the witness behind the lens", angle: 150 },
  { key: "feedback", dev: "प्रतिक्रिया", en: "Feedback", meta: "leave emotional residue", angle: 210 }];


  const all = window.DARSHAN || [];

  // Five curated photographs become the editorial "preface" spreads.
  // The remaining fifteen drift below as a horizontal ribbon (all twenty visible).
  const featured = [all[0], all[3], all[10], all[6], all[15]].filter(Boolean);
  const driftLane = all; // marquee shows all twenty

  const themePreviews = [
  { key: "street", dev: "मार्ग", en: "Street", photo: all[10], line: "the city is a slow scripture" },
  { key: "travel", dev: "यात्रा", en: "Travel", photo: all[6], line: "every road is a small pilgrimage" },
  { key: "documentary", dev: "साक्ष्य", en: "Documentary", photo: all[4], line: "to witness is the oldest verb" },
  { key: "nature", dev: "प्रकृति", en: "Nature", photo: all[15], line: "the divine wears weather today" },
  { key: "sacred", dev: "पावन", en: "The Sacred", photo: all[11], line: "ordinary things, lit from inside" }];


  return (
    <div className="portal-scroll" ref={scrollRef}>

      {/* ─── Act I · HERO — pure text composition, small ॐ above ─── */}
      <section className="hero">
        <div
          className="hero-stage"
          style={{
            transform: `translateY(${-scrollY * 0.15}px)`,
            opacity: Math.max(0, 1 - scrollY / 600)
          }}>
          
          <div className="hero-om-small"></div>

          <div className="hero-eyebrow">
            <span className="rule"></span>
            <span>दर्शन · sacred seeing</span>
            <span className="rule"></span>
          </div>

          <h1 className="hero-message">
            <span className="line-1">welcome, traveller —</span>
            <span className="line-2">you have been <em>seen</em>,</span>
            <span className="line-3">long before you arrived.</span>
          </h1>

          <p className="hero-blessing" style={{ textAlign: "center", fontFamily: "\"JetBrains Mono\"" }}>
            THESE PHOTOGRAPHS WERE MADE WITH ONE BEATING HEART, AND THEY WILL OPEN TO ANOTHER.
            <br />
            and they will only open to another.
          </p>

          <div className={`hero-mutate ${fading ? "fading" : ""}`}>
            — {phrases[phraseIdx]} —
          </div>
        </div>

        {/* Scroll cue */}
        <div className="hero-down">
          <span>scroll, gently</span>
          <span className="line"></span>
        </div>
      </section>

      {/* ─── Act II · The Twenty — editorial preface + drifting ribbon ─── */}
      <section className="twenty reveal">
        <div className="twenty-head">
          <div className="twenty-tag">
            <span>·  i.  ·</span>
            <span>विंशति — the twenty</span>
          </div>
          <h2 className="twenty-title">
            an archive of <em>my photographs</em> —
          </h2>
          <p className="twenty-sub">
            MADE ON FOOT ACROSS BHARAT, BETWEEN SPANS OF 5 YEARS <br />
            five glances below — the remaining fifteen drift past at the bottom.
          </p>
        </div>

        {/* Editorial spreads — five curated photographs at varied scales */}
        <div className="spreads">
          {/* spread I — asymmetric pair */}
          {featured[0] && featured[1] &&
          <div className="spread spread-pair">
              <figure className="sp-fig sp-feature" onClick={() => onEnter("gallery")} data-cursor>
                <div className="sp-fig-img">
                  <img src={featured[0].file} alt={featured[0].title} loading="lazy" />
                </div>
                <figcaption>
                  <div className="sp-num">№ {featured[0].id}</div>
                  <div className="sp-cap">
                    <span className="sp-dev">{featured[0].dev}</span>
                    <span className="sp-ttl">{featured[0].title}</span>
                  </div>
                  <div className="sp-place">{featured[0].place} · {featured[0].year}</div>
                </figcaption>
              </figure>

              <figure className="sp-fig sp-side" onClick={() => onEnter("gallery")} data-cursor>
                <div className="sp-fig-img">
                  <img src={featured[1].file} alt={featured[1].title} loading="lazy" />
                </div>
                <figcaption>
                  <div className="sp-num">№ {featured[1].id}</div>
                  <div className="sp-cap">
                    <span className="sp-dev">{featured[1].dev}</span>
                    <span className="sp-ttl">{featured[1].title}</span>
                  </div>
                  <div className="sp-place">{featured[1].place} · {featured[1].year}</div>
                </figcaption>
              </figure>
            </div>
          }

          {/* spread II — single full-bleed wide */}
          {featured[2] &&
          <div className="spread spread-bleed">
              <figure className="sp-fig sp-bleed" onClick={() => onEnter("gallery")} data-cursor>
                <div className="sp-fig-img">
                  <img src={featured[2].file} alt={featured[2].title} loading="lazy" />
                </div>
                <figcaption>
                  <div className="sp-num">№ {featured[2].id}</div>
                  <div className="sp-cap">
                    <span className="sp-dev">{featured[2].dev}</span>
                    <span className="sp-ttl">{featured[2].title}</span>
                  </div>
                  <div className="sp-place">{featured[2].place} · {featured[2].year}</div>
                </figcaption>
              </figure>
            </div>
          }

          {/* spread III — pair + inline epigraph */}
          {featured[3] && featured[4] &&
          <div className="spread spread-tryp">
              <figure className="sp-fig sp-third" onClick={() => onEnter("gallery")} data-cursor>
                <div className="sp-fig-img">
                  <img src={featured[3].file} alt={featured[3].title} loading="lazy" />
                </div>
                <figcaption>
                  <div className="sp-num">№ {featured[3].id}</div>
                  <div className="sp-cap">
                    <span className="sp-dev">{featured[3].dev}</span>
                    <span className="sp-ttl">{featured[3].title}</span>
                  </div>
                  <div className="sp-place">{featured[3].place} · {featured[3].year}</div>
                </figcaption>
              </figure>

              <blockquote className="sp-epigraph">
                <span className="sp-quote-mark">“</span>
                <p>each frame is asking <em>for one breath,</em><br />no more — and no less.</p>
                <span className="sp-quote-attr">— a note pinned above the darkroom</span>
              </blockquote>

              <figure className="sp-fig sp-third" onClick={() => onEnter("gallery")} data-cursor>
                <div className="sp-fig-img">
                  <img src={featured[4].file} alt={featured[4].title} loading="lazy" />
                </div>
                <figcaption>
                  <div className="sp-num">№ {featured[4].id}</div>
                  <div className="sp-cap">
                    <span className="sp-dev">{featured[4].dev}</span>
                    <span className="sp-ttl">{featured[4].title}</span>
                  </div>
                  <div className="sp-place">{featured[4].place} · {featured[4].year}</div>
                </figcaption>
              </figure>
            </div>
          }
        </div>

        {/* Drifting ribbon — every photograph passes through, slowly */}
        <div className="drift-band">
          <div className="drift-band-head">
            <span className="rule"></span>
            <span className="dev">सर्व</span>
            <span>all twenty — drifting past</span>
            <span className="rule"></span>
          </div>
          <Marquee lane={driftLane} speed={120} direction="left" />
        </div>

        <button className="twenty-cta" onClick={() => onEnter("gallery")} data-cursor>
          <span className="dev">दर्शन</span>
          <span>walk all twenty, slowly</span>
          <span className="arrow">→</span>
        </button>
      </section>

      {/* ─── Act IV · the five themes (philosophical chapters) ─── */}
      <section className="themes reveal">
        <div className="section-head">
          <div className="section-tag">
            <span>·  ii.  ·</span>
            <span>विषय — the five chambers</span>
          </div>
          <h2 className="section-title">Five exploration, one looking.</h2>
          <p className="section-sub">the work is gathered into five philosophical chapters — each a slow river, not a category.</p>
        </div>

        <div className="theme-grid">
          {themePreviews.map((t, i) =>
          <button
            key={t.key}
            className="theme-card"
            onClick={() => onEnter("themes")}
            data-cursor
            style={{ "--i": i }}>
            
              <div className="theme-img">
                <img src={t.photo?.file} alt={t.en} loading="lazy" style={{ objectFit: "cover" }} />
                <div className="theme-overlay"></div>
              </div>
              <div className="theme-meta">
                <div className="theme-num">{String(i + 1).padStart(2, "0")}</div>
                <div className="theme-titles">
                  <span className="dev">{t.dev}</span>
                  <span className="en">{t.en}</span>
                </div>
              </div>
              <div className="theme-line">— {t.line}</div>
            </button>
          )}
        </div>
      </section>

      {/* ─── Act V · the yantra — the spiritual portal ─── */}
      <section className="act-yantra reveal">
        <div className="section-head">
          <div className="section-tag">
            <span>·  iii.  ·</span>
            <span>द्वारम् — the six thresholds</span>
          </div>
          <h2 className="section-title">choose <em>where</em> to enter.</h2>
          <p className="section-sub">each chamber holds the same archive, lit from a different angle.</p>
        </div>

        <div className="threshold-ring" ref={ringRef}>
          <Yantra />
          <div className="center">ॐ</div>
          {thresholds.map((t) => {
            const rad = t.angle * Math.PI / 180;
            const x = Math.cos(rad) * radius;
            const y = Math.sin(rad) * radius;
            return (
              <button
                key={t.key}
                className="threshold"
                onClick={() => onEnter(t.key)}
                data-cursor="threshold"
                style={{
                  transform: `translate(${x}px, ${y}px) translate(-50%, -50%)`,
                  top: "50%", left: "50%",
                  background: "none", border: "none", color: "inherit",
                  cursor: "none"
                }}>
                
                <span className="label-dev">{t.dev}</span>
                <span className="label-en">{t.en}</span>
                <span className="label-meta">{t.meta}</span>
              </button>);

          })}
        </div>

        <div className="yantra-foot">
          <span>“ darshan — to see, and in seeing, be seen ”</span>
        </div>
      </section>

      {/* ─── Act VI · the witness ─── */}
      <section className="witness reveal">
        <div className="section-head">
          <div className="section-tag">
            <span>·  iv.  ·</span>
            <span>परिचय — the witness</span>
          </div>
        </div>
        <div className="witness-body">
          <div className="witness-photo">
            <img src={all[2]?.file} alt="" />
            <div className="witness-photo-tag">
              <span className="dev">{all[2]?.dev}</span>
              <span>{all[2]?.place}</span>
            </div>
          </div>
          <div className="witness-text">
            <h3 className="witness-name">Rahul Malviya</h3>
            <p className="witness-bio">
              I work in street, travel, and documentary photography — and I love
              the quiet detail shots of nature. It has been <em>five years</em> since
              I first held my Fujifilm X-T200; photography has been the ride that
              taught me to see life with a different lens.
            </p>
            <p className="witness-bio">
              This site is a souvenir to the world: a small, organised
              reflection of mine, so that you may see a fragment of what I have
              been lucky enough to witness.
            </p>
            <div className="witness-stats">
              <div><b>5</b><span>years</span></div>
              <div><b>9</b><span>cities</span></div>
              <div><b>20</b><span>photographs</span></div>
              <div><b>1</b><span>camera</span></div>
            </div>
          </div>
        </div>
      </section>

      {/* ─── Final invitation ─── */}
      <section className="final reveal">
        <div className="final-rule"></div>
        <h2 className="final-call">
          enter the gallery —<br />
          <em>walk slowly, please.</em>
        </h2>
        <button className="final-cta" onClick={() => onEnter("gallery")} data-cursor>
          <span className="dev">दर्शन</span>
          <span>begin the seeing</span>
          <span className="arrow">→</span>
        </button>
        <div className="final-signature">
          <div className="signature-name">
            <span className="dev">राहुल मालविया</span>
            <span className="en">Rahul Malviya</span>
          </div>
          <div className="signature-sub">
            fujifilm x-t200 · five years on the road · still learning to look.
          </div>
          <div className="signature-foot">
            MMXX — MMXXVI · दर्शन · all photographs made with permission, gratitude, and bare feet.
          </div>
        </div>
      </section>
    </div>);

}

function Marquee({ lane, speed, direction, scrollY }) {
  const doubled = [...lane, ...lane, ...lane];
  return (
    <div className={`marquee marquee-${direction}`} style={{ "--speed": `${speed}s` }}>
      <div className="marquee-track">
        {doubled.map((p, i) =>
        <figure className="marquee-card" key={`${p.id}-${i}`}>
            <img src={p.file} alt={p.title} draggable="false" loading="lazy" />
            <figcaption>
              <span className="dev">{p.dev}</span>
              <span className="place">{p.place}</span>
            </figcaption>
          </figure>
        )}
      </div>
    </div>);

}

function Yantra() {
  return (
    <svg className="yantra" viewBox="-100 -100 200 200" preserveAspectRatio="xMidYMid meet">
      <defs>
        <radialGradient id="yg" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#c9a96a" stopOpacity="0.05" />
          <stop offset="60%" stopColor="#6a5a8a" stopOpacity="0.10" />
          <stop offset="100%" stopColor="#6a5a8a" stopOpacity="0" />
        </radialGradient>
      </defs>
      <circle cx="0" cy="0" r="95" fill="url(#yg)" />
      <circle cx="0" cy="0" r="95" fill="none" stroke="#c9a96a" strokeOpacity="0.18" strokeWidth="0.4" />
      <circle cx="0" cy="0" r="80" fill="none" stroke="#c9a96a" strokeOpacity="0.14" strokeWidth="0.3" />
      <circle cx="0" cy="0" r="60" fill="none" stroke="#c9a96a" strokeOpacity="0.20" strokeWidth="0.3" strokeDasharray="1 3" />
      <circle cx="0" cy="0" r="36" fill="none" stroke="#c9a96a" strokeOpacity="0.28" strokeWidth="0.4" />
      <polygon points="0,-70 60.6,35 -60.6,35" fill="none" stroke="#c9a96a" strokeOpacity="0.22" strokeWidth="0.3" />
      <polygon points="0,70 -60.6,-35 60.6,-35" fill="none" stroke="#c9a96a" strokeOpacity="0.22" strokeWidth="0.3" />
      <polygon
        points={Array.from({ length: 12 }).map((_, i) => {const a = i / 12 * Math.PI * 2 - Math.PI / 2;return `${(Math.cos(a) * 88).toFixed(2)},${(Math.sin(a) * 88).toFixed(2)}`;}).join(" ")}
        fill="none" stroke="#c9a96a" strokeOpacity="0.12" strokeWidth="0.3" />
      
      {Array.from({ length: 24 }).map((_, i) => {
        const a = i / 24 * Math.PI * 2;
        const x1 = Math.cos(a) * 36,y1 = Math.sin(a) * 36;
        const x2 = Math.cos(a) * 92,y2 = Math.sin(a) * 92;
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="#c9a96a" strokeOpacity="0.08" strokeWidth="0.2" />;
      })}
    </svg>);

}

window.Portal = Portal;