"use client"; import Link from "next/link"; import { useRouter, useSearchParams } from "next/navigation"; import { useMemo, useState } from "react"; import { fetchWithAnon } from "@/lib/client-anon"; type LinkItem = { id: string; url: string; label: string | null; createdByAnonId: string | null; createdByUserId: string | null; }; type TaskItem = { id: string; title: string; description: string | null; acceptance_criteria: string[]; effort: string | null; status: "OPEN" | "IN_PROGRESS" | "DONE"; claimedByAnonId: string | null; claimedByUserId: string | null; claimantNickname: string | null; claimantDisplayName: string | null; links: LinkItem[]; working_count: number; working: boolean; }; type CommentItem = { id: string; body: string; createdAt: string; author_label?: string; }; type SolutionItem = { id: string; ideaId: string; taskId: string | null; taskTitle: string | null; url: string; label: string | null; description: string | null; type: "APP_URL" | "GITHUB_REPO" | "OTHER"; createdAt: string; approvedAt: string | null; createdByDisplayName: string; voteScore: number; myVote: number; commentsCount: number; }; type IdeaPayload = { id: string; title: string; problemStatement: string; rawInputText: string; targetUsers: string | null; platform: string | null; constraints: string | null; tags: string[]; features: string[]; open_questions: string[]; upvotesCount: number; commentsCount: number; submitter_label: string; viewerAnonId: string; viewerUserId: string | null; isAuthenticated: boolean; canApproveSolutions: boolean; canDelete: boolean; merged_submission_count: number; idea_working_count: number; idea_working: boolean; tasks: TaskItem[]; comments: CommentItem[]; solutions: SolutionItem[]; }; type TaskUpdate = { id: string; status: "OPEN" | "IN_PROGRESS" | "DONE"; claimedByAnonId: string | null; claimedByUserId: string | null; claimantNickname?: string | null; claimantDisplayName?: string | null; links?: LinkItem[]; }; type SolutionCommentItem = { id: string; body: string; createdAt: string; author_label?: string; }; function formatStatus(status: TaskItem["status"]): string { if (status === "IN_PROGRESS") return "In Progress"; if (status === "DONE") return "Done"; return "Open"; } export function IdeaDetailClient({ initialIdea, isVoted, initialNickname, }: { initialIdea: IdeaPayload; isVoted: boolean; initialNickname: string; }) { const router = useRouter(); const searchParams = useSearchParams(); const [idea, setIdea] = useState(initialIdea); const [voted, setVoted] = useState(isVoted); const [nickname, setNickname] = useState(initialNickname); const [nickInput, setNickInput] = useState(initialNickname); const [commentInput, setCommentInput] = useState(""); const [solutions, setSolutions] = useState(initialIdea.solutions || []); const [solutionUrl, setSolutionUrl] = useState(""); const [solutionLabel, setSolutionLabel] = useState(""); const [solutionDescription, setSolutionDescription] = useState(""); const [solutionType, setSolutionType] = useState<"APP_URL" | "GITHUB_REPO" | "OTHER">("APP_URL"); const [solutionTaskId, setSolutionTaskId] = useState(""); const [solutionComments, setSolutionComments] = useState>({}); const [solutionCommentInput, setSolutionCommentInput] = useState>({}); const [actionError, setActionError] = useState(""); const mergeNotice = useMemo(() => { if (searchParams.get("merged") !== "1") return ""; return searchParams.get("reason") === "SUBSET" ? "Your submission was merged: it is a subset of this existing idea." : "Your submission was merged: this idea already exists, so discussion stays in one thread."; }, [searchParams]); function applyTaskUpdate(taskId: string, taskUpdate: TaskUpdate) { setIdea((prev) => ({ ...prev, tasks: prev.tasks.map((task) => { if (task.id !== taskId) return task; const nextClaimedByUser = taskUpdate.claimedByUserId; const nextClaimedByAnon = taskUpdate.claimedByAnonId; const nextClaimantDisplayName = taskUpdate.claimantDisplayName ?? taskUpdate.claimantNickname ?? (nextClaimedByAnon === prev.viewerAnonId ? nickname || "anon" : task.claimantDisplayName); return { ...task, status: taskUpdate.status, claimedByUserId: nextClaimedByUser, claimedByAnonId: nextClaimedByAnon, claimantNickname: nextClaimantDisplayName, claimantDisplayName: nextClaimantDisplayName, links: taskUpdate.links ?? task.links, }; }), })); } async function toggleVote() { const next = !voted; setVoted(next); setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? 1 : -1) })); const method = next ? "POST" : "DELETE"; const response = await fetchWithAnon(`/api/ideas/${idea.id}/upvote`, { method }); if (!response.ok) { setVoted(!next); setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? -1 : 1) })); } } async function toggleIdeaWorking() { if (!idea.isAuthenticated) return; const next = !idea.idea_working; const method = next ? "POST" : "DELETE"; const response = await fetchWithAnon(`/api/ideas/${idea.id}/work-vote`, { method }); if (!response.ok) return; const data = await response.json(); setIdea((prev) => ({ ...prev, idea_working: data.working, idea_working_count: data.working_count, })); } async function toggleTaskWorking(taskId: string, working: boolean) { if (!idea.isAuthenticated) return; const response = await fetchWithAnon(`/api/tasks/${taskId}/work-vote`, { method: working ? "DELETE" : "POST" }); if (!response.ok) return; const data = await response.json(); setIdea((prev) => ({ ...prev, tasks: prev.tasks.map((task) => task.id === taskId ? { ...task, working: data.working, working_count: data.working_count, } : task ), })); } async function saveNickname() { const response = await fetchWithAnon("/api/me/nickname", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nickname: nickInput }), }); if (response.ok) { setNickname(nickInput); setIdea((prev) => ({ ...prev, tasks: prev.tasks.map((task) => task.claimedByAnonId === prev.viewerAnonId ? { ...task, claimantNickname: nickInput || "anon", claimantDisplayName: nickInput || "anon" } : task ), })); } } async function addComment() { const body = commentInput.trim(); if (!body) return; const response = await fetchWithAnon(`/api/ideas/${idea.id}/comments`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ body }), }); if (!response.ok) return; const data = await response.json(); setIdea((prev) => ({ ...prev, commentsCount: prev.commentsCount + 1, comments: [data.comment, ...prev.comments], })); setCommentInput(""); } async function claim(taskId: string) { const response = await fetchWithAnon(`/api/tasks/${taskId}/claim`, { method: "POST" }); if (!response.ok) return; const data = await response.json(); applyTaskUpdate(taskId, data.task); } async function unclaim(taskId: string) { const response = await fetchWithAnon(`/api/tasks/${taskId}/unclaim`, { method: "POST" }); if (!response.ok) return; const data = await response.json(); applyTaskUpdate(taskId, data.task); } async function setStatus(taskId: string, status: TaskItem["status"]) { const response = await fetchWithAnon(`/api/tasks/${taskId}/status`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status }), }); if (!response.ok) return; const data = await response.json(); applyTaskUpdate(taskId, data.task); } async function addLink(taskId: string) { const url = window.prompt("Paste URL (repo/PR/demo)"); if (!url) return; const label = window.prompt("Label (optional)") || undefined; const response = await fetchWithAnon(`/api/tasks/${taskId}/links`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url, label }), }); if (!response.ok) return; const data = await response.json(); setIdea((prev) => ({ ...prev, tasks: prev.tasks.map((task) => (task.id === taskId ? { ...task, links: [...task.links, data.link] } : task)), })); } async function removeLink(taskId: string, linkId: string) { const response = await fetchWithAnon(`/api/task-links/${linkId}`, { method: "DELETE" }); if (!response.ok) return; setIdea((prev) => ({ ...prev, tasks: prev.tasks.map((task) => task.id === taskId ? { ...task, links: task.links.filter((link) => link.id !== linkId), } : task ), })); } async function submitSolution() { if (!idea.isAuthenticated) return; if (!solutionUrl.trim()) return; const response = await fetchWithAnon(`/api/ideas/${idea.id}/solutions`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ taskId: solutionTaskId || undefined, url: solutionUrl.trim(), label: solutionLabel.trim() || undefined, description: solutionDescription.trim() || undefined, type: solutionType, }), }); if (!response.ok) return; const data = await response.json(); setSolutions(data.items || []); setSolutionUrl(""); setSolutionLabel(""); setSolutionDescription(""); setSolutionTaskId(""); setSolutionType("APP_URL"); } async function setSolutionVote(solutionId: string, value: number) { const current = solutions.find((solution) => solution.id === solutionId)?.myVote || 0; const response = current === value ? await fetchWithAnon(`/api/solutions/${solutionId}/vote`, { method: "DELETE" }) : await fetchWithAnon(`/api/solutions/${solutionId}/vote`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ value }), }); if (!response.ok) return; const data = await response.json(); setSolutions((prev) => prev.map((solution) => solution.id === solutionId ? { ...solution, voteScore: data.score, myVote: data.myVote, } : solution ) ); } async function approveSolution(solutionId: string) { const response = await fetchWithAnon(`/api/solutions/${solutionId}/approve`, { method: "POST" }); if (!response.ok) return; const data = await response.json(); const approvedAt = data.solution?.approvedAt || new Date().toISOString(); setSolutions((prev) => prev.map((solution) => (solution.id === solutionId ? { ...solution, approvedAt } : solution))); } async function deleteIdea() { if (!idea.canDelete) return; const confirmed = window.confirm("Delete this post? This action cannot be undone."); if (!confirmed) return; setActionError(""); const response = await fetchWithAnon(`/api/ideas/${idea.id}`, { method: "DELETE" }); if (!response.ok) { const data = await response.json().catch(() => null); setActionError((data && typeof data.error === "string" ? data.error : "Failed to delete post.") || "Failed to delete post."); return; } router.push("/"); router.refresh(); } async function loadSolutionComments(solutionId: string) { const response = await fetchWithAnon(`/api/solutions/${solutionId}/comments`); if (!response.ok) return; const data = await response.json(); setSolutionComments((prev) => ({ ...prev, [solutionId]: data.items || [] })); } async function addSolutionComment(solutionId: string) { const body = (solutionCommentInput[solutionId] || "").trim(); if (!body) return; const response = await fetchWithAnon(`/api/solutions/${solutionId}/comments`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ body }), }); if (!response.ok) return; const data = await response.json(); setSolutionComments((prev) => ({ ...prev, [solutionId]: data.items || [] })); setSolutionCommentInput((prev) => ({ ...prev, [solutionId]: "" })); setSolutions((prev) => prev.map((solution) => (solution.id === solutionId ? { ...solution, commentsCount: (data.items || []).length } : solution)) ); } const grouped = useMemo(() => { return { open: idea.tasks.filter((task) => task.status === "OPEN"), inProgress: idea.tasks.filter((task) => task.status === "IN_PROGRESS"), done: idea.tasks.filter((task) => task.status === "DONE"), }; }, [idea.tasks]); return (

Generated Idea

{idea.title}

{idea.problemStatement}

{mergeNotice ? (

{mergeNotice}

) : null}
{idea.tags.map((tag) => ( {tag} ))} Submitter: {idea.submitter_label} Merged submissions: {idea.merged_submission_count}
{idea.commentsCount} comments {idea.tasks.length} tasks {idea.canDelete ? ( ) : null}
{actionError ?

{actionError}

: null} {!idea.isAuthenticated ? (

Sign in to submit solutions and add developer work votes.

) : null}

Original Submission

{idea.platform ? Platform: {idea.platform} : null} {idea.targetUsers ? Target: {idea.targetUsers} : null}
{idea.constraints ?

Constraints: {idea.constraints}

: null}

{idea.rawInputText}

Tasks

Claim tasks, attach implementation links, and vote to signal developer interest.

Solutions

Only developers who marked "Working on this" can submit solutions.

{solutions.length} submitted
View Submitted Solutions
{idea.isAuthenticated && idea.idea_working ? (
setSolutionUrl(e.target.value)} placeholder="Solution URL (app or repo)" /> setSolutionLabel(e.target.value)} placeholder="Label (optional)" />