/* ==========================================================
   大安梟婆宮 — 全站共用 chrome
   TopBar / Footer / IntroOverlay / MusicPlayer
   ========================================================== */

/* ---------- TopBar (跨頁) ----------
   props: current = "home" | "fortune" | "donate"
*/
const TopBar = ({current = "home"}) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  React.useEffect(() => {
    const onResize = () => {
      if (window.innerWidth > 980) setMenuOpen(false);
    };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  /* 跨頁的錨點需要絕對指到 index.html */
  const home = (anchor) => current === "home" ? `#${anchor}` : `index.html#${anchor}`;

  const nav = [
    { href: home("origin"), label: "沿　革" },
    { href: home("deity"),  label: "神　祇" },
    { href: "fortune.html", label: "求　籤",   key: "fortune" },
    { href: "donate.html",  label: "綠界廟",   key: "donate"  },
    { href: home("events"), label: "法　會" },
    { href: home("visit"),  label: "參拜資訊" },
  ];

  return (
    <header className={"topbar" + (scrolled ? " scrolled" : "") + (menuOpen ? " menu-open" : "")}>
      <a className="brand" href="index.html">
        <img src="assets/logo.png" alt="大安梟婆宮" />
        <div className="name">
          大安梟婆宮
          <span className="small">DA·AN  XIAO·PO  GONG  EST. 2020</span>
        </div>
      </a>
      <button
        type="button"
        className="menu-toggle"
        aria-label={menuOpen ? "關閉選單" : "開啟選單"}
        aria-expanded={menuOpen}
        onClick={() => setMenuOpen(!menuOpen)}
      >
        <span></span>
        <span></span>
        <span></span>
      </button>
      <nav aria-label="主選單">
        <ul>
          {nav.map((n, i) => (
            <li key={i}>
              <a href={n.href}
                 onClick={() => setMenuOpen(false)}
                 className={current === n.key ? "active" : ""}>
                {n.label}
              </a>
            </li>
          ))}
        </ul>
      </nav>
      <a href="donate.html" className="cta" onClick={() => setMenuOpen(false)}>
        <span className="icn">⚯</span>線上參拜
      </a>
    </header>
  );
};

/* ---------- Footer (跨頁) ---------- */
const Footer = () => (
  <footer className="foot">
    <div className="wrap foot-grid">
      <div className="foot-brand">
        <img src="assets/logo.png" alt="大安梟婆宮" />
        <div className="name">大安梟婆宮</div>
        <div className="lat">DA·AN  XIAO·PO  GONG  ·  EST. 2020</div>
        <p>
          夜啼為號，香煙為信。<br/>
          奉祀梟婆神娘娘 · 貓頭鷹形 · 夜行庇民。<br/>
          凡入廟者，敬上一炷清香，諸事順遂。
        </p>
      </div>
      <div className="foot-col">
        <h5>關於本宮</h5>
        <ul>
          <li><a href="index.html#origin">沿革傳說</a></li>
          <li><a href="index.html#deity">主祀神祇</a></li>
          <li><a href="index.html#events">法會活動</a></li>
          <li><a href="index.html#visit">交通指引</a></li>
        </ul>
      </div>
      <div className="foot-col">
        <h5>線上服務</h5>
        <ul>
          <li><a href="fortune.html">線上求籤</a></li>
          <li><a href="donate.html">綠界廟參拜</a></li>
          <li><a href="donate.html#lamps">點光明燈</a></li>
          <li><a href="donate.html#lucky">梟婆財運卦</a></li>
        </ul>
      </div>
      <div className="foot-col">
        <h5>聯繫敬問</h5>
        <ul>
          <li><a href="#">服務台：廟埕服務台</a></li>
          <li><a href="mailto:tobarana.yenz@gmail.com">tobarana.yenz@gmail.com</a></li>
          <li><a href="https://discord.gg/ainomori" target="_blank" rel="noopener noreferrer">discord.gg/ainomori</a></li>
          <li className="social-icons" aria-label="社群連結">
            <a href="https://www.youtube.com/@RanaVTB" target="_blank" rel="noopener noreferrer" aria-label="YouTube">
              <img src="https://cdn.simpleicons.org/youtube/D6B878" alt="" />
            </a>
            <a href="https://www.twitch.tv/tobarana" target="_blank" rel="noopener noreferrer" aria-label="Twitch">
              <img src="https://cdn.simpleicons.org/twitch/D6B878" alt="" />
            </a>
            <a href="https://x.com/RanaVtb" target="_blank" rel="noopener noreferrer" aria-label="X">
              <img src="https://cdn.simpleicons.org/x/D6B878" alt="" />
            </a>
            <a href="https://www.instagram.com/RanaVtb/" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
              <img src="https://cdn.simpleicons.org/instagram/D6B878" alt="" />
            </a>
            <a href="https://www.facebook.com/RanaVtb/" target="_blank" rel="noopener noreferrer" aria-label="Facebook">
              <img src="https://cdn.simpleicons.org/facebook/D6B878" alt="" />
            </a>
          </li>
        </ul>
      </div>
    </div>
    <div className="wrap foot-bottom">
      <span>© 2020 – 2026　大安梟婆宮 管理委員會　謹啟　·　tobarana.com</span>
      <span className="est">EST. 2020  ·  夜啼為號  ·  雲端有靈</span>
    </div>
  </footer>
);

/* ---------- IntroOverlay 進站動畫 ---------- */
const IntroOverlay = ({onOpen, onEnter}) => {
  const videoRef = React.useRef(null);
  const [show, setShow] = React.useState(() => {
    try {
      if (new URLSearchParams(window.location.search).has("intro")) {
        sessionStorage.removeItem("xpg_intro_seen");
      }
      return !sessionStorage.getItem("xpg_intro_seen");
    }
    catch (e) { return true; }
  });
  const [opening, setOpening] = React.useState(false);
  const [leaving, setLeaving] = React.useState(false);

  if (!show) return null;

  const enter = () => {
    setOpening(true);
    onOpen && onOpen();
    try {
      const video = videoRef.current;
      if (video) {
        video.currentTime = 0;
        video.play().catch(() => {});
      }
    } catch (e) {}
    setTimeout(() => setLeaving(true), 3600);
    setTimeout(() => {
      try { sessionStorage.setItem("xpg_intro_seen", "1"); } catch (e) {}
      setShow(false);
      onEnter && onEnter();
    }, 4500);
  };

  const skip = () => {
    try { sessionStorage.setItem("xpg_intro_seen", "1"); } catch (e) {}
    setShow(false);
  };

  return (
    <div className={
      "intro" + (opening ? " opening" : "") + (leaving ? " leaving" : "")
    }>
      <div className="intro-backdrop" aria-hidden="true"></div>
      <video
        ref={videoRef}
        className="intro-door"
        src="assets/door-opening-transparent.webm"
        muted
        playsInline
        preload="auto"
        aria-hidden="true"
      ></video>
      <div className="core">
        <div className="logo-wrap">
          <img src="assets/logo.png" alt="大安梟婆宮" />
        </div>
        <div className="ch">大安梟婆宮</div>
        <div className="en">DA·AN  XIAO·PO  GONG</div>
        <button className="enter" onClick={enter}>
          <span className="stamp"></span>
          敬　入　廟　堂
          <span className="stamp"></span>
        </button>
      </div>
      <button className="skip" onClick={skip}>SKIP →</button>
    </div>
  );
};

/* ---------- MusicPlayer 跨頁背景音 — 單顆按鈕版 ----------
   - 進度存 sessionStorage (xpg_audio_time)
   - 播放狀態存 sessionStorage (xpg_audio_playing)
*/
const MusicPlayer = React.forwardRef((props, ref) => {
  const audioRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const musicVolume = 0.3;

  React.useImperativeHandle(ref, () => ({
    play: () => {
      const a = audioRef.current;
      if (!a) return;
      a.volume = musicVolume;
      a.play().then(() => setPlaying(true)).catch(() => {});
    },
  }));

  React.useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    a.volume = musicVolume;
    try {
      const t = parseFloat(sessionStorage.getItem("xpg_audio_time") || "0");
      if (!isNaN(t) && t > 0) a.currentTime = t;
    } catch (e) {}
    try {
      if (sessionStorage.getItem("xpg_audio_playing") === "1") {
        a.play().then(() => setPlaying(true)).catch(() => setPlaying(false));
      }
    } catch (e) {}

    const onTime = () => {
      setProgress(a.duration ? a.currentTime / a.duration : 0);
      try { sessionStorage.setItem("xpg_audio_time", String(a.currentTime)); } catch (e) {}
    };
    const onPlay  = () => { setPlaying(true);
      try { sessionStorage.setItem("xpg_audio_playing", "1"); } catch (e) {} };
    const onPause = () => { setPlaying(false);
      try { sessionStorage.setItem("xpg_audio_playing", "0"); } catch (e) {} };
    a.addEventListener("timeupdate", onTime);
    a.addEventListener("play", onPlay);
    a.addEventListener("pause", onPause);
    return () => {
      a.removeEventListener("timeupdate", onTime);
      a.removeEventListener("play", onPlay);
      a.removeEventListener("pause", onPause);
    };
  }, []);

  const toggle = () => {
    const a = audioRef.current;
    if (!a) return;
    a.volume = musicVolume;
    if (a.paused) a.play().catch(() => {});
    else a.pause();
  };

  const C = 2 * Math.PI * 35; // r=35

  return (
    <div className="music">
      <button
        className={"music-toggle" + (playing ? " playing" : "")}
        onClick={toggle}
        aria-label={playing ? "暫停音樂" : "播放音樂"}
      >
        <svg className="ring-progress" viewBox="0 0 76 76">
          <circle cx="38" cy="38" r="35" stroke="rgba(184,146,74,0.25)"
                  fill="none" strokeWidth="2"/>
          <circle cx="38" cy="38" r="35" stroke="var(--gold-l)"
                  fill="none" strokeWidth="2"
                  strokeDasharray={C}
                  strokeDashoffset={(1 - progress) * C}
                  strokeLinecap="round"
                  style={{transition: "stroke-dashoffset .3s linear"}}/>
        </svg>
        {playing
          ? <svg className="icon" viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
          : <svg className="icon" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>}
      </button>
      <audio ref={audioRef} src="assets/music.mp3" preload="auto" loop></audio>
    </div>
  );
});

