Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(ar-creature): add Next.js AR creature app
nirholasadd087b558b2
diff --git a/ar-creature/.env.example b/ar-creature/.env.examplenew file mode 100644index 000000000..81f600bae--- /dev/null+++ b/ar-creature/.env.example@@ -0,0 +1,32 @@+# ---------- App ----------+NEXT_PUBLIC_APP_URL="http://localhost:3000"+NEXTAUTH_URL="http://localhost:3000"+# generate with: openssl rand -base64 32+AUTH_SECRET=""++# ---------- Database (Postgres) ----------+# Neon / Supabase / Railway / RDS — all work.+DATABASE_URL="postgresql://user:password@host:5432/dbname?sslmode=require"++# ---------- OAuth (Google) ----------+# https://console.cloud.google.com → Credentials → OAuth client ID (Web)+# Authorized redirect URI: http://localhost:3000/api/auth/callback/google+AUTH_GOOGLE_ID=""+AUTH_GOOGLE_SECRET=""++# ---------- Magic-link email (Resend) ----------+# https://resend.com → API Keys+AUTH_RESEND_KEY=""+EMAIL_FROM="ar-creature <[email protected]>"++# ---------- Stripe ----------+# https://dashboard.stripe.com/apikeys+STRIPE_SECRET_KEY="sk_test_..."+NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_..."++# Create a recurring Price in Stripe Dashboard, paste the price_... id here.+STRIPE_PRO_PRICE_ID="price_..."++# For local dev: run `pnpm stripe:listen` and paste the whsec_... it prints.+# For prod: create a webhook endpoint at /api/stripe/webhook in the dashboard.+STRIPE_WEBHOOK_SECRET="whsec_..."diff --git a/ar-creature/.eslintrc.json b/ar-creature/.eslintrc.jsonnew file mode 100644index 000000000..1eb49acc0--- /dev/null+++ b/ar-creature/.eslintrc.json@@ -0,0 +1,6 @@+{+ "extends": ["next/core-web-vitals", "next/typescript"],+ "rules": {+ "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]+ }+}diff --git a/ar-creature/.gitignore b/ar-creature/.gitignorenew file mode 100644index 000000000..44d55f60c--- /dev/null+++ b/ar-creature/.gitignore@@ -0,0 +1,10 @@+node_modules+.next+.env+.env.local+.env*.local+*.tsbuildinfo+next-env.d.ts+.DS_Store+.vercel+/prisma/migrations/dev.db*diff --git a/ar-creature/README.md b/ar-creature/README.mdnew file mode 100644index 000000000..33b394149--- /dev/null+++ b/ar-creature/README.md@@ -0,0 +1,158 @@+# Pocket AR++A real Next.js 15 SaaS. A creature lives in the user's camera, walks around via on-screen joystick, scales with depth. Free tier with 1 creature + watermarked photo capture; Pro tier ($9/mo by default) unlocks 4 creatures, video recording, no watermark, 4K capture.++The code is real. The infrastructure (Stripe account, DB, OAuth credentials, deployment) is yours to bring.++## Stack++- **Next.js 15** App Router + Server Components+- **TypeScript** strict mode+- **NextAuth v5** with Prisma adapter — Google OAuth + Resend magic-link email+- **Prisma** + **Postgres** (Neon / Supabase / Railway — any Postgres)+- **Stripe** subscriptions with signature-verified webhook+- **Tailwind CSS**++## What you need to provide++Before this runs, you need accounts and credentials for:++1. **Postgres database.** [Neon](https://neon.tech) free tier is fine. Get the connection string.+2. **Stripe account** at [stripe.com](https://stripe.com).+ - Get test API keys from Dashboard → Developers → API keys.+ - Create a recurring Price in Dashboard → Products → Add product. Copy the `price_...` ID.+3. **Google OAuth** at [console.cloud.google.com](https://console.cloud.google.com).+ - APIs & Services → Credentials → Create OAuth 2.0 Client ID (Web).+ - Authorized redirect URI: `http://localhost:3000/api/auth/callback/google` (and your prod URL).+4. **Resend** at [resend.com](https://resend.com) for magic-link email. Get an API key.+5. **Stripe CLI** for local webhook testing: [stripe.com/docs/stripe-cli](https://stripe.com/docs/stripe-cli).++## Setup++```bash+# 1. Install+pnpm install # or: npm install / yarn++# 2. Configure env+cp .env.example .env+# Fill in every value. Generate AUTH_SECRET with: openssl rand -base64 32++# 3. Push the schema to your Postgres+pnpm db:push++# 4. In one terminal, forward Stripe webhooks to your local server.+# This prints a whsec_... secret — paste it into .env as STRIPE_WEBHOOK_SECRET.+pnpm stripe:listen++# 5. In another terminal, run the app+pnpm dev+```++Open `http://localhost:3000`. Log in. Click START PLAYING. Allow camera access in the browser prompt. Walk your creature around.++To test payments, use Stripe test card `4242 4242 4242 4242` with any future expiry and any CVC.++## Production deployment++### Vercel (recommended)++```bash+vercel+```++In the Vercel dashboard, add all env vars from `.env.example`. Update these for production:++- `NEXT_PUBLIC_APP_URL` and `NEXTAUTH_URL` → your real domain+- `STRIPE_SECRET_KEY` / `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` → live keys, NOT test keys+- `STRIPE_PRO_PRICE_ID` → the live mode price ID (separate from test mode)++### Stripe webhook for production++1. In Stripe Dashboard → Developers → Webhooks → Add endpoint.+2. URL: `https://yourdomain.com/api/stripe/webhook`+3. Listen to these events:+ - `checkout.session.completed`+ - `customer.subscription.created`+ - `customer.subscription.updated`+ - `customer.subscription.deleted`+ - `invoice.payment_failed`+4. Copy the **signing secret** (`whsec_...`) into `STRIPE_WEBHOOK_SECRET` in Vercel env.++### Google OAuth for production++Add `https://yourdomain.com/api/auth/callback/google` to Authorized redirect URIs in the Google Cloud console.++## Project layout++```+src/+├── app/+│ ├── api/+│ │ ├── auth/[...nextauth]/route.ts NextAuth handlers+│ │ ├── stripe/checkout/route.ts Creates a Stripe Checkout session+│ │ ├── stripe/portal/route.ts Opens Stripe billing portal+│ │ ├── stripe/webhook/route.ts Verifies signature, syncs subscription state+│ │ └── user/route.ts Returns current plan+│ ├── account/page.tsx Plan status, manage billing, sign out+│ ├── login/page.tsx Google + magic link+│ ├── play/page.tsx The AR experience (auth-gated)+│ ├── pricing/page.tsx Tiers + checkout button+│ ├── page.tsx Landing+│ ├── layout.tsx+│ └── globals.css+├── components/+│ ├── ManageBillingButton.tsx+│ └── ar/+│ ├── ARStage.tsx Main orchestrator: camera + joystick + avatar + capture+│ ├── CameraFeed.tsx getUserMedia, facing switch, error handling+│ ├── Joystick.tsx Pointer-driven joystick UI+│ ├── useJoystick.ts Joystick input hook (pointer + keyboard)+│ ├── Avatar.tsx Side-view SVG creature (4 palette variants)+│ ├── AvatarSelector.tsx Tier-gated character picker+│ ├── HUD.tsx Top status bar+│ └── PaywallModal.tsx Triggered when free user taps locked feature+├── lib/+│ ├── auth.ts NextAuth config+│ ├── db.ts Prisma client singleton+│ ├── stripe.ts Stripe SDK+│ ├── plans.ts Plan/entitlement definitions+│ ├── subscription.ts Resolves user's effective plan from DB+│ └── cn.ts Class merging utility+└── types/+ └── next-auth.d.ts Session.user.id type augmentation+```++## How gating works++`src/lib/plans.ts` is the single source of truth for what each tier includes. `getUserPlan(userId)` reads the user's `Subscription` row (kept fresh by the Stripe webhook) and returns the active entitlements. Both server pages and client components consult this:++- `src/app/play/page.tsx` (server) passes entitlements into `ARStage`+- `ARStage` (client) consults entitlements when the user taps a locked avatar or tries to capture a photo+- The watermark logic in `capturePhoto` checks `entitlements.watermark` and burns text into the canvas before download++There is no client-side trust: even if a free user bypassed the UI, the entitlements come from a server fetch tied to their authenticated session.++## Camera access in deployed environments++`getUserMedia` requires HTTPS (except on `localhost`). When deployed to your real domain it works on iOS Safari, Android Chrome, and desktop browsers. The user must grant camera permission via the native browser prompt.++## What's not included (intentionally)++These are common scope-creep additions that aren't shipped here. They're easy to add when you actually need them:++- Email transactional flow beyond magic-link sign-in+- User-uploaded custom avatars (requires file storage like S3/R2)+- Analytics (PostHog or Plausible — add to `layout.tsx`)+- Admin dashboard+- Internationalization++## Security notes++- Webhook signature verification uses `stripe.webhooks.constructEvent` and the raw request body — never bypass this.+- `Permissions-Policy` header in `next.config.mjs` restricts camera access to same-origin.+- All API routes that mutate state check the session.+- The Stripe customer ID and subscription state are stored server-side; the client never sees Stripe secrets.++## License++MIT. Build a business on it.diff --git a/ar-creature/middleware.ts b/ar-creature/middleware.tsnew file mode 100644index 000000000..1ad3dd50a--- /dev/null+++ b/ar-creature/middleware.ts@@ -0,0 +1,22 @@+import { auth } from "@/lib/auth";+import { NextResponse } from "next/server";++export default auth((req) => {+ const isAuthed = !!req.auth;+ const pathname = req.nextUrl.pathname;++ const protectedPaths = ["/play", "/account"];+ const needsAuth = protectedPaths.some((p) => pathname === p || pathname.startsWith(p + "/"));++ if (needsAuth && !isAuthed) {+ const loginUrl = new URL("/login", req.nextUrl.origin);+ loginUrl.searchParams.set("next", pathname);+ return NextResponse.redirect(loginUrl);+ }++ return NextResponse.next();+});++export const config = {+ matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"],+};diff --git a/ar-creature/next.config.mjs b/ar-creature/next.config.mjsnew file mode 100644index 000000000..2f3b990e5--- /dev/null+++ b/ar-creature/next.config.mjs@@ -0,0 +1,26 @@+/** @type {import('next').NextConfig} */+const nextConfig = {+ reactStrictMode: true,+ poweredByHeader: false,+ async headers() {+ return [+ {+ source: "/(.*)",+ headers: [+ { key: "X-Frame-Options", value: "SAMEORIGIN" },+ { key: "X-Content-Type-Options", value: "nosniff" },+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },+ {+ key: "Permissions-Policy",+ value: "camera=(self), microphone=(), geolocation=()",+ },+ ],+ },+ ];+ },+ experimental: {+ serverActions: { bodySizeLimit: "2mb" },+ },+};++export default nextConfig;diff --git a/ar-creature/package.json b/ar-creature/package.jsonnew file mode 100644index 000000000..f52dd9021--- /dev/null+++ b/ar-creature/package.json@@ -0,0 +1,45 @@+{+ "name": "ar-creature",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "dev": "next dev",+ "build": "prisma generate && next build",+ "start": "next start",+ "lint": "next lint",+ "typecheck": "tsc --noEmit",+ "db:push": "prisma db push",+ "db:generate": "prisma generate",+ "db:studio": "prisma studio",+ "stripe:listen": "stripe listen --forward-to localhost:3000/api/stripe/webhook",+ "postinstall": "prisma generate"+ },+ "dependencies": {+ "@auth/prisma-adapter": "^2.7.4",+ "@prisma/client": "^5.22.0",+ "clsx": "^2.1.1",+ "next": "15.0.3",+ "next-auth": "5.0.0-beta.25",+ "react": "19.0.0-rc-66855b96-20241106",+ "react-dom": "19.0.0-rc-66855b96-20241106",+ "resend": "^4.0.1",+ "stripe": "^17.4.0",+ "tailwind-merge": "^2.5.4",+ "zod": "^3.23.8"+ },+ "devDependencies": {+ "@types/node": "^22.9.0",+ "@types/react": "^18.3.12",+ "@types/react-dom": "^18.3.1",+ "autoprefixer": "^10.4.20",+ "eslint": "^9.14.0",+ "eslint-config-next": "15.0.3",+ "postcss": "^8.4.49",+ "prisma": "^5.22.0",+ "tailwindcss": "^3.4.15",+ "typescript": "^5.6.3"+ },+ "engines": {+ "node": ">=20"+ }+}diff --git a/ar-creature/postcss.config.mjs b/ar-creature/postcss.config.mjsnew file mode 100644index 000000000..2aa7205d4--- /dev/null+++ b/ar-creature/postcss.config.mjs@@ -0,0 +1,6 @@+export default {+ plugins: {+ tailwindcss: {},+ autoprefixer: {},+ },+};diff --git a/ar-creature/prisma/schema.prisma b/ar-creature/prisma/schema.prismanew file mode 100644index 000000000..749c206b2--- /dev/null+++ b/ar-creature/prisma/schema.prisma@@ -0,0 +1,81 @@+generator client {+ provider = "prisma-client-js"+}++datasource db {+ provider = "postgresql"+ url = env("DATABASE_URL")+}++model User {+ id String @id @default(cuid())+ name String?+ email String @unique+ emailVerified DateTime?+ image String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ accounts Account[]+ sessions Session[]+ subscription Subscription?+}++// NextAuth: linked OAuth accounts+model Account {+ id String @id @default(cuid())+ userId String+ type String+ provider String+ providerAccountId String+ refresh_token String? @db.Text+ access_token String? @db.Text+ expires_at Int?+ token_type String?+ scope String?+ id_token String? @db.Text+ session_state String?++ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@unique([provider, providerAccountId])+ @@index([userId])+}++// NextAuth: server-side session+model Session {+ id String @id @default(cuid())+ sessionToken String @unique+ userId String+ expires DateTime+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@index([userId])+}++// NextAuth: magic-link verification+model VerificationToken {+ identifier String+ token String @unique+ expires DateTime++ @@unique([identifier, token])+}++// Stripe subscription state, synced via webhook+model Subscription {+ id String @id @default(cuid())+ userId String @unique+ stripeCustomerId String @unique+ stripeSubscriptionId String @unique+ stripePriceId String+ status String // active, trialing, past_due, canceled, etc.+ currentPeriodEnd DateTime+ cancelAtPeriodEnd Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ @@index([stripeCustomerId])+ @@index([status])+}diff --git a/ar-creature/src/app/account/page.tsx b/ar-creature/src/app/account/page.tsxnew file mode 100644index 000000000..285c2ec00--- /dev/null+++ b/ar-creature/src/app/account/page.tsx@@ -0,0 +1,100 @@+import Link from "next/link";+import { redirect } from "next/navigation";+import { auth, signOut } from "@/lib/auth";+import { getUserPlan } from "@/lib/subscription";+import { ManageBillingButton } from "@/components/ManageBillingButton";++export default async function AccountPage({+ searchParams,+}: {+ searchParams: Promise<{ checkout?: string }>;+}) {+ const session = await auth();+ if (!session?.user?.id) {+ redirect("/login?next=/account");+ }+ const plan = await getUserPlan(session.user.id);+ const sp = await searchParams;++ return (+ <main className="relative min-h-screen px-6 py-12">+ <div+ aria-hidden+ className="absolute inset-0 -z-10"+ style={{ background: "radial-gradient(60% 60% at 50% 30%, rgba(33,241,255,.15), transparent 60%), #0b0b10" }}+ />+ <Link href="/" className="font-display text-2xl tracking-wide">+ ← POCKET <span className="text-neon">◆</span> AR+ </Link>++ <div className="mx-auto mt-16 max-w-xl">+ {sp.checkout === "success" && (+ <div className="mb-8 rounded-2xl border border-acid/40 bg-acid/10 px-5 py-4 text-acid">+ 🎉 you're on pro. it can take a few seconds for the webhook to confirm.+ </div>+ )}++ <h1 className="font-display text-5xl leading-none">account.</h1>+ <p className="mt-2 text-paper/60">{session.user.email}</p>++ <div className="mt-10 rounded-3xl border border-white/10 bg-ink/40 p-6 backdrop-blur-sm">+ <div className="flex items-baseline justify-between">+ <h2 className="font-display text-3xl tracking-wide">PLAN</h2>+ <span+ className={`rounded-full px-3 py-1 font-display text-sm tracking-widest ${+ plan.planId === "pro" ? "bg-neon/15 text-neon" : "bg-white/5 text-paper/70"+ }`}+ >+ {plan.planId.toUpperCase()}+ </span>+ </div>++ {plan.planId === "pro" ? (+ <>+ <p className="mt-4 text-sm text-paper/70">+ Status: <span className="text-paper">{plan.status}</span>+ </p>+ {plan.currentPeriodEnd && (+ <p className="text-sm text-paper/70">+ {plan.cancelAtPeriodEnd ? "Ends" : "Renews"} on{" "}+ <span className="text-paper">+ {plan.currentPeriodEnd.toLocaleDateString()}+ </span>+ </p>+ )}+ <div className="mt-6">+ <ManageBillingButton />+ </div>+ </>+ ) : (+ <>+ <p className="mt-4 text-sm text-paper/70">+ You're on the free plan. Upgrade for more creatures, video recording, and no+ watermark.+ </p>+ <Link href="/pricing" className="btn-primary mt-6">+ UPGRADE TO PRO+ </Link>+ </>+ )}+ </div>++ <div className="mt-6 flex gap-3">+ <Link href="/play" className="btn-ghost">+ ← BACK TO PLAY+ </Link>+ <form+ action={async () => {+ "use server";+ await signOut({ redirectTo: "/" });+ }}+ >+ <button type="submit" className="btn-ghost">+ SIGN OUT+ </button>+ </form>+ </div>+ </div>+ </main>+ );+}diff --git a/ar-creature/src/app/api/auth/[...nextauth]/route.ts b/ar-creature/src/app/api/auth/[...nextauth]/route.tsnew file mode 100644index 000000000..c55a45ed7--- /dev/null+++ b/ar-creature/src/app/api/auth/[...nextauth]/route.ts@@ -0,0 +1,3 @@+import { handlers } from "@/lib/auth";++export const { GET, POST } = handlers;diff --git a/ar-creature/src/app/api/stripe/checkout/route.ts b/ar-creature/src/app/api/stripe/checkout/route.tsnew file mode 100644index 000000000..42f9245b4--- /dev/null+++ b/ar-creature/src/app/api/stripe/checkout/route.ts@@ -0,0 +1,50 @@+import { NextResponse } from "next/server";+import { auth } from "@/lib/auth";+import { stripe, PRO_PRICE_ID } from "@/lib/stripe";+import { prisma } from "@/lib/db";++export const runtime = "nodejs";++export async function POST() {+ const session = await auth();+ if (!session?.user?.id || !session.user.email) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ if (!PRO_PRICE_ID) {+ return NextResponse.json(+ { error: "STRIPE_PRO_PRICE_ID is not configured" },+ { status: 500 },+ );+ }++ // Re-use an existing Stripe customer if we have one; otherwise let Checkout create one.+ const existingSub = await prisma.subscription.findUnique({+ where: { userId: session.user.id },+ select: { stripeCustomerId: true },+ });++ const appUrl = process.env.NEXT_PUBLIC_APP_URL!;++ const checkoutSession = await stripe.checkout.sessions.create({+ mode: "subscription",+ payment_method_types: ["card"],+ line_items: [{ price: PRO_PRICE_ID, quantity: 1 }],+ success_url: `${appUrl}/account?checkout=success`,+ cancel_url: `${appUrl}/pricing?checkout=cancelled`,+ customer: existingSub?.stripeCustomerId ?? undefined,+ customer_email: existingSub?.stripeCustomerId ? undefined : session.user.email,+ client_reference_id: session.user.id,+ metadata: { userId: session.user.id },+ subscription_data: {+ metadata: { userId: session.user.id },+ },+ allow_promotion_codes: true,+ });++ if (!checkoutSession.url) {+ return NextResponse.json({ error: "Failed to create checkout session" }, { status: 500 });+ }++ return NextResponse.json({ url: checkoutSession.url });+}diff --git a/ar-creature/src/app/api/stripe/portal/route.ts b/ar-creature/src/app/api/stripe/portal/route.tsnew file mode 100644index 000000000..09b8dba2f--- /dev/null+++ b/ar-creature/src/app/api/stripe/portal/route.ts@@ -0,0 +1,29 @@+import { NextResponse } from "next/server";+import { auth } from "@/lib/auth";+import { stripe } from "@/lib/stripe";+import { prisma } from "@/lib/db";++export const runtime = "nodejs";++export async function POST() {+ const session = await auth();+ if (!session?.user?.id) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const sub = await prisma.subscription.findUnique({+ where: { userId: session.user.id },+ select: { stripeCustomerId: true },+ });++ if (!sub?.stripeCustomerId) {+ return NextResponse.json({ error: "No active subscription" }, { status: 404 });+ }++ const portal = await stripe.billingPortal.sessions.create({+ customer: sub.stripeCustomerId,+ return_url: `${process.env.NEXT_PUBLIC_APP_URL}/account`,+ });++ return NextResponse.json({ url: portal.url });+}diff --git a/ar-creature/src/app/api/stripe/webhook/route.ts b/ar-creature/src/app/api/stripe/webhook/route.tsnew file mode 100644index 000000000..d41a5e40d--- /dev/null+++ b/ar-creature/src/app/api/stripe/webhook/route.ts@@ -0,0 +1,121 @@+import { NextResponse } from "next/server";+import { headers } from "next/headers";+import type Stripe from "stripe";+import { stripe } from "@/lib/stripe";+import { prisma } from "@/lib/db";++export const runtime = "nodejs";+// Stripe sends raw body; we must NOT touch it before signature verification.+export const dynamic = "force-dynamic";++export async function POST(req: Request) {+ const body = await req.text();+ const signature = (await headers()).get("stripe-signature");++ if (!signature) {+ return NextResponse.json({ error: "Missing stripe-signature" }, { status: 400 });+ }++ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;+ if (!webhookSecret) {+ console.error("STRIPE_WEBHOOK_SECRET is not set");+ return NextResponse.json({ error: "Server misconfigured" }, { status: 500 });+ }++ let event: Stripe.Event;+ try {+ event = stripe.webhooks.constructEvent(body, signature, webhookSecret);+ } catch (err) {+ const message = err instanceof Error ? err.message : "Unknown error";+ console.error("Webhook signature verification failed:", message);+ return NextResponse.json({ error: `Webhook Error: ${message}` }, { status: 400 });+ }++ try {+ switch (event.type) {+ case "checkout.session.completed": {+ const checkoutSession = event.data.object as Stripe.Checkout.Session;+ const userId = checkoutSession.metadata?.userId ?? checkoutSession.client_reference_id;+ if (!userId) {+ console.error("checkout.session.completed missing userId", checkoutSession.id);+ break;+ }+ if (!checkoutSession.subscription) break;++ const subscription = await stripe.subscriptions.retrieve(+ checkoutSession.subscription as string,+ );++ await upsertSubscription(userId, subscription);+ break;+ }++ case "customer.subscription.updated":+ case "customer.subscription.created":+ case "customer.subscription.deleted": {+ const subscription = event.data.object as Stripe.Subscription;+ const userId =+ subscription.metadata?.userId ??+ (await resolveUserIdFromCustomer(subscription.customer as string));+ if (!userId) {+ console.error(`${event.type} missing userId`, subscription.id);+ break;+ }+ await upsertSubscription(userId, subscription);+ break;+ }++ case "invoice.payment_failed": {+ const invoice = event.data.object as Stripe.Invoice;+ if (invoice.subscription) {+ const subscription = await stripe.subscriptions.retrieve(+ invoice.subscription as string,+ );+ const userId =+ subscription.metadata?.userId ??+ (await resolveUserIdFromCustomer(subscription.customer as string));+ if (userId) await upsertSubscription(userId, subscription);+ }+ break;+ }++ default:+ // We don't act on other events but acknowledge receipt.+ break;+ }+ } catch (err) {+ console.error(`Error handling ${event.type}:`, err);+ return NextResponse.json({ error: "Internal error" }, { status: 500 });+ }++ return NextResponse.json({ received: true });+}++async function upsertSubscription(userId: string, sub: Stripe.Subscription) {+ const data = {+ stripeCustomerId: sub.customer as string,+ stripeSubscriptionId: sub.id,+ stripePriceId: sub.items.data[0]?.price.id ?? "",+ status: sub.status,+ currentPeriodEnd: new Date(sub.current_period_end * 1000),+ cancelAtPeriodEnd: sub.cancel_at_period_end,+ };++ await prisma.subscription.upsert({+ where: { userId },+ create: { userId, ...data },+ update: data,+ });+}++/**+ * Some webhook events arrive without metadata (e.g. subscriptions created+ * outside Checkout). Fall back to looking up the user by Stripe customer ID.+ */+async function resolveUserIdFromCustomer(customerId: string): Promise<string | null> {+ const existing = await prisma.subscription.findFirst({+ where: { stripeCustomerId: customerId },+ select: { userId: true },+ });+ return existing?.userId ?? null;+}diff --git a/ar-creature/src/app/api/user/route.ts b/ar-creature/src/app/api/user/route.tsnew file mode 100644index 000000000..309e89844--- /dev/null+++ b/ar-creature/src/app/api/user/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from "next/server";+import { auth } from "@/lib/auth";+import { getUserPlan } from "@/lib/subscription";++export const runtime = "nodejs";++export async function GET() {+ const session = await auth();+ if (!session?.user?.id) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const plan = await getUserPlan(session.user.id);++ return NextResponse.json({+ user: {+ id: session.user.id,+ email: session.user.email,+ name: session.user.name,+ image: session.user.image,+ },+ plan,+ });+}diff --git a/ar-creature/src/app/globals.css b/ar-creature/src/app/globals.cssnew file mode 100644index 000000000..7e49866b5--- /dev/null+++ b/ar-creature/src/app/globals.css@@ -0,0 +1,60 @@+@import url("https://fonts.googleapis.com/css2?family=VT323&family=Space+Mono:wght@400;700&display=swap");++@tailwind base;+@tailwind components;+@tailwind utilities;++@layer base {+ :root {+ --ink: #0b0b10;+ --paper: #f4f0e6;+ --neon: #ff2a87;+ --cyan: #21f1ff;+ --acid: #d9ff3c;+ }++ html,+ body {+ background: #000;+ color: var(--paper);+ font-family: "Space Mono", ui-monospace, monospace;+ -webkit-font-smoothing: antialiased;+ }++ body {+ overscroll-behavior: none;+ }++ * {+ -webkit-tap-highlight-color: transparent;+ }+}++@layer components {+ .btn-primary {+ @apply inline-flex items-center justify-center rounded-full bg-paper px-7 py-4 font-display text-2xl tracking-widest text-ink transition-transform active:translate-y-0.5;+ box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4), inset 0 -4px 0 rgba(0, 0, 0, 0.15);+ }+ .btn-ghost {+ @apply inline-flex items-center justify-center rounded-full border border-white/25 bg-transparent px-5 py-3 font-display text-lg tracking-widest text-paper transition-colors hover:bg-white/5;+ }+ .pill {+ @apply inline-flex items-center gap-2 rounded-full border border-white/10 bg-ink/55 px-4 py-2 font-display text-lg tracking-wider backdrop-blur-md;+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.08), 0 8px 30px rgba(0, 0, 0, 0.45);+ }+}++/* AR-specific styles that don't fit Tailwind utilities cleanly */+.ar-shadow {+ background: radial-gradient(50% 60% at 50% 50%, rgba(0, 0, 0, 0.55), rgba(0, 0, 0, 0) 70%);+}++.ar-noise {+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='160'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/></filter><rect width='100%25' height='100%25' filter='url(%23n)' opacity='0.5'/></svg>");+}++/* SVG group transforms need fill-box for predictable rotation origins */+.svg-pivot {+ transform-box: fill-box;+ transform-origin: 50% 0%;+}diff --git a/ar-creature/src/app/layout.tsx b/ar-creature/src/app/layout.tsxnew file mode 100644index 000000000..22e3bd24f--- /dev/null+++ b/ar-creature/src/app/layout.tsx@@ -0,0 +1,30 @@+import type { Metadata, Viewport } from "next";+import "./globals.css";++export const metadata: Metadata = {+ title: "Pocket AR — a creature lives in your camera",+ description:+ "A tiny creature you can walk around your real world. Open the camera, grab the joystick, explore.",+ openGraph: {+ title: "Pocket AR",+ description: "A tiny creature lives in your camera. Walk it around.",+ type: "website",+ },+};++export const viewport: Viewport = {+ width: "device-width",+ initialScale: 1,+ maximumScale: 1,+ userScalable: false,+ viewportFit: "cover",+ themeColor: "#0b0b10",+};++export default function RootLayout({ children }: { children: React.ReactNode }) {+ return (+ <html lang="en">+ <body>{children}</body>+ </html>+ );+}diff --git a/ar-creature/src/app/login/page.tsx b/ar-creature/src/app/login/page.tsxnew file mode 100644index 000000000..39e149618--- /dev/null+++ b/ar-creature/src/app/login/page.tsx@@ -0,0 +1,97 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { signIn } from "next-auth/react";++export default function LoginPage() {+ const [email, setEmail] = useState("");+ const [loading, setLoading] = useState<null | "google" | "email">(null);+ const [sent, setSent] = useState(false);++ const handleEmail = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!email) return;+ setLoading("email");+ try {+ await signIn("resend", { email, callbackUrl: "/play", redirect: false });+ setSent(true);+ } finally {+ setLoading(null);+ }+ };++ return (+ <main className="relative flex min-h-screen items-center justify-center px-6">+ <div+ aria-hidden+ className="absolute inset-0 -z-10"+ style={{+ background:+ "radial-gradient(60% 60% at 50% 30%, rgba(255,42,135,.18), transparent 60%), #0b0b10",+ }}+ />+ <div className="w-full max-w-sm rounded-3xl border border-white/10 bg-ink/60 p-8 backdrop-blur-md">+ <Link href="/" className="font-display text-2xl tracking-wide">+ POCKET <span className="text-neon">◆</span> AR+ </Link>+ <h1 className="mt-6 font-display text-4xl leading-none">log in.</h1>+ <p className="mt-2 text-sm text-paper/60">to play, save creatures, or upgrade.</p>++ <button+ type="button"+ onClick={() => {+ setLoading("google");+ signIn("google", { callbackUrl: "/play" });+ }}+ disabled={loading !== null}+ className="mt-8 flex w-full items-center justify-center gap-3 rounded-full bg-paper px-5 py-3 font-display text-lg tracking-widest text-ink transition-transform active:translate-y-0.5 disabled:opacity-60"+ >+ <GoogleIcon className="h-5 w-5" />+ {loading === "google" ? "OPENING…" : "CONTINUE WITH GOOGLE"}+ </button>++ <div className="my-6 flex items-center gap-3 text-xs text-paper/40">+ <div className="h-px flex-1 bg-white/10" />+ OR+ <div className="h-px flex-1 bg-white/10" />+ </div>++ {sent ? (+ <p className="rounded-xl border border-acid/40 bg-acid/10 px-4 py-3 text-sm text-acid">+ check your email. we sent you a magic link.+ </p>+ ) : (+ <form onSubmit={handleEmail} className="space-y-3">+ <input+ type="email"+ required+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder="[email protected]"+ className="w-full rounded-full border border-white/15 bg-black/40 px-5 py-3 text-paper placeholder:text-paper/30 focus:border-cyan/60 focus:outline-none"+ />+ <button+ type="submit"+ disabled={loading !== null || !email}+ className="btn-ghost w-full disabled:opacity-50"+ >+ {loading === "email" ? "SENDING…" : "EMAIL ME A LINK"}+ </button>+ </form>+ )}+ </div>+ </main>+ );+}++function GoogleIcon({ className }: { className?: string }) {+ return (+ <svg viewBox="0 0 24 24" className={className} aria-hidden>+ <path+ fill="#EA4335"+ d="M12 11v3.2h4.5c-.2 1.2-1.4 3.5-4.5 3.5-2.7 0-4.9-2.2-4.9-5s2.2-5 4.9-5c1.5 0 2.6.7 3.2 1.2l2.2-2.1C16 5.4 14.2 4.5 12 4.5 7.9 4.5 4.5 7.9 4.5 12s3.4 7.5 7.5 7.5c4.3 0 7.2-3 7.2-7.3 0-.5-.1-.9-.1-1.2H12z"+ />+ </svg>+ );+}diff --git a/ar-creature/src/app/not-found.tsx b/ar-creature/src/app/not-found.tsxnew file mode 100644index 000000000..39f7db847--- /dev/null+++ b/ar-creature/src/app/not-found.tsx@@ -0,0 +1,13 @@+import Link from "next/link";++export default function NotFound() {+ return (+ <main className="flex min-h-screen flex-col items-center justify-center px-6 text-center">+ <p className="font-display text-3xl tracking-widest text-neon">404</p>+ <h1 className="mt-2 font-display text-5xl">nothing here.</h1>+ <Link href="/" className="btn-ghost mt-8">+ ← BACK HOME+ </Link>+ </main>+ );+}diff --git a/ar-creature/src/app/page.tsx b/ar-creature/src/app/page.tsxnew file mode 100644index 000000000..3d400912b--- /dev/null+++ b/ar-creature/src/app/page.tsx@@ -0,0 +1,84 @@+import Link from "next/link";+import { auth } from "@/lib/auth";++export default async function HomePage() {+ const session = await auth();+ const ctaHref = session ? "/play" : "/login";++ return (+ <main className="relative min-h-screen overflow-hidden">+ {/* atmospheric background */}+ <div+ aria-hidden+ className="absolute inset-0 -z-10"+ style={{+ background:+ "radial-gradient(60% 60% at 30% 30%, rgba(255,42,135,.22), transparent 60%), radial-gradient(60% 60% at 70% 70%, rgba(33,241,255,.22), transparent 60%), #0b0b10",+ }}+ />+ <div aria-hidden className="ar-noise pointer-events-none absolute inset-0 -z-10 opacity-[0.06]" />++ <nav className="flex items-center justify-between px-6 py-5 sm:px-10">+ <Link href="/" className="font-display text-3xl tracking-wide">+ POCKET <span className="text-neon">◆</span> <span className="text-cyan">AR</span>+ </Link>+ <div className="flex items-center gap-3">+ <Link href="/pricing" className="btn-ghost text-sm sm:text-lg">+ PRICING+ </Link>+ {session ? (+ <Link href="/account" className="btn-ghost text-sm sm:text-lg">+ ACCOUNT+ </Link>+ ) : (+ <Link href="/login" className="btn-ghost text-sm sm:text-lg">+ LOG IN+ </Link>+ )}+ </div>+ </nav>++ <section className="mx-auto flex max-w-3xl flex-col items-center px-6 pt-16 text-center sm:pt-24">+ <p className="mb-6 font-display text-xl tracking-[0.3em] text-acid drop-shadow-[0_0_12px_rgba(217,255,60,0.4)]">+ ▷ ▷ ▷ NEW & LIVE ◁ ◁ ◁+ </p>+ <h1 className="font-display text-6xl leading-none tracking-tight sm:text-8xl">+ a creature+ <br />+ lives in your+ <br />+ <span className="text-neon">camera.</span>+ </h1>+ <p className="mt-8 max-w-md text-base leading-relaxed text-paper/70 sm:text-lg">+ Open the camera. A tiny creature appears, standing in your room. Grab the joystick and walk+ it across the floor, into the kitchen, anywhere. It scales with depth, casts a shadow, and+ looks like it's really there.+ </p>+ <div className="mt-10 flex flex-col items-center gap-3">+ <Link href={ctaHref} className="btn-primary text-2xl">+ START PLAYING+ </Link>+ <p className="font-display text-sm tracking-widest text-paper/40">+ FREE TIER — NO CARD REQUIRED+ </p>+ </div>+ </section>++ <section className="mx-auto mt-32 grid max-w-4xl grid-cols-1 gap-6 px-6 pb-24 sm:grid-cols-3">+ {[+ { title: "REAL CAMERA", body: "Live video feed from your phone or laptop. The creature lives on top of it." },+ { title: "DEPTH ILLUSION", body: "Walk it up the screen and it shrinks. Walk it down and it grows. Reads as a tiny being in your space." },+ { title: "JOYSTICK", body: "Real analog joystick on screen. Drag, push, run. Side-view walking sprite with leg animation." },+ ].map((card) => (+ <div+ key={card.title}+ className="rounded-2xl border border-white/10 bg-ink/40 p-6 backdrop-blur-sm"+ >+ <h3 className="font-display text-2xl tracking-widest text-neon">{card.title}</h3>+ <p className="mt-3 text-sm leading-relaxed text-paper/70">{card.body}</p>+ </div>+ ))}+ </section>+ </main>+ );+}diff --git a/ar-creature/src/app/play/page.tsx b/ar-creature/src/app/play/page.tsxnew file mode 100644index 000000000..d1595f51c--- /dev/null+++ b/ar-creature/src/app/play/page.tsx@@ -0,0 +1,19 @@+import { redirect } from "next/navigation";+import { auth } from "@/lib/auth";+import { getUserPlan } from "@/lib/subscription";+import { ARStage } from "@/components/ar/ARStage";++export default async function PlayPage() {+ const session = await auth();+ if (!session?.user?.id) {+ redirect("/login?next=/play");+ }+ const plan = await getUserPlan(session.user.id);++ return (+ <ARStage+ entitlements={plan.entitlements}+ planLabel={plan.planId.toUpperCase()}+ />+ );+}diff --git a/ar-creature/src/app/pricing/page.tsx b/ar-creature/src/app/pricing/page.tsxnew file mode 100644index 000000000..574e1ea3a--- /dev/null+++ b/ar-creature/src/app/pricing/page.tsx@@ -0,0 +1,137 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { PLANS } from "@/lib/plans";++export default function PricingPage() {+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const handleUpgrade = async () => {+ setLoading(true);+ setError(null);+ try {+ const res = await fetch("/api/stripe/checkout", { method: "POST" });+ if (res.status === 401) {+ window.location.href = "/login?next=/pricing";+ return;+ }+ const data = await res.json();+ if (!res.ok) throw new Error(data.error ?? "Could not create checkout session");+ window.location.href = data.url;+ } catch (err) {+ setError(err instanceof Error ? err.message : "Something went wrong");+ setLoading(false);+ }+ };++ return (+ <main className="relative min-h-screen px-6 py-12">+ <div+ aria-hidden+ className="absolute inset-0 -z-10"+ style={{+ background:+ "radial-gradient(60% 60% at 30% 30%, rgba(255,42,135,.18), transparent 60%), radial-gradient(60% 60% at 70% 70%, rgba(33,241,255,.18), transparent 60%), #0b0b10",+ }}+ />+ <Link href="/" className="font-display text-2xl tracking-wide">+ ← POCKET <span className="text-neon">◆</span> AR+ </Link>++ <div className="mx-auto mt-16 max-w-3xl text-center">+ <h1 className="font-display text-6xl leading-none sm:text-7xl">+ simple <span className="text-neon">pricing.</span>+ </h1>+ <p className="mt-4 text-paper/60">free to start. upgrade when you want more creatures.</p>+ </div>++ <div className="mx-auto mt-12 grid max-w-3xl grid-cols-1 gap-6 sm:grid-cols-2">+ <PlanCard+ name={PLANS.free.name}+ price={PLANS.free.price}+ features={[+ "1 creature",+ "AR camera mode",+ "Photo capture (with watermark)",+ "Up to 1080p",+ ]}+ cta={+ <Link href="/play" className="btn-ghost w-full">+ START FREE+ </Link>+ }+ />+ <PlanCard+ name={PLANS.pro.name}+ price={PLANS.pro.price}+ highlight+ features={[+ "4 creatures (more coming)",+ "Video recording",+ "No watermark",+ "Up to 4K capture",+ "Priority support",+ ]}+ cta={+ <button+ onClick={handleUpgrade}+ disabled={loading}+ className="btn-primary w-full disabled:opacity-60"+ >+ {loading ? "REDIRECTING…" : "UPGRADE TO PRO"}+ </button>+ }+ />+ </div>++ {error && (+ <p className="mx-auto mt-6 max-w-md rounded-xl border border-neon/40 bg-neon/10 px-4 py-3 text-center text-sm text-neon">+ {error}+ </p>+ )}++ <p className="mx-auto mt-10 max-w-md text-center text-xs text-paper/40">+ Payments handled by Stripe. Cancel anytime from your account.+ </p>+ </main>+ );+}++function PlanCard({+ name,+ price,+ features,+ cta,+ highlight,+}: {+ name: string;+ price: number;+ features: string[];+ cta: React.ReactNode;+ highlight?: boolean;+}) {+ return (+ <div+ className={`rounded-3xl border p-8 backdrop-blur-sm ${+ highlight ? "border-neon/40 bg-neon/5" : "border-white/10 bg-ink/40"+ }`}+ >+ <p className="font-display text-2xl tracking-widest text-paper/70">{name.toUpperCase()}</p>+ <p className="mt-2 font-display text-6xl leading-none">+ ${price}+ <span className="ml-1 text-base text-paper/50">/mo</span>+ </p>+ <ul className="mt-6 space-y-2 text-sm text-paper/80">+ {features.map((f) => (+ <li key={f} className="flex items-start gap-2">+ <span className={highlight ? "text-neon" : "text-cyan"}>◆</span>+ <span>{f}</span>+ </li>+ ))}+ </ul>+ <div className="mt-8">{cta}</div>+ </div>+ );+}diff --git a/ar-creature/src/components/ManageBillingButton.tsx b/ar-creature/src/components/ManageBillingButton.tsxnew file mode 100644index 000000000..0b9eb7ffe--- /dev/null+++ b/ar-creature/src/components/ManageBillingButton.tsx@@ -0,0 +1,31 @@+"use client";++import { useState } from "react";++export function ManageBillingButton() {+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const onClick = async () => {+ setLoading(true);+ setError(null);+ try {+ const res = await fetch("/api/stripe/portal", { method: "POST" });+ const data = await res.json();+ if (!res.ok) throw new Error(data.error ?? "Failed to open billing portal");+ window.location.href = data.url;+ } catch (err) {+ setError(err instanceof Error ? err.message : "Something went wrong");+ setLoading(false);+ }+ };++ return (+ <>+ <button onClick={onClick} disabled={loading} className="btn-ghost disabled:opacity-60">+ {loading ? "OPENING…" : "MANAGE BILLING"}+ </button>+ {error && <p className="mt-3 text-sm text-neon">{error}</p>}+ </>+ );+}diff --git a/ar-creature/src/components/ar/ARStage.tsx b/ar-creature/src/components/ar/ARStage.tsxnew file mode 100644index 000000000..c659e0b66--- /dev/null+++ b/ar-creature/src/components/ar/ARStage.tsx@@ -0,0 +1,401 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { CameraFeed, type CameraHandle } from "./CameraFeed";+import { Joystick } from "./Joystick";+import { Avatar, type AvatarVariant } from "./Avatar";+import { AvatarSelector } from "./AvatarSelector";+import { HUD } from "./HUD";+import { PaywallModal } from "./PaywallModal";+import { useJoystick } from "./useJoystick";+import type { PlanEntitlements } from "@/lib/plans";++const AVATAR_W = 120;+const AVATAR_H = 160;+const BASE_SPEED = 360;+const DEAD = 0.08;+const ALL_VARIANTS: AvatarVariant[] = ["rosie", "void", "moss", "sun"];++interface ARStageProps {+ entitlements: PlanEntitlements;+ planLabel: string;+}++export function ARStage({ entitlements, planLabel }: ARStageProps) {+ // Camera+ const cameraRef = useRef<CameraHandle>(null);+ const [facing, setFacing] = useState<"user" | "environment">("environment");+ const [cameraError, setCameraError] = useState<string | null>(null);++ // Avatar+ const avatarRef = useRef<HTMLDivElement | null>(null);+ const [variant, setVariant] = useState<AvatarVariant>("rosie");+ const posRef = useRef({+ x: typeof window !== "undefined" ? window.innerWidth / 2 : 400,+ y: typeof window !== "undefined" ? window.innerHeight * 0.78 : 500,+ });+ const facingDirRef = useRef<1 | -1>(1);+ const [coords, setCoords] = useState({ x: posRef.current.x, y: posRef.current.y });++ // Joystick+ const { baseRef, knobRef, vectorRef, handlers } = useJoystick();++ // Paywall+ const [paywall, setPaywall] = useState<{ open: boolean; reason: string }>({+ open: false,+ reason: "",+ });+ const [toast, setToast] = useState<string | null>(null);++ // ---------- depth scaling ----------+ const depthFromY = useCallback((y: number) => {+ const h = window.innerHeight;+ const top = h * 0.25;+ const bot = h * 0.95;+ const t = Math.max(0, Math.min(1, (y - top) / (bot - top)));+ return 0.45 + t * 0.85;+ }, []);++ // ---------- main loop ----------+ useEffect(() => {+ let raf = 0;+ let lastT = performance.now();+ let coordTick = 0;++ const tick = (t: number) => {+ const dt = Math.min(0.04, (t - lastT) / 1000);+ lastT = t;++ let { dx, dy } = vectorRef.current;+ const mag = Math.hypot(dx, dy);+ const moving = mag >= DEAD;+ if (!moving) {+ dx = 0;+ dy = 0;+ }++ const av = avatarRef.current;+ if (!av) {+ raf = requestAnimationFrame(tick);+ return;+ }++ if (moving) {+ const s = depthFromY(posRef.current.y);+ const speed = BASE_SPEED * (0.5 + s * 0.6);+ posRef.current.x += dx * speed * dt;+ posRef.current.y += dy * speed * dt;++ // clamp+ const halfW = (AVATAR_W * depthFromY(posRef.current.y)) / 2;+ posRef.current.x = Math.max(halfW, Math.min(window.innerWidth - halfW, posRef.current.x));+ posRef.current.y = Math.max(+ window.innerHeight * 0.18,+ Math.min(window.innerHeight - 8, posRef.current.y),+ );++ // facing direction+ if (dx < -0.12) facingDirRef.current = -1;+ else if (dx > 0.12) facingDirRef.current = 1;+ }++ // apply transform: position + depth scale (origin at feet)+ const s = depthFromY(posRef.current.y);+ av.style.transform =+ `translate(${posRef.current.x - AVATAR_W / 2}px, ${posRef.current.y - AVATAR_H}px) ` ++ `scale(${s})`;++ // movement class (drives CSS leg/arm/stride animations)+ av.classList.toggle("ar-moving", moving);+ // facing direction on .dir element+ const dirEl = av.querySelector("[data-dir]") as HTMLElement | null;+ if (dirEl) {+ dirEl.style.transform = `scaleX(${facingDirRef.current})`;+ }+ // shadow opacity scales with depth+ const sh = av.querySelector("[data-shadow]") as HTMLElement | null;+ if (sh) sh.style.opacity = (0.45 + s * 0.35).toFixed(2);++ // throttle coord state updates (HUD) to ~15fps to avoid extra renders+ coordTick++;+ if (coordTick % 4 === 0) {+ setCoords({ x: posRef.current.x, y: posRef.current.y });+ }++ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [depthFromY, vectorRef]);++ // keep avatar inside on resize+ useEffect(() => {+ const onResize = () => {+ posRef.current.x = Math.min(posRef.current.x, window.innerWidth - 60);+ posRef.current.y = Math.min(posRef.current.y, window.innerHeight - 8);+ };+ window.addEventListener("resize", onResize);+ return () => window.removeEventListener("resize", onResize);+ }, []);++ // ---------- handlers ----------+ const flipCamera = async () => {+ const next = facing === "environment" ? "user" : "environment";+ await cameraRef.current?.setFacing(next);+ setFacing(next);+ showToast(next === "user" ? "FRONT CAM" : "REAR CAM");+ };++ const selectAvatar = (v: AvatarVariant) => {+ setVariant(v);+ showToast(`HELLO, ${v.toUpperCase()}`);+ };++ const onLockedAvatar = () => {+ setPaywall({+ open: true,+ reason: "Free includes 1 creature. Pro unlocks the full cast.",+ });+ };++ // ---------- capture (REAL — composites video frame + avatar onto canvas) ----------+ const capturePhoto = async () => {+ if (!entitlements.canCapturePhotos) {+ setPaywall({ open: true, reason: "Photo capture is locked on this plan." });+ return;+ }+ const video = cameraRef.current?.videoEl;+ const av = avatarRef.current;+ if (!video || !av || cameraError) return;++ const maxEdge = entitlements.maxCaptureRes;+ const vw = video.videoWidth;+ const vh = video.videoHeight;+ if (!vw || !vh) return;++ // scale to match screen aspect (cover behaviour), capped by maxCaptureRes+ const ww = window.innerWidth;+ const wh = window.innerHeight;+ const scale = Math.min(maxEdge / Math.max(ww, wh), 2);+ const outW = Math.round(ww * scale);+ const outH = Math.round(wh * scale);++ const canvas = document.createElement("canvas");+ canvas.width = outW;+ canvas.height = outH;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ // 1. draw video with object-cover behaviour+ const videoAspect = vw / vh;+ const outAspect = outW / outH;+ let drawW: number, drawH: number, drawX: number, drawY: number;+ if (videoAspect > outAspect) {+ drawH = outH;+ drawW = outH * videoAspect;+ drawX = (outW - drawW) / 2;+ drawY = 0;+ } else {+ drawW = outW;+ drawH = outW / videoAspect;+ drawX = 0;+ drawY = (outH - drawH) / 2;+ }+ if (facing === "user") {+ ctx.save();+ ctx.scale(-1, 1);+ ctx.drawImage(video, -drawX - drawW, drawY, drawW, drawH);+ ctx.restore();+ } else {+ ctx.drawImage(video, drawX, drawY, drawW, drawH);+ }++ // 2. rasterize avatar SVG onto an Image and composite+ const svgEl = av.querySelector("svg");+ if (svgEl) {+ const xml = new XMLSerializer().serializeToString(svgEl);+ const svgBlob = new Blob([xml], { type: "image/svg+xml;charset=utf-8" });+ const svgUrl = URL.createObjectURL(svgBlob);+ try {+ const img = await loadImage(svgUrl);+ const s = depthFromY(posRef.current.y);+ const aW = AVATAR_W * s * scale;+ const aH = AVATAR_H * s * scale;+ const ax = posRef.current.x * scale - aW / 2;+ const ay = posRef.current.y * scale - aH;++ // shadow+ ctx.save();+ ctx.globalAlpha = 0.45 + s * 0.35;+ ctx.fillStyle = "rgba(0,0,0,0.55)";+ ctx.beginPath();+ ctx.ellipse(+ posRef.current.x * scale,+ posRef.current.y * scale,+ 45 * s * scale,+ 9 * s * scale,+ 0,+ 0,+ Math.PI * 2,+ );+ ctx.fill();+ ctx.restore();++ // avatar (flip horizontally if facing left)+ ctx.save();+ if (facingDirRef.current === -1) {+ ctx.translate(ax + aW / 2, 0);+ ctx.scale(-1, 1);+ ctx.translate(-(ax + aW / 2), 0);+ }+ ctx.drawImage(img, ax, ay, aW, aH);+ ctx.restore();+ } finally {+ URL.revokeObjectURL(svgUrl);+ }+ }++ // 3. watermark (free tier only)+ if (entitlements.watermark) {+ ctx.save();+ ctx.font = `${Math.round(outW * 0.025)}px "Space Mono", monospace`;+ ctx.fillStyle = "rgba(255,255,255,0.85)";+ ctx.textBaseline = "bottom";+ ctx.shadowColor = "rgba(0,0,0,0.6)";+ ctx.shadowBlur = 8;+ ctx.fillText("◆ pocket-ar.app", outW * 0.025, outH - outW * 0.025);+ ctx.restore();+ }++ // 4. download+ canvas.toBlob((blob) => {+ if (!blob) return;+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `pocket-ar-${Date.now()}.png`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ }, "image/png");++ showToast("SAVED");+ };++ const showToast = (msg: string) => {+ setToast(msg);+ setTimeout(() => setToast(null), 1200);+ };++ return (+ <main className="fixed inset-0 overflow-hidden bg-black">+ <CameraFeed+ ref={cameraRef}+ initialFacing="environment"+ onError={(e) => setCameraError(e.name === "NotAllowedError" ? "Camera permission denied. Allow camera access in your browser." : e.message)}+ />++ {/* subtle vignette */}+ <div+ aria-hidden+ className="pointer-events-none absolute inset-0"+ style={{+ background:+ "radial-gradient(120% 80% at 50% 50%, transparent 70%, rgba(0,0,0,.35) 100%)",+ }}+ />++ <Avatar ref={avatarRef} variant={variant} />++ <HUD+ coords={coords}+ onFlipCamera={flipCamera}+ facing={facing}+ planLabel={planLabel}+ />++ <AvatarSelector+ variants={ALL_VARIANTS}+ active={variant}+ unlockedCount={entitlements.avatarCount}+ onSelect={selectAvatar}+ onLockedTap={onLockedAvatar}+ />++ <Joystick baseRef={baseRef} knobRef={knobRef} handlers={handlers} />++ <button+ onClick={capturePhoto}+ aria-label="Capture photo"+ className="fixed right-7 z-30 flex h-20 w-20 items-center justify-center rounded-full font-display text-xl text-ink transition-transform active:scale-90"+ style={{+ bottom: "calc(env(safe-area-inset-bottom, 0px) + 64px)",+ background:+ "radial-gradient(circle at 35% 30%, #fff, #d9ff3c 55%, #6c8a00 100%)",+ border: "1px solid rgba(255,255,255,.4)",+ boxShadow:+ "0 10px 24px rgba(217,255,60,.4), inset 0 -8px 14px rgba(0,0,0,.25), inset 0 4px 8px rgba(255,255,255,.5)",+ }}+ >+ <span+ aria-hidden+ className="absolute inset-[-8px] rounded-full border border-dashed border-acid/60 animate-spin-slow"+ />+ SNAP+ </button>++ {cameraError && (+ <div className="fixed inset-x-0 top-24 z-40 mx-auto max-w-sm rounded-2xl border border-neon/40 bg-ink/90 p-4 text-center text-sm text-neon">+ {cameraError}+ </div>+ )}++ {toast && (+ <div+ className="pointer-events-none fixed left-1/2 z-40 -translate-x-1/2 font-display text-lg tracking-widest text-cyan"+ style={{+ bottom: "calc(env(safe-area-inset-bottom, 0px) + 250px)",+ textShadow: "0 0 10px rgba(33,241,255,0.5)",+ }}+ >+ ◆ {toast} ◆+ </div>+ )}++ <PaywallModal+ open={paywall.open}+ reason={paywall.reason}+ onClose={() => setPaywall({ open: false, reason: "" })}+ />++ <style jsx global>{`+ #avatar [data-body-wrap] {+ animation: breath 2.4s ease-in-out infinite;+ }+ #avatar.ar-moving [data-body-wrap] {+ animation: stride 0.46s ease-in-out infinite;+ }+ #avatar.ar-moving .leg-front {+ animation: legFront 0.46s ease-in-out infinite;+ }+ #avatar.ar-moving .leg-back {+ animation: legBack 0.46s ease-in-out infinite;+ }+ #avatar.ar-moving .arm {+ animation: armSwing 0.46s ease-in-out infinite;+ }+ `}</style>+ </main>+ );+}++function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.crossOrigin = "anonymous";+ img.onload = () => resolve(img);+ img.onerror = reject;+ img.src = src;+ });+}diff --git a/ar-creature/src/components/ar/Avatar.tsx b/ar-creature/src/components/ar/Avatar.tsxnew file mode 100644index 000000000..a0f94d7e1--- /dev/null+++ b/ar-creature/src/components/ar/Avatar.tsx@@ -0,0 +1,176 @@+"use client";++import { forwardRef } from "react";++export type AvatarVariant = "rosie" | "void" | "moss" | "sun";++const PALETTES: Record<+ AvatarVariant,+ { body: [string, string, string]; trim: string; cheek: string; legDark: string; antenna: string }+> = {+ rosie: {+ body: ["#ffffff", "#ffd1e6", "#ff2a87"],+ trim: "#7a0a3c",+ cheek: "#ff6aa6",+ legDark: "#52082a",+ antenna: "#21f1ff",+ },+ void: {+ body: ["#9aa0ff", "#4a4a8a", "#0e0e2a"],+ trim: "#000019",+ cheek: "#7a7aff",+ legDark: "#020210",+ antenna: "#d9ff3c",+ },+ moss: {+ body: ["#f6ffe0", "#aedb8a", "#3a6b1a"],+ trim: "#1e3a0a",+ cheek: "#6fb04a",+ legDark: "#142706",+ antenna: "#ff8e3c",+ },+ sun: {+ body: ["#fff8d6", "#ffd86b", "#e88a00"],+ trim: "#6b3a00",+ cheek: "#ffb84d",+ legDark: "#4a2700",+ antenna: "#ff2a87",+ },+};++interface AvatarProps {+ variant: AvatarVariant;+}++/**+ * Side-view creature. Legs/arm have stable class names (.leg-front, .leg-back, .arm)+ * so the parent can drive walking animations via CSS class toggles.+ */+export const Avatar = forwardRef<HTMLDivElement, AvatarProps>(function Avatar(+ { variant },+ ref,+) {+ const p = PALETTES[variant];+ const gid = `g-${variant}`; // unique gradient ids per variant+ return (+ <div+ ref={ref}+ id="avatar"+ className="pointer-events-none absolute left-0 top-0 z-10"+ style={{+ width: 120,+ height: 160,+ transformOrigin: "50% 100%",+ willChange: "transform",+ filter: "drop-shadow(0 8px 6px rgba(0,0,0,.35))",+ }}+ >+ <div+ className="ar-shadow pointer-events-none absolute left-1/2 -translate-x-1/2"+ style={{ width: 90, height: 18, bottom: -2, borderRadius: "50%" }}+ data-shadow+ />+ <div+ data-body-wrap+ className="absolute left-0 right-0 flex justify-center"+ style={{ bottom: 14, transformOrigin: "50% 100%" }}+ >+ <div data-dir style={{ transformOrigin: "50% 100%", transition: "transform 180ms ease" }}>+ <svg viewBox="0 0 120 160" width="120" height="160" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <radialGradient id={`${gid}-body`} cx="35%" cy="30%" r="80%">+ <stop offset="0%" stopColor={p.body[0]} />+ <stop offset="35%" stopColor={p.body[1]} />+ <stop offset="100%" stopColor={p.body[2]} />+ </radialGradient>+ <radialGradient id={`${gid}-cheek`} cx="50%" cy="50%" r="50%">+ <stop offset="0%" stopColor={p.cheek} stopOpacity="0.85" />+ <stop offset="100%" stopColor={p.cheek} stopOpacity="0" />+ </radialGradient>+ <linearGradient id={`${gid}-antenna`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={p.antenna} />+ <stop offset="100%" stopColor={p.trim} />+ </linearGradient>+ <linearGradient id={`${gid}-leg`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={p.body[2]} />+ <stop offset="100%" stopColor={p.legDark} />+ </linearGradient>+ <filter id={`${gid}-glow`} x="-50%" y="-50%" width="200%" height="200%">+ <feGaussianBlur stdDeviation="2.5" />+ </filter>+ </defs>++ {/* back leg */}+ <g className="leg-back svg-pivot">+ <rect x="52" y="108" width="10" height="32" rx="5" fill={p.legDark} />+ <ellipse cx="57" cy="142" rx="11" ry="4" fill={p.trim} />+ </g>++ {/* back arm */}+ <g className="arm svg-pivot" style={{ animationDirection: "reverse" }}>+ <rect x="50" y="76" width="8" height="22" rx="4" fill={p.body[2]} opacity="0.7" />+ </g>++ {/* antenna */}+ <path+ d="M70 42 Q 76 22 82 14"+ stroke={`url(#${gid}-antenna)`}+ strokeWidth="3.5"+ fill="none"+ strokeLinecap="round"+ />+ <circle cx="82" cy="14" r="7" fill={p.antenna} filter={`url(#${gid}-glow)`} opacity="0.85" />+ <circle cx="82" cy="14" r="4" fill="#ffffff" />++ {/* body */}+ <ellipse+ cx="60"+ cy="74"+ rx="34"+ ry="38"+ fill={`url(#${gid}-body)`}+ stroke={p.trim}+ strokeWidth="1.6"+ />+ <ellipse cx="52" cy="62" rx="14" ry="18" fill="#ffffff" opacity="0.25" />++ {/* eye */}+ <ellipse cx="78" cy="66" rx="7.5" ry="9.5" fill="#1a0014" />+ <circle cx="81" cy="62" r="3" fill="#ffffff" />+ <circle cx="76" cy="70" r="1.5" fill="#ffffff" opacity="0.7" />++ <path+ d="M71 54 Q 78 50 86 54"+ stroke="#1a0014"+ strokeWidth="2"+ fill="none"+ strokeLinecap="round"+ opacity="0.6"+ />++ <ellipse cx="72" cy="82" rx="7" ry="4" fill={`url(#${gid}-cheek)`} />+ <path+ d="M80 80 Q 86 86 90 82"+ stroke={p.trim}+ strokeWidth="2.2"+ fill="none"+ strokeLinecap="round"+ />++ {/* front arm */}+ <g className="arm svg-pivot">+ <rect x="62" y="76" width="8" height="22" rx="4" fill={p.body[2]} />+ <ellipse cx="66" cy="100" rx="6" ry="4" fill={p.trim} />+ </g>++ {/* front leg */}+ <g className="leg-front svg-pivot">+ <rect x="64" y="108" width="10" height="32" rx="5" fill={`url(#${gid}-leg)`} />+ <ellipse cx="69" cy="142" rx="12" ry="4.5" fill={p.legDark} />+ </g>+ </svg>+ </div>+ </div>+ </div>+ );+});diff --git a/ar-creature/src/components/ar/AvatarSelector.tsx b/ar-creature/src/components/ar/AvatarSelector.tsxnew file mode 100644index 000000000..4562ec5fc--- /dev/null+++ b/ar-creature/src/components/ar/AvatarSelector.tsx@@ -0,0 +1,64 @@+"use client";++import type { AvatarVariant } from "./Avatar";++interface AvatarSelectorProps {+ variants: AvatarVariant[];+ active: AvatarVariant;+ unlockedCount: number;+ onSelect: (v: AvatarVariant) => void;+ onLockedTap: (v: AvatarVariant) => void;+}++const COLORS: Record<AvatarVariant, string> = {+ rosie: "linear-gradient(135deg, #ffd1e6, #ff2a87)",+ void: "linear-gradient(135deg, #9aa0ff, #0e0e2a)",+ moss: "linear-gradient(135deg, #aedb8a, #3a6b1a)",+ sun: "linear-gradient(135deg, #ffd86b, #e88a00)",+};++export function AvatarSelector({+ variants,+ active,+ unlockedCount,+ onSelect,+ onLockedTap,+}: AvatarSelectorProps) {+ return (+ <div+ className="fixed left-1/2 z-30 flex -translate-x-1/2 gap-2 rounded-full border border-white/10 bg-ink/55 p-1.5 backdrop-blur-md"+ style={{+ bottom: "calc(env(safe-area-inset-bottom, 0px) + 200px)",+ boxShadow: "0 0 0 1px rgba(255,255,255,.08), 0 8px 30px rgba(0,0,0,.45)",+ }}+ >+ {variants.map((v, i) => {+ const locked = i >= unlockedCount;+ const isActive = v === active;+ return (+ <button+ key={v}+ onClick={() => (locked ? onLockedTap(v) : onSelect(v))}+ aria-label={`Select ${v}${locked ? " (locked)" : ""}`}+ className="relative h-9 w-9 rounded-full transition-transform active:scale-90"+ style={{+ background: COLORS[v],+ border: isActive ? "2px solid var(--acid)" : "2px solid rgba(255,255,255,0.2)",+ boxShadow: isActive ? "0 0 12px rgba(217,255,60,0.6)" : "none",+ opacity: locked ? 0.45 : 1,+ }}+ >+ {locked && (+ <span+ className="absolute inset-0 flex items-center justify-center text-base text-paper"+ aria-hidden+ >+ 🔒+ </span>+ )}+ </button>+ );+ })}+ </div>+ );+}diff --git a/ar-creature/src/components/ar/CameraFeed.tsx b/ar-creature/src/components/ar/CameraFeed.tsxnew file mode 100644index 000000000..b54603918--- /dev/null+++ b/ar-creature/src/components/ar/CameraFeed.tsx@@ -0,0 +1,89 @@+"use client";++import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";++export type CameraFacing = "user" | "environment";++export interface CameraHandle {+ /** Switch which camera is active */+ setFacing: (facing: CameraFacing) => Promise<void>;+ /** Current facing mode */+ facing: CameraFacing;+ /** Underlying video element (for canvas capture) */+ videoEl: HTMLVideoElement | null;+}++interface CameraFeedProps {+ initialFacing?: CameraFacing;+ onReady?: () => void;+ onError?: (err: Error) => void;+}++export const CameraFeed = forwardRef<CameraHandle, CameraFeedProps>(function CameraFeed(+ { initialFacing = "environment", onReady, onError },+ ref,+) {+ const videoRef = useRef<HTMLVideoElement | null>(null);+ const streamRef = useRef<MediaStream | null>(null);+ const [facing, setFacingState] = useState<CameraFacing>(initialFacing);++ const start = async (next: CameraFacing) => {+ try {+ if (!navigator.mediaDevices?.getUserMedia) {+ throw new Error("This browser does not support camera access.");+ }+ if (streamRef.current) {+ streamRef.current.getTracks().forEach((t) => t.stop());+ streamRef.current = null;+ }+ const stream = await navigator.mediaDevices.getUserMedia({+ video: {+ facingMode: { ideal: next },+ width: { ideal: 1920 },+ height: { ideal: 1080 },+ },+ audio: false,+ });+ streamRef.current = stream;+ if (videoRef.current) {+ videoRef.current.srcObject = stream;+ videoRef.current.style.transform = next === "user" ? "scaleX(-1)" : "scaleX(1)";+ await videoRef.current.play().catch(() => {});+ }+ setFacingState(next);+ onReady?.();+ } catch (err) {+ const e = err instanceof Error ? err : new Error(String(err));+ onError?.(e);+ }+ };++ useImperativeHandle(+ ref,+ () => ({+ setFacing: start,+ facing,+ videoEl: videoRef.current,+ }),+ [facing],+ );++ useEffect(() => {+ void start(initialFacing);+ return () => {+ streamRef.current?.getTracks().forEach((t) => t.stop());+ streamRef.current = null;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ return (+ <video+ ref={videoRef}+ autoPlay+ playsInline+ muted+ className="absolute inset-0 h-full w-full bg-black object-cover"+ />+ );+});diff --git a/ar-creature/src/components/ar/HUD.tsx b/ar-creature/src/components/ar/HUD.tsxnew file mode 100644index 000000000..57459bbfd--- /dev/null+++ b/ar-creature/src/components/ar/HUD.tsx@@ -0,0 +1,64 @@+"use client";++import Link from "next/link";++interface HUDProps {+ coords: { x: number; y: number };+ onFlipCamera: () => void;+ facing: "user" | "environment";+ planLabel: string;+}++export function HUD({ coords, onFlipCamera, facing, planLabel }: HUDProps) {+ return (+ <header+ className="pointer-events-none fixed inset-x-0 top-0 z-30 flex items-start justify-between p-4"+ style={{ paddingTop: "max(env(safe-area-inset-top, 16px), 16px)" }}+ >+ <div className="flex flex-col items-start gap-2">+ <div className="pill pointer-events-auto">+ <span+ className="h-2.5 w-2.5 animate-pulse-dot rounded-full bg-acid"+ style={{ boxShadow: "0 0 10px var(--acid)" }}+ aria-hidden+ />+ <span className="font-display text-xl">+ POCKET <span className="text-neon">◆</span> AR+ </span>+ </div>+ <Link+ href="/account"+ className="pill pointer-events-auto !py-1.5 !text-sm"+ style={{ textDecoration: "none" }}+ >+ <span className="text-paper/60">PLAN</span>+ <span className={planLabel === "PRO" ? "text-neon" : "text-paper"}>{planLabel}</span>+ </Link>+ </div>++ <div className="flex flex-col items-end gap-2">+ <button+ onClick={onFlipCamera}+ aria-label={`Switch to ${facing === "environment" ? "front" : "rear"} camera`}+ className="pointer-events-auto flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-ink/55 text-paper backdrop-blur-md transition-transform active:scale-90"+ style={{+ boxShadow:+ "0 0 0 1px rgba(255,255,255,.08), 0 8px 30px rgba(0,0,0,.45)",+ }}+ >+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5">+ <path d="M3 7h3l2-2h8l2 2h3v12H3z" />+ <path d="M9 13a3 3 0 0 1 5-2.2" />+ <path d="M15 13a3 3 0 0 1-5 2.2" />+ <path d="M14 9l1-1-1-1" />+ <path d="M10 17l-1 1 1 1" />+ </svg>+ </button>+ <div className="pill !text-base font-mono tabular-nums">+ x:{String(Math.round(coords.x)).padStart(3, "0")} y:+ {String(Math.round(coords.y)).padStart(3, "0")}+ </div>+ </div>+ </header>+ );+}diff --git a/ar-creature/src/components/ar/Joystick.tsx b/ar-creature/src/components/ar/Joystick.tsxnew file mode 100644index 000000000..23b88055c--- /dev/null+++ b/ar-creature/src/components/ar/Joystick.tsx@@ -0,0 +1,62 @@+"use client";++import type { MutableRefObject } from "react";++interface JoystickProps {+ baseRef: MutableRefObject<HTMLDivElement | null>;+ knobRef: MutableRefObject<HTMLDivElement | null>;+ handlers: {+ onPointerDown: (e: React.PointerEvent) => void;+ onPointerMove: (e: React.PointerEvent) => void;+ onPointerUp: (e: React.PointerEvent) => void;+ onPointerCancel: (e: React.PointerEvent) => void;+ onPointerLeave: (e: React.PointerEvent) => void;+ };+}++export function Joystick({ baseRef, knobRef, handlers }: JoystickProps) {+ return (+ <div+ ref={baseRef}+ {...handlers}+ className="fixed z-30 touch-none select-none"+ style={{+ left: 24,+ bottom: "calc(env(safe-area-inset-bottom, 0px) + 28px)",+ width: 140,+ height: 140,+ borderRadius: "50%",+ background:+ "radial-gradient(60% 60% at 50% 50%, rgba(33,241,255,.08), rgba(33,241,255,0) 70%), rgba(11,11,16,.42)",+ backdropFilter: "blur(10px) saturate(140%)",+ WebkitBackdropFilter: "blur(10px) saturate(140%)",+ border: "1px solid rgba(255,255,255,.14)",+ boxShadow:+ "0 0 0 1px rgba(255,255,255,.08), 0 8px 30px rgba(0,0,0,.45), inset 0 0 30px rgba(33,241,255,.08)",+ }}+ >+ <span+ className="pointer-events-none absolute left-1/2 -top-6 -translate-x-1/2 font-display text-lg tracking-[0.3em] text-cyan"+ style={{ textShadow: "0 0 8px rgba(33,241,255,0.5)" }}+ >+ MOVE+ </span>+ <div+ ref={knobRef}+ className="absolute left-1/2 top-1/2 [&.is-dragging]:!transition-none"+ style={{+ width: 60,+ height: 60,+ borderRadius: "50%",+ transform: "translate(-50%, -50%)",+ background:+ "radial-gradient(circle at 35% 30%, #fff, #ffb4d5 30%, #ff2a87 65%, #7a0a3c 100%)",+ border: "1px solid rgba(255,255,255,.4)",+ boxShadow:+ "0 8px 20px rgba(255,42,135,.45), inset 0 -6px 12px rgba(0,0,0,.35), inset 0 4px 8px rgba(255,255,255,.4)",+ transition: "transform 180ms cubic-bezier(.2,.8,.2,1)",+ }}+ />+ </div>+ );+}diff --git a/ar-creature/src/components/ar/PaywallModal.tsx b/ar-creature/src/components/ar/PaywallModal.tsxnew file mode 100644index 000000000..980585037--- /dev/null+++ b/ar-creature/src/components/ar/PaywallModal.tsx@@ -0,0 +1,56 @@+"use client";++import { useState } from "react";++interface PaywallModalProps {+ open: boolean;+ reason: string;+ onClose: () => void;+}++export function PaywallModal({ open, reason, onClose }: PaywallModalProps) {+ const [loading, setLoading] = useState(false);++ if (!open) return null;++ const upgrade = async () => {+ setLoading(true);+ try {+ const res = await fetch("/api/stripe/checkout", { method: "POST" });+ if (res.status === 401) {+ window.location.href = "/login?next=/play";+ return;+ }+ const data = await res.json();+ if (data.url) window.location.href = data.url;+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center p-6">+ <div+ className="absolute inset-0 bg-black/70 backdrop-blur-sm"+ onClick={onClose}+ aria-hidden+ />+ <div className="relative max-w-sm rounded-3xl border border-white/15 bg-ink p-8">+ <p className="font-display text-2xl tracking-widest text-neon">PRO ONLY</p>+ <h2 className="mt-2 font-display text-4xl leading-none">unlock more.</h2>+ <p className="mt-4 text-sm text-paper/70">{reason}</p>+ <p className="mt-4 text-sm text-paper/60">+ Pro is $9/month. 4 creatures, video recording, no watermark, 4K capture.+ </p>+ <div className="mt-6 flex gap-2">+ <button onClick={onClose} className="btn-ghost flex-1">+ NOT NOW+ </button>+ <button onClick={upgrade} disabled={loading} className="btn-primary flex-1">+ {loading ? "…" : "UPGRADE"}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/ar-creature/src/components/ar/useJoystick.ts b/ar-creature/src/components/ar/useJoystick.tsnew file mode 100644index 000000000..21b64f38d--- /dev/null+++ b/ar-creature/src/components/ar/useJoystick.ts@@ -0,0 +1,130 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++export interface JoystickVector {+ /** -1 (left) → 1 (right) */+ dx: number;+ /** -1 (up) → 1 (down) */+ dy: number;+}++/**+ * Pointer-driven joystick. Returns a normalized vector and a ref to attach+ * to the joystick base + knob elements.+ *+ * The knob is clamped to a radius (32% of the base width) and the vector is+ * read on every animation frame via the `getVector` callback to avoid+ * re-renders. Use `useJoystickVector` consumer in your loop, NOT React state.+ */+export function useJoystick() {+ const baseRef = useRef<HTMLDivElement | null>(null);+ const knobRef = useRef<HTMLDivElement | null>(null);+ const vectorRef = useRef<JoystickVector>({ dx: 0, dy: 0 });+ const [active, setActive] = useState(false);+ const activeRef = useRef(false);++ const setKnobPos = (dx: number, dy: number) => {+ if (!knobRef.current) return;+ knobRef.current.style.transform = `translate(calc(-50% + ${dx}px), calc(-50% + ${dy}px))`;+ };++ const onPointerDown = useCallback((e: React.PointerEvent) => {+ if (!baseRef.current) return;+ activeRef.current = true;+ setActive(true);+ knobRef.current?.classList.add("is-dragging");+ baseRef.current.setPointerCapture(e.pointerId);+ handleMove(e.clientX, e.clientY);+ }, []);++ const handleMove = (clientX: number, clientY: number) => {+ const base = baseRef.current;+ if (!base) return;+ const rect = base.getBoundingClientRect();+ const cx = rect.left + rect.width / 2;+ const cy = rect.top + rect.height / 2;+ const max = rect.width * 0.32;+ let dx = clientX - cx;+ let dy = clientY - cy;+ const dist = Math.hypot(dx, dy);+ if (dist > max) {+ dx = (dx / dist) * max;+ dy = (dy / dist) * max;+ }+ setKnobPos(dx, dy);+ vectorRef.current.dx = dx / max;+ vectorRef.current.dy = dy / max;+ };++ const onPointerMove = useCallback((e: React.PointerEvent) => {+ if (!activeRef.current) return;+ handleMove(e.clientX, e.clientY);+ }, []);++ const release = useCallback(() => {+ activeRef.current = false;+ setActive(false);+ vectorRef.current.dx = 0;+ vectorRef.current.dy = 0;+ setKnobPos(0, 0);+ knobRef.current?.classList.remove("is-dragging");+ }, []);++ // Keyboard fallback for desktop+ useEffect(() => {+ const keys: Record<string, boolean> = {};+ const sync = () => {+ let dx = 0;+ let dy = 0;+ if (keys["arrowleft"] || keys["a"]) dx -= 1;+ if (keys["arrowright"] || keys["d"]) dx += 1;+ if (keys["arrowup"] || keys["w"]) dy -= 1;+ if (keys["arrowdown"] || keys["s"]) dy += 1;+ if (dx === 0 && dy === 0) {+ if (!activeRef.current) {+ vectorRef.current.dx = 0;+ vectorRef.current.dy = 0;+ setKnobPos(0, 0);+ }+ return;+ }+ const m = Math.hypot(dx, dy);+ vectorRef.current.dx = dx / m;+ vectorRef.current.dy = dy / m;+ if (baseRef.current) {+ const max = baseRef.current.getBoundingClientRect().width * 0.32;+ setKnobPos(vectorRef.current.dx * max, vectorRef.current.dy * max);+ }+ };++ const down = (e: KeyboardEvent) => {+ keys[e.key.toLowerCase()] = true;+ sync();+ };+ const up = (e: KeyboardEvent) => {+ keys[e.key.toLowerCase()] = false;+ sync();+ };+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ return () => {+ window.removeEventListener("keydown", down);+ window.removeEventListener("keyup", up);+ };+ }, []);++ return {+ baseRef,+ knobRef,+ vectorRef,+ active,+ handlers: {+ onPointerDown,+ onPointerMove,+ onPointerUp: release,+ onPointerCancel: release,+ onPointerLeave: release,+ },+ };+}diff --git a/ar-creature/src/lib/auth.ts b/ar-creature/src/lib/auth.tsnew file mode 100644index 000000000..cd6fc6826--- /dev/null+++ b/ar-creature/src/lib/auth.ts@@ -0,0 +1,31 @@+import NextAuth from "next-auth";+import Google from "next-auth/providers/google";+import Resend from "next-auth/providers/resend";+import { PrismaAdapter } from "@auth/prisma-adapter";+import { prisma } from "./db";++export const { handlers, auth, signIn, signOut } = NextAuth({+ adapter: PrismaAdapter(prisma),+ session: { strategy: "database" },+ pages: { signIn: "/login" },+ providers: [+ Google({+ clientId: process.env.AUTH_GOOGLE_ID,+ clientSecret: process.env.AUTH_GOOGLE_SECRET,+ allowDangerousEmailAccountLinking: true,+ }),+ Resend({+ apiKey: process.env.AUTH_RESEND_KEY,+ from: process.env.EMAIL_FROM,+ }),+ ],+ callbacks: {+ session({ session, user }) {+ if (session.user && user) {+ session.user.id = user.id;+ }+ return session;+ },+ },+ trustHost: true,+});diff --git a/ar-creature/src/lib/cn.ts b/ar-creature/src/lib/cn.tsnew file mode 100644index 000000000..a5ef19350--- /dev/null+++ b/ar-creature/src/lib/cn.ts@@ -0,0 +1,6 @@+import { clsx, type ClassValue } from "clsx";+import { twMerge } from "tailwind-merge";++export function cn(...inputs: ClassValue[]) {+ return twMerge(clsx(inputs));+}diff --git a/ar-creature/src/lib/db.ts b/ar-creature/src/lib/db.tsnew file mode 100644index 000000000..5785ddc70--- /dev/null+++ b/ar-creature/src/lib/db.ts@@ -0,0 +1,11 @@+import { PrismaClient } from "@prisma/client";++const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };++export const prisma =+ globalForPrisma.prisma ??+ new PrismaClient({+ log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],+ });++if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;diff --git a/ar-creature/src/lib/plans.ts b/ar-creature/src/lib/plans.tsnew file mode 100644index 000000000..d232f5b77--- /dev/null+++ b/ar-creature/src/lib/plans.ts@@ -0,0 +1,57 @@+/**+ * Single source of truth for plan tiers and entitlements.+ * Adding a new entitlement here automatically gates it on the server and client.+ */++export type PlanId = "free" | "pro";++export interface PlanEntitlements {+ /** Number of avatar characters the user can select */+ avatarCount: number;+ /** Can capture AR photos to disk */+ canCapturePhotos: boolean;+ /** Watermark on captured photos */+ watermark: boolean;+ /** Can record AR videos */+ canRecordVideo: boolean;+ /** Max photo resolution (long edge in pixels) */+ maxCaptureRes: number;+}++export const PLANS: Record<PlanId, { name: string; price: number; entitlements: PlanEntitlements }> = {+ free: {+ name: "Free",+ price: 0,+ entitlements: {+ avatarCount: 1,+ canCapturePhotos: true,+ watermark: true,+ canRecordVideo: false,+ maxCaptureRes: 1080,+ },+ },+ pro: {+ name: "Pro",+ price: 9,+ entitlements: {+ avatarCount: 4,+ canCapturePhotos: true,+ watermark: false,+ canRecordVideo: true,+ maxCaptureRes: 2160,+ },+ },+};++/** Active statuses that grant entitlements. Anything else falls back to free. */+const ACTIVE_STATUSES = new Set(["active", "trialing"]);++export function isSubscriptionActive(opts: {+ status?: string | null;+ currentPeriodEnd?: Date | null;+}): boolean {+ if (!opts.status) return false;+ if (!ACTIVE_STATUSES.has(opts.status)) return false;+ if (!opts.currentPeriodEnd) return false;+ return opts.currentPeriodEnd.getTime() > Date.now();+}diff --git a/ar-creature/src/lib/stripe.ts b/ar-creature/src/lib/stripe.tsnew file mode 100644index 000000000..aca8eba38--- /dev/null+++ b/ar-creature/src/lib/stripe.ts@@ -0,0 +1,13 @@+import Stripe from "stripe";++if (!process.env.STRIPE_SECRET_KEY) {+ throw new Error("STRIPE_SECRET_KEY is not set");+}++export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {+ apiVersion: "2024-10-28.acacia",+ typescript: true,+ appInfo: { name: "ar-creature", version: "0.1.0" },+});++export const PRO_PRICE_ID = process.env.STRIPE_PRO_PRICE_ID!;diff --git a/ar-creature/src/lib/subscription.ts b/ar-creature/src/lib/subscription.tsnew file mode 100644index 000000000..042764fb1--- /dev/null+++ b/ar-creature/src/lib/subscription.ts@@ -0,0 +1,33 @@+import { prisma } from "./db";+import { isSubscriptionActive, PLANS, type PlanId } from "./plans";++export interface UserPlan {+ planId: PlanId;+ entitlements: (typeof PLANS)[PlanId]["entitlements"];+ status: string | null;+ currentPeriodEnd: Date | null;+ cancelAtPeriodEnd: boolean;+}++/**+ * Resolves the user's effective plan by checking their Stripe subscription+ * state in our database. The webhook keeps this up to date.+ */+export async function getUserPlan(userId: string): Promise<UserPlan> {+ const sub = await prisma.subscription.findUnique({ where: { userId } });++ const active = isSubscriptionActive({+ status: sub?.status,+ currentPeriodEnd: sub?.currentPeriodEnd,+ });++ const planId: PlanId = active ? "pro" : "free";++ return {+ planId,+ entitlements: PLANS[planId].entitlements,+ status: sub?.status ?? null,+ currentPeriodEnd: sub?.currentPeriodEnd ?? null,+ cancelAtPeriodEnd: sub?.cancelAtPeriodEnd ?? false,+ };+}diff --git a/ar-creature/src/types/next-auth.d.ts b/ar-creature/src/types/next-auth.d.tsnew file mode 100644index 000000000..5832ba0e7--- /dev/null+++ b/ar-creature/src/types/next-auth.d.ts@@ -0,0 +1,9 @@+import type { DefaultSession } from "next-auth";++declare module "next-auth" {+ interface Session {+ user: {+ id: string;+ } & DefaultSession["user"];+ }+}diff --git a/ar-creature/tailwind.config.ts b/ar-creature/tailwind.config.tsnew file mode 100644index 000000000..e03ec145b--- /dev/null+++ b/ar-creature/tailwind.config.ts@@ -0,0 +1,54 @@+import type { Config } from "tailwindcss";++export default {+ content: ["./src/**/*.{ts,tsx}"],+ theme: {+ extend: {+ colors: {+ ink: "#0b0b10",+ paper: "#f4f0e6",+ neon: "#ff2a87",+ cyan: "#21f1ff",+ acid: "#d9ff3c",+ },+ fontFamily: {+ display: ["VT323", "ui-monospace", "monospace"],+ mono: ["Space Mono", "ui-monospace", "monospace"],+ },+ animation: {+ breath: "breath 2.4s ease-in-out infinite",+ stride: "stride 0.46s ease-in-out infinite",+ "leg-front": "legFront 0.46s ease-in-out infinite",+ "leg-back": "legBack 0.46s ease-in-out infinite",+ "arm-swing": "armSwing 0.46s ease-in-out infinite",+ "spin-slow": "spin 8s linear infinite",+ "pulse-dot": "pulse 1.6s ease-in-out infinite",+ },+ keyframes: {+ breath: {+ "0%,100%": { transform: "translateY(0) scaleY(1)" },+ "50%": { transform: "translateY(-1px) scaleY(0.98)" },+ },+ stride: {+ "0%,100%": { transform: "translateY(0)" },+ "25%": { transform: "translateY(-4px)" },+ "50%": { transform: "translateY(0)" },+ "75%": { transform: "translateY(-4px)" },+ },+ legFront: {+ "0%,100%": { transform: "rotate(-26deg)" },+ "50%": { transform: "rotate(26deg)" },+ },+ legBack: {+ "0%,100%": { transform: "rotate(26deg)" },+ "50%": { transform: "rotate(-26deg)" },+ },+ armSwing: {+ "0%,100%": { transform: "rotate(15deg)" },+ "50%": { transform: "rotate(-15deg)" },+ },+ },+ },+ },+ plugins: [],+} satisfies Config;diff --git a/ar-creature/tsconfig.json b/ar-creature/tsconfig.jsonnew file mode 100644index 000000000..07de7bc00--- /dev/null+++ b/ar-creature/tsconfig.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": false,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "preserve",+ "incremental": true,+ "plugins": [{ "name": "next" }],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]+}