"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; import { useLocale, useTranslations } from "next-intl"; import { toast } from "sonner"; import { ExternalLink, Loader2, MoreHorizontal, XCircle } from "lucide-react"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Skeleton } from "@/components/ui/skeleton"; import { SocialProviderIcon } from "@/components/social-provider-icon"; import { intlLocale } from "@/i18n/config"; import { timeAgo } from "@/lib/generations"; import { PROVIDER_LABELS, type SocialPost } from "@/lib/social"; function dayLabel(date: Date, todayLabel: string, tomorrowLabel: string, format: Intl.DateTimeFormat): string { const today = new Date(); const startOf = (value: Date) => new Date(value.getFullYear(), value.getMonth(), value.getDate()).getTime(); const days = Math.round((startOf(date) - startOf(today)) / 86_400_000); if (days === 0) return todayLabel; if (days === 1) return tomorrowLabel; return format.format(date); } function accountName(post: SocialPost): string { return ( post.account.display_name || (post.account.username ? `@${post.account.username.replace(/^@/, "")}` : null) || PROVIDER_LABELS[post.provider] ); } /** Every upcoming scheduled post across the user's tasks, soonest first. */ export function ScheduledPosts({ sectionHeadingClassName }: { sectionHeadingClassName: string }) { const t = useTranslations("social"); const locale = useLocale(); const dayFormat = useMemo( () => new Intl.DateTimeFormat(intlLocale(locale), { weekday: "long", month: "short", day: "numeric" }), [locale], ); const timeFormat = useMemo( () => new Intl.DateTimeFormat(intlLocale(locale), { hour: "numeric", minute: "2-digit" }), [locale], ); const [posts, setPosts] = useState(null); const [busyPostId, setBusyPostId] = useState(null); const load = useCallback(async () => { try { const response = await fetch("/api/social/posts?status=scheduled&limit=200", { cache: "no-store" }); if (!response.ok) return; const data = (await response.json()) as { posts?: SocialPost[] }; setPosts(data.posts ?? []); } catch { // Keep whatever was last loaded; the next poll retries. } }, []); // Posts leave this list as the worker picks them up, so refresh periodically. useEffect(() => { void load(); const interval = window.setInterval(() => void load(), 30_000); return () => window.clearInterval(interval); }, [load]); const groups = useMemo(() => { const sorted = [...(posts ?? [])] .filter((post) => post.scheduled_for) .sort((a, b) => new Date(a.scheduled_for!).getTime() - new Date(b.scheduled_for!).getTime()); const byDay = new Map(); for (const post of sorted) { const label = dayLabel(new Date(post.scheduled_for!), t("scheduled.today"), t("scheduled.tomorrow"), dayFormat); byDay.set(label, [...(byDay.get(label) ?? []), post]); } return [...byDay.entries()]; }, [posts, dayFormat, t]); const cancel = async (post: SocialPost) => { setBusyPostId(post.id); try { const response = await fetch(`/api/social/posts/${post.id}/cancel`, { method: "POST" }); if (response.ok) { toast.success(t("toasts.scheduleCancelled")); } else { const data = await response.json().catch(() => ({})); toast.error(typeof data?.detail === "string" ? data.detail : t("toasts.cancelFailed")); } await load(); } finally { setBusyPostId(null); } }; return (

{t("scheduled.heading")}

{posts === null ? ( ) : groups.length === 0 ? (

{t("scheduled.empty")}

) : (
{groups.map(([label, dayPosts]) => (

{label}

{dayPosts.map((post) => { const when = new Date(post.scheduled_for!); const title = post.hook_title || post.title || t("scheduled.untitled"); return (
{timeFormat.format(when)}
{post.task_id ? ( {title} ) : ( {title} )}

{accountName(post)} ยท {timeAgo(post.scheduled_for!, locale)}

{post.task_id && ( {t("scheduled.openClip")} )} cancel(post)}> {t("cancelPost")}
); })}
))}
)}
); }