From 05677924b5180be63bd8e6b36800e370321b7168 Mon Sep 17 00:00:00 2001 From: SlavaVlad Date: Sun, 14 Jun 2026 21:29:43 +0300 Subject: [PATCH] V1 bingo --- .dockerignore | 12 + .gitea/workflows/deploy.yml | 38 + .gitignore | 46 + Dockerfile | 32 + README.md | 36 + app/admin/campaigns/[campaignId]/page.tsx | 72 + app/admin/page.tsx | 34 + app/api/auth/login/route.ts | 39 + app/api/auth/me/route.ts | 10 + app/api/auth/register/route.ts | 24 + app/api/campaigns/[campaignId]/items/route.ts | 83 + app/api/campaigns/[campaignId]/route.ts | 34 + app/api/campaigns/route.ts | 37 + app/api/game/[campaignId]/state/route.ts | 74 + app/api/game/mark/route.ts | 58 + app/api/upload/sound/route.ts | 39 + app/favicon.ico | Bin 0 -> 25931 bytes app/game/[campaignId]/page.tsx | 91 + app/globals.css | 89 + app/layout.tsx | 35 + app/page.tsx | 61 + components/AdminDashboard.tsx | 164 + components/AuthProvider.tsx | 79 + components/BingoCard.tsx | 299 + components/BingoCell.tsx | 113 + components/CampaignList.tsx | 73 + components/ChaosMeter.tsx | 57 + components/ItemEditor.tsx | 303 + components/LoginForm.tsx | 83 + components/Navbar.tsx | 47 + components/ui/badge.tsx | 30 + components/ui/button.tsx | 48 + components/ui/card.tsx | 53 + components/ui/dialog.tsx | 95 + components/ui/input.tsx | 21 + components/ui/select.tsx | 137 + components/ui/separator.tsx | 15 + docker-compose.yml | 12 + eslint.config.mjs | 18 + lib/auth.ts | 78 + lib/bingo-data.ts | 65 + lib/db/index.ts | 64 + lib/db/schema.ts | 48 + lib/sounds.ts | 134 + lib/utils.ts | 6 + next.config.ts | 8 + package-lock.json | 7731 +++++++++++++++++ package.json | 45 + postcss.config.mjs | 7 + public/file.svg | 1 + public/globe.svg | 1 + public/next.svg | 1 + public/vercel.svg | 1 + public/window.svg | 1 + tsconfig.json | 34 + 55 files changed, 10816 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitea/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 app/admin/campaigns/[campaignId]/page.tsx create mode 100644 app/admin/page.tsx create mode 100644 app/api/auth/login/route.ts create mode 100644 app/api/auth/me/route.ts create mode 100644 app/api/auth/register/route.ts create mode 100644 app/api/campaigns/[campaignId]/items/route.ts create mode 100644 app/api/campaigns/[campaignId]/route.ts create mode 100644 app/api/campaigns/route.ts create mode 100644 app/api/game/[campaignId]/state/route.ts create mode 100644 app/api/game/mark/route.ts create mode 100644 app/api/upload/sound/route.ts create mode 100644 app/favicon.ico create mode 100644 app/game/[campaignId]/page.tsx create mode 100644 app/globals.css create mode 100644 app/layout.tsx create mode 100644 app/page.tsx create mode 100644 components/AdminDashboard.tsx create mode 100644 components/AuthProvider.tsx create mode 100644 components/BingoCard.tsx create mode 100644 components/BingoCell.tsx create mode 100644 components/CampaignList.tsx create mode 100644 components/ChaosMeter.tsx create mode 100644 components/ItemEditor.tsx create mode 100644 components/LoginForm.tsx create mode 100644 components/Navbar.tsx create mode 100644 components/ui/badge.tsx create mode 100644 components/ui/button.tsx create mode 100644 components/ui/card.tsx create mode 100644 components/ui/dialog.tsx create mode 100644 components/ui/input.tsx create mode 100644 components/ui/select.tsx create mode 100644 components/ui/separator.tsx create mode 100644 docker-compose.yml create mode 100644 eslint.config.mjs create mode 100644 lib/auth.ts create mode 100644 lib/bingo-data.ts create mode 100644 lib/db/index.ts create mode 100644 lib/db/schema.ts create mode 100644 lib/sounds.ts create mode 100644 lib/utils.ts create mode 100644 next.config.ts create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 postcss.config.mjs create mode 100644 public/file.svg create mode 100644 public/globe.svg create mode 100644 public/next.svg create mode 100644 public/vercel.svg create mode 100644 public/window.svg create mode 100644 tsconfig.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f8b472a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules +.next +data/*.db +data/*.db-wal +data/*.db-shm +.git +.gitignore +*.md +.env +.env.local +tsconfig.tsbuildinfo +next-env.d.ts diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..5e3086f --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,38 @@ +name: Deploy +run-name: Deploy to barabingo + +on: + push: + branches: [main, master] + +jobs: + build-and-deploy: + runs-on: [ubuntu-22.04] + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Install SSH key + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PKEY }}" > ~/.ssh/id_ed25519 + chmod 600 ~/.ssh/id_ed25519 + ssh-keyscan -H barabingo >> ~/.ssh/known_hosts 2>/dev/null + + - name: Build Docker image + run: | + docker build -t barabingo:latest . + + - name: Save and compress image + run: | + docker save barabingo:latest | gzip > /tmp/barabingo.tar.gz + + - name: Copy image to server + run: | + scp /tmp/barabingo.tar.gz root@barabingo:/tmp/barabingo.tar.gz + + - name: Deploy on server + run: | + ssh root@barabingo 'cd /opt/barabingo && docker load < /tmp/barabingo.tar.gz && docker compose down --remove-orphans 2>/dev/null; docker compose up -d && rm -f /tmp/barabingo.tar.gz && docker image prune -f' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..83d4758 --- /dev/null +++ b/.gitignore @@ -0,0 +1,46 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# sqlite +/data/*.db +/data/*.db-wal +/data/*.db-shm + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7fec4b1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +FROM node:22-alpine AS builder + +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM node:22-alpine AS runner + +WORKDIR /app + +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 + +RUN addgroup --system --gid 1001 nodejs && \ + adduser --system --uid 1001 nextjs + +COPY --from=builder /app/public ./public +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static + +RUN mkdir -p /app/data && chown nextjs:nodejs /app/data + +USER nextjs + +EXPOSE 3000 + +ENV PORT=3000 +ENV HOSTNAME=0.0.0.0 + +CMD ["node", "server.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..e215bc4 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/app/admin/campaigns/[campaignId]/page.tsx b/app/admin/campaigns/[campaignId]/page.tsx new file mode 100644 index 0000000..5f42c3f --- /dev/null +++ b/app/admin/campaigns/[campaignId]/page.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { useAuth } from "@/components/AuthProvider"; +import { ItemEditor } from "@/components/ItemEditor"; +import { useParams, useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; + +type Campaign = { + id: string; + name: string; + gridSize: number; +}; + +export default function EditCampaignPage() { + const { user, loading: authLoading } = useAuth(); + const params = useParams(); + const router = useRouter(); + const [campaign, setCampaign] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + if (authLoading) return; + if (!user || !user.isAdmin) { router.push("/"); return; } + + const campaignId = params.campaignId as string; + fetch("/api/campaigns") + .then(r => r.json()) + .then(campaigns => { + const c = campaigns.find((c: Campaign) => c.id === campaignId); + if (c) setCampaign(c); + }) + .finally(() => setLoading(false)); + }, [user, authLoading, params.campaignId, router]); + + if (authLoading || loading) { + return ( +
+
Loading...
+
+ ); + } + + if (!campaign) { + return ( +
+
+
🗺️💀
+

Campaign not found

+ +
+
+ ); + } + + return ( +
+
+ +
+

{campaign.name}

+

{campaign.gridSize}×{campaign.gridSize} grid

+
+
+ +
+ ); +} diff --git a/app/admin/page.tsx b/app/admin/page.tsx new file mode 100644 index 0000000..11b8b90 --- /dev/null +++ b/app/admin/page.tsx @@ -0,0 +1,34 @@ +"use client"; + +import { useAuth } from "@/components/AuthProvider"; +import { AdminDashboard } from "@/components/AdminDashboard"; +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +export default function AdminPage() { + const { user, loading } = useAuth(); + const router = useRouter(); + + useEffect(() => { + if (loading) return; + if (!user) { router.push("/"); return; } + if (!user.isAdmin) { router.push("/"); return; } + }, [user, loading, router]); + + if (loading) { + return ( +
+
+
🔐
+ Verifying command clearance... +
+
+ ); + } + + if (!user || !user.isAdmin) { + return null; + } + + return ; +} diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts new file mode 100644 index 0000000..479cb6f --- /dev/null +++ b/app/api/auth/login/route.ts @@ -0,0 +1,39 @@ +import { NextRequest, NextResponse } from "next/server"; +import { loginUser, deleteSession, getServerSession, SESSION_COOKIE } from "@/lib/auth"; +import { cookies } from "next/headers"; + +export async function POST(req: NextRequest) { + try { + const { nickname, password } = await req.json(); + if (!nickname || !password) { + return NextResponse.json({ error: "Nickname and password required" }, { status: 400 }); + } + const result = await loginUser(nickname, password); + if ("error" in result) { + return NextResponse.json(result, { status: 401 }); + } + const res = NextResponse.json(result.user); + res.cookies.set(SESSION_COOKIE, result.sessionId, { + httpOnly: true, + secure: false, + sameSite: "lax", + path: "/", + maxAge: 7 * 86400, + }); + return res; + } catch { + return NextResponse.json({ error: "Login failed" }, { status: 500 }); + } +} + +export async function DELETE() { + const session = await getServerSession(); + if (session) { + const cookieStore = await cookies(); + const token = cookieStore.get(SESSION_COOKIE)?.value; + if (token) await deleteSession(token); + } + const res = NextResponse.json({ ok: true }); + res.cookies.set(SESSION_COOKIE, "", { httpOnly: true, path: "/", maxAge: 0 }); + return res; +} diff --git a/app/api/auth/me/route.ts b/app/api/auth/me/route.ts new file mode 100644 index 0000000..22ffb11 --- /dev/null +++ b/app/api/auth/me/route.ts @@ -0,0 +1,10 @@ +import { NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; + +export async function GET() { + const session = await getServerSession(); + if (!session) { + return NextResponse.json({ user: null }); + } + return NextResponse.json({ user: { id: session.id, nickname: session.nickname, isAdmin: session.isAdmin } }); +} diff --git a/app/api/auth/register/route.ts b/app/api/auth/register/route.ts new file mode 100644 index 0000000..54f6903 --- /dev/null +++ b/app/api/auth/register/route.ts @@ -0,0 +1,24 @@ +import { NextRequest, NextResponse } from "next/server"; +import { registerUser } from "@/lib/auth"; + +export async function POST(req: NextRequest) { + try { + const { nickname, password } = await req.json(); + if (!nickname || !password) { + return NextResponse.json({ error: "Nickname and password required" }, { status: 400 }); + } + if (nickname.length < 2 || nickname.length > 20) { + return NextResponse.json({ error: "Nickname 2-20 characters" }, { status: 400 }); + } + if (password.length < 4) { + return NextResponse.json({ error: "Password min 4 characters" }, { status: 400 }); + } + const result = await registerUser(nickname, password); + if ("error" in result) { + return NextResponse.json(result, { status: 409 }); + } + return NextResponse.json(result); + } catch { + return NextResponse.json({ error: "Registration failed" }, { status: 500 }); + } +} diff --git a/app/api/campaigns/[campaignId]/items/route.ts b/app/api/campaigns/[campaignId]/items/route.ts new file mode 100644 index 0000000..ea22c18 --- /dev/null +++ b/app/api/campaigns/[campaignId]/items/route.ts @@ -0,0 +1,83 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { bingoItems } from "@/lib/db/schema"; +import { eq, and } from "drizzle-orm"; +import { v4 as uuidv4 } from "uuid"; + +export async function GET(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + const { campaignId } = await params; + const items = db.select().from(bingoItems).where(eq(bingoItems.campaignId, campaignId)).orderBy(bingoItems.gridIndex).all(); + return NextResponse.json(items); +} + +export async function POST(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + try { + const { campaignId } = await params; + const { text, emoji, soundCategory, soundUrl, gridIndex } = await req.json(); + if (!text) return NextResponse.json({ error: "Text required" }, { status: 400 }); + + const existing = db.select().from(bingoItems) + .where(and(eq(bingoItems.campaignId, campaignId), eq(bingoItems.gridIndex, gridIndex))) + .get(); + if (existing) { + return NextResponse.json({ error: "Grid position taken" }, { status: 409 }); + } + + const id = uuidv4(); + const now = new Date().toISOString(); + db.insert(bingoItems).values({ id, campaignId, text, emoji: emoji || "💀", soundCategory: soundCategory || "horn", soundUrl: soundUrl || null, gridIndex, createdAt: now }).run(); + return NextResponse.json({ id }); + } catch { + return NextResponse.json({ error: "Failed to add item" }, { status: 500 }); + } +} + +export async function PUT(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + try { + const { campaignId } = await params; + const body = await req.json(); + if (!body.id) return NextResponse.json({ error: "Item ID required" }, { status: 400 }); + const updates: Record = {}; + if (body.text) updates.text = body.text; + if (body.emoji) updates.emoji = body.emoji; + if (body.soundCategory) updates.soundCategory = body.soundCategory; + if (body.soundUrl !== undefined) updates.soundUrl = body.soundUrl; + if (body.gridIndex !== undefined) updates.gridIndex = body.gridIndex; + db.update(bingoItems).set(updates) + .where(and(eq(bingoItems.id, body.id), eq(bingoItems.campaignId, campaignId))) + .run(); + return NextResponse.json({ ok: true }); + } catch { + return NextResponse.json({ error: "Update failed" }, { status: 500 }); + } +} + +export async function DELETE(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + try { + const { campaignId } = await params; + const url = new URL(req.url); + const itemId = url.searchParams.get("itemId"); + if (!itemId) return NextResponse.json({ error: "itemId required" }, { status: 400 }); + db.delete(bingoItems) + .where(and(eq(bingoItems.id, itemId), eq(bingoItems.campaignId, campaignId))) + .run(); + return NextResponse.json({ ok: true }); + } catch { + return NextResponse.json({ error: "Delete failed" }, { status: 500 }); + } +} diff --git a/app/api/campaigns/[campaignId]/route.ts b/app/api/campaigns/[campaignId]/route.ts new file mode 100644 index 0000000..b135a65 --- /dev/null +++ b/app/api/campaigns/[campaignId]/route.ts @@ -0,0 +1,34 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { campaigns } from "@/lib/db/schema"; +import { eq } from "drizzle-orm"; + +export async function DELETE(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + const { campaignId } = await params; + db.delete(campaigns).where(eq(campaigns.id, campaignId)).run(); + return NextResponse.json({ ok: true }); +} + +export async function PATCH(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + try { + const { campaignId } = await params; + const body = await req.json(); + const updates: Record = {}; + if (body.name) updates.name = body.name; + if (body.status) updates.status = body.status; + if (body.gridSize) updates.gridSize = body.gridSize; + db.update(campaigns).set(updates).where(eq(campaigns.id, campaignId)).run(); + return NextResponse.json({ ok: true }); + } catch { + return NextResponse.json({ error: "Update failed" }, { status: 500 }); + } +} diff --git a/app/api/campaigns/route.ts b/app/api/campaigns/route.ts new file mode 100644 index 0000000..f1f5ee5 --- /dev/null +++ b/app/api/campaigns/route.ts @@ -0,0 +1,37 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { campaigns } from "@/lib/db/schema"; +import { desc } from "drizzle-orm"; +import { v4 as uuidv4 } from "uuid"; + +export async function GET() { + const session = await getServerSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const all = db.select().from(campaigns).orderBy(desc(campaigns.createdAt)).all(); + return NextResponse.json(all); +} + +export async function POST(req: NextRequest) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + try { + const { name, gridSize = 5 } = await req.json(); + if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 }); + if (gridSize < 3 || gridSize > 10) { + return NextResponse.json({ error: "Grid size 3-10" }, { status: 400 }); + } + + const id = uuidv4(); + const now = new Date().toISOString(); + db.insert(campaigns).values({ id, name, gridSize, createdBy: session.id, createdAt: now }).run(); + + return NextResponse.json({ id, name, gridSize }); + } catch { + return NextResponse.json({ error: "Failed to create campaign" }, { status: 500 }); + } +} diff --git a/app/api/game/[campaignId]/state/route.ts b/app/api/game/[campaignId]/state/route.ts new file mode 100644 index 0000000..258df39 --- /dev/null +++ b/app/api/game/[campaignId]/state/route.ts @@ -0,0 +1,74 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { campaigns, bingoItems, marks, users } from "@/lib/db/schema"; +import { eq, inArray, desc } from "drizzle-orm"; + +export async function GET(req: NextRequest, { params }: { params: Promise<{ campaignId: string }> }) { + const session = await getServerSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + try { + const { campaignId } = await params; + const campaign = db.select().from(campaigns).where(eq(campaigns.id, campaignId)).get(); + if (!campaign) return NextResponse.json({ error: "Campaign not found" }, { status: 404 }); + + const items = db.select().from(bingoItems).where(eq(bingoItems.campaignId, campaignId)).orderBy(bingoItems.gridIndex).all(); + const allMarks = db.select().from(marks).where(eq(marks.campaignId, campaignId)).orderBy(desc(marks.createdAt)).all(); + + const userIds = [...new Set(allMarks.map(m => m.userId))]; + const userMap: Record = {}; + if (userIds.length > 0) { + const markedUsers = db.select({ id: users.id, nickname: users.nickname }) + .from(users).where(inArray(users.id, userIds)).all(); + markedUsers.forEach(u => { userMap[u.id] = u.nickname; }); + } + + const itemMap: Record = {}; + items.forEach(it => { itemMap[it.id] = it; }); + + const markedItemIds = allMarks.map(m => m.itemId); + const markCountMap: Record = {}; + const markUsersMap: Record = {}; + for (const m of allMarks) { + markCountMap[m.itemId] = (markCountMap[m.itemId] || 0) + 1; + if (!markUsersMap[m.itemId]) markUsersMap[m.itemId] = []; + if (!markUsersMap[m.itemId].includes(userMap[m.userId] || "???")) { + markUsersMap[m.itemId].push(userMap[m.userId] || "???"); + } + } + + const activityLog = allMarks.slice(0, 20).map(m => { + const nickname = userMap[m.userId] || "???"; + const item = itemMap[m.itemId]; + const emoji = item?.emoji || "💀"; + const text = item?.text || "unknown"; + const time = new Date(m.createdAt).toLocaleTimeString(); + return `${time} ${nickname} marked ${emoji} "${text}"`; + }); + + const totalCells = campaign.gridSize * campaign.gridSize; + const grid: Array<{ + index: number; + item: typeof items[0] | null; + marked: boolean; + markedBy: string[]; + markCount: number; + }> = []; + + for (let i = 0; i < totalCells; i++) { + const item = items.find(it => it.gridIndex === i) || null; + grid.push({ + index: i, + item, + marked: markedItemIds.includes(item?.id || ""), + markedBy: markUsersMap[item?.id || ""] || [], + markCount: markCountMap[item?.id || ""] || 0, + }); + } + + return NextResponse.json({ campaign, grid, activityLog }); + } catch { + return NextResponse.json({ error: "Failed to load game state" }, { status: 500 }); + } +} diff --git a/app/api/game/mark/route.ts b/app/api/game/mark/route.ts new file mode 100644 index 0000000..fc5ca67 --- /dev/null +++ b/app/api/game/mark/route.ts @@ -0,0 +1,58 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { marks, bingoItems } from "@/lib/db/schema"; +import { eq, and } from "drizzle-orm"; +import { v4 as uuidv4 } from "uuid"; + +export async function POST(req: NextRequest) { + const session = await getServerSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + try { + const { campaignId, itemId } = await req.json(); + if (!campaignId || !itemId) { + return NextResponse.json({ error: "campaignId and itemId required" }, { status: 400 }); + } + + const item = db.select().from(bingoItems) + .where(and(eq(bingoItems.id, itemId), eq(bingoItems.campaignId, campaignId))) + .get(); + if (!item) return NextResponse.json({ error: "Item not found" }, { status: 404 }); + + const existing = db.select().from(marks) + .where(and(eq(marks.campaignId, campaignId), eq(marks.itemId, itemId))) + .get(); + if (existing) { + return NextResponse.json({ error: "Already marked", mark: existing }, { status: 409 }); + } + + const id = uuidv4(); + const now = new Date().toISOString(); + db.insert(marks).values({ id, campaignId, itemId, userId: session.id, createdAt: now }).run(); + + return NextResponse.json({ id, markedBy: session.nickname }); + } catch { + return NextResponse.json({ error: "Failed to mark" }, { status: 500 }); + } +} + +export async function DELETE(req: NextRequest) { + const session = await getServerSession(); + if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + try { + const { campaignId, itemId } = await req.json(); + if (!campaignId || !itemId) { + return NextResponse.json({ error: "campaignId and itemId required" }, { status: 400 }); + } + + db.delete(marks) + .where(and(eq(marks.campaignId, campaignId), eq(marks.itemId, itemId))) + .run(); + + return NextResponse.json({ ok: true }); + } catch { + return NextResponse.json({ error: "Failed to unmark" }, { status: 500 }); + } +} diff --git a/app/api/upload/sound/route.ts b/app/api/upload/sound/route.ts new file mode 100644 index 0000000..2d843be --- /dev/null +++ b/app/api/upload/sound/route.ts @@ -0,0 +1,39 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "@/lib/auth"; +import { writeFile, mkdir } from "fs/promises"; +import path from "path"; +import { v4 as uuidv4 } from "uuid"; + +const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds"); + +export async function POST(req: NextRequest) { + const session = await getServerSession(); + if (!session || !session.isAdmin) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + try { + const formData = await req.formData(); + const file = formData.get("file") as File | null; + if (!file) return NextResponse.json({ error: "No file" }, { status: 400 }); + + if (!file.name.toLowerCase().endsWith(".ogg")) { + return NextResponse.json({ error: "Only OGG files allowed" }, { status: 400 }); + } + + if (file.size > 2 * 1024 * 1024) { + return NextResponse.json({ error: "File too large (max 2MB)" }, { status: 400 }); + } + + await mkdir(UPLOAD_DIR, { recursive: true }); + const ext = path.extname(file.name); + const filename = `${uuidv4()}${ext}`; + const filepath = path.join(UPLOAD_DIR, filename); + const bytes = await file.arrayBuffer(); + await writeFile(filepath, Buffer.from(bytes)); + + return NextResponse.json({ url: `/uploads/sounds/${filename}` }); + } catch { + return NextResponse.json({ error: "Upload failed" }, { status: 500 }); + } +} diff --git a/app/favicon.ico b/app/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..718d6fea4835ec2d246af9800eddb7ffb276240c G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o6IB2_j60eOeBB1Br!boW7JnoeX6Gs)?7rW0^5psc- zjS16yb>dFn>KPOF;imD}e!enuIniFzv}n$m2#gCCv4jM#ArwlzZ$7@9&XkFxZ4n!V zj3dyiwW4Ki2QG{@i>yuZXQizw_OkZI^-3otXC{!(lUpJF33gI60ak;Uqitp74|B6I zgg{b=Iz}WkhCGj1M=hu4#Aw173YxIVbISaoc z-nLZC*6Tgivd5V`K%GxhBsp@SUU60-rfc$=wb>zdJzXS&-5(NRRodFk;Kxk!S(O(a0e7oY=E( zAyS;Ow?6Q&XA+cnkCb{28_1N8H#?J!*$MmIwLq^*T_9-z^&UE@A(z9oGYtFy6EZef LrJugUA?W`A8`#=m literal 0 HcmV?d00001 diff --git a/app/game/[campaignId]/page.tsx b/app/game/[campaignId]/page.tsx new file mode 100644 index 0000000..7320b87 --- /dev/null +++ b/app/game/[campaignId]/page.tsx @@ -0,0 +1,91 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { useAuth } from "@/components/AuthProvider"; +import { BingoCard } from "@/components/BingoCard"; +import { useParams, useRouter } from "next/navigation"; + +type Campaign = { + id: string; + name: string; + gridSize: number; + status: string; +}; + +type GridCell = { + index: number; + item: Item | null; + marked: boolean; + markedBy: string[]; + markCount: number; +}; + +type Item = { + id: string; + text: string; + emoji: string; + soundCategory: string; + soundUrl?: string | null; + gridIndex: number; +}; + +export default function GamePage() { + const { user, loading: authLoading } = useAuth(); + const params = useParams(); + const router = useRouter(); + const [campaign, setCampaign] = useState(null); + const [grid, setGrid] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + + useEffect(() => { + if (authLoading) return; + if (!user) { router.push("/"); return; } + + const campaignId = params.campaignId as string; + + fetch(`/api/game/${campaignId}/state`) + .then(r => r.json()) + .then(data => { + if (data.error) { setError(data.error); return; } + setCampaign(data.campaign); + setGrid(data.grid); + }) + .catch(() => setError("Failed to load game state")) + .finally(() => setLoading(false)); + }, [user, authLoading, params.campaignId, router]); + + if (authLoading || loading) { + return ( +
+
+
🔄
+ Loading submarine systems... +
+
+ ); + } + + if (error || !campaign) { + return ( +
+
+
💀
+

Campaign Lost

+

{error || "Campaign not found"}

+
+
+ ); + } + + return ( +
+ +
+ ); +} diff --git a/app/globals.css b/app/globals.css new file mode 100644 index 0000000..f5fc39d --- /dev/null +++ b/app/globals.css @@ -0,0 +1,89 @@ +@import "tailwindcss"; + +@theme inline { + --color-background: #0a0e1a; + --color-foreground: #e0e0e0; + --font-sans: var(--font-geist-sans), ui-monospace, monospace; + --font-mono: var(--font-geist-mono), ui-monospace, monospace; + + --animate-shake: shake 0.3s ease-in-out; + --animate-glow-pulse: glow-pulse 2s ease-in-out; + --animate-scan: scan 4s linear infinite; + --animate-flicker: flicker 0.15s ease-in-out 3; + --animate-float: float 3s ease-in-out infinite; +} + +@keyframes shake { + 0%, 100% { transform: translateX(0); } + 20% { transform: translateX(-3px) rotate(-1deg); } + 40% { transform: translateX(3px) rotate(1deg); } + 60% { transform: translateX(-2px); } + 80% { transform: translateX(2px); } +} + +@keyframes glow-pulse { + 0%, 100% { box-shadow: 0 0 5px rgba(0, 229, 255, 0.2); } + 50% { box-shadow: 0 0 20px rgba(0, 229, 255, 0.4), 0 0 40px rgba(0, 229, 255, 0.1); } +} + +@keyframes scan { + 0% { transform: translateY(-100%); } + 100% { transform: translateY(100vh); } +} + +@keyframes flicker { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.3; } +} + +@keyframes float { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-5px); } +} + +body { + background: var(--color-background); + color: var(--color-foreground); + font-family: var(--font-sans); + min-height: 100vh; +} + +/* Scrollbar */ +::-webkit-scrollbar { + width: 6px; +} +::-webkit-scrollbar-track { + background: #0a0e1a; +} +::-webkit-scrollbar-thumb { + background: #1e293b; + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: #334155; +} + +/* Selection */ +::selection { + background: rgba(0, 229, 255, 0.2); + color: #e0e0e0; +} + +/* Scanline overlay */ +body::after { + content: ''; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: repeating-linear-gradient( + 0deg, + transparent, + transparent 2px, + rgba(0, 0, 0, 0.03) 2px, + rgba(0, 0, 0, 0.03) 4px + ); + pointer-events: none; + z-index: 9999; +} diff --git a/app/layout.tsx b/app/layout.tsx new file mode 100644 index 0000000..745c57b --- /dev/null +++ b/app/layout.tsx @@ -0,0 +1,35 @@ +import type { Metadata } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; +import "./globals.css"; +import { AuthProvider } from "@/components/AuthProvider"; +import { Navbar } from "@/components/Navbar"; + +const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] }); +const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] }); + +export const metadata: Metadata = { + title: "BaraBingo — Barotrauma Bingo", + description: "Chaotic bingo for Barotrauma crews", +}; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + + +
+ {children} +
+ {/* Floating bubbles */} +
+
+
+
+
+
+ + + + ); +} diff --git a/app/page.tsx b/app/page.tsx new file mode 100644 index 0000000..229431b --- /dev/null +++ b/app/page.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { useAuth } from "@/components/AuthProvider"; +import { LoginForm } from "@/components/LoginForm"; +import { CampaignList } from "@/components/CampaignList"; +import { useRouter } from "next/navigation"; + +export default function Home() { + const { user, loading } = useAuth(); + const router = useRouter(); + + if (loading) { + return ( +
+
+
🔊
+ Connecting to submarine network... +
+
+ ); + } + + if (!user) { + return ( +
+
+
+
🤡💥
+

+ BaraBingo +

+

+ Barotrauma Chaos Bingo — mark the madness as it happens +

+
+ +
+

+ First user to register as “admin” gets command access +

+
+
+
+ ); + } + + return ( +
+
+
🌊🎮
+

+ Welcome, {user.nickname} +

+

+ Pick a campaign and dive in +

+
+ router.push(`/game/${id}`)} /> +
+ ); +} diff --git a/components/AdminDashboard.tsx b/components/AdminDashboard.tsx new file mode 100644 index 0000000..0c07dcf --- /dev/null +++ b/components/AdminDashboard.tsx @@ -0,0 +1,164 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "./ui/card"; +import { Button } from "./ui/button"; +import { Input } from "./ui/input"; +import { Badge } from "./ui/badge"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogTrigger } from "./ui/dialog"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; +import { Separator } from "./ui/separator"; + +type Campaign = { + id: string; + name: string; + gridSize: number; + status: string; + createdAt: string; +}; + +export function AdminDashboard() { + const [campaigns, setCampaigns] = useState([]); + const [loading, setLoading] = useState(true); + const [newName, setNewName] = useState(""); + const [newGridSize, setNewGridSize] = useState("5"); + const [creating, setCreating] = useState(false); + const [dialogOpen, setDialogOpen] = useState(false); + + const fetchCampaigns = async () => { + const res = await fetch("/api/campaigns"); + const data = await res.json(); + setCampaigns(data); + setLoading(false); + }; + + useEffect(() => { fetchCampaigns(); }, []); + + const createCampaign = async () => { + if (!newName) return; + setCreating(true); + await fetch("/api/campaigns", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name: newName, gridSize: parseInt(newGridSize) }), + }); + setNewName(""); + setDialogOpen(false); + await fetchCampaigns(); + setCreating(false); + }; + + const deleteCampaign = async (id: string) => { + await fetch(`/api/campaigns/${id}`, { method: "DELETE" }); + await fetchCampaigns(); + }; + + const statusColors: Record = { + active: "success", + completed: "warning", + archived: "secondary", + }; + + return ( +
+
+
+

⚙ Command Center

+

Admin terminal — v1.0

+
+ + + + + + + New Campaign + + Deploy a new bingo operation + + +
+
+ + setNewName(e.target.value)} + className="font-mono" + /> +
+
+ + +
+
+ + + + +
+
+
+ + + + {loading ? ( +
+ Loading submarine manifests... +
+ ) : campaigns.length === 0 ? ( + + +
🗺️💀
+

No campaigns deployed

+

Click “New Campaign” to start the chaos

+
+
+ ) : ( +
+ {campaigns.map(c => ( + + +
+
+ {c.name} + + {c.status} + +
+
+ {c.gridSize}×{c.gridSize} + {new Date(c.createdAt).toLocaleDateString()} +
+
+
+ + + + +
+
+
+ ))} +
+ )} +
+ ); +} diff --git a/components/AuthProvider.tsx b/components/AuthProvider.tsx new file mode 100644 index 0000000..75daa0d --- /dev/null +++ b/components/AuthProvider.tsx @@ -0,0 +1,79 @@ +"use client"; + +import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from "react"; + +type User = { id: string; nickname: string; isAdmin: boolean } | null; + +type AuthContext = { + user: User; + login: (nickname: string, password: string) => Promise; + register: (nickname: string, password: string) => Promise; + logout: () => Promise; + loading: boolean; + refetch: () => Promise; +}; + +const ctx = createContext({ + user: null, + login: async () => null, + register: async () => null, + logout: async () => {}, + loading: true, + refetch: async () => {}, +}); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + const refetch = useCallback(async () => { + try { + const res = await fetch("/api/auth/me"); + const data = await res.json(); + setUser(data.user); + } catch { + setUser(null); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { refetch(); }, [refetch]); + + const login = async (nickname: string, password: string): Promise => { + const res = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ nickname, password }), + }); + const data = await res.json(); + if (data.error) return data.error; + setUser(data); + return null; + }; + + const register = async (nickname: string, password: string): Promise => { + const res = await fetch("/api/auth/register", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ nickname, password }), + }); + const data = await res.json(); + if (data.error) return data.error; + const loginErr = await login(nickname, password); + return loginErr; + }; + + const logout = async () => { + await fetch("/api/auth/login", { method: "DELETE" }); + setUser(null); + }; + + return ( + + {children} + + ); +} + +export const useAuth = () => useContext(ctx); diff --git a/components/BingoCard.tsx b/components/BingoCard.tsx new file mode 100644 index 0000000..d67e158 --- /dev/null +++ b/components/BingoCard.tsx @@ -0,0 +1,299 @@ +"use client"; + +import { useState, useEffect, useCallback, useRef } from "react"; +import { BingoCell } from "./BingoCell"; +import { Badge } from "./ui/badge"; +import { Button } from "./ui/button"; +import { playSound, playBingo } from "@/lib/sounds"; +import { cn } from "@/lib/utils"; + +type Item = { + id: string; + text: string; + emoji: string; + soundCategory: string; + soundUrl?: string | null; + gridIndex: number; +}; + +type GridCell = { + index: number; + item: Item | null; + marked: boolean; + markedBy: string[]; + markCount: number; +}; + +type Campaign = { + id: string; + name: string; + gridSize: number; + status: string; +}; + +type Props = { + campaign: Campaign; + initialGrid: GridCell[]; + currentUserNickname: string; + isAdmin: boolean; +}; + +function checkBingo(grid: GridCell[], gridSize: number): number[][] { + const lines: number[][] = []; + const size = gridSize; + + for (let row = 0; row < size; row++) { + const indices = Array.from({ length: size }, (_, c) => row * size + c); + if (indices.every(i => grid[i]?.marked)) lines.push(indices); + } + + for (let col = 0; col < size; col++) { + const indices = Array.from({ length: size }, (_, r) => r * size + col); + if (indices.every(i => grid[i]?.marked)) lines.push(indices); + } + + const diag1 = Array.from({ length: size }, (_, i) => i * size + i); + if (diag1.every(i => grid[i]?.marked)) lines.push(diag1); + + const diag2 = Array.from({ length: size }, (_, i) => (i + 1) * size - i - 1); + if (diag2.every(i => grid[i]?.marked)) lines.push(diag2); + + return lines; +} + +export function BingoCard({ campaign, initialGrid, currentUserNickname, isAdmin }: Props) { + const [grid, setGrid] = useState(initialGrid); + const [bingoLines, setBingoLines] = useState([]); + const [marking, setMarking] = useState(null); + const [chaosLevel, setChaosLevel] = useState(0); + const [showBingo, setShowBingo] = useState(false); + const [activityLog, setActivityLog] = useState([]); + const bingoNotified = useRef(false); + const pollingRef = useRef | null>(null); + + const fetchState = useCallback(async () => { + try { + const res = await fetch(`/api/game/${campaign.id}/state`); + const data = await res.json(); + if (data.grid) { + setGrid(data.grid); + const lines = checkBingo(data.grid, campaign.gridSize); + setBingoLines(lines); + const markedCount = data.grid.filter((c: GridCell) => c.marked).length; + const totalItems = data.grid.filter((c: GridCell) => c.item).length; + setChaosLevel(totalItems > 0 ? Math.min(markedCount / totalItems, 1) : 0); + if (lines.length > 0 && !bingoNotified.current) { + bingoNotified.current = true; + setShowBingo(true); + playBingo(); + } + if (data.activityLog) { + setActivityLog(data.activityLog); + } + } + } catch {} + }, [campaign.id, campaign.gridSize]); + + useEffect(() => { + fetchState(); + pollingRef.current = setInterval(fetchState, 3000); + return () => { if (pollingRef.current) clearInterval(pollingRef.current); }; + }, [fetchState]); + + const handleMark = async (itemId: string) => { + if (marking) return; + setMarking(itemId); + try { + const res = await fetch("/api/game/mark", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ campaignId: campaign.id, itemId }), + }); + if (res.ok) { + const item = grid.find(c => c.item?.id === itemId); + if (item?.item) playSound(item.item.soundCategory, item.item.soundUrl); + await fetchState(); + } else if (res.status === 409) { + await fetchState(); + } + } catch {} + setMarking(null); + }; + + const markedCount = grid.filter(c => c.marked).length; + const totalItems = grid.filter(c => c.item).length; + + const hullHealth = Math.max(0, 100 - chaosLevel * 100); + const reactorTemp = 80 + chaosLevel * 120; + const o2Level = Math.max(0, 100 - chaosLevel * 130); + + const stageLabel = + chaosLevel < 0.25 ? "✅ Sub stable" : + chaosLevel < 0.5 ? "⚠️ Leaking" : + chaosLevel < 0.75 ? "🚨 MELTDOWN" : "☢️ SUB DESTROYED"; + + const chaosStageClass = + chaosLevel < 0.3 ? "from-cyan-600 to-cyan-500" : + chaosLevel < 0.6 ? "from-amber-600 to-orange-500" : + "from-red-600 to-red-500"; + + return ( +
+ {/* Header */} +
+

+ {campaign.name} +

+

+ {markedCount}/{totalItems} cells marked +

+
+ + {/* Chaos Meter */} +
+
+ {stageLabel} + {Math.round(chaosLevel * 100)}% chaos +
+
+
= 0.6 && "animate-pulse" + )} + style={{ width: `${chaosLevel * 100}%` }} + /> +
+
+ + {/* Sub Status + Grid Row */} +
+ {/* Sub Status Panel */} +
+
+

