'use client' import { useState } from 'react' import { useTranslations, useLocale } from 'next-intl' import { useRouter } from '@/i18n/navigation' import type { VoteSiteStatus } from '@/lib/vote' const REFRESH_ICON = '/ns-themes/ns-ryu/ns-images/ns-icons/refresh.webp' export function VotePanel({ sites, canVote }: { sites: VoteSiteStatus[]; canVote: boolean }) { const t = useTranslations('Vote') const locale = useLocale() const router = useRouter() const [busyId, setBusyId] = useState(null) const [voted, setVoted] = useState>(new Set()) const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null) async function vote(site: VoteSiteStatus) { if (busyId !== null || voted.has(site.id)) return // Abre el sitio de votos en otra pestaƱa (como el original) y acredita al volver. window.open(site.url, '_blank', 'noopener,noreferrer') setBusyId(site.id) setMessage(null) try { const res = await fetch('/api/vote', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ url: site.url }), }) const d: { success?: boolean; error?: string; points?: number; siteName?: string; hours?: number; minutes?: number } = await res.json() if (d.success) { setVoted((v) => new Set(v).add(site.id)) setMessage({ ok: true, text: t('success', { site: d.siteName ?? site.name, points: d.points ?? 0 }) }) } else if (d.error === 'cooldown') { setMessage({ ok: false, text: t('cooldown', { hours: d.hours ?? 0, minutes: d.minutes ?? 0 }) }) setTimeout(() => setMessage(null), 5000) } else { setMessage({ ok: false, text: t(d.error === 'siteNotFound' ? 'siteNotFound' : 'genericError') }) setTimeout(() => setMessage(null), 5000) } } catch { setMessage({ ok: false, text: t('genericError') }) setTimeout(() => setMessage(null), 5000) } finally { setBusyId(null) } } if (sites.length === 0) return

{t('noSites')}

return ( <>

{t('noteLabel')} {t('note')}


{sites.map((s) => { const isVoted = voted.has(s.id) return (
{s.image_url && ( // eslint-disable-next-line @next/next/no-img-element {s.name} )}
{s.name}

{t('pv')}: {s.points}
{s.lastVoteAt ? t('lastVote', { date: new Date(s.lastVoteAt).toLocaleString(locale) }) : ''}

{!canVote ? ( {t('vote')} ) : isVoted || s.onCooldown ? ( ) : ( )}
) })}
{message && {message.text}}
{!canVote &&

{t('loginToVote')}

}
) }