"use client";
import { Progress } from "@/components/ui/progress";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";

type WordDensityProps = {
    density: Record<string, number>;
};

export default function WordDensity({ density }: WordDensityProps) {
    const sorted = Object.entries(density).sort((a, b) => b[1] - a[1]);
    const firstFive = sorted.slice(0, 5);
    const rest = sorted.slice(5);

    return (
        <div className="h-auto w-full pt-8">
            <h2 className="text-2xl">Word Density</h2>
            <table className="w-full table-auto border-separate border-spacing-y-2">
                <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
                </thead>
                <tbody>
                {firstFive.map(([word, value]) => (
                    <tr key={word}>
                        <td className="uppercase text-lg pr-4">{word}</td>
                        <td className="w-full">
                            <Progress className="h-4" value={value * 100}/>
                        </td>
                        <td className="pl-4 text-md">{(value * 100).toFixed(2)}%</td>
                    </tr>
                ))}
                </tbody>
            </table>
            {rest.length > 0 && (
                <Accordion type="single" collapsible>
                    <AccordionItem value="item-1">
                        <AccordionTrigger className="text-xl">See more</AccordionTrigger>
                        <AccordionContent>
                            <table className="w-full table-auto border-separate border-spacing-y-2">
                                <thead>
                                <tr>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                </tr>
                                </thead>
                                <tbody>
                                {rest.map(([word, value]) => (
                                    <tr key={word}>
                                        <td className="uppercase text-lg pr-4">{word}</td>
                                        <td className="w-full">
                                            <Progress className="h-4" value={value * 100}/>
                                        </td>
                                        <td className="pl-4 text-md">{(value * 100).toFixed(2)}%</td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                        </AccordionContent>
                    </AccordionItem>
                </Accordion>
            )}
        </div>
    );
}
