commit 05677924b5180be63bd8e6b36800e370321b7168 Author: SlavaVlad Date: Sun Jun 14 21:29:43 2026 +0300 V1 bingo 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 0000000..718d6fe Binary files /dev/null and b/app/favicon.ico differ 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 ( +