"use client"; import React, { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { Card, CardContent } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Category } from "@/lib/types"; const defaultLogo = "/default-logo.png"; // Fallback logo path const MAX_DESCRIPTION_LENGTH = 100; // Set max length for description const CategoryView = () => { const [categories, setCategories] = useState([]); const [selectedCategory, setSelectedCategory] = useState(null); const router = useRouter(); useEffect(() => { const fetchCategories = async () => { try { const basePath = process.env.NODE_ENV === "production" ? "/ProxmoxVE" : ""; const response = await fetch(`${basePath}/api/categories`); if (!response.ok) { throw new Error("Failed to fetch categories"); } const data = await response.json(); console.log("Fetched categories:", data); // Debugging setCategories(data); } catch (error) { console.error("Error fetching categories:", error); } }; fetchCategories(); }, []); const handleCategoryClick = (category: Category) => { setSelectedCategory(category); }; const handleBackClick = () => { setSelectedCategory(null); }; const handleScriptClick = (scriptSlug: string) => { router.push(`/scripts?id=${scriptSlug}`); }; const truncateDescription = (text: string) => { return text.length > MAX_DESCRIPTION_LENGTH ? `${text.slice(0, MAX_DESCRIPTION_LENGTH)}...` : text; }; const getRandomScripts = (scripts: any[]) => { if (!scripts || scripts.length <= 5) return scripts; return scripts.sort(() => 0.5 - Math.random()).slice(0, 5); }; return (
{categories.length === 0 && (

No categories available. Please check the API endpoint.

)} {selectedCategory ? (

{selectedCategory.name}

{selectedCategory.scripts .sort((a, b) => a.name.localeCompare(b.name)) .map((script) => ( handleScriptClick(script.slug)} >
{script.name}

{script.name}

Created at: {script.date_created || "No date available"}

{truncateDescription(script.description || "No description available.")}

CPU: {script.install_methods[0]?.resources.cpu || "N/A"}vCPU |{" "} RAM: {script.install_methods[0]?.resources.ram || "N/A"}MB |{" "} HDD: {script.install_methods[0]?.resources.hdd || "N/A"}GB
))}
) : (

Categories

{categories.reduce((acc, cat) => acc + (cat.scripts?.length || 0), 0)} Total scripts

{categories.map((category) => ( handleCategoryClick(category)} className="cursor-pointer hover:shadow-lg flex flex-col items-center justify-center" >
{category.scripts && getRandomScripts(category.scripts).map((script, index) => ( {script.name ))}

{category.name}

{category.description || "No description available."}

))}
)}
); }; export default CategoryView;