// GameSection.jsx — INTERACTIVE section
// 모바일: 타이틀 프리뷰 + TAP TO PLAY → position:fixed 풀스크린 오버레이
// PC: iframe 직접 임베드 (포인터이벤트 auto)

const GameSection = ({ t, noCanvas }) => {
  const _t = t || ((k) => k);
  const { useState, useEffect, useRef } = React;
  const sectionRef    = useRef(null);
  const gameWrapRef   = useRef(null);
  const [w, setW]     = useState(window.innerWidth);
  const [showOverlay, setShowOverlay] = useState(false);

  useEffect(() => {
    const handler = () => setW(window.innerWidth);
    window.addEventListener("resize", handler, { passive: true });
    return () => window.removeEventListener("resize", handler);
  }, []);
  const isMobile = w < 768;

  const canUseChromeCanvas = typeof window.ChromeCanvas !== "undefined";

  /* ─── 오버레이 열기 ─── */
  const enterGame = async () => {
    const el = gameWrapRef.current;
    // Android Chrome: native fullscreen 시도
    if (el) {
      const fs = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen;
      if (fs) {
        try {
          await fs.call(el);
          // native fullscreen 성공: 헤더 숨기기
          document.body.classList.add('game-overlay-open');
          return; // 성공하면 CSS 오버레이 불필요
        } catch (_) { /* iOS는 여기서 실패 → 아래 CSS 방식으로 */ }
      }
    }
    // iOS / 기타: position:fixed CSS 오버레이
    setShowOverlay(true);
    document.body.classList.add('game-overlay-open');
    document.body.style.setProperty('overflow', 'hidden', 'important');
  };

  /* ─── 오버레이 닫기 ─── */
  const exitGame = () => {
    setShowOverlay(false);
    // 헤더 다시 표시
    document.body.classList.remove('game-overlay-open');
    // 스크롤 락 완전 해제
    ['overflow','height','position'].forEach(p => {
      document.body.style.removeProperty(p);
      document.documentElement.style.removeProperty(p);
    });
    document.body.style.touchAction = '';
    document.documentElement.style.touchAction = '';
    screen.orientation?.unlock?.();
    // 브라우저가 스크롤 상태를 재계산하도록 nudge
    setTimeout(() => {
      window.scrollTo(window.scrollX, window.scrollY + 1);
      window.scrollTo(window.scrollX, window.scrollY - 1);
    }, 80);
  };

  /* fullscreenchange (Android) → exitGame */
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") exitGame(); };
    const onFS  = () => { if (!document.fullscreenElement && !document.webkitFullscreenElement) exitGame(); };
    window.addEventListener("keydown", onKey);
    document.addEventListener("fullscreenchange", onFS);
    document.addEventListener("webkitfullscreenchange", onFS);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.removeEventListener("fullscreenchange", onFS);
      document.removeEventListener("webkitfullscreenchange", onFS);
    };
  }, []);

  return (
    <>
      {/* 게임 오버레이 활성화 시 nav 헤더 숨기기 */}
      <style>{`
        body.game-overlay-open header,
        body.game-overlay-open nav { display: none !important; }
      `}</style>
      {/* ═══════════════════════════════════════════
          모바일 전체화면 오버레이 (iOS 포함)
          — 기기를 가로로 돌리면 자연스럽게 landscape
          ═══════════════════════════════════════════ */}
      {showOverlay && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 9999,
          background: "#000",
        }}>
          <iframe
            src="game.html"
            style={{ width: "100%", height: "100%", border: "none", display: "block" }}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; pointer-lock; fullscreen"
            allowFullScreen
          />
          <button onClick={exitGame} style={{
            position: "fixed", top: 14, right: 14, zIndex: 10000,
            background: "rgba(0,0,0,0.75)", border: "1px solid rgba(255,255,255,0.25)",
            color: "#fff", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
            padding: "7px 14px", cursor: "pointer", fontFamily: "'Inter',sans-serif",
            borderRadius: 2, lineHeight: 1,
          }}>
            ✕ CLOSE
          </button>
        </div>
      )}

      <section
        id="game"
        ref={sectionRef}
        style={{
          position: "relative",
          background: noCanvas ? "transparent" : "#C8CACC",
          cursor: "crosshair",
          overflow: "hidden",
        }}
      >
        {!noCanvas && canUseChromeCanvas && <window.ChromeCanvas sectionRef={sectionRef} />}

        <div style={{ position: "relative", zIndex: 2 }}>

          {/* ─── 헤더 ─── */}
          <div style={{ padding: isMobile ? "64px 24px 40px" : "80px 40px 48px" }}>
            <div style={{
              fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
              fontWeight: 500, color: "rgba(0,0,0,0.45)", marginBottom: 10,
              fontFamily: "'Inter',-apple-system,sans-serif",
            }}>
              {_t("interactiveLabel") || "INTERACTIVE"}
            </div>
            <h2 style={{
              fontSize: "clamp(32px,5vw,48px)", fontWeight: 400, letterSpacing: "-0.02em",
              margin: 0, color: "#0A0A0A", lineHeight: 1.05,
              fontFamily: "'Inter',-apple-system,sans-serif",
            }}>
              {_t("interactiveTitle") || "BEAM: THE LASER STRIKE"}
            </h2>
          </div>

          {/* ─── 게임 프레임 ─── */}
          <div style={{ padding: isMobile ? "0 24px" : "0 40px" }}>
            <div
              ref={gameWrapRef}
              id="game-wrap"
              style={{
                position: "relative",
                width: "100%",
                maxWidth: 1200,
                margin: "0 auto",
                border: "1px solid rgba(0,0,0,0.15)",
                boxShadow: "0 12px 48px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.1)",
                background: "#000",
                aspectRatio: isMobile ? "4/3" : "16/9",
                overflow: "hidden",
              }}
            >
              {/* ── PC: iframe 직접 임베드 ── */}
              {!isMobile && (
                <iframe
                  src="game.html"
                  title="BEAM: THE LASER STRIKE"
                  style={{ width: "100%", height: "100%", border: "none", display: "block", pointerEvents: "auto" }}
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; pointer-lock; fullscreen"
                  allowFullScreen
                  loading="eager"
                />
              )}

              {/* ── 모바일: 타이틀 프리뷰 + TAP TO PLAY ── */}
              {isMobile && (
                <>
                  <img
                    src="game assets/Background image/title-screen.png"
                    alt="BEAM: THE LASER STRIKE"
                    style={{
                      position: "absolute", inset: 0,
                      width: "100%", height: "100%",
                      objectFit: "cover", objectPosition: "center top",
                    }}
                    onError={(e) => { e.target.style.display = "none"; }}
                  />
                  <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.45)" }} />
                  <div
                    onClick={enterGame}
                    style={{
                      position: "absolute", inset: 0, zIndex: 5,
                      display: "flex", flexDirection: "column",
                      alignItems: "center", justifyContent: "center",
                      cursor: "pointer", gap: 14,
                    }}
                  >
                    <div style={{
                      width: 60, height: 60, borderRadius: "50%",
                      border: "1.5px solid rgba(255,255,255,0.8)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                        <polygon points="6 3 20 12 6 21 6 3"/>
                      </svg>
                    </div>
                    <div style={{
                      fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
                      fontWeight: 500, color: "rgba(255,255,255,0.9)",
                      fontFamily: "'Inter',-apple-system,sans-serif",
                    }}>
                      TAP TO PLAY
                    </div>
                    <div style={{
                      fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase",
                      color: "rgba(255,255,255,0.4)", fontFamily: "'Inter',-apple-system,sans-serif",
                    }}>
                      ROTATE DEVICE FOR LANDSCAPE
                    </div>
                  </div>
                </>
              )}
            </div>
          </div>

          {/* ─── 게임 설명 ─── */}
          <div style={{ padding: isMobile ? "40px 24px 64px" : "48px 40px 80px" }}>
            <style>{`
              @media (max-width: 640px) {
                .game-desc-grid { grid-template-columns: 1fr !important; }
                .game-desc-right {
                  border-left: none !important; padding-left: 0 !important;
                  border-top: 1px solid rgba(0,0,0,0.1) !important; padding-top: 32px !important;
                }
              }
            `}</style>
            <div className="game-desc-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: isMobile ? 32 : 48, maxWidth: 1200, margin: "0 auto" }}>
              <div>
                <h3 style={{
                  fontSize: 20, fontWeight: 400, letterSpacing: "-0.01em",
                  margin: "0 0 12px", color: "#0A0A0A",
                  fontFamily: "'Inter',-apple-system,sans-serif",
                }}>
                  BEAM: THE LASER STRIKE
                </h3>
                <p style={{ fontSize: 14, color: "rgba(0,0,0,0.5)", margin: "0 0 20px", lineHeight: 1.7, fontFamily: "Georgia,serif" }}>
                  {_t("interactiveDesc") || "An original 2D arcade game set in the POST(DOT)SERVICE universe. Navigate, fight, and survive — then own the real thing."}
                </p>
                <p style={{
                  fontSize: 11, color: "rgba(0,0,0,0.3)", margin: 0,
                  letterSpacing: "0.08em", textTransform: "uppercase", lineHeight: 2,
                  fontFamily: "'Inter',-apple-system,sans-serif",
                }}>
                  WASD / ARROW — Move<br/>
                  MOUSE — Aim<br/>
                  CLICK — Shoot<br/>
                  SPACE — Kick<br/>
                  R — Reload &nbsp;·&nbsp; E — Interact &nbsp;·&nbsp; ESC — Pause
                </p>
              </div>
              <div className="game-desc-right" style={{ borderLeft: "1px solid rgba(0,0,0,0.1)", paddingLeft: isMobile ? 0 : 48 }}>
                <div style={{
                  fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase",
                  fontWeight: 500, color: "rgba(0,0,0,0.3)", marginBottom: 20,
                  fontFamily: "'Inter',-apple-system,sans-serif",
                }}>
                  GAME INFO
                </div>
                {[
                  ["TITLE",    "BEAM: THE LASER STRIKE"],
                  ["GENRE",    "2D Arcade Shooter"],
                  ["PLATFORM", "Browser · WebGL Canvas"],
                  ["DEVELOPER","POST(DOT)SERVICE"],
                ].map(([k, v]) => (
                  <div key={k} style={{
                    display: "flex", justifyContent: "space-between",
                    padding: "10px 0", borderTop: "1px solid rgba(0,0,0,0.08)",
                    fontSize: 11, letterSpacing: "0.1em",
                    fontFamily: "'Inter',-apple-system,sans-serif",
                  }}>
                    <span style={{ color: "rgba(0,0,0,0.35)", textTransform: "uppercase" }}>{k}</span>
                    <span style={{ color: "rgba(0,0,0,0.75)", textAlign: "right", maxWidth: 220 }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

window.GameSection = GameSection;