/* ---------- 共用 Toast ---------- */
const Toast = ({msg, sub}) => (
  <div className={"toast" + (msg ? " show" : "")}>
    <span className="tag">梟婆有應</span>
    <span>{msg}</span>
    {sub && <span style={{opacity: 0.6, marginLeft: 14, letterSpacing: "0.15em", fontSize: 12}}>{sub}</span>}
  </div>
);

/* ---------- Chrome 容器 ---------- */
const Chrome = ({current, children}) => {
  const musicRef = React.useRef();
  const [walkingIn, setWalkingIn] = React.useState(false);
  const [toast, setToast] = React.useState({msg:"", sub:""});
  const timer = React.useRef();

  const showToast = (msg, sub) => {
    setToast({msg, sub});
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setToast({msg:"", sub:""}), 3000);
  };

  /* 把 showToast 透過 context-like 全域注入 */
  window.__xpgToast = showToast;

  return (
    <React.Fragment>
      <IntroOverlay
        onOpen={() => {
          setWalkingIn(true);
          setTimeout(() => setWalkingIn(false), 4600);
        }}
        onEnter={() => {
          musicRef.current && musicRef.current.play();
        }}
      />
      <div className={"site-stage" + (walkingIn ? " walking-in" : "")}>
        <TopBar current={current} />
        {children}
        <Footer />
      </div>
      <MusicPlayer ref={musicRef} />
      <Toast msg={toast.msg} sub={toast.sub} />
    </React.Fragment>
  );
};

Object.assign(window, { TopBar, Footer, IntroOverlay, MusicPlayer, Chrome, Toast });
