import { useContext, useState } from 'preact/hooks' import { Problem as ProblemModel } from '../../shared/model' import { sortByNumericKey, sortByStringKey } from '../../shared/utils' import { Header } from '../components/Header' import { Problem } from '../components/Problem' import { Select } from '../components/Select' import { useResource, MetadataContext } from '../hooks' function byTime(p: ProblemModel): string { return p.createdAt } function bySolvedProblems(p: ProblemModel & { solutionsCount: number }): number { return p.solutionsCount } type SortOrder = 'latest' | 'oldest' | 'top-solved' | 'least-solved' const SORT_ORDER: Record = { 'latest': false, 'oldest': true, 'top-solved': false, 'least-solved': true, } export const HomePage = () => { const metadata = useContext(MetadataContext) metadata.title = `PHC Problemi` metadata.description = 'Bacheca di problemi di matematica creato dal PHC' const [problems] = useResource<(ProblemModel & { solutionsCount: number })[]>('/api/problems', []) const [sortOrder, setSortOrder] = useState('oldest') const sortedProblems = sortOrder === 'latest' || sortOrder === 'oldest' ? sortByStringKey(problems, byTime, SORT_ORDER[sortOrder]) : sortByNumericKey(problems, bySolvedProblems, SORT_ORDER[sortOrder]) return ( <>