"use client"; import React, { useEffect, useRef, useState } from "react"; import { loadInvestigation, saveInvestigation } from "@/lib/storage/investigation-storage"; import Link from "next/link"; export default function ReportPage() { const [existing, setExisting] = useState(null); const [hydrated, setHydrated] = useState(false); const [generationLoading, setGenerationLoading] = useState(false); const [generationError, setGenerationError] = useState(false); const generationAttempted = useRef(false); useEffect(() => { setExisting(loadInvestigation()); setHydrated(true); }, []); // First-generation: create report when none persists (v0.58) useEffect(() => { if (!hydrated) return; if (existing?.investigationReport) return; if (generationAttempted.current) return; generationAttempted.current = true; const situationGraph = existing?.situationGraph; const findings = existing?.findings ?? []; if (!situationGraph) { setGenerationError(true); return; } (async () => { setGenerationLoading(true); try { const res = await fetch("/api/cases/overview", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ situationGraph, findings }), }); if (!res.ok) { setGenerationError(true); return; } const data = await res.json(); if (data.success) { setExisting((prev) => { const updated = { ...prev, investigationReport: { understanding: data.understanding, plausibleInterpretations: data.plausibleInterpretations, hasPlausibleInterpretations: true } }; saveInvestigation(updated); return updated; }); } else { setGenerationError(true); } } catch { setGenerationError(true); } finally { setGenerationLoading(false); } })(); }, [hydrated, existing]); const report = existing?.investigationReport || null; const scenario = hydrated ? (existing?.scenario || "") : null; const paragraphs = (report?.understanding || "") .split("\n") .filter(Boolean); return (

Investigation Report

{/* Situation */} {scenario && (

Situation

{scenario}

)} {/* What we understand */} {report ? ( <> {paragraphs.length > 0 ? ( paragraphs.map((p, i) => (

What we understand

{p}

)) ) : (

What we understand

{report.understanding || ""}

)} {/* What remains plausible — conditional */} {report.hasPlausibleInterpretations && report.plausibleInterpretations ? (

What remains plausible

{report.plausibleInterpretations}

) : null} ) : ( /* Skeleton / loading state when no persisted report exists */ <>

What we understand

{generationLoading ? (
Generating report… {[0, 1, 2].map((i) => (
))}
) : generationError ? (

Report generation failed. You may try again from the Investigation page.

) : null}
)} {/* Back to investigation */}
Back to investigation
{/* Back to portfolio */}
Back to portfolio
); }