import Head from "next/head"; import Link from "next/link"; import { useState, useEffect, useRef } from "react"; import { toast } from "sonner"; import { RiMailLine, RiLinkedinBoxLine, RiSearchLine, RiInboxLine, RiExternalLinkLine, RiSendPlaneLine, RiCloseLine, RiLoader4Line, } from "react-icons/ri"; import type { InboxReply } from "./api/inbox/index"; import type { EmailMessage } from "./api/inbox/thread"; function timeAgo(iso: string): string { const diff = Date.now() - new Date(iso).getTime(); const mins = Math.floor(diff / 60000); if (mins < 1) return "just now"; if (mins < 60) return `${mins}m`; const hours = Math.floor(mins / 60); if (hours < 24) return `${hours}h`; const days = Math.floor(hours / 24); if (days < 7) return `${days}d`; return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric" }); } function formatDate(iso: string): string { return new Date(iso).toLocaleString("en-US", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } const CHANNEL_TABS = [ { key: "all", label: "All" }, { key: "email", label: "Email" }, { key: "linkedin", label: "LinkedIn" }, ] as const; type ChannelFilter = typeof CHANNEL_TABS[number]["key"]; // ── Classifier verdict badges ─────────────────────────────────────────────── const VERDICT_BADGES: Record = { ooo_followup: { label: "OOO follow-up", cls: "bg-warning/15 text-warning" }, substitute: { label: "Substitute", cls: "bg-secondary/15 text-secondary" }, call_task: { label: "Call task", cls: "bg-success/15 text-success" }, human_reply: { label: "Human reply", cls: "bg-info/15 text-info" }, not_interested: { label: "Not interested", cls: "bg-error/15 text-error" }, cancelled: { label: "Cancelled", cls: "bg-base-300/60 text-base-content/50" }, }; function verdictBadge(reply: InboxReply): { label: string; cls: string } { if (reply.classification_error) return { label: "Failed", cls: "bg-error/15 text-error" }; if (reply.reply_id && !reply.classified_at) return { label: "Pending", cls: "bg-base-300/60 text-base-content/50" }; if (reply.reply_kind && VERDICT_BADGES[reply.reply_kind]) return VERDICT_BADGES[reply.reply_kind]; return { label: "—", cls: "bg-base-300/40 text-base-content/30" }; } // Stable key for filtering — matches the categories the badge renders. function verdictKey(reply: InboxReply): string { if (reply.classification_error) return "failed"; if (reply.reply_id && !reply.classified_at) return "pending"; if (reply.reply_kind && VERDICT_BADGES[reply.reply_kind]) return reply.reply_kind; return "none"; } const VERDICT_FILTERS: Array<{ key: string; label: string }> = [ { key: "all", label: "All verdicts" }, { key: "ooo_followup", label: "OOO follow-up" }, { key: "substitute", label: "Substitute" }, { key: "call_task", label: "Call task" }, { key: "human_reply", label: "Human reply" }, { key: "not_interested", label: "Not interested" }, { key: "pending", label: "Pending" }, { key: "failed", label: "Failed" }, { key: "none", label: "Unclassified" }, ]; // ── Reply Modal ─────────────────────────────────────────────────────────────── interface ReplyModalProps { reply: InboxReply; onClose: () => void; onActionDone: () => void; hasPremium: boolean; } function ReplyModal({ reply, onClose, onActionDone, hasPremium }: ReplyModalProps) { const [messages, setMessages] = useState([]); const [loadingThread, setLoadingThread] = useState(true); const [replyText, setReplyText] = useState(""); const [replySubject, setReplySubject] = useState(""); const [sending, setSending] = useState(false); const [acting, setActing] = useState<"reclassify" | "cancel" | null>(null); const threadEndRef = useRef(null); const verdict = verdictBadge(reply); const dispatch = (() => { if (!reply.dispatch_result_json) return null; try { return JSON.parse(reply.dispatch_result_json) as Record; } catch { return null; } })(); const scheduledFor = dispatch?.scheduled_for as string | undefined; async function handleReclassify() { if (!reply.reply_id) return; setActing("reclassify"); try { const r = await fetch(`/api/inbox/${reply.reply_id}/reclassify`, { method: "POST" }); const d = await r.json(); if (!r.ok) throw new Error(d.error ?? "Reclassify failed"); toast.success("Reclassified"); onActionDone(); onClose(); } catch (err) { toast.error(err instanceof Error ? err.message : "Reclassify failed"); } finally { setActing(null); } } async function handleCancelFollowup() { if (!reply.reply_id) return; setActing("cancel"); try { const r = await fetch(`/api/inbox/${reply.reply_id}/cancel-followup`, { method: "POST" }); const d = await r.json(); if (!r.ok) throw new Error(d.error ?? "Cancel failed"); toast.success("Follow-up cancelled"); onActionDone(); onClose(); } catch (err) { toast.error(err instanceof Error ? err.message : "Cancel failed"); } finally { setActing(null); } } useEffect(() => { if (!reply.email_account_id || !reply.email) { setLoadingThread(false); return; } setLoadingThread(true); const params = new URLSearchParams({ targetId: reply.id, emailAccountId: reply.email_account_id }); fetch(`/api/inbox/thread?${params}`) .then((r) => r.json()) .then((d) => { setMessages(d.messages ?? []); // Pre-fill reply subject from last message const last = (d.messages ?? []).at(-1) as EmailMessage | undefined; if (last) { setReplySubject(last.subject.startsWith("Re:") ? last.subject : `Re: ${last.subject}`); } }) .catch(() => toast.error("Failed to load thread")) .finally(() => setLoadingThread(false)); }, [reply.id, reply.email_account_id, reply.email]); useEffect(() => { threadEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); async function handleSend() { if (!replyText.trim() || !reply.email || !reply.email_account_id) return; setSending(true); try { const r = await fetch("/api/inbox/reply", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ emailAccountId: reply.email_account_id, to: reply.email, subject: replySubject, body: replyText, }), }); const d = await r.json(); if (!r.ok) throw new Error(d.error ?? "Send failed"); toast.success("Reply sent"); setReplyText(""); } catch (err) { toast.error(err instanceof Error ? err.message : "Failed to send"); } finally { setSending(false); } } const canReply = !!reply.email && !!reply.email_account_id; return (
{/* Backdrop */}
{/* Modal */}
{/* Header */}
{reply.full_name ?? reply.email ?? "Unknown"}
{reply.email && {reply.email}} {reply.email_account_from && ( via {reply.email_account_from} )}
{/* Classifier verdict + dispatch trail */} {reply.reply_id && (
{verdict.label} {reply.manually_edited === 1 && ( edited )} {reply.reply_summary && ( {reply.reply_summary} )}
{reply.classification_error && (
Classifier error: {reply.classification_error}
)} {dispatch && (
{scheduledFor &&
Follow-up scheduled for {formatDate(scheduledFor)}
} {dispatch.substitute_target_id ?
Substitute enrolled
: null} {dispatch.todo_id ?
Call task created{dispatch.phone_number ? ` · ${dispatch.phone_number}` : ""}
: null}
)}
{hasPremium && ( )} {scheduledFor && ( )}
)} {/* Thread */}
{loadingThread ? (
Loading thread…
) : messages.length === 0 ? (
{canReply ? "No messages found in thread" : "No email account linked to this reply"}
) : ( messages.map((msg, i) => { const isFromContact = msg.from.toLowerCase().includes((reply.email ?? "").toLowerCase()); return (
{msg.from} {formatDate(msg.date)}

{msg.text || "(no text content)"}

); }) )}
{/* Reply composer */} {canReply && (
setReplySubject(e.target.value)} placeholder="Subject" className="w-full bg-base-200 border border-base-300/50 rounded-lg px-3 py-1.5 text-sm text-base-content placeholder:text-base-content/30 focus:outline-none focus:border-primary/40" />