Sub Status

+
+
+
+ Hull + {Math.round(hullHealth)}% +
+
+
+
+
+
+
+ Reactor + 120 ? "text-orange-400" : "text-slate-400")}>{Math.round(reactorTemp)}°C +
+
+
120 ? "bg-orange-500 animate-pulse" : "bg-cyan-500")} style={{ width: `${Math.min(reactorTemp / 2, 100)}%` }} /> +
+
+
+
+ O₂ + {Math.round(o2Level)}% +
+
+
+
+
+
+
+ {chaosLevel < 0.25 && "All systems nominal"} + {chaosLevel >= 0.25 && chaosLevel < 0.5 && "⚠️ Minor breaches detected"} + {chaosLevel >= 0.5 && chaosLevel < 0.75 && "🚨 EVACUATE! SUB COMPROMISED"} + {chaosLevel >= 0.75 && "☢️ MELTDOWN IN PROGRESS"} +
+
+ + {/* Activity Log */} +
+

Crew Log

+
+ {activityLog.length === 0 && ( +

Awaiting chaos...

+ )} + {activityLog.map((entry, i) => ( +

{entry}

+ ))} +
+
+
+ + {/* Bingo Grid */} +
+
+ {grid.map((cell) => ( + + ))} +
+
+
+ + {/* Bingo Lines */} + {bingoLines.length > 0 && ( +
+ + 🏆 BINGO! {bingoLines.length} line(s) + +
+ )} + + {/* Bingo Celebration Modal */} + {showBingo && ( +
setShowBingo(false)}> +
e.stopPropagation()}> +
🏆🔥💀
+

