"use client"; import { useTranslations } from "next-intl"; import { useState } from "react"; import { toast } from "sonner"; import { voteOnPoll } from "@/actions/polls"; import { useServerAction } from "@/hooks/use-server-action"; interface Question { id: number; question: string; type: string; options: string; } function parseOptions(options: string): string[] { return options .split("\n") .map((o) => o.trim()) .filter(Boolean); } export function PollVoteForm({ pollId, questions, }: { pollId: number; questions: Question[]; }) { const t = useTranslations("pages.polls"); const { run, isPending } = useServerAction(); const [answers, setAnswers] = useState>({}); const [multi, setMulti] = useState>({}); function setSingle(questionId: number, value: string) { setAnswers((prev) => ({ ...prev, [questionId]: value })); } function toggleMulti(questionId: number, option: string) { setMulti((prev) => { const current = prev[questionId] ?? []; const next = current.includes(option) ? current.filter((o) => o !== option) : [...current, option]; return { ...prev, [questionId]: next }; }); } function handleSubmit(e: React.FormEvent) { e.preventDefault(); const votes = questions.map((q) => { if (q.type === "multiple") { return { questionId: q.id, answer: (multi[q.id] ?? []).join("\n"), }; } return { questionId: q.id, answer: (answers[q.id] ?? "").trim(), }; }); if (votes.some((v) => !v.answer)) { toast.error(t("voteError")); return; } run(() => voteOnPoll({ pollId, votes }), { successMessage: t("voteSuccess"), errorMessage: t("voteError"), }); } return (
{questions.map((q) => { const options = parseOptions(q.options); return (
{q.question} {q.type === "text" ? (