"use client"; import { useState } from "react"; type DraftSection = { section: string; content: string; generatedAt: string; }; function humanize(section: string) { return section .toLowerCase() .split("_") .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(" "); } export default function DraftViewer({ tenderId, drafts, onRefresh, }: { tenderId: string; drafts: DraftSection[]; onRefresh: () => Promise; }) { const [generating, setGenerating] = useState(false); const [exporting, setExporting] = useState(false); const [exportUrl, setExportUrl] = useState(null); const [expanded, setExpanded] = useState(drafts[0]?.section ?? null); async function generateDrafts() { setGenerating(true); try { const res = await fetch(`/api/tenders/${tenderId}/drafts/batch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ tone: "FORMAL" }), }); const json = await res.json(); if (!res.ok || !json.ok) { throw new Error(json.error?.message || "Draft generation failed"); } const isQueued = res.status === 202 || Boolean(json.data?.queued); const maxPollAttempts = isQueued ? 30 : 3; for (let attempt = 0; attempt < maxPollAttempts; attempt += 1) { const count = await onRefresh(); if (count > 0 && (!isQueued || attempt > 0)) { break; } if (attempt < maxPollAttempts - 1) { await new Promise((resolve) => setTimeout(resolve, 1500)); } } } catch { // Error handled silently for now } finally { setGenerating(false); } } async function exportDocx() { setExporting(true); try { const res = await fetch(`/api/tenders/${tenderId}/drafts/export`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({}), }); const json = await res.json(); if (res.ok && json.ok && json.data?.downloadUrl) { setExportUrl(json.data.downloadUrl); } } catch { // Error handled silently } finally { setExporting(false); } } if (drafts.length === 0) { return (
✍️

No drafts yet

Generate AI-drafted proposal sections based on your compliance analysis.

); } return (
{drafts.length} sections
{exportUrl && (
📥 Download DOCX
)}
{drafts.map((draft) => (
setExpanded(expanded === draft.section ? null : draft.section)} > {humanize(draft.section)} {expanded === draft.section ? "▼" : "▶"}
{expanded === draft.section && (
{draft.content}
)}
))}
); }