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

// ===== Cursor =====
function CandleCursor() {
  const ref = useRef(null);
  useEffect(() => {
    if (!window.matchMedia("(hover: hover)").matches) return;
    document.body.classList.add("story-mode");
    const move = (e) => {
      if (ref.current) {
        ref.current.style.transform = `translate(${e.clientX}px, ${e.clientY}px) translate(-50%, -50%)`;
      }
    };
    window.addEventListener("mousemove", move);
    return () => {
      window.removeEventListener("mousemove", move);
      document.body.classList.remove("story-mode");
    };
  }, []);
  return <div ref={ref} className="cursor-spark" />;
}

// ===== Scroll progress =====
function ScrollProgress() {
  const [p, setP] = useState(0);
  useEffect(() => {
    const update = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setP(max > 0 ? (h.scrollTop / max) * 100 : 0);
    };
    window.addEventListener("scroll", update, { passive: true });
    update();
    return () => window.removeEventListener("scroll", update);
  }, []);
  return (
    <div className="scroll-progress">
      <div className="scroll-progress-bar" style={{ width: `${p}%` }} />
    </div>
  );
}

// ===== Audio toggle (visual only — no real audio asset) =====
function AudioToggle() {
  const [muted, setMuted] = useState(true);
  return (
    <button
      className={`audio-toggle ${muted ? "muted" : ""}`}
      onClick={() => setMuted(!muted)}
      aria-label={muted ? "Bật âm thanh" : "Tắt âm thanh"}
      title={muted ? "Bật âm thanh dịu nhẹ" : "Tắt âm thanh"}
    >
      <div className="audio-bars">
        <span></span><span></span><span></span><span></span>
      </div>
    </button>
  );
}

// ===== Drift stars =====
function DriftStars({ count = 30 }) {
  const stars = React.useMemo(() => Array.from({ length: count }, () => ({
    left: Math.random() * 100,
    top: Math.random() * 100,
    size: 1 + Math.random() * 2.5,
    delay: Math.random() * 4,
    duration: 3 + Math.random() * 4,
  })), [count]);
  return (
    <div className="star-field">
      {stars.map((s, i) => (
        <div
          key={i}
          className="drift-star"
          style={{
            left: `${s.left}%`,
            top: `${s.top}%`,
            width: `${s.size}px`,
            height: `${s.size}px`,
            animationDelay: `${s.delay}s`,
            animationDuration: `${s.duration}s`,
          }}
        />
      ))}
    </div>
  );
}

// ===== Petals =====
function Petals({ count = 14 }) {
  const petals = React.useMemo(() => Array.from({ length: count }, (_, i) => ({
    left: Math.random() * 100,
    delay: Math.random() * 12,
    duration: 10 + Math.random() * 8,
    size: 0.6 + Math.random() * 0.8,
  })), [count]);
  return (
    <>
      {petals.map((p, i) => (
        <div
          key={i}
          className="petal"
          style={{
            left: `${p.left}%`,
            top: 0,
            transform: `scale(${p.size})`,
            animationDelay: `-${p.delay}s`,
            animationDuration: `${p.duration}s`,
          }}
        />
      ))}
    </>
  );
}

// ===== Scene: Breath =====
function SceneBreath() {
  return (
    <section className="story-section scene-breath" data-screen-label="01 Breath">
      <div className="breath-orb"><div className="breath-orb-ring"></div></div>
      <DriftStars count={40} />
      <div className="breath-content">
        <div className="breath-eyebrow">Holy Dan · Một khoảng tĩnh</div>
        <div className="breath-script">
          <span className="line">Hít vào.</span>
          <span className="line">Thở ra.</span>
          <span className="line">Bạn đang ở đây.</span>
        </div>
        <div className="breath-sub">Hành trình bắt đầu từ một hơi thở</div>
      </div>
      <div className="scroll-cue">Cuộn xuống</div>
    </section>
  );
}

