/* PhonePreview — a true iPhone (393×852 logical) shell framing the live wallet
   pass, auto-scaled to fit its pane so the studio never overflows. */
const { WalletPass: PP_WalletPass } = window.SpoonityWalletPassDesignSystem_de20b8;
const PP_I18N = window.SpoonityI18n;

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

const PP_BACKDROPS = {
  wallet: "radial-gradient(120% 80% at 50% 8%, #f3eff7 0%, var(--background) 58%)",
  light: "var(--background)",
  // Rich, layered near-black with a purple cast — never flat #000.
  dark: "radial-gradient(130% 100% at 50% 0%, #1A1026 0%, #120D18 46%, #0F0A16 100%)",
};

// Faint film grain so the gradients read as "expensive" rather than banded.
const PP_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 PP_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 PhonePreview({ 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;
      // Allow a touch of upscale so the device fills the stage with confidence
      // instead of floating small in dead space.
      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);
    return () => ro.disconnect();
  }, [showDevice, pass.passStyle, !!pass.barcode]);

  const isDark = backdrop === "dark";
  // Apple Wallet's own chrome flips with the system appearance: dark canvas,
  // light text, and an inverted "Add to Wallet" button. The pass face keeps
  // the designer's colors either way.
  const chrome = isDark ? "#f5f5f7" : "#1d1d1f";

  const Screen = (
    <div style={{
      width: 393, height: 852,
      borderRadius: showDevice ? 46 : 0,
      background: showDevice ? (isDark ? "linear-gradient(180deg, #1c1c1e 0%, #000 100%)" : "linear-gradient(180deg, #f5f5f7 0%, #ebe9ee 100%)") : "transparent",
      overflow: "hidden", position: "relative", display: "flex", flexDirection: "column",
    }}>
      {showDevice && (
        <div style={{
          position: "absolute", top: 13, left: "50%", transform: "translateX(-50%)",
          width: 118, height: 33, background: "#0b0b0d", borderRadius: 18, zIndex: 5,
        }} />
      )}
      {showDevice && (
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "17px 30px 0", fontFamily: "var(--font-pass)", fontSize: 15, fontWeight: 600, color: chrome,
        }}>
          <span>9:41</span>
          <span style={{ fontSize: 14, letterSpacing: "1px" }}>􀙇 􀛪 􀛨</span>
        </div>
      )}
      <div style={{ padding: showDevice ? "30px 26px 8px" : "10px 26px 8px" }}>
        <span style={{ fontFamily: "var(--font-pass)", fontSize: 32, fontWeight: 700, color: chrome, letterSpacing: "-0.02em" }}>{PP_I18N.T("wallet")}</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;
          // Display the custom title (labelText) when set, otherwise the
          // translated default. `label` stays the stable identity for the
          // backend / lock detection; only the shown text changes.
          const tr = (f) => {
            if (!f) return f;
            const custom = f.labelText && f.labelText.trim();
            return { ...f, label: custom ? f.labelText : (f.label ? PP_I18N.passLabel(lang, f.label) : f.label) };
          };
          const disp = { ...face,
            headerFields: (face.headerFields || []).map(tr),
            primaryFields: (face.primaryFields || []).map(tr),
            secondaryFields: (face.secondaryFields || []).map(tr),
            auxiliaryFields: (face.auxiliaryFields || []).map(tr),
          };
          // POINTS and TIER are backend-driven loyalty data — lock them so they
          // can't be clicked/edited from the live preview.
          const lockField = (group, index) => {
            const f = (face[group] || [])[index];
            return !!(f && PP_LOCKED_LABELS.includes(String(f.label || "").toUpperCase()));
          };
          // Keyed by pass type so React remounts it on a switch, replaying the
          // gentle flip-in — the studio's one little moment of delight.
          return (
            <div key={face.passStyle} className="spoonity-pass-flip">
              <PP_WalletPass {...disp} guides={guides} onSlot={setPass ? setSlot : null} lockField={lockField} width={360} height={468} />
            </div>
          );
        })()}
      </div>
      <div style={{ padding: "0 26px 34px", display: "flex", justifyContent: "center" }}>
        <div style={{
          fontFamily: "var(--font-pass)", fontSize: 16, fontWeight: 600, color: isDark ? "#1d1d1f" : "#fff",
          background: chrome, padding: "14px 0", borderRadius: 15, width: "100%", textAlign: "center",
        }}>{PP_I18N.T("addToWallet")}</div>
      </div>
    </div>
  );

  const passRgb = PP_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: PP_BACKDROPS[backdrop], borderLeft: "1px solid var(--border-primary)", overflow: "hidden",
      transition: "background .35s ease",
    }}>
      {/* Stage atmosphere — all behind the device, none interactive. */}
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: spotlight, transition: "background .35s ease", pointerEvents: "none", zIndex: 0 }} />
      {/* Ambient brand glow: a big, soft, blurred bloom of the pass color. */}
      <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,
      }} />
      {/* Faint grain to make the gradients feel filmic. */}
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: PP_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: 58, 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}
            {/* Environmental reflection across the glass — barely there. */}
            <div aria-hidden="true" style={{
              position: "absolute", inset: 13, borderRadius: 46, 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)" }}>
          {PP_I18N.T("livePreview")} · 393 × 852
        </span>
      </div>
      {slot && SlotEditor && setPass && (
        <SlotEditor slot={slot} pass={pass} setPass={setPass} onClose={() => setSlot(null)} />
      )}
    </div>
  );
}
window.PhonePreview = PhonePreview;
