Skip to content

Commit b030407

Browse files
Feat: Random Script picker
1 parent 9068dbb commit b030407

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"use client";
2+
3+
import { useEffect, useState } from "react";
4+
import { fetchCategories } from "@/lib/data";
5+
import { Category, Script } from "@/lib/types";
6+
import { ScriptItem } from "@/app/scripts/_components/ScriptItem";
7+
import { Loader2, RefreshCw } from "lucide-react";
8+
9+
function getRandomScript(categories: Category[]): Script | null {
10+
const allScripts = categories.flatMap((cat) => cat.scripts || []);
11+
if (allScripts.length === 0) return null;
12+
const idx = Math.floor(Math.random() * allScripts.length);
13+
return allScripts[idx];
14+
}
15+
16+
export default function RandomScriptPage() {
17+
const [categories, setCategories] = useState<Category[]>([]);
18+
const [randomScript, setRandomScript] = useState<Script | null>(null);
19+
const [loading, setLoading] = useState(true);
20+
21+
// Fetch categories/scripts on mount
22+
useEffect(() => {
23+
setLoading(true);
24+
fetchCategories()
25+
.then((cats) => {
26+
setCategories(cats);
27+
setRandomScript(getRandomScript(cats));
28+
})
29+
.finally(() => setLoading(false));
30+
}, []);
31+
32+
// Handler to re-roll a new random script
33+
const reroll = () => {
34+
setRandomScript(getRandomScript(categories));
35+
};
36+
37+
return (
38+
<div className="mb-3">
39+
<div className="mt-20 flex flex-col items-center sm:px-4 xl:px-0">
40+
<div className="w-full max-w-5xl flex flex-col items-center">
41+
<div className="w-full flex justify-between items-center mb-6">
42+
<h1 className="text-2xl font-semibold tracking-tight">Random Script</h1>
43+
<button
44+
onClick={reroll}
45+
className="flex items-center gap-2 rounded-lg bg-accent/30 px-4 py-2 text-base font-medium hover:bg-accent/50 transition-colors"
46+
title="Pick another random script"
47+
disabled={loading || categories.length === 0}
48+
>
49+
<RefreshCw className="h-5 w-5" />
50+
Re-Roll
51+
</button>
52+
</div>
53+
{loading ? (
54+
<div className="flex flex-col items-center justify-center w-full h-64">
55+
<Loader2 className="h-10 w-10 animate-spin" />
56+
</div>
57+
) : randomScript ? (
58+
<ScriptItem item={randomScript} setSelectedScript={() => { }} />
59+
) : (
60+
<div className="text-center text-muted-foreground">
61+
No scripts available.
62+
</div>
63+
)}
64+
</div>
65+
</div>
66+
</div>
67+
);
68+
}

0 commit comments

Comments
 (0)