"use client"; import { useCallback, useEffect, useState } from "react"; import { api, ApiError, errorText } from "@/lib/api"; import type { Question, UnitBalance } from "@/lib/types"; import { AnalysisLoading } from "./AnalysisLoading"; import { PackageChooser } from "./PackageCards"; import { RegenerateButton } from "./RegenerateButton"; import { RetryNotice } from "./RetryNotice"; import { Paragraphs } from "./Rich"; const MAX_CHARS = 600; const TEXTS = { natal: { title: "Kérdezz az elemzésedről", hint: "Mit jelent ez a te életedben, hogyan kapcsolódik két rész egymáshoz? A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban.", example: "Pl. Hogyan hat a Hold helyzete a kapcsolataimra?", }, synastry: { title: "Kérdezz a kapcsolatotokról", hint: "Hol erősítitek egymást, mire figyeljetek egy vitában, mit ad nektek a kapcsolat? A válasz a két képlet és az elemzés alapján készül, legfeljebb 250 szóban. A kérdéseket és a válaszokat mindketten látjátok.", example: "Pl. Hogyan kezeljük jobban a nézeteltéréseinket?", }, forecast: { title: "Kérdezz az előrejelzésedről", hint: "Mire figyelj egy időszakban, mit hozhat egy tranzit a munkádban vagy a kapcsolataidban? A válasz az év adatai és az előrejelzés alapján készül, legfeljebb 250 szóban.", example: "Pl. Mire figyeljek a nyári időszakban a munkámban?", }, }; const POLL_MS = 3000; const MAX_POLLS = 80; // 4 minutes /** * Questions about a finished analysis or forecast, and their answers. Each * question uses one from the user's questions (admins ask for free); the * answer comes from the model that wrote the analysis. */ export function AnalysisQuestions({ analysisId, left: initialLeft, isAdmin, canPay, about, }: { analysisId: string; left: number; isAdmin: boolean; canPay: boolean; /** What the analysis is about: the heading and the example question follow it. */ about: "natal" | "synastry" | "forecast"; }) { const [questions, setQuestions] = useState(null); const [left, setLeft] = useState(initialLeft); const [text, setText] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [buying, setBuying] = useState(false); const waiting = questions?.some((q) => q.status === "pending" || q.status === "running") ?? false; const fieldId = `question-${analysisId}`; useEffect(() => { api<{ questions: Question[] }>(`/analyses/${analysisId}/questions`) .then((d) => setQuestions(d.questions)) .catch(() => setQuestions([])); }, [analysisId]); const replace = useCallback( (next: Question) => setQuestions((all) => all?.map((q) => (q.id === next.id ? next : q)) ?? [next]), [], ); // Polls the open question until it is answered. const openId = questions?.find((q) => q.status === "pending" || q.status === "running")?.id; useEffect(() => { if (!openId) return; let polls = 0; let stopped = false; let timer: ReturnType | undefined; const tick = async () => { try { const next = await api(`/questions/${openId}`); if (stopped) return; replace(next); if (next.status === "done" || next.status === "failed") { if (next.status === "failed" && next.credits_charged > 0) setLeft((n) => n + next.credits_charged); return; } } catch { // try again on the next tick } if (++polls < MAX_POLLS) timer = setTimeout(tick, POLL_MS); }; timer = setTimeout(tick, POLL_MS); return () => { stopped = true; clearTimeout(timer); }; }, [openId, replace]); async function ask(e: React.FormEvent) { e.preventDefault(); setBusy(true); setError(null); try { const q = await api(`/analyses/${analysisId}/questions`, { body: { question: text } }); setQuestions((all) => [...(all ?? []), q]); setLeft((n) => n - q.credits_charged); setText(""); } catch (err) { if (err instanceof ApiError && err.status === 402) { setLeft(0); setBuying(true); } else { setError(errorText(err)); } } finally { setBusy(false); } } async function bought() { try { const me = await api<{ analyses_left: UnitBalance }>("/me"); setLeft(me.analyses_left.question); } catch { setLeft((n) => n + 5); } setBuying(false); } const canAsk = isAdmin || left > 0; return (

{TEXTS[about].title}

{TEXTS[about].hint}

{questions?.map((q) => (

Kérdésed {q.question}

{q.status === "done" && q.answer ? (
{isAdmin && ( url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} /> )}
) : q.status === "failed" ? (
{isAdmin && ( url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} /> )}

Erre többszöri próbálkozás után sem sikerült válaszolni {q.credits_charged > 0 ? ". A kérdést visszaadtuk, így ingyen újra felteheted" : ""}. Kérdezz újra egy kicsit később.

{isAdmin && q.error &&

Hiba: {q.error}

}
) : ( <> )}
))} {canAsk && !buying ? (