diff --git a/.env.example b/.env.example
index 7bd9b32..408844a 100644
--- a/.env.example
+++ b/.env.example
@@ -4,8 +4,11 @@
# secrets, API keys or tokens in this file. PokeGuru needs no API keys.
# Canonical public origin, with no trailing slash, e.g. https://pokeguru.example.com
-# Used for canonical links, Open Graph URLs, robots.txt and sitemap.xml.
-# Leave empty to derive URLs from the address the app is served from.
+# Used for canonical links, Open Graph URLs, robots.txt, sitemap.xml AND the QR
+# code on the printable 5 x 7 in flyer.
+# Leave empty to derive URLs from the address the app is served from; the flyer
+# then refuses to generate a QR code unless that address is a real production
+# origin (never localhost, preview or sandbox hosts).
VITE_PUBLIC_SITE_URL=
# "Buy Me a Pack" support destination (a real, verified payment/support page).
diff --git a/README.md b/README.md
index 6c471ca..3f79f21 100644
--- a/README.md
+++ b/README.md
@@ -58,8 +58,13 @@ and keeps a private collection vault in the browser.
or estimated, shows the modelled tier odds with sources, and keeps simulated
pulls in their own store (`pokeguru_pack_sim_v1`) so they can never leak into
your real collection or its valuation.
-- **Offline-tolerant PWA** — app shell cached, clearly labelled cached data, and
- a safe update prompt that never traps you on an old version.
+- **Printable 5 × 7 in flyer** — one-click, vector, print-ready PDF
+ (`PokeGuru-5x7-QR-Flyer.pdf`) with a QR code that always points at the live
+ production site, plus a Print option that opens your print dialogue. Linked
+ from the footer, the homepage “Share PokeGuru” panel and the About page.
+- **Offline-tolerant PWA** — app shell cached, clearly labelled cached data, a
+ safe update prompt that never traps you on an old version, and an optional
+ install invitation (“Take PokeGuru with you!”).
---
@@ -111,7 +116,7 @@ so never put secrets in them.
| Variable | Required | Purpose |
| --- | --- | --- |
-| `VITE_PUBLIC_SITE_URL` | no | Canonical origin used for canonical/OG tags, `sitemap.xml` and absolute `robots.txt` entries, e.g. `https://pokeguru.example.com` (no trailing slash). Empty = derive from the browser and skip the sitemap. When set, the build asks TCGdex for the live set list so every `/set/:id` page is listed (static routes only if the API is unreachable). |
+| `VITE_PUBLIC_SITE_URL` | **yes for the flyer** | Canonical origin used for canonical/OG tags, `sitemap.xml`, absolute `robots.txt` entries **and the QR code on the printable flyer**, e.g. `https://pokeguru.example.com` (no trailing slash). Empty = derive from the browser and skip the sitemap; for the flyer the served origin is used only when it looks like a real production address (see below). When set, the build asks TCGdex for the live set list so every `/set/:id` page is listed (static routes only if the API is unreachable). |
| `VITE_BUY_ME_A_PACK_URL` | no | A real support/payment page for “Buy Me a Pack”. When empty the call-to-action renders in a clearly labelled *not configured* state — no fabricated link is ever shown. |
| `DEPLOY_TARGET` | no | `github-pages` builds with the `/PokeGuru/` base path. Leave unset for Vercel and other root-hosted deployments. |
@@ -120,6 +125,42 @@ so never put secrets in them.
---
+## 🎴 Printable flyer
+
+Every page footer, the homepage “Share PokeGuru” panel and the About page offer
+**🎴 Download PokeGuru Flyer** (and **Print flyer**).
+
+- **File:** `PokeGuru-5x7-QR-Flyer.pdf` — exactly one page, exactly **5 × 7 in
+ portrait (127 × 177.8 mm = 360 × 504 pt)**. The PDF is generated in the browser
+ on demand, so it is never a stale checked-in binary: one current design, one
+ download, no server work.
+- **Everything is vector** — text uses the standard Helvetica faces, the artwork
+ is native PDF paths and the QR code is one rectangle per module, so it stays
+ sharp at any print resolution.
+- **The QR code is verified.** `tests/flyer.test.ts` decodes the generated
+ matrix with the independent `jsqr` decoder and asserts the payload is the
+ production URL, and also re-opens the produced PDF to assert the page count
+ and page box.
+- **The production address is enforced.** `src/services/flyer/qr.ts` accepts
+ `VITE_PUBLIC_SITE_URL` (or, if unset, the origin the app is served from) only
+ when it is `https`, has no path/query/hash, and is not `localhost`, `127.x`,
+ `*.local`, a sandbox preview (`*.e2b.app`) or a Vercel preview/branch
+ deployment. If nothing passes, the buttons show a **configuration warning**
+ instead of generating a QR code that would not work once printed — no dummy
+ URLs, ever.
+- **Printing:** choose 100% / “Actual size” (never “Fit to page”). The design is
+ full-bleed dark, so a slightly heavier paper stock keeps it crisp.
+- **Wording:** the flyer advertises only shipped features (search, set archive,
+ collection, real market prices, free virtual packs) and carries an unofficial
+ fan-project disclaimer. No official artwork, logos, character images or
+ partnership claims are used.
+
+To point the flyer at your own domain, set `VITE_PUBLIC_SITE_URL` (for example
+in the Vercel project’s environment variables) and redeploy; Google Fonts, the
+sitemap, canonical tags and the printed QR code all follow that one value.
+
+---
+
## 🎁 Pack Opening Simulator
| Piece | Where |
@@ -215,6 +256,14 @@ card.
- Cached/offline data is labelled in the UI.
- Updates are non-blocking: a prompt appears, and `SKIP_WAITING` swaps versions
on your next action instead of pinning an old build.
+- **Install invitation** (`src/components/UI/InstallPrompt.tsx`): a branded
+ “Take PokeGuru with you!” card appears ~7 s after load, only when the browser
+ can actually install the app (`beforeinstallprompt` has fired) or on iOS,
+ where it explains the Safari “Add to Home Screen” route instead of pretending
+ a one-tap prompt exists. The browser’s own install dialogue is opened **only**
+ after the visitor chooses *Install PokeGuru*; *Maybe later* or a dismissal is
+ remembered in `localStorage` for 60 days, and the card never appears when the
+ app is already installed (standalone display mode).
---
diff --git a/package-lock.json b/package-lock.json
index 74256dd..dfd461c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,18 +1,20 @@
{
"name": "pokeguru",
- "version": "1.6.0",
+ "version": "1.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pokeguru",
- "version": "1.6.0",
+ "version": "1.7.0",
"license": "MIT",
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/space-grotesk": "^5.3.0",
"clsx": "2.1.1",
"lucide-react": "^1.18.0",
+ "pdf-lib": "^1.17.1",
+ "qrcode-generator": "^2.0.4",
"react": "19.2.6",
"react-dom": "19.2.6",
"react-router-dom": "^7.17.0",
@@ -33,6 +35,7 @@
"gh-pages": "^6.3.0",
"globals": "^17.14.0",
"jsdom": "^31.0.1",
+ "jsqr": "^1.4.0",
"sharp": "^0.35.5",
"tailwindcss": "4.1.17",
"typescript": "5.9.3",
@@ -1267,6 +1270,24 @@
"url": "https://github.com/sponsors/oxc-project"
}
},
+ "node_modules/@pdf-lib/standard-fonts": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
+ "integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
+ "license": "MIT",
+ "dependencies": {
+ "pako": "^1.0.6"
+ }
+ },
+ "node_modules/@pdf-lib/upng": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
+ "integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pako": "^1.0.10"
+ }
+ },
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.19",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
@@ -3724,6 +3745,13 @@
"graceful-fs": "^4.1.6"
}
},
+ "node_modules/jsqr": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/jsqr/-/jsqr-1.4.0.tgz",
+ "integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/keyv": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz",
@@ -4272,6 +4300,12 @@
"node": ">=6"
}
},
+ "node_modules/pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/parse5": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -4328,6 +4362,24 @@
"node": ">=8"
}
},
+ "node_modules/pdf-lib": {
+ "version": "1.17.1",
+ "resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
+ "integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
+ "license": "MIT",
+ "dependencies": {
+ "@pdf-lib/standard-fonts": "^1.0.0",
+ "@pdf-lib/upng": "^1.0.1",
+ "pako": "^1.0.11",
+ "tslib": "^1.11.1"
+ }
+ },
+ "node_modules/pdf-lib/node_modules/tslib": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
+ "license": "0BSD"
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"dev": true,
@@ -4443,6 +4495,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/qrcode-generator": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
+ "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
+ "license": "MIT"
+ },
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
diff --git a/package.json b/package.json
index f854a94..120874d 100644
--- a/package.json
+++ b/package.json
@@ -29,6 +29,8 @@
"@fontsource-variable/space-grotesk": "^5.3.0",
"clsx": "2.1.1",
"lucide-react": "^1.18.0",
+ "pdf-lib": "^1.17.1",
+ "qrcode-generator": "^2.0.4",
"react": "19.2.6",
"react-dom": "19.2.6",
"react-router-dom": "^7.17.0",
@@ -49,6 +51,7 @@
"gh-pages": "^6.3.0",
"globals": "^17.14.0",
"jsdom": "^31.0.1",
+ "jsqr": "^1.4.0",
"sharp": "^0.35.5",
"tailwindcss": "4.1.17",
"typescript": "5.9.3",
diff --git a/src/components/Flyer/FlyerActions.tsx b/src/components/Flyer/FlyerActions.tsx
new file mode 100644
index 0000000..84efbae
--- /dev/null
+++ b/src/components/Flyer/FlyerActions.tsx
@@ -0,0 +1,154 @@
+import { useMemo, useState } from "react";
+import { AlertTriangle, Check, Download, Loader2, Printer } from "lucide-react";
+import { cn } from "../../utils/cn";
+import { FlyerConfigurationError, downloadFlyer, printFlyer, resolveFlyerOrigin } from "../../services/flyer";
+
+type Status = { tone: "ok" | "warn" | "error"; text: string } | null;
+
+interface FlyerActionsProps {
+ variant?: "full" | "compact";
+ className?: string;
+ /** Show the printer button (kept on for every surface by default). */
+ showPrint?: boolean;
+}
+
+/**
+ * Download / print controls for the 5 × 7 in promotional flyer.
+ *
+ * The PDF is generated in the browser on demand, so the button always hands
+ * out the current design with a QR code for the live production address — there
+ * is no stale static file to forget about, and no server work.
+ */
+export default function FlyerActions({ variant = "full", className, showPrint = true }: FlyerActionsProps) {
+ const [busy, setBusy] = useState<"download" | "print" | null>(null);
+ const [status, setStatus] = useState(null);
+
+ const origin = useMemo(() => resolveFlyerOrigin(), []);
+ const compact = variant === "compact";
+
+ const handleDownload = async () => {
+ if (busy) return;
+ setBusy("download");
+ setStatus(null);
+ try {
+ const file = await downloadFlyer();
+ setStatus({
+ tone: "ok",
+ text: `Saved ${file.fileName} — ${file.millimetres.width} × ${file.millimetres.height} mm, print at 100%.`,
+ });
+ } catch (error) {
+ setStatus({
+ tone: error instanceof FlyerConfigurationError ? "warn" : "error",
+ text:
+ error instanceof FlyerConfigurationError
+ ? error.message
+ : "The flyer could not be generated in this browser. Please try again.",
+ });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const handlePrint = async () => {
+ if (busy) return;
+ setBusy("print");
+ setStatus(null);
+ try {
+ const { printed } = await printFlyer();
+ setStatus({
+ tone: "ok",
+ text: printed
+ ? "Opened the PDF in a new tab — in the print dialogue choose 100% / Actual size."
+ : "Your browser blocked the new tab, so the flyer was downloaded instead. Print it at 100%.",
+ });
+ } catch (error) {
+ setStatus({
+ tone: error instanceof FlyerConfigurationError ? "warn" : "error",
+ text:
+ error instanceof FlyerConfigurationError
+ ? error.message
+ : "The flyer could not be generated in this browser. Please try again.",
+ });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+
+
+
+
+ {showPrint && (
+
+ )}
+
+
+ {compact ? (
+
+ 5 × 7 in print-ready PDF · QR links to{" "}
+ {origin.origin ? origin.host : "the live site once configured"}
+
+ ) : (
+
+ One-page, print-ready PDF · exactly 5 × 7 in (127 × 177.8 mm) · the QR code links to{" "}
+ {origin.origin ? origin.host : "the live site once configured"}. Free to
+ download, print and share — no account needed.
+
+
+
+ Flyer not configured: set VITE_PUBLIC_SITE_URL to the live site address and
+ rebuild, so the printed QR code can never point at a preview deployment.
+
+
+ )}
+
+ {!compact && (
+
+ Wrapper artwork and logo are original PokeGuru designs. Promotional flyer for an unofficial fan-made companion — no physical
+ cards are supplied and there is no affiliation with The Pokémon Company.
+
+ )}
+
+ );
+}
diff --git a/src/components/Flyer/FlyerPreview.tsx b/src/components/Flyer/FlyerPreview.tsx
new file mode 100644
index 0000000..6bda959
--- /dev/null
+++ b/src/components/Flyer/FlyerPreview.tsx
@@ -0,0 +1,54 @@
+import { useEffect, useState } from "react";
+import { cn } from "../../utils/cn";
+import { buildFlyerSvg, resolveFlyerOrigin } from "../../services/flyer";
+
+interface FlyerPreviewProps {
+ className?: string;
+ /** Alt text for the rasterised preview. */
+ label?: string;
+}
+
+/**
+ * Live vector preview of the printable flyer, rendered from exactly the same
+ * scene as the PDF so what visitors see is what the printer gets.
+ */
+export default function FlyerPreview({ className, label = "Preview of the printable PokeGuru 5 × 7 in flyer" }: FlyerPreviewProps) {
+ const [src, setSrc] = useState(null);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!resolveFlyerOrigin().origin) {
+ setFailed(true);
+ return;
+ }
+ buildFlyerSvg()
+ .then((svg) => {
+ if (cancelled) return;
+ setSrc(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`);
+ })
+ .catch(() => {
+ if (!cancelled) setFailed(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return (
+
+ {src ? (
+
+ ) : (
+
+ {failed ? "Flyer preview needs a live site address (VITE_PUBLIC_SITE_URL)." : "Rendering flyer preview…"}
+
+ )}
+
+ );
+}
diff --git a/src/components/Layout/Footer.tsx b/src/components/Layout/Footer.tsx
index 8e2a1d4..62aa782 100644
--- a/src/components/Layout/Footer.tsx
+++ b/src/components/Layout/Footer.tsx
@@ -1,6 +1,7 @@
import { ExternalLink, Info } from "lucide-react";
import { Link } from "react-router-dom";
import { BuyMeAPackPanel } from "../UI/BuyMeAPack";
+import FlyerActions from "../Flyer/FlyerActions";
import Brand from "./Brand";
const LINKS = [
@@ -53,6 +54,11 @@ export default function Footer() {
Source on GitHub
+
+
+
Share PokeGuru
+
+
+
+
Share PokeGuru
+
+ A printable 5 × 7 in flyer with a QR code to the live site — perfect for card shops, league nights and
+ trade binders.
+
+
+
+
+
Limitations
diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx
index 0f6ccce..42a2778 100644
--- a/src/pages/HomePage.tsx
+++ b/src/pages/HomePage.tsx
@@ -10,6 +10,8 @@ import SkeletonGrid from "../components/UI/SkeletonGrid";
import ErrorMessage from "../components/UI/ErrorMessage";
import SetTile from "../components/Sets/SetTile";
import Brand from "../components/Layout/Brand";
+import FlyerActions from "../components/Flyer/FlyerActions";
+import FlyerPreview from "../components/Flyer/FlyerPreview";
import { getTotalSetCount } from "../data/ukSets";
import { enrichSetWithWikiMeta } from "../utils/setMeta";
import { formatGbp, getCardValueGbp } from "../services/pricing";
@@ -291,6 +293,22 @@ export default function HomePage() {
+
+
+
+
+
+
+ Share PokeGuru
+
+
+ Printed a flyer for your local card shop, league night or binder? Download the official 5 × 7 in poster, print it at
+ 100% and pin it up — the QR code takes anyone straight to PokeGuru.
+
+
+
+
+
);
}
diff --git a/src/services/flyer/index.ts b/src/services/flyer/index.ts
new file mode 100644
index 0000000..48900db
--- /dev/null
+++ b/src/services/flyer/index.ts
@@ -0,0 +1,102 @@
+/**
+ * Promotional flyer — public API used by the UI.
+ *
+ * The flyer is a 5 × 7 in, single-page, vector PDF with a QR code that points
+ * at the live production site. It is generated on demand (never bundled as a
+ * static asset) so there is exactly one copy, it always matches the current
+ * design, and the QR code can never go stale after a redeploy.
+ */
+
+import { FLYER_FILE_NAME, buildQrMatrix, resolveFlyerOrigin, type FlyerOrigin } from "./qr";
+import { buildFlyerScene, FLYER_MM, FLYER_PT, sceneToSvg } from "./scene";
+import { renderFlyerPdf } from "./pdf";
+
+export { FLYER_FILE_NAME, FLYER_MM, FLYER_PT, resolveFlyerOrigin };
+export type { FlyerOrigin };
+
+export class FlyerConfigurationError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "FlyerConfigurationError";
+ }
+}
+
+export interface FlyerFile {
+ blob: Blob;
+ fileName: string;
+ origin: FlyerOrigin;
+ points: { width: number; height: number };
+ millimetres: { width: number; height: number };
+}
+
+function originOrThrow(): FlyerOrigin {
+ const resolved = resolveFlyerOrigin();
+ if (resolved.origin === null) throw new FlyerConfigurationError(resolved.message);
+ return resolved;
+}
+
+/** Builds the PDF once per call; callers keep the object URL for reuse. */
+export async function buildFlyerFile(): Promise {
+ const origin = originOrThrow();
+ const qr = await buildQrMatrix(origin.origin);
+ const scene = buildFlyerScene({ url: origin.origin, host: origin.host, modules: qr.modules, quietZone: qr.quietZone });
+ const rendered = await renderFlyerPdf(scene);
+
+ return {
+ // Copy into a fresh ArrayBuffer so the Blob never shares memory with the
+ // PDF library's working buffer.
+ blob: new Blob([rendered.bytes.slice()], { type: "application/pdf" }),
+ fileName: FLYER_FILE_NAME,
+ origin,
+ points: rendered.points,
+ millimetres: rendered.millimetres,
+ };
+}
+
+/** Triggers a download of the print-ready PDF. */
+export async function downloadFlyer(): Promise {
+ const file = await buildFlyerFile();
+ triggerDownload(file.blob, file.fileName);
+ return file;
+}
+
+/**
+ * Opens the generated PDF in a new tab so the visitor can use the browser's
+ * own print dialogue. Falls back to downloading the file when pop-ups are
+ * blocked, so the action never becomes a dead end.
+ */
+export async function printFlyer(): Promise<{ printed: boolean; file: FlyerFile }> {
+ const file = await buildFlyerFile();
+ const url = URL.createObjectURL(file.blob);
+ const opened = typeof window !== "undefined" ? window.open(url, "_blank", "noopener,noreferrer") : null;
+
+ if (!opened) {
+ triggerDownload(file.blob, file.fileName);
+ return { printed: false, file };
+ }
+
+ // Leave the URL alive long enough for the PDF viewer to load it.
+ window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
+ return { printed: true, file };
+}
+
+function triggerDownload(blob: Blob, fileName: string): void {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = fileName;
+ link.rel = "noopener";
+ link.style.display = "none";
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
+}
+
+/** Vector SVG copy of the same design (used by previews/tests, no PDF). */
+export async function buildFlyerSvg(): Promise {
+ const origin = originOrThrow();
+ const qr = await buildQrMatrix(origin.origin);
+ const scene = buildFlyerScene({ url: origin.origin, host: origin.host, modules: qr.modules, quietZone: qr.quietZone });
+ return sceneToSvg(scene);
+}
diff --git a/src/services/flyer/pdf.ts b/src/services/flyer/pdf.ts
new file mode 100644
index 0000000..065cd54
--- /dev/null
+++ b/src/services/flyer/pdf.ts
@@ -0,0 +1,269 @@
+/**
+ * PDF renderer for the flyer scene.
+ *
+ * pdf-lib is imported lazily so the ~350 kB library is only fetched when a
+ * visitor actually asks for the flyer. Everything drawn here is vector: text
+ * uses the standard PDF fonts (no font files to download, no bitmaps), shapes
+ * are native paths and the QR code is one rectangle per module.
+ */
+
+import type { FontFace, FlyerScene, ScenePrimitive } from "./scene";
+import { FLYER_MM } from "./scene";
+
+import type { PDFFont, PDFPage } from "pdf-lib";
+
+type PdfDocumentModule = typeof import("pdf-lib");
+
+function hexToRgb(hex: string): { r: number; g: number; b: number } {
+ const clean = hex.replace("#", "");
+ const value = Number.parseInt(clean.length === 3 ? clean.replace(/./g, (c) => c + c) : clean, 16);
+ return {
+ r: ((value >> 16) & 255) / 255,
+ g: ((value >> 8) & 255) / 255,
+ b: (value & 255) / 255,
+ };
+}
+
+export interface RenderedPdf {
+ bytes: Uint8Array;
+ /** Page size in PostScript points (1/72 in). */
+ points: { width: number; height: number };
+ /** Page size in millimetres, for the report and the UI. */
+ millimetres: { width: number; height: number };
+}
+
+export async function renderFlyerPdf(scene: FlyerScene): Promise {
+ const pdfLib: PdfDocumentModule = await import("pdf-lib");
+ const { PDFDocument, StandardFonts, degrees, rgb } = pdfLib;
+
+ const doc = await PDFDocument.create();
+ doc.setTitle(scene.title);
+ doc.setAuthor("PokeGuru");
+ doc.setSubject(`PokeGuru promotional flyer (5 × 7 in) — ${scene.url}`);
+ doc.setKeywords(["PokeGuru", "Pokémon TCG", "flyer", "QR code", "promotional"]);
+ doc.setCreator("PokeGuru flyer generator");
+ doc.setProducer("PokeGuru (pdf-lib)");
+ doc.setCreationDate(new Date());
+
+ const page = doc.addPage([scene.width, scene.height]);
+ // Belt and braces: the page box is the flyer size, so no viewer can silently
+ // re-page it to A4 on export.
+ page.setMediaBox(0, 0, scene.width, scene.height);
+ page.setCropBox(0, 0, scene.width, scene.height);
+
+ const fonts = {
+ regular: await doc.embedFont(StandardFonts.Helvetica),
+ bold: await doc.embedFont(StandardFonts.HelveticaBold),
+ italic: await doc.embedFont(StandardFonts.HelveticaOblique),
+ };
+
+ const flip = (y: number) => scene.height - y;
+
+ for (const primitive of scene.primitives) {
+ drawPrimitive(page, primitive, { pageHeight: scene.height, flip, fonts, rgb, degrees });
+ }
+
+ const bytes = await doc.save();
+ return {
+ bytes,
+ points: { width: scene.width, height: scene.height },
+ millimetres: { width: FLYER_MM.width, height: FLYER_MM.height },
+ };
+}
+
+interface DrawContext {
+ pageHeight: number;
+ flip: (y: number) => number;
+ fonts: Record;
+ rgb: PdfDocumentModule["rgb"];
+ degrees: PdfDocumentModule["degrees"];
+}
+
+/** Draws text with optional letter tracking, honouring left/centre/right alignment. */
+function drawTrackedText(
+ page: PDFPage,
+ context: DrawContext,
+ primitive: Extract
+) {
+ const font = context.fonts[primitive.font];
+ const tracking = primitive.tracking ?? 0;
+ const characters = [...primitive.text];
+ const width =
+ characters.reduce((sum, char) => sum + font.widthOfTextAtSize(char, primitive.size), 0) +
+ tracking * Math.max(0, characters.length - 1);
+
+ let x = primitive.x;
+ if (primitive.align === "center") x -= width / 2;
+ if (primitive.align === "right") x -= width;
+
+ const options = {
+ size: primitive.size,
+ font,
+ color: context.rgb(...toTriplet(primitive.color)),
+ opacity: primitive.opacity,
+ };
+
+ if (!tracking) {
+ page.drawText(primitive.text, { ...options, x, y: context.flip(primitive.y) });
+ return;
+ }
+
+ let cursor = x;
+ for (const char of characters) {
+ page.drawText(char, { ...options, x: cursor, y: context.flip(primitive.y) });
+ cursor += font.widthOfTextAtSize(char, primitive.size) + tracking;
+ }
+}
+
+function toTriplet(hex: string): [number, number, number] {
+ const { r, g, b } = hexToRgb(hex);
+ return [r, g, b];
+}
+
+/** SVG path for a rounded rectangle, using the flyer's top-left origin convention. */
+function roundedRectPath(w: number, h: number, radius: number): string {
+ const r = Math.max(0.1, Math.min(radius, w / 2, h / 2));
+ return [
+ `M ${r} 0`,
+ `H ${w - r}`,
+ `A ${r} ${r} 0 0 1 ${w} ${r}`,
+ `V ${h - r}`,
+ `A ${r} ${r} 0 0 1 ${w - r} ${h}`,
+ `H ${r}`,
+ `A ${r} ${r} 0 0 1 0 ${h - r}`,
+ `V ${r}`,
+ `A ${r} ${r} 0 0 1 ${r} 0`,
+ "Z",
+ ].join(" ");
+}
+
+/**
+ * Origin for a path drawn in top-left coordinates, rotated about its centre.
+ * drawSvgPath places the path's (0,0) at x,y and grows downwards, and its
+ * `rotate` turns the path about that same point.
+ */
+function pathOrigin(
+ primitive: Extract,
+ pageHeight: number,
+ degrees: DrawContext["degrees"]
+) {
+ const rotation = primitive.rotate ?? 0;
+ const centreX = primitive.x + primitive.w / 2;
+ const centreY = pageHeight - (primitive.y + primitive.h / 2);
+ if (!rotation) {
+ // Path origin is the top-left corner: shift up by the height.
+ return { x: primitive.x, y: pageHeight - primitive.y, rotate: degrees(0) };
+ }
+ const phi = (-rotation * Math.PI) / 180;
+ const local = { x: primitive.w / 2, y: -primitive.h / 2 };
+ const rotated = {
+ x: local.x * Math.cos(phi) - local.y * Math.sin(phi),
+ y: local.x * Math.sin(phi) + local.y * Math.cos(phi),
+ };
+ return { x: centreX - rotated.x, y: centreY - rotated.y, rotate: degrees(-rotation) };
+}
+
+/** Rotates a scene rectangle about its centre, returning the PDF-space origin. */
+function rotatedOrigin(
+ primitive: Extract,
+ pageHeight: number,
+ degrees: DrawContext["degrees"]
+) {
+ const centreX = primitive.x + primitive.w / 2;
+ const centreY = pageHeight - (primitive.y + primitive.h / 2);
+ const rotation = primitive.rotate ?? 0;
+ if (!rotation) return { x: primitive.x, y: pageHeight - primitive.y - primitive.h, rotate: degrees(0) };
+
+ // Scene rotation is clockwise (y grows down), PDF rotation is anticlockwise.
+ const theta = (-rotation * Math.PI) / 180;
+ const dx = -(primitive.w / 2) * Math.cos(theta) + (primitive.h / 2) * Math.sin(theta);
+ const dy = -(primitive.w / 2) * Math.sin(theta) - (primitive.h / 2) * Math.cos(theta);
+ return { x: centreX + dx, y: centreY + dy, rotate: degrees(-rotation) };
+}
+
+function drawPrimitive(page: PDFPage, primitive: ScenePrimitive, context: DrawContext) {
+ switch (primitive.type) {
+ case "rect": {
+ const hasFill = Boolean(primitive.fill) && primitive.fill !== "none";
+ const hasStroke = Boolean(primitive.stroke);
+ if (!hasFill && !hasStroke) return;
+
+ if (primitive.r && primitive.r > 0) {
+ const origin = pathOrigin(primitive, context.pageHeight, context.degrees);
+ page.drawSvgPath(roundedRectPath(primitive.w, primitive.h, primitive.r), {
+ x: origin.x,
+ y: origin.y,
+ rotate: origin.rotate,
+ ...(hasFill ? { color: context.rgb(...toTriplet(primitive.fill as string)) } : {}),
+ ...(hasStroke
+ ? { borderColor: context.rgb(...toTriplet(primitive.stroke as string)), borderWidth: primitive.strokeWidth ?? 1 }
+ : {}),
+ opacity: primitive.opacity ?? 1,
+ borderOpacity: primitive.opacity ?? 1,
+ });
+ return;
+ }
+
+ const origin = rotatedOrigin(primitive, context.pageHeight, context.degrees);
+ page.drawRectangle({
+ x: origin.x,
+ y: origin.y,
+ width: primitive.w,
+ height: primitive.h,
+ rotate: origin.rotate,
+ ...(hasFill ? { color: context.rgb(...toTriplet(primitive.fill as string)) } : {}),
+ ...(hasStroke ? { borderColor: context.rgb(...toTriplet(primitive.stroke as string)), borderWidth: primitive.strokeWidth ?? 1 } : {}),
+ opacity: primitive.opacity ?? 1,
+ borderOpacity: primitive.opacity ?? 1,
+ });
+ return;
+ }
+ case "circle": {
+ page.drawCircle({
+ x: primitive.cx,
+ y: context.flip(primitive.cy),
+ size: primitive.r,
+ ...(primitive.fill ? { color: context.rgb(...toTriplet(primitive.fill)) } : {}),
+ ...(primitive.stroke
+ ? { borderColor: context.rgb(...toTriplet(primitive.stroke)), borderWidth: primitive.strokeWidth ?? 1 }
+ : {}),
+ opacity: primitive.opacity ?? 1,
+ borderOpacity: primitive.opacity ?? 1,
+ });
+ return;
+ }
+ case "text": {
+ drawTrackedText(page, context, primitive);
+ return;
+ }
+ case "qr": {
+ const total = primitive.modules.length + primitive.quiet * 2;
+ const cell = primitive.size / total;
+ // Light plate (includes the required quiet zone).
+ page.drawRectangle({
+ x: primitive.x,
+ y: context.flip(primitive.y + primitive.size),
+ width: primitive.size,
+ height: primitive.size,
+ color: context.rgb(...toTriplet(primitive.light)),
+ });
+ const dark = context.rgb(...toTriplet(primitive.dark));
+ for (let row = 0; row < primitive.modules.length; row += 1) {
+ for (let col = 0; col < primitive.modules[row].length; col += 1) {
+ if (!primitive.modules[row][col]) continue;
+ const x = primitive.x + (col + primitive.quiet) * cell;
+ const y = primitive.y + (row + primitive.quiet) * cell;
+ page.drawRectangle({
+ x,
+ y: context.flip(y + cell),
+ // Tiny overlap stops hairline seams between neighbouring modules.
+ width: cell + 0.05,
+ height: cell + 0.05,
+ color: dark,
+ });
+ }
+ }
+ return;
+ }
+ }
+}
diff --git a/src/services/flyer/qr.ts b/src/services/flyer/qr.ts
new file mode 100644
index 0000000..b0a1f8f
--- /dev/null
+++ b/src/services/flyer/qr.ts
@@ -0,0 +1,143 @@
+/**
+ * Production-address resolution and QR generation for the printed flyer.
+ *
+ * Two rules drive this file:
+ * 1. The QR code may only ever encode the real production site. A missing or
+ * preview-only address is a configuration error we surface, never a reason
+ * to print something that will not resolve.
+ * 2. No camera, no scanner, no third-party service. The QR is generated
+ * locally as vector data and drawn straight into the PDF.
+ */
+
+/** Filename used for every download, on every platform. */
+export const FLYER_FILE_NAME = "PokeGuru-5x7-QR-Flyer.pdf";
+
+export interface FlyerOrigin {
+ /** Absolute origin with no trailing slash, e.g. https://pokeguru.vercel.app */
+ origin: string;
+ /** Host without scheme, e.g. pokeguru.vercel.app — printed under the QR. */
+ host: string;
+ source: "configured" | "served";
+}
+
+export interface FlyerOriginError {
+ origin: null;
+ host: null;
+ message: string;
+}
+
+export type FlyerOriginResult = FlyerOrigin | FlyerOriginError;
+
+/**
+ * Rejects addresses that cannot be the public site: local dev servers, sandbox
+ * previews and Vercel preview deployments (which carry a generated hostname).
+ */
+export function isPublicOrigin(candidate: string): boolean {
+ let url: URL;
+ try {
+ url = new URL(candidate);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== "https:") return false;
+ if (url.pathname !== "/" && url.pathname !== "") return false;
+ if (url.search || url.hash) return false;
+
+ const host = url.hostname.toLowerCase();
+ if (!host.includes(".")) return false;
+ if (/^localhost$/.test(host) || /^127\./.test(host) || host === "0.0.0.0" || host === "[::1]") return false;
+ if (host.endsWith(".local") || host.endsWith(".e2b.app") || host.endsWith(".internal")) return false;
+
+ if (host.endsWith(".vercel.app")) {
+ // Production aliases are exactly three labels (pokeguru.vercel.app).
+ // Preview deployments add labels (name-abc123-team-projects.vercel.app) and
+ // branch aliases contain "-git-"; both must never reach a printed QR code.
+ const labels = host.split(".");
+ if (labels.length !== 3) return false;
+ if (labels[0].includes("-git-")) return false;
+ // Deployment-scoped aliases embed a hash or team segment, e.g.
+ // "pokeguru-8f3k2l-team": a hyphen-delimited segment containing digits.
+ const segments = labels[0].split("-");
+ const hasNumericSegment = segments.some((segment, index) => index > 0 && index < segments.length - 1 && /\d/.test(segment));
+ if (hasNumericSegment) return false;
+ }
+
+ return true;
+}
+
+/**
+ * Resolves the address the flyer links to.
+ *
+ * `VITE_PUBLIC_SITE_URL` is the single source of truth (it is also what the
+ * canonical URLs, sitemap and robots.txt use). If it is unset we accept the
+ * address the app is actually served from, but only when that address is a
+ * plausible production origin — otherwise the caller shows a configuration
+ * warning instead of generating a QR code that would not work in print.
+ */
+export function resolveFlyerOrigin(
+ configured: string | undefined = import.meta.env.VITE_PUBLIC_SITE_URL,
+ served: string | undefined = typeof window !== "undefined" ? window.location.origin : undefined
+): FlyerOriginResult {
+ const cleanConfigured = (configured ?? "").trim().replace(/\/+$/, "");
+ if (cleanConfigured) {
+ if (!isPublicOrigin(cleanConfigured)) {
+ return {
+ origin: null,
+ host: null,
+ message: `The configured site address (${cleanConfigured}) is not a public production address, so no QR code was generated.`,
+ };
+ }
+ return { origin: cleanConfigured, host: new URL(cleanConfigured).hostname, source: "configured" };
+ }
+
+ const cleanServed = (served ?? "").trim().replace(/\/+$/, "");
+ if (cleanServed && isPublicOrigin(cleanServed)) {
+ return { origin: cleanServed, host: new URL(cleanServed).hostname, source: "served" };
+ }
+
+ return {
+ origin: null,
+ host: null,
+ message:
+ "The flyer needs a public site address. Set VITE_PUBLIC_SITE_URL (for example https://pokeguru.vercel.app) and rebuild, so the printed QR code cannot point at a preview deployment.",
+ };
+}
+
+export interface QrMatrix {
+ /** One array per row; true = dark module. */
+ modules: boolean[][];
+ /** Modules per side (excluding the quiet zone). */
+ size: number;
+ /** Quiet zone in modules (4 is what the QR specification requires). */
+ quietZone: number;
+}
+
+type QrFactory = (typeNumber: number, level: "L" | "M" | "Q" | "H") => {
+ addData: (data: string) => void;
+ make: () => void;
+ getModuleCount: () => number;
+ isDark: (row: number, col: number) => boolean;
+};
+
+/**
+ * Builds the QR matrix for the flyer. Error-correction level Q survives a
+ * slightly scuffed print; the generator picks the smallest version that fits.
+ */
+export async function buildQrMatrix(url: string, quietZone = 4): Promise {
+ const loaded = (await import("qrcode-generator")) as unknown as
+ | QrFactory
+ | { default: QrFactory };
+ const factory: QrFactory =
+ typeof loaded === "function" ? loaded : (loaded as { default: QrFactory }).default;
+ if (!factory) throw new Error("The QR generator could not be loaded.");
+
+ const code = factory(0, "Q");
+ code.addData(url);
+ code.make();
+
+ const size = code.getModuleCount();
+ const modules = Array.from({ length: size }, (_, row) =>
+ Array.from({ length: size }, (_, col) => code.isDark(row, col))
+ );
+ return { modules, size, quietZone };
+}
diff --git a/src/services/flyer/scene.ts b/src/services/flyer/scene.ts
new file mode 100644
index 0000000..5e6100d
--- /dev/null
+++ b/src/services/flyer/scene.ts
@@ -0,0 +1,599 @@
+/**
+ * Flyer scene model.
+ *
+ * The promotional flyer is described once, as a tiny declarative scene, and
+ * rendered twice: to PDF (the downloadable, print-ready artefact) and to SVG
+ * (used by the visual regression preview and by anyone who wants a vector
+ * copy). Keeping the description separate from the renderer means the PDF and
+ * the preview can never drift apart, and the renderer stays testable without a
+ * browser canvas.
+ *
+ * Coordinates are top-left origin with y growing downwards, which matches SVG
+ * and reads naturally when laying a poster out from the header down.
+ */
+
+export const FLYER_PT = { width: 360, height: 504 } as const; // exactly 5 × 7 in
+export const FLYER_MM = { width: 127, height: 177.8 } as const;
+
+export type FontFace = "bold" | "regular" | "italic";
+
+export type ScenePrimitive =
+ | {
+ type: "rect";
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ /** Corner radius in points. */
+ r?: number;
+ fill?: string;
+ opacity?: number;
+ stroke?: string;
+ strokeWidth?: number;
+ /** Rotation in degrees about the rectangle's centre. */
+ rotate?: number;
+ }
+ | {
+ type: "circle";
+ cx: number;
+ cy: number;
+ r: number;
+ fill?: string;
+ opacity?: number;
+ stroke?: string;
+ strokeWidth?: number;
+ }
+ | {
+ type: "text";
+ x: number;
+ y: number;
+ text: string;
+ size: number;
+ font: FontFace;
+ color: string;
+ align?: "left" | "center" | "right";
+ /** Extra space between characters, in points. */
+ tracking?: number;
+ opacity?: number;
+ }
+ | {
+ type: "qr";
+ x: number;
+ y: number;
+ size: number;
+ modules: boolean[][];
+ /** Quiet zone in modules, included inside the given size. */
+ quiet: number;
+ dark: string;
+ light: string;
+ };
+
+export interface FlyerScene {
+ width: number;
+ height: number;
+ /** Title used for the PDF document properties and the SVG . */
+ title: string;
+ /** Production URL encoded in the QR code; recorded in the document metadata. */
+ url: string;
+ primitives: ScenePrimitive[];
+}
+
+/* ------------------------------------------------------------------ */
+/* Palette — mirrors the app's design tokens */
+/* ------------------------------------------------------------------ */
+
+export const FLYER_COLORS = {
+ ink: "#08090d",
+ soft: "#101319",
+ card: "#151923",
+ elevated: "#1c212d",
+ border: "#2c3344",
+ accent: "#f04452",
+ gold: "#f5a524",
+ blue: "#7cc4ff",
+ green: "#2fbf71",
+ text: "#f4f6fb",
+ muted: "#aab3c2",
+ mutedDim: "#8b93a3",
+ white: "#ffffff",
+} as const;
+
+/* ------------------------------------------------------------------ */
+/* Shape helpers */
+/* ------------------------------------------------------------------ */
+
+function hexToRgb(hex: string): [number, number, number] {
+ const clean = hex.replace("#", "");
+ const value = Number.parseInt(clean.length === 3 ? clean.replace(/./g, (c) => c + c) : clean, 16);
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
+}
+
+function mix(from: string, to: string, t: number): string {
+ const [r1, g1, b1] = hexToRgb(from);
+ const [r2, g2, b2] = hexToRgb(to);
+ const channel = (a: number, b: number) => Math.round(a + (b - a) * t).toString(16).padStart(2, "0");
+ return `#${channel(r1, r2)}${channel(g1, g2)}${channel(b1, b2)}`;
+}
+
+/**
+ * A vertical gradient built from flat bands. Vector output, no images, and it
+ * renders identically in PDF and SVG.
+ */
+export function verticalGradient(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ from: string,
+ to: string,
+ stops = 72
+): ScenePrimitive[] {
+ const bandHeight = h / stops;
+ return Array.from({ length: stops }, (_, index) => ({
+ type: "rect" as const,
+ x,
+ y: y + index * bandHeight,
+ w,
+ // Overlap by a hair so no seams appear at low resolutions.
+ h: bandHeight + 0.6,
+ fill: mix(from, to, index / (stops - 1)),
+ }));
+}
+
+/** Soft radial glow approximated by stacked translucent circles. */
+export function radialGlow(cx: number, cy: number, radius: number, color: string, strength = 0.16): ScenePrimitive[] {
+ const rings = 9;
+ return Array.from({ length: rings }, (_, index) => {
+ const t = (index + 1) / rings;
+ return {
+ type: "circle" as const,
+ cx,
+ cy,
+ r: radius * (1 - t * 0.72),
+ fill: color,
+ opacity: (strength / rings) * (0.45 + t),
+ };
+ });
+}
+
+function sparkle(cx: number, cy: number, size: number, color: string, opacity = 0.85): ScenePrimitive[] {
+ // Four-point sparkle: two rotated diamonds of different sizes.
+ return [
+ {
+ type: "rect",
+ x: cx - size / 2,
+ y: cy - size / 9,
+ w: size,
+ h: size / 4.5,
+ r: size / 9,
+ fill: color,
+ opacity,
+ },
+ {
+ type: "rect",
+ x: cx - size / 9,
+ y: cy - size / 2,
+ w: size / 4.5,
+ h: size,
+ r: size / 9,
+ fill: color,
+ opacity,
+ },
+ ];
+}
+
+/**
+ * A stylised card face: foil band, inner frame, art window and a type pip.
+ * Abstract on purpose — no Pokémon characters, logos or trade dress.
+ */
+function cardFace(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ rotate: number,
+ palette: { frame: string; art: string; glow: string }
+): ScenePrimitive[] {
+ const pad = w * 0.07;
+ return [
+ // Drop shadow
+ { type: "rect", x: x + 2, y: y + 3, w, h, r: 5, fill: "#000000", opacity: 0.45, rotate },
+ // Frame
+ {
+ type: "rect",
+ x,
+ y,
+ w,
+ h,
+ r: 5,
+ fill: palette.frame,
+ opacity: 1,
+ stroke: "#ffffff",
+ strokeWidth: 0.6,
+ rotate,
+ },
+ // Art window
+ {
+ type: "rect",
+ x: x + pad,
+ y: y + pad,
+ w: w - pad * 2,
+ h: h * 0.52,
+ r: 3,
+ fill: palette.art,
+ rotate,
+ },
+ // Art glow
+ { type: "circle", cx: x + w / 2, cy: y + pad + h * 0.26, r: w * 0.16, fill: palette.glow, opacity: 0.55 },
+ { type: "circle", cx: x + w / 2, cy: y + pad + h * 0.26, r: w * 0.09, fill: "#ffffff", opacity: 0.35 },
+ // Text rules
+ { type: "rect", x: x + pad, y: y + h * 0.62, w: w * 0.55, h: 2.4, r: 1.2, fill: "#000000", opacity: 0.35, rotate },
+ { type: "rect", x: x + pad, y: y + h * 0.7, w: w * 0.8, h: 1.8, r: 0.9, fill: "#000000", opacity: 0.22, rotate },
+ { type: "rect", x: x + pad, y: y + h * 0.76, w: w * 0.7, h: 1.8, r: 0.9, fill: "#000000", opacity: 0.22, rotate },
+ // Type pip
+ {
+ type: "circle",
+ cx: x + w - pad - w * 0.09,
+ cy: y + h - pad - w * 0.09,
+ r: w * 0.09,
+ fill: "#ffffff",
+ opacity: 0.9,
+ },
+ ];
+}
+
+/** A booster-pack silhouette with a tear notch and foil strip. */
+function boosterPack(x: number, y: number, w: number, h: number, rotate: number): ScenePrimitive[] {
+ return [
+ { type: "rect", x: x + 2, y: y + 3, w, h, r: 6, fill: "#000000", opacity: 0.45, rotate },
+ { type: "rect", x, y, w, h, r: 6, fill: "#26313f", stroke: "#5b6a80", strokeWidth: 0.9, rotate },
+ { type: "rect", x: x + 5, y: y + 5, w: w - 10, h: 8, r: 2, fill: FLYER_COLORS.accent, opacity: 0.95, rotate },
+ {
+ type: "rect",
+ x: x + 5,
+ y: y + h * 0.32,
+ w: w - 10,
+ h: h * 0.4,
+ r: 3,
+ fill: FLYER_COLORS.gold,
+ opacity: 0.22,
+ rotate,
+ },
+ { type: "circle", cx: x + w / 2, cy: y + h * 0.52, r: w * 0.17, fill: FLYER_COLORS.white, opacity: 0.16 },
+ { type: "rect", x: x + 8, y: y + h - 14, w: w * 0.5, h: 3, r: 1.5, fill: FLYER_COLORS.white, opacity: 0.35, rotate },
+ ];
+}
+
+export interface FlyerSceneOptions {
+ /** Production URL encoded in the QR code and printed in full. */
+ url: string;
+ /** Host shown in the large, readable line beneath the QR. */
+ host: string;
+ /** QR modules, dark = true. Row-major, `modules[row][col]`. */
+ modules: boolean[][];
+ quietZone?: number;
+}
+
+/**
+ * Builds the whole flyer. Everything is vector: text, shapes and the QR code
+ * itself (one rectangle per dark module), so the PDF stays crisp at any print
+ * resolution and needs no bitmaps.
+ */
+export function buildFlyerScene({ url, host, modules, quietZone = 4 }: FlyerSceneOptions): FlyerScene {
+ const { width, height } = FLYER_PT;
+ const primitives: ScenePrimitive[] = [];
+
+ // Background
+ primitives.push(...verticalGradient(0, 0, width, height, "#141a26", "#07080c"));
+ primitives.push(...radialGlow(width - 26, 74, 150, FLYER_COLORS.accent, 0.5));
+ primitives.push(...radialGlow(22, height - 96, 140, FLYER_COLORS.gold, 0.34));
+ primitives.push(...radialGlow(width / 2, 250, 190, FLYER_COLORS.blue, 0.12));
+
+ // Thin accent rule at the very top
+ primitives.push({ type: "rect", x: 0, y: 0, w: width, h: 3, fill: FLYER_COLORS.accent });
+
+ /* ---------------- Header ---------------- */
+ const markX = 24;
+ const markY = 24;
+ primitives.push({
+ type: "rect",
+ x: markX,
+ y: markY,
+ w: 32,
+ h: 32,
+ r: 9,
+ fill: FLYER_COLORS.accent,
+ stroke: "#ffffff",
+ strokeWidth: 0.7,
+ });
+ // Monogram: a stylised card + spark, drawn with rectangles only.
+ primitives.push({ type: "rect", x: markX + 9, y: markY + 7.5, w: 14, h: 17, r: 2.5, fill: FLYER_COLORS.white, opacity: 0.95 });
+ primitives.push({ type: "rect", x: markX + 11.5, y: markY + 10, w: 9, h: 6, r: 1.4, fill: FLYER_COLORS.accent });
+ primitives.push({ type: "rect", x: markX + 11.5, y: markY + 18, w: 6.5, h: 1.7, r: 0.85, fill: FLYER_COLORS.accent, opacity: 0.8 });
+ primitives.push({ type: "rect", x: markX + 11.5, y: markY + 21, w: 5, h: 1.7, r: 0.85, fill: FLYER_COLORS.accent, opacity: 0.55 });
+
+ primitives.push({
+ type: "text",
+ x: markX + 42,
+ y: markY + 15,
+ text: "POKEGURU",
+ size: 21,
+ font: "bold",
+ color: FLYER_COLORS.text,
+ tracking: 2.4,
+ });
+ primitives.push({
+ type: "text",
+ x: markX + 43,
+ y: markY + 29,
+ text: "Your Pokémon TCG companion.",
+ size: 9.5,
+ font: "italic",
+ color: FLYER_COLORS.muted,
+ });
+
+ /* ---------------- Hero artwork ---------------- */
+ primitives.push(...boosterPack(248, 62, 56, 82, 13));
+ primitives.push(
+ ...cardFace(64, 96, 62, 86, -11, {
+ frame: "#e8566a",
+ art: "#2a1220",
+ glow: FLYER_COLORS.gold,
+ })
+ );
+ primitives.push(
+ ...cardFace(150, 82, 76, 104, 2, {
+ frame: "#1d2740",
+ art: "#0e1a2c",
+ glow: FLYER_COLORS.blue,
+ })
+ );
+ // Holo sheen sweeping across the centre card.
+ primitives.push({ type: "rect", x: 156, y: 96, w: 16, h: 84, r: 8, fill: "#ffffff", opacity: 0.07, rotate: 18 });
+ primitives.push({ type: "rect", x: 196, y: 96, w: 7, h: 84, r: 3.5, fill: FLYER_COLORS.blue, opacity: 0.12, rotate: 18 });
+ primitives.push(
+ ...cardFace(236, 100, 62, 86, 12, {
+ frame: "#f0c05a",
+ art: "#241a08",
+ glow: FLYER_COLORS.green,
+ })
+ );
+ primitives.push(...sparkle(126, 92, 13, FLYER_COLORS.gold, 0.95));
+ primitives.push(...sparkle(300, 168, 10, FLYER_COLORS.blue, 0.9));
+ primitives.push(...sparkle(46, 176, 8, FLYER_COLORS.accent, 0.85));
+
+ /* ---------------- Headline ---------------- */
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: 236,
+ text: "DISCOVER. COLLECT. OPEN.",
+ size: 18,
+ font: "bold",
+ color: FLYER_COLORS.gold,
+ align: "center",
+ tracking: 1.5,
+ });
+ primitives.push({
+ type: "rect",
+ x: width / 2 - 26,
+ y: 245,
+ w: 52,
+ h: 2,
+ r: 1,
+ fill: FLYER_COLORS.accent,
+ });
+
+ const body = [
+ "Explore every Pokémon card and expansion.",
+ "Track your collection and follow real market prices.",
+ "Open unlimited FREE virtual booster packs.",
+ ];
+ body.forEach((line, index) => {
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: 264 + index * 12,
+ text: line,
+ size: 9,
+ font: "regular",
+ color: FLYER_COLORS.muted,
+ align: "center",
+ });
+ });
+
+ /* ---------------- QR code ---------------- */
+ const panelX = 62;
+ const panelY = 296;
+ const panelW = width - panelX * 2;
+ const panelH = 156;
+ primitives.push({
+ type: "rect",
+ x: panelX,
+ y: panelY,
+ w: panelW,
+ h: panelH,
+ r: 12,
+ fill: FLYER_COLORS.white,
+ });
+ const qrSize = 118;
+ const qrX = width / 2 - qrSize / 2;
+ const qrY = panelY + 8;
+ primitives.push({
+ type: "qr",
+ x: qrX,
+ y: qrY,
+ size: qrSize,
+ modules,
+ quiet: quietZone,
+ dark: "#000000",
+ light: FLYER_COLORS.white,
+ });
+
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: qrY + qrSize + 19,
+ text: host,
+ size: 13,
+ font: "bold",
+ color: "#0b0d12",
+ align: "center",
+ tracking: 0.2,
+ });
+
+ /* ---------------- Badge + footer ---------------- */
+ const badgeText = "FREE TO EXPLORE · UNLIMITED VIRTUAL PACK OPENINGS";
+ const badgeW = 268;
+ const badgeX = width / 2 - badgeW / 2;
+ primitives.push({
+ type: "rect",
+ x: badgeX,
+ y: 458,
+ w: badgeW,
+ h: 18,
+ r: 9,
+ fill: FLYER_COLORS.gold,
+ });
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: 466,
+ text: badgeText,
+ size: 7.2,
+ font: "bold",
+ color: "#20160a",
+ align: "center",
+ tracking: 0.55,
+ });
+
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: 484,
+ text: "Unofficial fan-made companion. No physical cards are supplied or sold.",
+ size: 5.6,
+ font: "regular",
+ color: FLYER_COLORS.mutedDim,
+ align: "center",
+ });
+ primitives.push({
+ type: "text",
+ x: width / 2,
+ y: 493,
+ text: "Not affiliated with or endorsed by The Pokémon Company, Nintendo, Creatures Inc. or GAME FREAK.",
+ size: 5.6,
+ font: "regular",
+ color: FLYER_COLORS.mutedDim,
+ align: "center",
+ });
+
+ return {
+ width,
+ height,
+ title: "PokeGuru — Your Pokémon TCG companion",
+ url,
+ primitives,
+ };
+}
+
+/** Renders the scene as standalone SVG (vector). Used by previews and tests. */
+export function sceneToSvg(scene: FlyerScene): string {
+ const parts: string[] = [
+ `");
+ return parts.join("\n");
+}
+
+function num(value: number): string {
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
+}
+
+function escapeXml(value: string): string {
+ return value
+ .replace(/&/g, "&")
+ .replace(//g, ">")
+ .replace(/"/g, """)
+ .replace(/'/g, "'");
+}
diff --git a/tests/flyer-actions.test.tsx b/tests/flyer-actions.test.tsx
new file mode 100644
index 0000000..7959494
--- /dev/null
+++ b/tests/flyer-actions.test.tsx
@@ -0,0 +1,66 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import FlyerActions from "../src/components/Flyer/FlyerActions";
+
+const PRODUCTION_URL = "https://pokeguru.vercel.app";
+
+beforeEach(() => {
+ Object.defineProperty(URL, "createObjectURL", { value: vi.fn(() => "blob:flyer"), writable: true });
+ Object.defineProperty(URL, "revokeObjectURL", { value: vi.fn(), writable: true });
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe("FlyerActions", () => {
+ it("downloads a single PDF with the agreed filename", async () => {
+ vi.stubEnv("VITE_PUBLIC_SITE_URL", PRODUCTION_URL);
+ render();
+
+ const button = screen.getByRole("button", { name: /Download PokeGuru Flyer/i });
+ expect(button.textContent).toContain("🎴");
+
+ await act(async () => {
+ fireEvent.click(button);
+ });
+
+ await waitFor(() => expect(screen.getByText(/PokeGuru-5x7-QR-Flyer\.pdf/)).toBeTruthy());
+ expect(HTMLAnchorElement.prototype.click).toHaveBeenCalledTimes(1);
+ expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
+
+ const blob = (URL.createObjectURL as unknown as ReturnType).mock.calls[0][0] as Blob;
+ expect(blob.type).toBe("application/pdf");
+ expect(blob.size).toBeGreaterThan(1000);
+ });
+
+ it("shows the production host it will print", () => {
+ vi.stubEnv("VITE_PUBLIC_SITE_URL", PRODUCTION_URL);
+ render();
+ expect(screen.getByText("pokeguru.vercel.app")).toBeTruthy();
+ expect(screen.queryByText(/Flyer not configured/i)).toBeNull();
+ });
+
+ it("warns clearly instead of producing a dummy flyer when the address is missing", async () => {
+ vi.stubEnv("VITE_PUBLIC_SITE_URL", "");
+ render();
+
+ expect(screen.getByText(/Flyer not configured/i)).toBeTruthy();
+ expect(screen.getByText(/VITE_PUBLIC_SITE_URL/)).toBeTruthy();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /Download PokeGuru Flyer/i }));
+ });
+
+ await waitFor(() => expect(screen.getByText(/needs a public site address/i)).toBeTruthy());
+ expect(HTMLAnchorElement.prototype.click).not.toHaveBeenCalled();
+ });
+
+ it("offers printing as a second, clearly labelled option", () => {
+ vi.stubEnv("VITE_PUBLIC_SITE_URL", PRODUCTION_URL);
+ render();
+ expect(screen.getByRole("button", { name: /Print flyer/i })).toBeTruthy();
+ });
+});
diff --git a/tests/flyer.test.ts b/tests/flyer.test.ts
new file mode 100644
index 0000000..960163f
--- /dev/null
+++ b/tests/flyer.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import jsQR from "jsqr";
+import { PDFDocument } from "pdf-lib";
+import { FLYER_FILE_NAME, buildFlyerFile, buildFlyerSvg, resolveFlyerOrigin } from "../src/services/flyer";
+import { buildQrMatrix, isPublicOrigin } from "../src/services/flyer/qr";
+
+const PRODUCTION_URL = "https://pokeguru.vercel.app";
+
+function stubSite(value: string | undefined) {
+ vi.stubEnv("VITE_PUBLIC_SITE_URL", value ?? "");
+}
+
+/** Rasterises the QR matrix (with its quiet zone) into an ImageData for jsQR. */
+function rasterise(modules: boolean[][], quietZone: number, scale = 8): ImageData {
+ const size = modules.length + quietZone * 2;
+ const width = size * scale;
+ const data = new Uint8ClampedArray(width * width * 4).fill(255);
+ for (let row = 0; row < modules.length; row += 1) {
+ for (let col = 0; col < modules.length; col += 1) {
+ if (!modules[row][col]) continue;
+ for (let dy = 0; dy < scale; dy += 1) {
+ for (let dx = 0; dx < scale; dx += 1) {
+ const x = (col + quietZone) * scale + dx;
+ const y = (row + quietZone) * scale + dy;
+ const index = (y * width + x) * 4;
+ data[index] = 0;
+ data[index + 1] = 0;
+ data[index + 2] = 0;
+ data[index + 3] = 255;
+ }
+ }
+ }
+ }
+ return { data, width, height: width, colorSpace: "srgb" } as ImageData;
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("production address resolution", () => {
+ it("accepts ordinary https sites but rejects anything that is not the live site", () => {
+ expect(isPublicOrigin(PRODUCTION_URL)).toBe(true);
+ expect(isPublicOrigin("https://pokeguru.co.uk")).toBe(true);
+
+ expect(isPublicOrigin("http://pokeguru.vercel.app")).toBe(false);
+ expect(isPublicOrigin("https://localhost:5173")).toBe(false);
+ expect(isPublicOrigin("https://127.0.0.1")).toBe(false);
+ expect(isPublicOrigin("https://pokeguru.local")).toBe(false);
+ expect(isPublicOrigin("https://5173-abc.e2b.app")).toBe(false);
+ expect(isPublicOrigin("https://pokeguru-git-main-team.vercel.app")).toBe(false);
+ expect(isPublicOrigin("https://pokeguru-8f3k2l-team-projects.vercel.app")).toBe(false);
+ expect(isPublicOrigin("https://pokeguru.vercel.app/about")).toBe(false);
+ expect(isPublicOrigin("not a url")).toBe(false);
+ });
+
+ it("uses VITE_PUBLIC_SITE_URL when it is a public address", () => {
+ stubSite(PRODUCTION_URL);
+ const resolved = resolveFlyerOrigin();
+ expect(resolved).toMatchObject({ origin: PRODUCTION_URL, host: "pokeguru.vercel.app", source: "configured" });
+ });
+
+ it("falls back to the served origin when the app runs on the real domain", () => {
+ const resolved = resolveFlyerOrigin("", PRODUCTION_URL);
+ expect(resolved).toMatchObject({ origin: PRODUCTION_URL, source: "served" });
+ });
+
+ it("refuses to build a QR code for a local or preview host", () => {
+ stubSite("");
+ const local = resolveFlyerOrigin("", "http://localhost:3000");
+ expect(local.origin).toBeNull();
+ expect(local.host).toBeNull();
+ expect("message" in local && local.message).toMatch(/VITE_PUBLIC_SITE_URL/);
+
+ const preview = resolveFlyerOrigin("", "https://pokeguru-8f3k2l-team.vercel.app");
+ expect(preview.origin).toBeNull();
+ });
+});
+
+describe("QR code", () => {
+ it("decodes back to the production URL with an independent decoder", async () => {
+ const matrix = await buildQrMatrix(PRODUCTION_URL);
+ expect(matrix.quietZone).toBe(4);
+ expect(matrix.size).toBeGreaterThanOrEqual(21);
+
+ const image = rasterise(matrix.modules, matrix.quietZone);
+ const decoded = jsQR(image.data, image.width, image.height, { inversionAttempts: "dontInvert" });
+ expect(decoded?.data).toBe(PRODUCTION_URL);
+ });
+});
+
+describe("flyer PDF", () => {
+ it("is a single 5 × 7 inch portrait page named PokeGuru-5x7-QR-Flyer.pdf", async () => {
+ stubSite(PRODUCTION_URL);
+ const file = await buildFlyerFile();
+
+ expect(file.fileName).toBe("PokeGuru-5x7-QR-Flyer.pdf");
+ expect(file.fileName).toBe(FLYER_FILE_NAME);
+
+ const doc = await PDFDocument.load(await file.blob.arrayBuffer());
+ expect(doc.getPageCount()).toBe(1);
+
+ const [page] = doc.getPages();
+ const { width, height } = page.getSize();
+ expect(width).toBeCloseTo(360, 3); // 5 in × 72 pt
+ expect(height).toBeCloseTo(504, 3); // 7 in × 72 pt
+ expect(width / 72).toBeCloseTo(5, 6);
+ expect(height / 72).toBeCloseTo(7, 6);
+ expect(height).toBeGreaterThan(width); // portrait
+
+ expect(page.getMediaBox()).toMatchObject({ x: 0, y: 0, width: 360, height: 504 });
+ expect(page.getCropBox()).toMatchObject({ x: 0, y: 0, width: 360, height: 504 });
+
+ expect(file.millimetres.width).toBeCloseTo(127, 1);
+ expect(file.millimetres.height).toBeCloseTo(177.8, 1);
+ expect(file.blob.type).toBe("application/pdf");
+ });
+
+ it("embeds the production address in the document and the vector copy", async () => {
+ stubSite(PRODUCTION_URL);
+ const file = await buildFlyerFile();
+ const raw = new TextDecoder("latin1").decode(new Uint8Array(await file.blob.arrayBuffer()));
+ expect(raw.startsWith("%PDF-")).toBe(true);
+
+ const svg = await buildFlyerSvg();
+ expect(svg).toContain("pokeguru.vercel.app");
+ expect(svg).toContain("");
+ expect(svg).toContain('viewBox="0 0 360 504"');
+ });
+
+ it("refuses to render when no public address is configured", async () => {
+ stubSite("");
+ await expect(buildFlyerFile()).rejects.toThrow(/VITE_PUBLIC_SITE_URL/);
+ });
+});
diff --git a/tests/install-prompt.test.tsx b/tests/install-prompt.test.tsx
new file mode 100644
index 0000000..fa33525
--- /dev/null
+++ b/tests/install-prompt.test.tsx
@@ -0,0 +1,156 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import InstallPrompt from "../src/components/UI/InstallPrompt";
+
+const SHOW_DELAY = 7000;
+const DISMISS_KEY = "pokeguru_install_prompt_v1";
+
+interface FakeInstallEvent extends Event {
+ prompt: ReturnType;
+ userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
+}
+
+function makeInstallEvent(buttonLabel = "beforeinstallprompt"): FakeInstallEvent {
+ const event = new Event(buttonLabel, { cancelable: true }) as FakeInstallEvent;
+ event.prompt = vi.fn().mockResolvedValue(undefined);
+ event.userChoice = Promise.resolve({ outcome: "accepted" });
+ return event;
+}
+
+function stubUserAgent(userAgent: string, platform = "Linux x86_64") {
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(userAgent);
+ vi.spyOn(window.navigator, "platform", "get").mockReturnValue(platform);
+}
+
+function stubStandalone(standalone: boolean) {
+ vi.stubGlobal(
+ "matchMedia",
+ vi.fn().mockImplementation((query: string) => ({
+ matches: standalone && query.includes("standalone"),
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }))
+ );
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("InstallPrompt", () => {
+ it("stays hidden until the app has loaded, then invites the visitor", async () => {
+ vi.useFakeTimers();
+ stubStandalone(false);
+ stubUserAgent("Mozilla/5.0 (X11; Linux x86_64) Chrome/131.0");
+
+ render();
+ await act(async () => {
+ window.dispatchEvent(makeInstallEvent());
+ });
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+
+ await act(async () => {
+ vi.advanceTimersByTime(SHOW_DELAY - 1);
+ });
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+
+ await act(async () => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.getByText(/take pokeguru with you/i)).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Install PokeGuru/i })).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Maybe later/i })).toBeTruthy();
+ });
+
+ it("only calls the browser's install prompt after Install is chosen", async () => {
+ vi.useFakeTimers();
+ stubStandalone(false);
+ stubUserAgent("Mozilla/5.0 (X11; Linux x86_64) Chrome/131.0");
+
+ render();
+ const event = makeInstallEvent();
+ await act(async () => {
+ window.dispatchEvent(event);
+ vi.advanceTimersByTime(SHOW_DELAY);
+ });
+
+ // Capturing the event must not open the browser dialogue on its own.
+ expect(event.prompt).not.toHaveBeenCalled();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /Install PokeGuru/i }));
+ });
+ expect(event.prompt).toHaveBeenCalledTimes(1);
+ });
+
+ it("remembers a dismissal instead of asking again on the next page view", async () => {
+ vi.useFakeTimers();
+ stubStandalone(false);
+ stubUserAgent("Mozilla/5.0 (X11; Linux x86_64) Chrome/131.0");
+
+ const first = render();
+ await act(async () => {
+ window.dispatchEvent(makeInstallEvent());
+ vi.advanceTimersByTime(SHOW_DELAY);
+ });
+ fireEvent.click(screen.getByRole("button", { name: /Maybe later/i }));
+
+ expect(localStorage.getItem(DISMISS_KEY)).toBeTruthy();
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+ first.unmount();
+
+ render();
+ await act(async () => {
+ window.dispatchEvent(makeInstallEvent());
+ vi.advanceTimersByTime(SHOW_DELAY);
+ });
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+ });
+
+ it("stays hidden once the app is installed", async () => {
+ vi.useFakeTimers();
+ stubStandalone(true);
+ stubUserAgent("Mozilla/5.0 (X11; Linux x86_64) Chrome/131.0");
+
+ render();
+ await act(async () => {
+ vi.advanceTimersByTime(SHOW_DELAY * 2);
+ });
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+ });
+
+ it("explains the Safari share sheet on iOS instead of pretending to install", async () => {
+ vi.useFakeTimers();
+ stubStandalone(false);
+ stubUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Safari/604.1", "iPhone");
+
+ render();
+ await act(async () => {
+ vi.advanceTimersByTime(SHOW_DELAY);
+ });
+
+ expect(screen.getByText(/take pokeguru with you/i)).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /Install PokeGuru/i }));
+ expect(screen.getByText(/Add to Home Screen/i)).toBeTruthy();
+ expect(screen.getByText(/Share button in Safari/i)).toBeTruthy();
+ });
+
+ it("never advertises an install it cannot perform on unsupported browsers", async () => {
+ vi.useFakeTimers();
+ stubStandalone(false);
+ stubUserAgent("Mozilla/5.0 (Windows NT 10.0; rv:130.0) Gecko/20100101 Firefox/130.0", "Win32");
+
+ render();
+ await act(async () => {
+ vi.advanceTimersByTime(SHOW_DELAY);
+ });
+ expect(screen.queryByText(/take pokeguru with you/i)).toBeNull();
+ });
+});