/* GooglePhonePreview — an Android phone shell framing the live Google Wallet
   pass, auto-scaled to fit its pane. Mirrors the Apple PhonePreview. */
const { GoogleWalletPass: GP_Pass } = window.SpoonityWalletPassDesignSystem_de20b8;
const GP_I18N = window.SpoonityI18n;

// Loyalty fields the backend owns — never editable from the preview.
const GP_LOCKED_LABELS = ["POINTS", "TIER"];

const GP_BACKDROPS = {
  wallet: "radial-gradient(120% 80% at 50% 8%, #eef0f3 0%, var(--background) 58%)",
  light: "var(--background)",
  dark: "radial-gradient(130% 100% at 50% 0%, #16171C 0%, #101114 46%, #0C0D10 100%)",
};

const GP_GRAIN = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")";

function GP_hexToRgb(hex) {
  if (!hex || hex[0] !== "#") return "124,47,247";
  const h = hex.length === 4 ? hex.slice(1).split("").map((c) => c + c).join("") : hex.slice(1, 7);
  const [r, g, b] = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
  return [r, g, b].join(",");
}

function GooglePhonePreview({ pass, setPass, lang = "en", backdrop = "wallet", showDevice = true, guides = false }) {
  const wrap = React.useRef(null);
  const inner = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  const [slot, setSlot] = React.useState(null);
  const SlotEditor = window.StudioSlotEditor;

  React.useLayoutEffect(() => {
    const recompute = () => {
      if (!wrap.current || !inner.current) return;
      const ww = wrap.current.clientWidth - 36;
      const wh = wrap.current.clientHeight - 36;
      const iw = inner.current.offsetWidth;
      const ih = inner.current.offsetHeight;
      if (iw && ih) setScale(Math.min(1.14, ww / iw, wh / ih));
    };
    recompute();
    const ro = new ResizeObserver(recompute);
    if (wrap.current) ro.observe(wrap.current);
    if (inner.current) ro.observe(inner.current);
    return () => ro.disconnect();
  }, [showDevice, pass.fields, !!pass.barcode, !!pass.heroSrc]);

  const isDark = backdrop === "dark";
  // Google Wallet chrome flips with the system theme; the pass face keeps the
  // designer's colors either way.
  const chrome = isDark ? "#e8eaed" : "#202124";
  const chromeDim = isDark ? "#9aa0a6" : "#5f6368";

  const Screen = (
    <div style={{
      width: 393, height: 852,
      borderRadius: showDevice ? 44 : 0,
      background: showDevice ? (isDark ? "#202124" : "#ffffff") : "transparent",
      overflow: "hidden", position: "relative", display: "flex", flexDirection: "column",
    }}>
      {showDevice && (
        <div style={{
          position: "absolute", top: 15, left: "50%", transform: "translateX(-50%)",
          width: 12, height: 12, background: "#0b0b0d", borderRadius: "50%", zIndex: 5,
        }} />
      )}
      {showDevice && (
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "15px 26px 0", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: chrome,
        }}>
          <span>9:41</span>
          <span style={{ fontSize: 12, letterSpacing: 2, color: chromeDim }}>5G ▥ 100%</span>
        </div>
      )}
      <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "18px 22px 6px" }}>
        <span style={{ fontSize: 22, color: chromeDim, lineHeight: 1 }}>←</span>
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 18, fontWeight: 600, color: chrome }}>Pass details</span>
      </div>
      <div style={{ flex: 1, display: "flex", justifyContent: "center", alignItems: "flex-start", paddingTop: 18, minHeight: 0 }}>
        {/* company / name / iconSrc are backend-contract fields, not pass-face props.
            Field labels are translated for DISPLAY only — state stays English. */}
        {(() => {
          const { company, name, iconSrc, ...face } = pass;
          const disp = { ...face, fields: (face.fields || []).map((f) => (f && f.label) ? { ...f, label: GP_I18N.passLabel(lang, f.label) } : f) };
          const lockField = (group, index) => {
            const f = (face[group] || [])[index];
            return !!(f && GP_LOCKED_LABELS.includes(String(f.label || "").toUpperCase()));
          };
          return <GP_Pass {...disp} guides={guides} onSlot={setPass ? setSlot : null} lockField={lockField} width={360} />;
        })()}
      </div>
    </div>
  );

  const passRgb = GP_hexToRgb(pass.backgroundColor);
  const spotlight = isDark
    ? "radial-gradient(60% 50% at 50% 42%, rgba(255,255,255,.10), transparent 70%)"
    : "radial-gradient(58% 48% at 50% 44%, rgba(255,255,255,.55), transparent 68%)";

  return (
    <div ref={wrap} style={{
      position: "relative", flex: 1, minWidth: 0, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", padding: 18,
      background: GP_BACKDROPS[backdrop], borderLeft: "1px solid var(--border-primary)", overflow: "hidden",
      transition: "background .35s ease",
    }}>
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: spotlight, transition: "background .35s ease", pointerEvents: "none", zIndex: 0 }} />
      <div aria-hidden="true" style={{
        position: "absolute", top: "50%", left: "50%", width: 560, height: 600,
        transform: "translate(-50%, -52%)", borderRadius: "50%",
        background: `radial-gradient(circle, rgba(${passRgb},${isDark ? 0.42 : 0.55}) 0%, rgba(${passRgb},0) 68%)`,
        filter: "blur(70px)", transition: "background .4s ease", pointerEvents: "none", zIndex: 0,
      }} />
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: GP_GRAIN, backgroundSize: "180px 180px", opacity: isDark ? 0.05 : 0.035, mixBlendMode: "overlay", pointerEvents: "none", zIndex: 0 }} />

      <div ref={inner} style={{ position: "relative", zIndex: 1, transform: `scale(${scale})`, transformOrigin: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 22, transition: "transform .3s cubic-bezier(.2,.8,.2,1)" }}>
        {showDevice ? (
          <div style={{
            position: "relative", width: 419, height: 878, borderRadius: 56, background: "#0b0b0d", padding: 13, boxSizing: "border-box",
            boxShadow: `0 60px 140px -40px rgba(0,0,0,${isDark ? 0.7 : 0.34}), 0 24px 60px -30px rgba(0,0,0,.25), 0 0 0 1px rgba(0,0,0,.4), inset 0 0 0 2px #2a2a2e`,
          }}>
            {Screen}
            <div aria-hidden="true" style={{
              position: "absolute", inset: 13, borderRadius: 44, pointerEvents: "none", zIndex: 10,
              background: "linear-gradient(110deg, rgba(255,255,255,.14) 0%, rgba(255,255,255,.04) 28%, rgba(255,255,255,0) 46%)",
            }} />
          </div>
        ) : Screen}
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: isDark ? "rgba(255,255,255,.6)" : "var(--typography-tertiary)" }}>
          Live preview · Google Wallet
        </span>
      </div>
      {slot && SlotEditor && setPass && (
        <SlotEditor slot={slot} pass={pass} setPass={setPass} onClose={() => setSlot(null)} />
      )}
    </div>
  );
}
window.GooglePhonePreview = GooglePhonePreview;
