'use client'; import { useState, useCallback } from 'react'; import { Loader2, Mail, Copy, Check } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, } from '@/components/ui/sheet'; import { useFeatureFlag } from '@/hooks/use-feature-flag'; import { apiFetch } from '@/lib/api/client'; // ─── Types ──────────────────────────────────────────────────────────────────── interface EmailDraftButtonProps { interestId: string; clientId: string; context?: 'follow_up' | 'introduction' | 'stage_update' | 'general'; additionalInstructions?: string; } interface DraftResult { subject: string; body: string; generatedAt: string; } // ─── Polling helper ─────────────────────────────────────────────────────────── const POLL_INTERVAL_MS = 1500; const POLL_MAX_ATTEMPTS = 20; // 30 s total async function pollDraftResult(jobId: string): Promise { for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) { await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); const res = await apiFetch<{ status: string; data?: DraftResult }>( `/api/v1/ai/email-draft/${jobId}`, ); if (res.status === 'complete' && res.data) { return res.data; } } throw new Error('Email draft generation timed out. Please try again.'); } // ─── Component ──────────────────────────────────────────────────────────────── export function EmailDraftButton({ interestId, clientId, context = 'follow_up', additionalInstructions, }: EmailDraftButtonProps) { const featureEnabled = useFeatureFlag('ai_email_drafts'); const [isLoading, setIsLoading] = useState(false); const [sheetOpen, setSheetOpen] = useState(false); const [draft, setDraft] = useState(null); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const handleGenerateDraft = useCallback(async () => { setIsLoading(true); setError(null); setDraft(null); try { const { jobId } = await apiFetch<{ jobId: string }>('/api/v1/ai/email-draft', { method: 'POST', body: { interestId, clientId, context, additionalInstructions }, }); const result = await pollDraftResult(jobId); setDraft(result); setSheetOpen(true); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to generate draft'); } finally { setIsLoading(false); } }, [interestId, clientId, context, additionalInstructions]); const handleCopy = useCallback(async () => { if (!draft) return; const text = `Subject: ${draft.subject}\n\n${draft.body}`; await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2000); }, [draft]); if (!featureEnabled) return null; return ( <> {error &&

{error}

} Generated Email Draft Review and edit the draft before sending. {draft && (
{/* Subject */}

{draft.subject}

{/* Body */}
                  {draft.body}
                
{/* Actions */}
)}
); }