// ===== Scene: Door (sticky scroll-driven) =====
function SceneDoor() {
  const sectionRef = useRef(null);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Phase 0-0.4: door appears, dim
  // Phase 0.4-0.7: light grows, door scales, text appears
  // Phase 0.7-1: door opens (rotates) and brightens
  const lightProg = Math.max(0, Math.min(1, (progress - 0.2) / 0.6));
  const doorScale = 1 + progress * 0.8;
  const doorOpenY = progress > 0.7 ? (progress - 0.7) / 0.3 : 0;
  const textOpacity = Math.max(0, Math.min(1, (progress - 0.15) / 0.3));
  const doorOpacity = 1 - doorOpenY;

  return (
    <section
      ref={sectionRef}
      className="story-section scene-door"
      data-screen-label="02 Door"
      style={{ "--door-progress": lightProg }}
    >
      <div className="door-sticky">
        <div className="door-bg-glow"></div>

        <div
          className="door-text door-text--left"
          style={{ opacity: textOpacity, transform: `translateY(-50%) translateX(${(1 - textOpacity) * -20}px)` }}
        >
          <div className="door-eyebrow">Trước cánh cửa</div>
          <h2><em>Bạn</em> mang theo gì<br />đến đây?</h2>
          <p>Một câu hỏi chưa kịp gọi tên. Một cảm xúc bị giấu đi quá lâu. Một quyết định đang đợi bạn nhìn rõ.</p>
        </div>

        <div
          className="door-frame"
          style={{
            transform: `scale(${doorScale}) translateY(${doorOpenY * -120}vh)`,
            opacity: doorOpacity,
            transition: "opacity 0.3s ease",
          }}
        >
          <div className="door-arch">
            <div className="door-light"></div>
            <div className="door-inner">
              <div className="door-keyhole"></div>
            </div>
          </div>
        </div>

        <div
          className="door-text door-text--right"
          style={{ opacity: textOpacity, transform: `translateY(-50%) translateX(${(1 - textOpacity) * 20}px)` }}
        >
          <div className="door-eyebrow">Holy Dan</div>
          <h2>Khẽ <em>mở</em><br />một lối vào.</h2>
          <p>Không phán xét. Không vội vàng. Chỉ một không gian để bạn đặt xuống — và lắng nghe chính mình.</p>
        </div>
      </div>
    </section>
  );
}

// ===== Scene: Opening (archway with garden glimpse) =====
function SceneOpening() {
  const sectionRef = useRef(null);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const skyShift = progress * -20;
  const mountShift = progress * -40;
  const treeShift = progress * -60;
  const groundShift = progress * -80;
  const archScale = 1 + progress * 0.3;

  return (
    <section ref={sectionRef} className="story-section scene-opening" data-screen-label="03 Opening">
      <div className="opening-sticky">
        <div
          className="opening-archway"
          style={{ transform: `scale(${archScale})` }}
        >
          <div
            className="garden-layer garden-sky"
            style={{ transform: `translateY(${skyShift}px)` }}
          ></div>
          <div className="garden-sun" style={{ transform: `translateX(-50%) translateY(${skyShift * 0.5}px)` }}></div>
          <div
            className="garden-layer garden-mountains"
            style={{ transform: `translateY(${mountShift}px)` }}
          ></div>
          <div
            className="garden-layer garden-trees"
            style={{ transform: `translateY(${treeShift}px)` }}
          ></div>
          <div
            className="garden-layer garden-ground"
            style={{ transform: `translateY(${groundShift}px)` }}
          ></div>
          <div className="garden-path" style={{ transform: `translateX(-50%) translateY(${groundShift * 0.5}px)` }}></div>
          <Petals count={10} />

          <div className="opening-text">
            <div className="script">
              Bên trong, là một <em>khu vườn</em><br />
              của chính bạn.
            </div>
            <p>Holy Dan đồng hành — không dẫn đường</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== Scene: Garden (reveal Holy Dan, photo strip) =====
function SceneGarden() {
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const ref3 = useRef(null);

  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) e.target.classList.add("in");
      });
    }, { threshold: 0.2 });
    [ref1.current, ref2.current, ref3.current].forEach((el) => el && obs.observe(el));
    return () => obs.disconnect();
  }, []);

  return (
    <section className="story-section scene-garden" data-screen-label="04 Garden">
      <div className="garden-content">
        <div ref={ref1} className="reveal-up">
          <div className="breath-eyebrow" style={{ color: "var(--mystic-gold)", opacity: 1, animation: "none", marginBottom: 28 }}>
            Holy Dan
          </div>
          <h2 className="garden-greeting">
            Tarot là một <em>chiếc gương</em>.<br />
            Đối thoại là <em>cánh cửa</em>.<br />
            Bạn — là khu vườn.
          </h2>
        </div>
        <p ref={ref2} className="garden-sub reveal-up">
          Holy Dan là không gian đồng hành cảm xúc. Tarot là một trong nhiều công cụ — bên cạnh trò chuyện sâu, thiền dẫn và các trải nghiệm chữa lành — Holy Dan dùng để cùng bạn nhìn thấu bản chất vấn đề và lắng nghe chính mình.
        </p>

        <div ref={ref3} className="garden-photo-strip reveal-up">
          <div className="photo-card">
            <div className="photo-card-caption script">Lắng nghe</div>
            <div className="photo-card-label">Soft conversation · candlelight</div>
          </div>
          <div className="photo-card">
            <div className="photo-card-caption script">Phản chiếu</div>
            <div className="photo-card-label">Tarot reading · soft hands</div>
          </div>
          <div className="photo-card">
            <div className="photo-card-caption script">Bình yên</div>
            <div className="photo-card-label">Quiet ritual · linen tablecloth</div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  CandleCursor, ScrollProgress, AudioToggle,
  SceneBreath, SceneDoor, SceneOpening, SceneGarden,
});
