refactor: code quality cleanup — remove any types, add logger, rename Kine to Tabata

- Phase 0: Rename all Kine references to Tabata (types, files, imports, i18n, analytics events)
- Phase 1: Add test coverage for tabataProgramStore, workoutProgramStore, and color utils (47 tests)
- Phase 2: Remove all `any` types from production code with proper typed replacements
- Phase 3: Replace ~60 raw console.* calls with __DEV__-gated logger utility
- Phase 4: Verify .DS_Store housekeeping (already clean)

0 TypeScript errors, 583/583 tests passing.
This commit is contained in:
Millian Lamiaux
2026-04-17 18:56:24 +02:00
parent e0e02c4550
commit 791f432334
176 changed files with 16508 additions and 2305 deletions

View File

@@ -0,0 +1,12 @@
<claude-mem-context>
# Recent Activity
<!-- This section is auto-generated by claude-mem. Edit content outside the tags. -->
### Apr 16, 2026
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #6321 | 9:38 PM | 🟣 | Created TabataEditor component for admin workout program management | ~327 |
| #6325 | " | 🟣 | Added Programs navigation link to admin sidebar | ~260 |
</claude-mem-context>

View File

@@ -0,0 +1,433 @@
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { Loader2, Save, X } from "lucide-react"
import { cn } from "@/lib/utils"
import { supabase } from "@/lib/supabase"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select } from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import TabataEditor, { TabataData } from "@/components/tabata-editor"
import { toast } from "sonner"
import type { Database } from "@/lib/supabase"
type WorkoutProgram = Database["public"]["Tables"]["workout_programs"]["Row"]
type ProgramTabata = Database["public"]["Tables"]["program_tabatas"]["Row"]
interface ProgramFormProps {
initialData?: WorkoutProgram & { tabatas?: ProgramTabata[] }
mode?: "create" | "edit"
}
const BODY_ZONE_OPTIONS = [
{ value: "upper-body", label: "Upper Body" },
{ value: "lower-body", label: "Lower Body" },
{ value: "full-body", label: "Full Body" },
]
const LEVEL_OPTIONS = [
{ value: "Beginner", label: "Beginner" },
{ value: "Intermediate", label: "Intermediate" },
{ value: "Advanced", label: "Advanced" },
]
export default function ProgramForm({ initialData, mode = "create" }: ProgramFormProps) {
const router = useRouter()
const [isLoading, setIsLoading] = React.useState(false)
const [errors, setErrors] = React.useState<Record<string, string>>({})
// Basics state
const [title, setTitle] = React.useState(initialData?.title || "")
const [description, setDescription] = React.useState(initialData?.description || "")
const [bodyZone, setBodyZone] = React.useState(initialData?.body_zone || "full-body")
const [level, setLevel] = React.useState(initialData?.level || "Beginner")
const [isFree, setIsFree] = React.useState(initialData?.is_free || false)
const [estimatedCalories, setEstimatedCalories] = React.useState(
String(initialData?.estimated_calories || "")
)
const [icon, setIcon] = React.useState(initialData?.icon || "")
const [accentColor, setAccentColor] = React.useState(initialData?.accent_color || "")
const [sortOrder, setSortOrder] = React.useState(
String(initialData?.sort_order ?? "0")
)
// Tabatas state
const [tabatas, setTabatas] = React.useState<TabataData[]>(() => {
if (initialData?.tabatas && initialData.tabatas.length > 0) {
return initialData.tabatas
.sort((a, b) => a.position - b.position)
.map((t) => ({
position: t.position,
exercise_1_name: t.exercise_1_name || "",
exercise_1_name_en: t.exercise_1_name_en || "",
exercise_1_tip: t.exercise_1_tip || "",
exercise_1_tip_en: t.exercise_1_tip_en || "",
exercise_1_modification: t.exercise_1_modification || "",
exercise_1_modification_en: t.exercise_1_modification_en || "",
exercise_1_progression: t.exercise_1_progression || "",
exercise_1_progression_en: t.exercise_1_progression_en || "",
exercise_2_name: t.exercise_2_name || "",
exercise_2_name_en: t.exercise_2_name_en || "",
exercise_2_tip: t.exercise_2_tip || "",
exercise_2_tip_en: t.exercise_2_tip_en || "",
exercise_2_modification: t.exercise_2_modification || "",
exercise_2_modification_en: t.exercise_2_modification_en || "",
exercise_2_progression: t.exercise_2_progression || "",
exercise_2_progression_en: t.exercise_2_progression_en || "",
rounds: t.rounds || 8,
work_time: t.work_time || 20,
rest_time: t.rest_time || 10,
}))
}
return [
{ position: 1, exercise_1_name: "", exercise_1_name_en: "", exercise_1_tip: "", exercise_1_tip_en: "", exercise_1_modification: "", exercise_1_modification_en: "", exercise_1_progression: "", exercise_1_progression_en: "", exercise_2_name: "", exercise_2_name_en: "", exercise_2_tip: "", exercise_2_tip_en: "", exercise_2_modification: "", exercise_2_modification_en: "", exercise_2_progression: "", exercise_2_progression_en: "", rounds: 8, work_time: 20, rest_time: 10 },
{ position: 2, exercise_1_name: "", exercise_1_name_en: "", exercise_1_tip: "", exercise_1_tip_en: "", exercise_1_modification: "", exercise_1_modification_en: "", exercise_1_progression: "", exercise_1_progression_en: "", exercise_2_name: "", exercise_2_name_en: "", exercise_2_tip: "", exercise_2_tip_en: "", exercise_2_modification: "", exercise_2_modification_en: "", exercise_2_progression: "", exercise_2_progression_en: "", rounds: 8, work_time: 20, rest_time: 10 },
{ position: 3, exercise_1_name: "", exercise_1_name_en: "", exercise_1_tip: "", exercise_1_tip_en: "", exercise_1_modification: "", exercise_1_modification_en: "", exercise_1_progression: "", exercise_1_progression_en: "", exercise_2_name: "", exercise_2_name_en: "", exercise_2_tip: "", exercise_2_tip_en: "", exercise_2_modification: "", exercise_2_modification_en: "", exercise_2_progression: "", exercise_2_progression_en: "", rounds: 8, work_time: 20, rest_time: 10 },
]
})
const validate = () => {
const newErrors: Record<string, string> = {}
if (!title.trim()) newErrors.title = "Title is required"
tabatas.forEach((tabata, i) => {
if (!tabata.exercise_1_name.trim()) {
newErrors[`tabata_${i + 1}_ex1`] = `Tabata ${i + 1}: Exercise 1 name is required`
}
if (!tabata.exercise_2_name.trim()) {
newErrors[`tabata_${i + 1}_ex2`] = `Tabata ${i + 1}: Exercise 2 name is required`
}
})
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!validate()) {
return
}
setIsLoading(true)
try {
// Calculate total estimated duration from tabatas
const totalSeconds = tabatas.reduce(
(sum, t) => sum + t.rounds * (t.work_time + t.rest_time),
0
)
const estimatedDuration = Math.ceil(totalSeconds / 60)
const programData = {
title: title.trim(),
description: description.trim(),
body_zone: bodyZone as WorkoutProgram["body_zone"],
level: level as WorkoutProgram["level"],
is_free: isFree,
estimated_duration: estimatedDuration,
estimated_calories: parseInt(estimatedCalories) || 0,
icon: icon.trim() || null,
accent_color: accentColor.trim() || null,
sort_order: parseInt(sortOrder) || 0,
}
let programId: string
if (mode === "edit" && initialData) {
const result = await (supabase.from("workout_programs") as any)
.update(programData)
.eq("id", initialData.id)
.select()
.single()
if (result.error) throw result.error
programId = initialData.id
} else {
const result = await (supabase.from("workout_programs") as any)
.insert(programData)
.select()
.single()
if (result.error) throw result.error
programId = result.data.id
}
// Upsert tabatas
for (const tabata of tabatas) {
const tabataPayload = {
program_id: programId,
position: tabata.position,
exercise_1_name: tabata.exercise_1_name.trim(),
exercise_1_name_en: tabata.exercise_1_name_en.trim() || null,
exercise_1_tip: tabata.exercise_1_tip.trim() || null,
exercise_1_tip_en: tabata.exercise_1_tip_en.trim() || null,
exercise_1_modification: tabata.exercise_1_modification.trim() || null,
exercise_1_modification_en: tabata.exercise_1_modification_en.trim() || null,
exercise_1_progression: tabata.exercise_1_progression.trim() || null,
exercise_1_progression_en: tabata.exercise_1_progression_en.trim() || null,
exercise_2_name: tabata.exercise_2_name.trim(),
exercise_2_name_en: tabata.exercise_2_name_en.trim() || null,
exercise_2_tip: tabata.exercise_2_tip.trim() || null,
exercise_2_tip_en: tabata.exercise_2_tip_en.trim() || null,
exercise_2_modification: tabata.exercise_2_modification.trim() || null,
exercise_2_modification_en: tabata.exercise_2_modification_en.trim() || null,
exercise_2_progression: tabata.exercise_2_progression.trim() || null,
exercise_2_progression_en: tabata.exercise_2_progression_en.trim() || null,
rounds: tabata.rounds,
work_time: tabata.work_time,
rest_time: tabata.rest_time,
}
// In edit mode, check if tabata exists for this position
if (mode === "edit") {
const existing = initialData?.tabatas?.find((t) => t.position === tabata.position)
if (existing) {
const { error } = await (supabase.from("program_tabatas") as any)
.update(tabataPayload)
.eq("id", existing.id)
if (error) throw error
} else {
const { error } = await (supabase.from("program_tabatas") as any)
.insert(tabataPayload)
if (error) throw error
}
} else {
const { error } = await (supabase.from("program_tabatas") as any)
.insert(tabataPayload)
if (error) throw error
}
}
toast.success(mode === "edit" ? "Program updated" : "Program created", {
description: `"${title}" has been ${mode === "edit" ? "updated" : "created"} successfully.`
})
router.push(`/programs/${programId}`)
} catch (err) {
console.error("Failed to save program:", err)
toast.error("Failed to save program. Please try again.")
} finally {
setIsLoading(false)
}
}
const handleCancel = () => {
if (mode === "edit" && initialData) {
router.push(`/programs/${initialData.id}`)
} else {
router.push("/programs")
}
}
const handleTabataChange = (position: number, data: TabataData) => {
setTabatas((prev) =>
prev.map((t) => (t.position === position ? { ...data, position } : t))
)
}
return (
<form onSubmit={handleSubmit} className="space-y-6">
<Tabs defaultValue="basics" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-neutral-900">
<TabsTrigger value="basics" className="data-[state=active]:bg-neutral-800">
Basics
</TabsTrigger>
<TabsTrigger value="tabatas" className="data-[state=active]:bg-neutral-800">
Tabatas
</TabsTrigger>
</TabsList>
{/* Tab 1: Basics */}
<TabsContent value="basics" className="space-y-4">
<div className="grid gap-4">
<div className="space-y-2">
<Label htmlFor="title">Program Title *</Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g., Full Body Blast"
className={cn(errors.title && "border-red-500")}
/>
{errors.title && <p className="text-xs text-red-500">{errors.title}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Describe this program..."
rows={3}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="bodyZone">Body Zone *</Label>
<Select
id="bodyZone"
value={bodyZone}
onValueChange={(value) => setBodyZone(value as typeof bodyZone)}
options={BODY_ZONE_OPTIONS}
/>
</div>
<div className="space-y-2">
<Label htmlFor="level">Level *</Label>
<Select
id="level"
value={level}
onValueChange={(value) => setLevel(value as typeof level)}
options={LEVEL_OPTIONS}
/>
</div>
</div>
<div className="flex items-center justify-between rounded-lg border border-neutral-800 bg-neutral-900/50 p-4">
<div className="space-y-0.5">
<Label htmlFor="isFree" className="text-base">
Free Program
</Label>
<p className="text-sm text-neutral-500">
Make this program available to free users
</p>
</div>
<Switch id="isFree" checked={isFree} onCheckedChange={setIsFree} />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="estimatedCalories">Estimated Calories</Label>
<Input
id="estimatedCalories"
type="number"
value={estimatedCalories}
onChange={(e) => setEstimatedCalories(e.target.value)}
min={0}
placeholder="e.g., 120"
/>
</div>
<div className="space-y-2">
<Label htmlFor="sortOrder">Sort Order</Label>
<Input
id="sortOrder"
type="number"
value={sortOrder}
onChange={(e) => setSortOrder(e.target.value)}
min={0}
placeholder="0"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="icon">Icon Name</Label>
<Input
id="icon"
value={icon}
onChange={(e) => setIcon(e.target.value)}
placeholder="e.g., flame, dumbbell"
/>
</div>
<div className="space-y-2">
<Label htmlFor="accentColor">Accent Color</Label>
<div className="flex gap-2">
<Input
id="accentColor"
value={accentColor}
onChange={(e) => setAccentColor(e.target.value)}
placeholder="#FF6B35"
className="flex-1"
/>
{accentColor && (
<div
className="h-10 w-10 rounded-md border border-neutral-700 flex-shrink-0"
style={{ backgroundColor: accentColor }}
/>
)}
</div>
</div>
</div>
</div>
</TabsContent>
{/* Tab 2: Tabatas */}
<TabsContent value="tabatas" className="space-y-4">
<div className="space-y-1 mb-4">
<p className="text-sm text-neutral-500">
Each program has 3 tabatas (exercise pairs). Every tabata alternates between two exercises for the specified number of rounds.
</p>
</div>
{errors.tabata_1_ex1 && (
<p className="text-xs text-red-500 bg-red-500/10 px-3 py-2 rounded-md">
{errors.tabata_1_ex1}
</p>
)}
{errors.tabata_1_ex2 && (
<p className="text-xs text-red-500 bg-red-500/10 px-3 py-2 rounded-md">
{errors.tabata_1_ex2}
</p>
)}
{([1, 2, 3] as const).map((pos) => {
const tabata = tabatas.find((t) => t.position === pos) || null
return (
<TabataEditor
key={pos}
tabata={tabata}
position={pos}
onChange={(data) => handleTabataChange(pos, data)}
/>
)
})}
</TabsContent>
</Tabs>
{/* Actions */}
<div className="flex justify-end gap-3 pt-4 border-t border-neutral-800">
<Button
type="button"
variant="outline"
onClick={handleCancel}
disabled={isLoading}
className="border-neutral-700 text-neutral-400 hover:bg-neutral-800 hover:text-white"
>
<X className="mr-2 h-4 w-4" />
Cancel
</Button>
<Button
type="submit"
disabled={isLoading}
className="bg-orange-500 hover:bg-orange-600"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
{mode === "edit" ? "Update Program" : "Create Program"}
</>
)}
</Button>
</div>
</form>
)
}