БИНГО!

+

Хаос победил! Суб взорван, экипаж мёртв, всем весело!

+
🎉💥🌊🤡
+ +
+
+ )} + + {/* Mobile Activity Log */} +
+

Crew Log

+
+ {activityLog.length === 0 && ( +

Awaiting chaos...

+ )} + {activityLog.map((entry, i) => ( +

{entry}

+ ))} +
+
+ + {/* Legend */} +
+ 🎺 horn + 🚨 alarm + 🌊 flood + 💥 boom + 👹 monster + 💀 death + 🔥 chaos +
+
+ ); +} diff --git a/components/BingoCell.tsx b/components/BingoCell.tsx new file mode 100644 index 0000000..e3ab27c --- /dev/null +++ b/components/BingoCell.tsx @@ -0,0 +1,113 @@ +"use client"; + +import { cn } from "@/lib/utils"; +import { useEffect, useState } from "react"; + +type Item = { + id: string; + text: string; + emoji: string; + soundCategory: string; + gridIndex: number; +}; + +type Props = { + item: Item | null; + index: number; + marked: boolean; + markCount: number; + markedBy: string[]; + gridSize: number; + onMark: (itemId: string) => void; + disabled?: boolean; + isFreeSpace?: boolean; +}; + +function getSoundEmoji(cat: string) { + switch (cat) { + case "horn": return "🎺"; + case "alarm": return "🚨"; + case "flood": return "🌊"; + case "explosion": return "💥"; + case "monster": return "👹"; + case "death": return "💀"; + case "chaos": return "🔥"; + default: return "🔔"; + } +} + +export function BingoCell({ item, index, marked, markCount, markedBy, gridSize, onMark, disabled, isFreeSpace }: Props) { + const [shake, setShake] = useState(false); + const [glow, setGlow] = useState(false); + + useEffect(() => { + if (marked) { + setShake(true); + setGlow(true); + const t1 = setTimeout(() => setShake(false), 300); + const t2 = setTimeout(() => setGlow(false), 2000); + return () => { clearTimeout(t1); clearTimeout(t2); }; + } + }, [marked]); + + if (!item) { + return ( +
5 ? "p-1" : "p-2" + )}> + ✖ +
+ ); + } + + const isFree = isFreeSpace || item.text.startsWith("FREE SPACE"); + + return ( + + ); +} diff --git a/components/CampaignList.tsx b/components/CampaignList.tsx new file mode 100644 index 0000000..2b1fb2b --- /dev/null +++ b/components/CampaignList.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "./ui/card"; +import { Badge } from "./ui/badge"; +import { Button } from "./ui/button"; +import { useAuth } from "./AuthProvider"; + +type Campaign = { + id: string; + name: string; + gridSize: number; + status: string; + createdAt: string; +}; + +export function CampaignList({ onSelect }: { onSelect: (id: string) => void }) { + const { user } = useAuth(); + const [campaigns, setCampaigns] = useState([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + fetch("/api/campaigns") + .then(r => r.json()) + .then(data => setCampaigns(data)) + .finally(() => setLoading(false)); + }, []); + + if (loading) { + return ( +
+ Scanning submarine network... +
+ ); + } + + if (campaigns.length === 0) { + return ( + + +
🗺️
+

No active campaigns

+

Admin can create one

+
+
+ ); + } + + return ( +
+ {campaigns.map(c => ( + onSelect(c.id)}> + +
+

+ {c.name} +

+
+ + {c.status} + + {c.gridSize}×{c.gridSize} +
+
+ +
+
+ ))} +
+ ); +} diff --git a/components/ChaosMeter.tsx b/components/ChaosMeter.tsx new file mode 100644 index 0000000..25c602e --- /dev/null +++ b/components/ChaosMeter.tsx @@ -0,0 +1,57 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { cn } from "@/lib/utils"; +import { playChaosRiser } from "@/lib/sounds"; + +type Props = { + markedCount: number; + totalItems: number; +}; + +export function ChaosMeter({ markedCount, totalItems }: Props) { + const [prevCount, setPrevCount] = useState(markedCount); + + const ratio = totalItems > 0 ? markedCount / totalItems : 0; + const percent = Math.round(ratio * 100); + + useEffect(() => { + if (markedCount > prevCount && markedCount % 3 === 0) { + playChaosRiser(); + } + setPrevCount(markedCount); + }, [markedCount, prevCount]); + + const stage = + ratio < 0.25 ? "stable" : + ratio < 0.5 ? "unstable" : + ratio < 0.75 ? "critical" : "meltdown"; + + const stageLabels: Record = { + stable: "✅ Sub stable", + unstable: "⚠️ Leaking", + critical: "🚨 MELTDOWN", + meltdown: "☢️ NUKE", + }; + + return ( +
+
+ {stageLabels[stage]} + {percent}% chaos +
+
+
+
+
+ ); +} diff --git a/components/ItemEditor.tsx b/components/ItemEditor.tsx new file mode 100644 index 0000000..181fefc --- /dev/null +++ b/components/ItemEditor.tsx @@ -0,0 +1,303 @@ +"use client"; + +import { useState, useEffect, useRef } from "react"; +import { Card, CardContent } from "./ui/card"; +import { Button } from "./ui/button"; +import { Input } from "./ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; +import { SOUND_CATEGORIES, EMOJIS } from "@/lib/bingo-data"; +import { Badge } from "./ui/badge"; + +type Item = { + id: string; + text: string; + emoji: string; + soundCategory: string; + soundUrl?: string | null; + gridIndex: number; +}; + +type Campaign = { + id: string; + name: string; + gridSize: number; +}; + +function EmojiPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) { + const [open, setOpen] = useState(false); + const ref = useRef(null); + + useEffect(() => { + function handleClick(e: MouseEvent) { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); + } + document.addEventListener("mousedown", handleClick); + return () => document.removeEventListener("mousedown", handleClick); + }, []); + + return ( +
+ + {open && ( +
+
+ {EMOJIS.map(e => ( + + ))} +
+
+ )} +
+ ); +} + +export function ItemEditor({ campaign }: { campaign: Campaign }) { + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(true); + const [editText, setEditText] = useState(""); + const [editEmoji, setEditEmoji] = useState("💀"); + const [editSound, setEditSound] = useState("horn"); + const [editSoundUrl, setEditSoundUrl] = useState(null); + const [uploading, setUploading] = useState(false); + const fileInputRef = useRef(null); + + const fetchItems = async () => { + const res = await fetch(`/api/campaigns/${campaign.id}/items`); + const data = await res.json(); + const sorted = [...data].sort((a: Item, b: Item) => a.gridIndex - b.gridIndex); + setItems(sorted); + setLoading(false); + }; + + useEffect(() => { fetchItems(); }, [campaign.id]); + + const updateItem = async (item: Item) => { + await fetch(`/api/campaigns/${campaign.id}/items`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + id: item.id, + text: item.text, + emoji: item.emoji, + soundCategory: item.soundCategory, + soundUrl: item.soundUrl, + gridIndex: item.gridIndex, + }), + }); + await fetchItems(); + }; + + const deleteItem = async (itemId: string) => { + await fetch(`/api/campaigns/${campaign.id}/items?itemId=${itemId}`, { method: "DELETE" }); + await fetchItems(); + }; + + const addItem = async () => { + if (!editText) return; + const maxIdx = items.reduce((max, it) => Math.max(max, it.gridIndex), -1); + const totalCells = campaign.gridSize * campaign.gridSize; + if (maxIdx + 1 >= totalCells) { + alert("Grid is full! Delete some items first."); + return; + } + await fetch(`/api/campaigns/${campaign.id}/items`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + text: editText, + emoji: editEmoji, + soundCategory: editSound, + soundUrl: editSoundUrl, + gridIndex: maxIdx + 1, + }), + }); + setEditText(""); + setEditEmoji("💀"); + setEditSound("horn"); + setEditSoundUrl(null); + await fetchItems(); + }; + + const uploadSound = async (file: File) => { + setUploading(true); + const formData = new FormData(); + formData.append("file", file); + const res = await fetch("/api/upload/sound", { method: "POST", body: formData }); + const data = await res.json(); + if (data.url) setEditSoundUrl(data.url); + setUploading(false); + }; + + const totalCells = campaign.gridSize * campaign.gridSize; + + if (loading) { + return
Loading items...
; + } + + return ( +
+ + +

+ Add New Cell

+
+
+ + setEditText(e.target.value)} + className="font-mono text-sm" + /> +
+
+ + +
+
+ + +
+ {editSound === "custom" && ( +
+ +
+ { const f = e.target.files?.[0]; if (f) uploadSound(f); }} + /> + + {editSoundUrl && ( + + )} +
+
+ )} + +
+
+
+ +
+ {Array.from({ length: totalCells }).map((_, idx) => { + const item = items.find(it => it.gridIndex === idx); + if (!item) { + return ( +
+ ✖ +
+ ); + } + return ( + + + {item.emoji} + + {item.text} + + + {item.soundUrl ? "🔊" : item.soundCategory} + +
+ +
+
+
+ ); + })} +
+ +
+

