'use client' import { getGroupsAction } from '@/app/groups/actions' import { AddGroupByUrlButton } from '@/app/groups/add-group-by-url-button' import { RecentGroups, getArchivedGroups, getRecentGroups, getStarredGroups, } from '@/app/groups/recent-groups-helpers' import { Button } from '@/components/ui/button' import { getGroups } from '@/lib/api' import { Loader2 } from 'lucide-react' import Link from 'next/link' import { PropsWithChildren, SetStateAction, useEffect, useState } from 'react' import { RecentGroupListCard } from './recent-group-list-card' export type RecentGroupsState = | { status: 'pending' } | { status: 'partial' groups: RecentGroups starredGroups: string[] archivedGroups: string[] } | { status: 'complete' groups: RecentGroups groupsDetails: Awaited> starredGroups: string[] archivedGroups: string[] } function sortGroups( state: RecentGroupsState & { status: 'complete' | 'partial' }, ) { const starredGroupInfo = [] const groupInfo = [] const archivedGroupInfo = [] for (const group of state.groups) { if (state.starredGroups.includes(group.id)) { starredGroupInfo.push(group) } else if (state.archivedGroups.includes(group.id)) { archivedGroupInfo.push(group) } else { groupInfo.push(group) } } return { starredGroupInfo, groupInfo, archivedGroupInfo, } } export function RecentGroupList() { const [state, setState] = useState({ status: 'pending' }) function loadGroups() { const groupsInStorage = getRecentGroups() const starredGroups = getStarredGroups() const archivedGroups = getArchivedGroups() setState({ status: 'partial', groups: groupsInStorage, starredGroups, archivedGroups, }) getGroupsAction(groupsInStorage.map((g) => g.id)).then((groupsDetails) => { setState({ status: 'complete', groups: groupsInStorage, groupsDetails, starredGroups, archivedGroups, }) }) } useEffect(() => { loadGroups() }, []) if (state.status === 'pending') { return (

Loading recent groups…

) } if (state.groups.length === 0) { return (

You have not visited any group recently.

{' '} or ask a friend to send you the link to an existing one.

) } const { starredGroupInfo, groupInfo, archivedGroupInfo } = sortGroups(state) return ( {starredGroupInfo.length > 0 && ( <>

Starred groups

)} {groupInfo.length > 0 && ( <>

Recent groups

)} {archivedGroupInfo.length > 0 && ( <>

Archived groups

)}
) } function GroupList({ groups, state, setState, }: { groups: RecentGroups state: RecentGroupsState setState: (state: SetStateAction) => void }) { return (
    {groups.map((group) => ( ))}
) } function GroupsPage({ children, reload, }: PropsWithChildren<{ reload: () => void }>) { return ( <>

My groups

{children}
) }