View File

@@ -13,11 +13,13 @@ import {
Music,
LogOut,
Flame,
LayoutGrid,
} from "lucide-react";
const navItems = [
{ href: "/", label: "Dashboard", icon: LayoutDashboard },
{ href: "/workouts", label: "Workouts", icon: Dumbbell },
{ href: "/programs", label: "Programs", icon: LayoutGrid },
{ href: "/trainers", label: "Trainers", icon: Users },
{ href: "/collections", label: "Collections", icon: FolderOpen },
{ href: "/media", label: "Media", icon: ImageIcon },

View File

@@ -0,0 +1,296 @@
"use client"
import * as React from "react"
import { ChevronDown, ChevronRight, Clock, Dumbbell } from "lucide-react"
import { cn } from "@/lib/utils"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import type { Database } from "@/lib/supabase"
type ProgramTabata = Database["public"]["Tables"]["program_tabatas"]["Row"]
interface TabataData {
position: number
exercise_1_name: string
exercise_1_name_en: string
exercise_1_tip: string
exercise_1_tip_en: string
exercise_1_modification: string
exercise_1_modification_en: string
exercise_1_progression: string
exercise_1_progression_en: string
exercise_2_name: string
exercise_2_name_en: string
exercise_2_tip: string
exercise_2_tip_en: string
exercise_2_modification: string
exercise_2_modification_en: string
exercise_2_progression: string
exercise_2_progression_en: string
rounds: number
work_time: number
rest_time: number
}
export type { TabataData }
interface TabataEditorProps {
tabata: TabataData | null
position: 1 | 2 | 3
onChange: (data: TabataData) => void
}
function getDefaultTabata(position: number): TabataData {
return {
position,
exercise_1_name: "",
exercise_1_name_en: "",
exercise_1_tip: "",
exercise_1_tip_en: "",
exercise_1_modification: "",
exercise_1_modification_en: "",
exercise_1_progression: "",
exercise_1_progression_en: "",
exercise_2_name: "",
exercise_2_name_en: "",
exercise_2_tip: "",
exercise_2_tip_en: "",
exercise_2_modification: "",
exercise_2_modification_en: "",
exercise_2_progression: "",
exercise_2_progression_en: "",
rounds: 8,
work_time: 20,
rest_time: 10,
}
}
interface ExerciseSectionProps {
label: string
number: 1 | 2
data: TabataData
onChange: (field: string, value: string) => void
errors: Record<string, string>
}
function ExerciseSection({ label, number, data, onChange, errors }: ExerciseSectionProps) {
const [isOpen, setIsOpen] = React.useState(true)
const prefix = `exercise_${number}` as const
const nameField = `${prefix}_name` as keyof TabataData
const nameValue = data[nameField] as string
return (
<div className="rounded-lg border border-neutral-800 bg-neutral-950 overflow-hidden">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="flex items-center justify-between w-full px-4 py-3 text-sm font-medium text-white hover:bg-neutral-800/50 transition-colors"
>
<div className="flex items-center gap-2">
{isOpen ? <ChevronDown className="h-4 w-4 text-neutral-500" /> : <ChevronRight className="h-4 w-4 text-neutral-500" />}
<Dumbbell className="h-4 w-4 text-orange-500" />
<span>{label}</span>
{nameValue && (
<span className="text-neutral-500 font-normal">- {nameValue}</span>
)}
</div>
</button>
{isOpen && (
<div className="px-4 pb-4 space-y-3 border-t border-neutral-800">
{/* Name fields */}
<div className="grid grid-cols-2 gap-3 pt-3">
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Name (FR) *</Label>
<Input
value={data[nameField] as string}
onChange={(e) => onChange(`${prefix}_name`, e.target.value)}
placeholder="e.g., Squats"
className={cn("h-9 text-sm", errors[`${prefix}_name`] && "border-red-500")}
/>
{errors[`${prefix}_name`] && <p className="text-xs text-red-500">{errors[`${prefix}_name`]}</p>}
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Name (EN)</Label>
<Input
value={data[`${prefix}_name_en` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_name_en`, e.target.value)}
placeholder="e.g., Squats"
className="h-9 text-sm"
/>
</div>
</div>
{/* Tip fields */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Tip (FR)</Label>
<Input
value={data[`${prefix}_tip` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_tip`, e.target.value)}
placeholder="Conseil en français"
className="h-9 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Tip (EN)</Label>
<Input
value={data[`${prefix}_tip_en` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_tip_en`, e.target.value)}
placeholder="Tip in English"
className="h-9 text-sm"
/>
</div>
</div>
{/* Modification fields */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Modification (FR)</Label>
<Input
value={data[`${prefix}_modification` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_modification`, e.target.value)}
placeholder="Version plus facile"
className="h-9 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Modification (EN)</Label>
<Input
value={data[`${prefix}_modification_en` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_modification_en`, e.target.value)}
placeholder="Easier variation"
className="h-9 text-sm"
/>
</div>
</div>
{/* Progression fields */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Progression (FR)</Label>
<Input
value={data[`${prefix}_progression` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_progression`, e.target.value)}
placeholder="Version plus difficile"
className="h-9 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Progression (EN)</Label>
<Input
value={data[`${prefix}_progression_en` as keyof TabataData] as string}
onChange={(e) => onChange(`${prefix}_progression_en`, e.target.value)}
placeholder="Harder variation"
className="h-9 text-sm"
/>
</div>
</div>
</div>
)}
</div>
)
}
export default function TabataEditor({ tabata, position, onChange }: TabataEditorProps) {
const data = tabata || getDefaultTabata(position)
const [errors, setErrors] = React.useState<Record<string, string>>({})
const handleChange = (field: string, value: string) => {
const updated = { ...data, [field]: value }
onChange(updated)
}
const handleTimingChange = (field: "rounds" | "work_time" | "rest_time", value: string) => {
const numValue = parseInt(value) || 0
const updated = { ...data, [field]: numValue }
onChange(updated)
}
return (
<div className="rounded-lg border border-neutral-700 bg-neutral-900 overflow-hidden">
{/* Header */}
<div className="flex items-center gap-3 px-4 py-3 bg-neutral-800/50 border-b border-neutral-700">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-500/20 text-orange-500 font-bold text-sm">
{position}
</div>
<div>
<h3 className="text-white font-medium">Tabata {position}</h3>
<p className="text-xs text-neutral-500">
{data.exercise_1_name && data.exercise_2_name
? `${data.exercise_1_name} / ${data.exercise_2_name}`
: "Configure exercises and timing"
}
</p>
</div>
<div className="ml-auto flex items-center gap-2 text-xs text-neutral-500">
<Clock className="h-3.5 w-3.5" />
<span>{data.rounds * (data.work_time + data.rest_time)}s total</span>
</div>
</div>
{/* Content */}
<div className="p-4 space-y-4">
{/* Exercise sections */}
<ExerciseSection
label="Exercise 1"
number={1}
data={data}
onChange={handleChange}
errors={errors}
/>
<ExerciseSection
label="Exercise 2"
number={2}
data={data}
onChange={handleChange}
errors={errors}
/>
{/* Timing */}
<div className="rounded-lg border border-neutral-800 bg-neutral-950 p-4">
<div className="flex items-center gap-2 mb-3">
<Clock className="h-4 w-4 text-orange-500" />
<span className="text-sm font-medium text-white">Timing</span>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Rounds</Label>
<Input
type="number"
value={data.rounds}
onChange={(e) => handleTimingChange("rounds", e.target.value)}
min={1}
max={20}
className="h-9 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Work (sec)</Label>
<Input
type="number"
value={data.work_time}
onChange={(e) => handleTimingChange("work_time", e.target.value)}
min={1}
className="h-9 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-neutral-400">Rest (sec)</Label>
<Input
type="number"
value={data.rest_time}
onChange={(e) => handleTimingChange("rest_time", e.target.value)}
min={0}
className="h-9 text-sm"
/>
</div>
</div>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,352 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { Loader2, Sparkles, Save, X, Upload } from "lucide-react"
import { cn } from "@/lib/utils"
import { supabase } from "@/lib/supabase"
import type { Database } from "@/lib/supabase"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select } from "@/components/ui/select"
import { toast } from "sonner"
type Trainer = Database["public"]["Tables"]["trainers"]["Row"]
type TrainerInsert = Database["public"]["Tables"]["trainers"]["Insert"]
type TrainerUpdate = Database["public"]["Tables"]["trainers"]["Update"]
interface TrainerFormProps {
initialData?: Trainer
mode?: "create" | "edit"
}
const SPECIALTY_OPTIONS = [
{ value: "Core", label: "Core" },
{ value: "Strength", label: "Strength" },
{ value: "Cardio", label: "Cardio" },
{ value: "Full Body", label: "Full Body" },
{ value: "Recovery", label: "Recovery" },
]
const PRESET_COLORS = [
"#FF6B35", "#FFD60A", "#30D158", "#5AC8FA", "#BF5AF2",
"#FF9500", "#FF2D55", "#5856D6", "#FF3B30", "#34C759",
]
export default function TrainerForm({ initialData, mode = "create" }: TrainerFormProps) {
const router = useRouter()
const [isLoading, setIsLoading] = useState(false)
const [isGenerating, setIsGenerating] = useState(false)
const [isUploading, setIsUploading] = useState(false)
const [generatedImages, setGeneratedImages] = useState<{ buffer: Buffer; url?: string }[]>([])
const [selectedImage, setSelectedImage] = useState<string | null>(null)
const [generatingPrompt, setGeneratingPrompt] = useState("")
const [errors, setErrors] = useState<Record<string, string>>({})
const [avatarFile, setAvatarFile] = useState<File | null>(null)
const [name, setName] = useState(initialData?.name || "")
const [specialty, setSpecialty] = useState(initialData?.specialty || "Core")
const [color, setColor] = useState(initialData?.color || "#FF6B35")
const [avatarUrl, setAvatarUrl] = useState(initialData?.avatar_url || "")
const validate = () => {
const newErrors: Record<string, string> = {}
if (!name.trim()) newErrors.name = "Name is required"
if (!specialty) newErrors.specialty = "Specialty is required"
if (!color) newErrors.color = "Color is required"
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleGenerateImages = async () => {
if (!name.trim()) {
toast.error("Please enter a name first")
return
}
const prompt = generatingPrompt ||
`Professional portrait photo of ${name}, fitness trainer, friendly smile, gym setting, high quality, facing camera directly, energetic and professional`
setIsGenerating(true)
try {
const trainerId = initialData?.id || "new-trainer"
const filename = `avatar_${Date.now()}.png`
const response = await fetch('/api/ai/generate-avatar', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, trainerId, filename }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Generation failed')
}
const { url } = await response.json()
const savedImages = [{ buffer: Buffer.alloc(0), url }]
setGeneratedImages(savedImages)
setSelectedImage(url)
setAvatarUrl(url)
toast.success('Avatar generated')
} catch (err) {
console.error("Generation failed:", err)
toast.error(err instanceof Error ? err.message : "Failed to generate images")
} finally {
setIsGenerating(false)
}
}
const handleSelectGenerated = (url: string) => {
setSelectedImage(url)
setAvatarUrl(url)
setAvatarFile(null)
}
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
setAvatarFile(file)
setSelectedImage(null)
setIsUploading(true)
try {
const trainerId = initialData?.id || "new-trainer"
const filename = `upload_${Date.now()}.png`
const path = `${trainerId}/${filename}`
const { error } = await supabase.storage
.from('trainer-avatars')
.upload(path, file, {
contentType: file.type,
upsert: true,
})
if (error) throw new Error(error.message)
const { data: { publicUrl } } = supabase.storage
.from('trainer-avatars')
.getPublicUrl(path)
setAvatarUrl(publicUrl)
setGeneratedImages([])
toast.success("Avatar uploaded")
} catch (err) {
console.error("Upload failed:", err)
toast.error(err instanceof Error ? err.message : "Failed to upload avatar")
} finally {
setIsUploading(false)
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!validate()) return
setIsLoading(true)
try {
const trainerData = {
name: name.trim(),
specialty,
color,
avatar_url: avatarUrl || null,
workout_count: initialData?.workout_count || 0,
}
let result
if (mode === "edit" && initialData) {
result = await (supabase
.from("trainers") as any)
.update(trainerData)
.eq("id", initialData.id)
.select()
.single()
} else {
result = await (supabase
.from("trainers") as any)
.insert(trainerData)
.select()
.single()
}
if (result.error) throw result.error
toast.success(mode === "edit" ? "Trainer updated" : "Trainer created")
router.push("/trainers")
} catch (err) {
console.error("Failed to save:", err)
toast.error("Failed to save trainer")
} finally {
setIsLoading(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-8">
<div className="space-y-4">
<h2 className="text-lg font-semibold text-white">Basic Information</h2>
<div className="grid gap-4">
<div className="space-y-2">
<Label htmlFor="name">Name *</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g., Félia"
className={cn(errors.name && "border-red-500")}
/>
{errors.name && <p className="text-xs text-red-500">{errors.name}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="specialty">Specialty *</Label>
<Select
id="specialty"
value={specialty}
onValueChange={setSpecialty}
options={SPECIALTY_OPTIONS}
/>
</div>
<div className="space-y-2">
<Label>Color</Label>
<div className="flex gap-2 flex-wrap">
{PRESET_COLORS.map((c) => (
<button
key={c}
type="button"
onClick={() => setColor(c)}
className={cn(
"w-8 h-8 rounded-full border-2 transition-all",
color === c ? "border-white scale-110" : "border-transparent"
)}
style={{ backgroundColor: c }}
/>
))}
<input
type="color"
value={color}
onChange={(e) => setColor(e.target.value)}
className="w-8 h-8 rounded-full cursor-pointer"
/>
</div>
</div>
</div>
</div>
<div className="space-y-4">
<h2 className="text-lg font-semibold text-white">Trainer Avatar</h2>
<div className="space-y-2">
<Label>Generate with AI (Nano Banana Pro)</Label>
<div className="flex gap-2">
<Input
value={generatingPrompt}
onChange={(e) => setGeneratingPrompt(e.target.value)}
placeholder={`Portrait of ${name || 'trainer'}, fitness, friendly...`}
className="flex-1"
/>
<Button
type="button"
onClick={handleGenerateImages}
disabled={isGenerating || !name.trim()}
className="bg-purple-500 hover:bg-purple-600"
>
{isGenerating ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Sparkles className="w-4 h-4" />
)}
Generate
</Button>
</div>
</div>
{generatedImages.length > 0 && (
<div className="space-y-2">
<Label>Select Generated Image</Label>
<div className="grid grid-cols-3 gap-4">
{generatedImages.map((img, i) => (
<div
key={i}
onClick={() => img.url && handleSelectGenerated(img.url)}
className={cn(
"relative aspect-square rounded-lg overflow-hidden cursor-pointer border-2 transition-all",
selectedImage === img.url ? "border-orange-500 scale-105" : "border-transparent hover:border-neutral-600"
)}
>
{img.url && <img src={img.url} alt={`Generated ${i + 1}`} className="w-full h-full object-cover" />}
</div>
))}
</div>
</div>
)}
<div className="space-y-2">
<Label>Or Upload Custom Image</Label>
<div className="flex items-center gap-4">
<Button
type="button"
variant="outline"
onClick={() => document.getElementById('avatar-upload')?.click()}
disabled={isUploading}
className="border-neutral-700"
>
{isUploading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
Choose File
</Button>
<input
id="avatar-upload"
type="file"
accept="image/jpeg,image/png,image/webp"
onChange={handleFileChange}
className="hidden"
/>
{avatarFile && <span className="text-sm text-neutral-400">{avatarFile.name}</span>}
</div>
</div>
{avatarUrl && (
<div className="space-y-2">
<Label>Current Avatar</Label>
<div className="relative w-32 h-32">
<img
src={avatarUrl}
alt="Current avatar"
className="w-full h-full object-cover rounded-full border-2 border-neutral-700"
/>
{selectedImage === avatarUrl && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full">
<Sparkles className="w-8 h-8 text-orange-500" />
</div>
)}
</div>
</div>
)}
</div>
<div className="flex justify-end gap-3 pt-4 border-t border-neutral-800">
<Button
type="button"
variant="outline"
onClick={() => router.back()}
className="border-neutral-700"
>
Cancel
</Button>
<Button type="submit" disabled={isLoading} className="bg-orange-500 hover:bg-orange-600">
{isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
{mode === "edit" ? "Update Trainer" : "Create Trainer"}
</Button>
</div>
</form>
)
}

View File

@@ -163,15 +163,13 @@ export default function WorkoutForm({ initialData, mode = "create" }: WorkoutFor
let result
if (mode === "edit" && initialData) {
result = await supabase
.from("workouts")
result = await (supabase.from("workouts") as any)
.update(workoutData)
.eq("id", initialData.id)
.select()
.single()
} else {
result = await supabase
.from("workouts")
result = await (supabase.from("workouts") as any)
.insert(workoutData)
.select()
.single()
@@ -199,8 +197,7 @@ export default function WorkoutForm({ initialData, mode = "create" }: WorkoutFor
}
if (Object.keys(updateData).length > 0) {
await supabase
.from("workouts")
await (supabase.from("workouts") as any)
.update(updateData)
.eq("id", result.data.id)
}