All Items

+ {items.map(item => ( +
+ {item.emoji} + { + setItems(prev => prev.map(it => it.id === item.id ? { ...it, text: e.target.value } : it)); + }} + onBlur={() => updateItem(item)} + /> + + #{item.gridIndex} +
+ ))} +
+
+ ); +} diff --git a/components/LoginForm.tsx b/components/LoginForm.tsx new file mode 100644 index 0000000..d81e3fe --- /dev/null +++ b/components/LoginForm.tsx @@ -0,0 +1,83 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "./ui/button"; +import { Input } from "./ui/input"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card"; +import { useAuth } from "./AuthProvider"; + +export function LoginForm() { + const { login, register } = useAuth(); + const [nickname, setNickname] = useState(""); + const [password, setPassword] = useState(""); + const [isRegister, setIsRegister] = useState(false); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(""); + setLoading(true); + const fn = isRegister ? register : login; + const err = await fn(nickname, password); + if (err) setError(err); + setLoading(false); + }; + + return ( + + +
🤡💥
+ + BaraBingo + + + {isRegister ? "SUB CREW REGISTRATION" : "SUB NETWORK LOGIN"} + +
+ +
+
+ + setNickname(e.target.value)} + required + minLength={2} + maxLength={20} + className="font-mono" + /> +
+
+ + setPassword(e.target.value)} + required + minLength={4} + className="font-mono" + /> +
+ {error && ( +
+ ⚠ {error} +
+ )} + + +
+
+
+ ); +} diff --git a/components/Navbar.tsx b/components/Navbar.tsx new file mode 100644 index 0000000..a017cc0 --- /dev/null +++ b/components/Navbar.tsx @@ -0,0 +1,47 @@ +"use client"; + +import { useAuth } from "./AuthProvider"; +import { Button } from "./ui/button"; +import { Badge } from "./ui/badge"; + +export function Navbar() { + const { user, loading, logout } = useAuth(); + + return ( + + ); +} diff --git a/components/ui/badge.tsx b/components/ui/badge.tsx new file mode 100644 index 0000000..b137b5d --- /dev/null +++ b/components/ui/badge.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors", + { + variants: { + variant: { + default: "border-transparent bg-cyan-600/80 text-cyan-50", + secondary: "border-transparent bg-slate-700 text-slate-200", + destructive: "border-transparent bg-red-600/80 text-red-50", + success: "border-transparent bg-emerald-600/80 text-emerald-50", + warning: "border-transparent bg-amber-600/80 text-amber-50", + outline: "text-slate-300 border-slate-600", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +interface BadgeProps extends React.HTMLAttributes, VariantProps {} + +function Badge({ className, variant, ...props }: BadgeProps) { + return
+} + +export { Badge, badgeVariants } diff --git a/components/ui/button.tsx b/components/ui/button.tsx new file mode 100644 index 0000000..450620d --- /dev/null +++ b/components/ui/button.tsx @@ -0,0 +1,48 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 cursor-pointer", + { + variants: { + variant: { + default: "bg-cyan-600 text-white hover:bg-cyan-500 shadow-lg shadow-cyan-900/30", + destructive: "bg-red-700 text-white hover:bg-red-600 shadow-lg shadow-red-900/30", + outline: "border border-cyan-700/50 bg-transparent text-cyan-300 hover:bg-cyan-950/50", + secondary: "bg-slate-800 text-slate-200 hover:bg-slate-700", + ghost: "text-slate-300 hover:bg-slate-800/50 hover:text-white", + link: "text-cyan-400 underline-offset-4 hover:underline", + }, + size: { + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps {} + +const Button = React.forwardRef( + ({ className, variant, size, ...props }, ref) => { + return ( +