"use client"; // components/GroupReportActions.tsx // View PDF + Mail PDF buttons for the group report page header. import { useState } from "react"; interface Props { groupId: string; groupName: string; } export default function GroupReportActions({ groupId, groupName }: Props) { const [pdfLoading, setPdfLoading] = useState(false); const [mailLoading, setMailLoading] = useState(false); const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null); async function handleViewPdf() { setPdfLoading(true); setResult(null); try { const res = await fetch(`/api/group-report/${groupId}/pdf`); if (!res.ok) { const err = await res.json().catch(() => ({ error: "Unknown error" })); setResult({ ok: false, message: err.error }); return; } const blob = await res.blob(); const disposition = res.headers.get("Content-Disposition") ?? ""; const nameMatch = disposition.match(/filename="?([^"]+)"?/); const filename = nameMatch ? nameMatch[1] : `${groupName}_group_report.pdf`; const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); } catch (e) { setResult({ ok: false, message: e instanceof Error ? e.message : String(e) }); } finally { setPdfLoading(false); } } async function handleMailPdf() { const email = prompt("Enter email address for this group report:"); if (!email) return; if (!confirm(`Send group PDF for "${groupName}" to ${email}?`)) return; setMailLoading(true); setResult(null); try { const res = await fetch(`/api/group-report/${groupId}/email`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ to: email }), }); const data = await res.json(); if (res.ok && data.ok) { setResult({ ok: true, message: `Sent to ${data.sent_to}` }); } else { setResult({ ok: false, message: data.error ?? "Send failed" }); } } catch (e) { setResult({ ok: false, message: e instanceof Error ? e.message : String(e) }); } finally { setMailLoading(false); } } return (