// mobile-preview.jsx — 좌측 하단 버튼 → 모바일(iPhone-style) 프레임으로 현재 페이지 미리보기
// iframe 으로 동일 페이지 로드하므로 미디어 쿼리·인터랙션 모두 그대로 작동

function MobilePreview() {
  const { useState, useEffect } = React;
  // 미리보기 iframe 내부일 때만 렌더 스킵 (재귀 방지) — URL 플래그로 판별
  if (typeof window !== "undefined" && /[?&]__mp=1/.test(window.location.search)) return null;

  const [open, setOpen] = useState(false);
  const [size, setSize] = useState("iphone");
  const [isAdmin, setIsAdmin] = useState(false);

  // Firebase Auth로 관리자 여부 확인 — 관리자만 버튼 표시
  useEffect(() => {
    if (typeof firebase === "undefined") return;
    const unsub = firebase.auth().onAuthStateChanged(function(user) {
      if (!user) { setIsAdmin(false); return; }
      firebase.firestore().collection("users").doc(user.uid).get().then(function(doc) {
        setIsAdmin(doc.exists && doc.data().isAdmin === true);
      }).catch(function() { setIsAdmin(false); });
    });
    return function() { unsub(); };
  }, []); // iphone / android / tablet

  // ESC로 닫기
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const presets = {
    iphone:  { w: 390, h: 844, label: "iPhone", bezel: 14, radius: 44 },
    android: { w: 412, h: 915, label: "Android", bezel: 10, radius: 34 },
    tablet:  { w: 768, h: 1024, label: "Tablet", bezel: 16, radius: 28 },
  };
  const p = presets[size];

  // 페이지를 가득 채울 수 있는 scale 계산
  const margin = 80;
  const maxH = typeof window !== "undefined" ? Math.max(400, window.innerHeight - margin) : 800;
  const maxW = typeof window !== "undefined" ? Math.max(360, window.innerWidth - margin) : 480;
  const frameH = p.h + p.bezel * 2;
  const frameW = p.w + p.bezel * 2;
  const scale = Math.min(1, maxH / frameH, maxW / frameW);

  if (!isAdmin) return null;

  return (
    <React.Fragment>
      {/* 토글 버튼 — 좌측 하단 (Tweaks 패널 우측 하단과 충돌 방지) */}
      <button
        data-noncommentable=""
        onClick={() => setOpen(true)}
        style={{
          position: "fixed", left: 18, bottom: 18, zIndex: 9000,
          background: "var(--ink, #1a2238)", color: "white", border: 0,
          padding: "11px 16px", borderRadius: 999,
          fontWeight: 700, fontSize: 13, cursor: "pointer",
          fontFamily: "var(--font-sans, sans-serif)",
          boxShadow: "0 14px 30px -10px rgba(20,30,60,0.4)",
          display: "inline-flex", alignItems: "center", gap: 8,
        }}
        title="모바일 미리보기">
        📱 모바일 미리보기
      </button>

      {open && (
        <div
          data-noncommentable=""
          onClick={() => setOpen(false)}
          style={{
            position: "fixed", inset: 0, zIndex: 9500,
            background: "rgba(15,20,40,0.78)",
            backdropFilter: "blur(8px)",
            WebkitBackdropFilter: "blur(8px)",
            display: "flex", alignItems: "center", justifyContent: "center",
            padding: 20,
            fontFamily: "var(--font-sans, sans-serif)",
          }}>
          <div onClick={(e) => e.stopPropagation()} style={{
            display: "flex", flexDirection: "column", alignItems: "center", gap: 14,
            position: "relative",
          }}>
            {/* 상단 컨트롤 바 */}
            <div style={{
              display: "flex", gap: 10, alignItems: "center",
              background: "rgba(255,255,255,0.95)",
              border: "1px solid rgba(255,255,255,0.4)",
              borderRadius: 999,
              padding: 5,
              boxShadow: "0 16px 40px -10px rgba(0,0,0,0.4)",
            }}>
              <div style={{ display: "flex", gap: 2, background: "rgba(20,30,60,0.06)", borderRadius: 999, padding: 3 }}>
                {Object.entries(presets).map(([k, v]) =>
                  <button key={k}
                    onClick={() => setSize(k)}
                    style={{
                      border: 0,
                      background: size === k ? "#1a2238" : "transparent",
                      color: size === k ? "white" : "#3b4358",
                      padding: "6px 12px",
                      borderRadius: 999,
                      fontSize: 12, fontWeight: 700,
                      cursor: "pointer",
                      transition: "all .15s ease",
                    }}>{v.label}</button>
                )}
              </div>
              <div style={{ fontSize: 11, color: "#6b7088", padding: "0 8px", whiteSpace: "nowrap" }}>
                {p.w} × {p.h}
              </div>
              <button onClick={() => setOpen(false)} style={{
                border: 0, background: "rgba(20,30,60,0.06)",
                color: "#3b4358", borderRadius: 999,
                width: 30, height: 30, cursor: "pointer",
                fontSize: 16, lineHeight: 1,
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>×</button>
            </div>

            {/* 폰 프레임 */}
            <div style={{
              transform: `scale(${scale})`,
              transformOrigin: "center top",
              transition: "all .2s ease",
            }}>
              <div style={{
                width: frameW,
                height: frameH,
                background: "#1a1d2a",
                borderRadius: p.radius,
                padding: p.bezel,
                boxShadow: "0 30px 80px -20px rgba(0,0,0,0.6), inset 0 0 0 1.5px rgba(255,255,255,0.08)",
                position: "relative",
              }}>
                {/* 노치 */}
                {size === "iphone" && (
                  <div style={{
                    position: "absolute", top: p.bezel + 8, left: "50%",
                    transform: "translateX(-50%)",
                    width: 110, height: 28,
                    background: "#1a1d2a", borderRadius: 999,
                    zIndex: 2,
                  }}/>
                )}
                <iframe
                  src={(() => {
                    const u = new URL(window.location.href);
                    u.searchParams.set("__mp", "1");
                    return u.toString();
                  })()}
                  title="모바일 미리보기"
                  style={{
                    width: "100%", height: "100%",
                    border: 0,
                    borderRadius: p.radius - p.bezel,
                    background: "white",
                    display: "block",
                  }}
                />
              </div>
            </div>

            {/* 안내 */}
            <div style={{
              fontSize: 11, color: "rgba(255,255,255,0.7)",
              background: "rgba(0,0,0,0.3)", padding: "5px 12px", borderRadius: 999,
            }}>
              ESC 또는 바깥쪽 클릭으로 닫기
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { MobilePreview });
