- Backend: FastAPI app with all models, services, schemas, routes - Admin Panel: Next.js dashboard with all modules (CRM, POS, repairs, warranties, billing, notifications, etc.) - Ecommerce: storefront (submodule) + product catalog - AI Agents: .agents/ skill library for Antigravity IDE - Docs: architecture, billing, notification gateway markdown - Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
711 lines
33 KiB
TypeScript
711 lines
33 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState, useRef, useCallback, Suspense } from 'react';
|
|
import { useSearchParams, useRouter } from 'next/navigation';
|
|
import {
|
|
openwaService,
|
|
type OWASession,
|
|
type OWAChat,
|
|
type OWAMessage,
|
|
type OWAContact,
|
|
} from '@/services/api/openwaService';
|
|
import {
|
|
MessageSquare,
|
|
Send,
|
|
Search,
|
|
CheckCheck,
|
|
Paperclip,
|
|
Phone,
|
|
RefreshCw,
|
|
Zap,
|
|
ArrowRight,
|
|
QrCode,
|
|
ShieldCheck,
|
|
Users,
|
|
Wifi,
|
|
WifiOff,
|
|
Loader2,
|
|
User,
|
|
} from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
|
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
|
|
function formatTimestamp(ts: number | string): string {
|
|
if (!ts) return '';
|
|
const date = typeof ts === 'number' ? new Date(ts * 1000) : new Date(ts);
|
|
if (isNaN(date.getTime())) return '';
|
|
const now = new Date();
|
|
const diffMs = now.getTime() - date.getTime();
|
|
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
|
if (diffDays === 0) return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
if (diffDays === 1) return 'Yesterday';
|
|
if (diffDays < 7) return date.toLocaleDateString([], { weekday: 'short' });
|
|
return date.toLocaleDateString([], { day: '2-digit', month: 'short' });
|
|
}
|
|
|
|
function formatMessageTime(ts: number | string): string {
|
|
if (!ts) return '';
|
|
const date = typeof ts === 'number' ? new Date(ts * 1000) : new Date(ts);
|
|
if (isNaN(date.getTime())) return '';
|
|
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
|
|
function getNameFromChat(chat: OWAChat, contacts: OWAContact[]): string {
|
|
if (chat.name && chat.name !== chat.id && !/^\d+$/.test(chat.name)) return chat.name;
|
|
// Try to match from contacts by id or number
|
|
const phoneRaw = chat.id.replace(/@.*/, '');
|
|
const contact = contacts.find((c) => c.number === phoneRaw || c.id === chat.id);
|
|
if (contact?.name) return contact.name;
|
|
// Format phone
|
|
if (phoneRaw.length >= 10) {
|
|
return `+${phoneRaw.slice(0, 2)} ${phoneRaw.slice(2, 7)} ${phoneRaw.slice(7)}`;
|
|
}
|
|
return chat.id.split('@')[0];
|
|
}
|
|
|
|
function getInitial(name: string): string {
|
|
return (name || '?').charAt(0).toUpperCase();
|
|
}
|
|
|
|
// ─── Active conversation state ────────────────────────────────────────────────
|
|
|
|
interface LocalMessage {
|
|
id: string;
|
|
body: string;
|
|
direction: 'incoming' | 'outgoing';
|
|
timestamp: number;
|
|
type: string;
|
|
status?: string;
|
|
}
|
|
|
|
// ─── Main component ──────────────────────────────────────────────────────────
|
|
|
|
function WhatsAppWebContent() {
|
|
const searchParams = useSearchParams();
|
|
const router = useRouter();
|
|
|
|
const paramPhone = searchParams.get('phone') || '';
|
|
const paramName = searchParams.get('name') || '';
|
|
|
|
// Session
|
|
const [session, setSession] = useState<OWASession | null>(null);
|
|
const [sessionLoading, setSessionLoading] = useState(true);
|
|
|
|
// Chats
|
|
const [chats, setChats] = useState<OWAChat[]>([]);
|
|
const [contacts, setContacts] = useState<OWAContact[]>([]);
|
|
const [chatsLoading, setChatsLoading] = useState(false);
|
|
|
|
// Active chat
|
|
const [activeChatId, setActiveChatId] = useState<string>('');
|
|
const [messages, setMessages] = useState<LocalMessage[]>([]);
|
|
const [messagesLoading, setMessagesLoading] = useState(false);
|
|
|
|
// UI
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const [activeTab, setActiveTab] = useState<'ALL' | 'UNREAD' | 'GROUPS'>('ALL');
|
|
const [inputText, setInputText] = useState('');
|
|
const [isSending, setIsSending] = useState(false);
|
|
|
|
// Confirm-before-send state
|
|
const [pendingMessage, setPendingMessage] = useState<{ text: string; chatId: string; recipientName: string; recipientPhone: string } | null>(null);
|
|
|
|
const messagesEndRef = useRef<HTMLDivElement>(null);
|
|
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
|
|
// ── Load session ────────────────────────────────────────────────────────────
|
|
|
|
const loadSession = useCallback(async () => {
|
|
try {
|
|
setSessionLoading(true);
|
|
const sess = await openwaService.getReadySession();
|
|
setSession(sess);
|
|
return sess;
|
|
} catch {
|
|
setSession(null);
|
|
return null;
|
|
} finally {
|
|
setSessionLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
// ── Load chats + contacts ────────────────────────────────────────────────────
|
|
|
|
const loadChats = useCallback(async (sessionId: string) => {
|
|
try {
|
|
setChatsLoading(true);
|
|
const [chatList, contactList] = await Promise.all([
|
|
openwaService.getChats(sessionId, 100),
|
|
openwaService.getContacts(sessionId, 200).catch(() => [] as OWAContact[]),
|
|
]);
|
|
setContacts(contactList);
|
|
// Sort chats: pinned first, then by timestamp desc
|
|
const sorted = [...chatList].sort((a, b) => {
|
|
if (a.pinned && !b.pinned) return -1;
|
|
if (!a.pinned && b.pinned) return 1;
|
|
return b.timestamp - a.timestamp;
|
|
});
|
|
setChats(sorted);
|
|
|
|
// Auto-select: if URL param phone, find that chat or construct target ID
|
|
if (paramPhone) {
|
|
const cleanDigits = paramPhone.replace(/\D/g, '');
|
|
const fullPhone = cleanDigits.length === 10 ? `91${cleanDigits}` : cleanDigits;
|
|
const targetId = fullPhone.includes('@') ? fullPhone : `${fullPhone}@c.us`;
|
|
const found = sorted.find((c) => c.id.includes(cleanDigits));
|
|
if (found) {
|
|
setActiveChatId(found.id);
|
|
} else {
|
|
setActiveChatId(targetId);
|
|
}
|
|
} else if (!activeChatId && sorted.length > 0) {
|
|
setActiveChatId(sorted[0].id);
|
|
}
|
|
} catch (err) {
|
|
console.error('Failed to load chats', err);
|
|
toast.error('Failed to load WhatsApp chats');
|
|
} finally {
|
|
setChatsLoading(false);
|
|
}
|
|
}, [paramPhone, activeChatId]);
|
|
|
|
// ── Load messages for active chat ────────────────────────────────────────────
|
|
|
|
const loadMessages = useCallback(async (sessionId: string, chatId: string) => {
|
|
if (!chatId) return;
|
|
try {
|
|
setMessagesLoading(true);
|
|
const res = await openwaService.getMessages(sessionId, { chatId, limit: 50 });
|
|
const sorted = [...(res.messages || [])].sort((a, b) => a.timestamp - b.timestamp);
|
|
setMessages(
|
|
sorted.map((m) => ({
|
|
id: m.id,
|
|
body: m.body || (m.type !== 'text' ? `[${m.type}]` : ''),
|
|
direction: m.direction,
|
|
timestamp: m.timestamp,
|
|
type: m.type,
|
|
status: m.status,
|
|
}))
|
|
);
|
|
} catch {
|
|
setMessages([]);
|
|
} finally {
|
|
setMessagesLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
// ── Init ──────────────────────────────────────────────────────────────────
|
|
|
|
useEffect(() => {
|
|
(async () => {
|
|
const sess = await loadSession();
|
|
if (sess?.id) {
|
|
await loadChats(sess.id);
|
|
}
|
|
})();
|
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
|
|
|
// ── Load messages on chat switch ─────────────────────────────────────────────
|
|
|
|
useEffect(() => {
|
|
if (session?.id && activeChatId) {
|
|
loadMessages(session.id, activeChatId);
|
|
}
|
|
}, [session?.id, activeChatId, loadMessages]);
|
|
|
|
// ── Scroll to bottom ──────────────────────────────────────────────────────────
|
|
|
|
useEffect(() => {
|
|
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
}, [messages]);
|
|
|
|
// ── Polling (refresh messages every 10s) ────────────────────────────────────
|
|
|
|
useEffect(() => {
|
|
if (pollingRef.current) clearInterval(pollingRef.current);
|
|
if (session?.id && activeChatId) {
|
|
pollingRef.current = setInterval(() => {
|
|
loadMessages(session.id, activeChatId);
|
|
}, 10000);
|
|
}
|
|
return () => {
|
|
if (pollingRef.current) clearInterval(pollingRef.current);
|
|
};
|
|
}, [session?.id, activeChatId, loadMessages]);
|
|
|
|
// ── Send message ──────────────────────────────────────────────────────────────
|
|
|
|
/** Stage a message for confirmation — does NOT send yet */
|
|
const handleSend = (textOverride?: string) => {
|
|
const text = (textOverride || inputText).trim();
|
|
if (!text || !session?.id || !activeChatId) return;
|
|
const activeChat = chats.find((c) => c.id === activeChatId);
|
|
const recipientName = activeChat ? getNameFromChat(activeChat, contacts) : activeChatId;
|
|
const recipientPhone = activeChatId.replace(/@.*/, '');
|
|
// Show confirmation dialog
|
|
setPendingMessage({ text, chatId: activeChatId, recipientName, recipientPhone });
|
|
};
|
|
|
|
/** Actually send after user confirmed */
|
|
const confirmSend = async () => {
|
|
if (!pendingMessage || !session?.id) return;
|
|
const { text, chatId } = pendingMessage;
|
|
setPendingMessage(null);
|
|
try {
|
|
setIsSending(true);
|
|
await openwaService.sendText(session.id, chatId, text);
|
|
// Optimistic update
|
|
setMessages((prev) => [
|
|
...prev,
|
|
{
|
|
id: `local-${Date.now()}`,
|
|
body: text,
|
|
direction: 'outgoing',
|
|
timestamp: Math.floor(Date.now() / 1000),
|
|
type: 'text',
|
|
status: 'sent',
|
|
},
|
|
]);
|
|
setInputText('');
|
|
toast.success('Message sent via OpenWA!');
|
|
// Refresh messages after 2s
|
|
setTimeout(() => {
|
|
if (session?.id && chatId) loadMessages(session.id, chatId);
|
|
}, 2000);
|
|
} catch (err: unknown) {
|
|
const msg = err instanceof Error ? err.message : 'Failed to send';
|
|
toast.error(msg);
|
|
} finally {
|
|
setIsSending(false);
|
|
}
|
|
};
|
|
|
|
const handleTemplate = (type: 'QUOTE' | 'REPAIR' | 'PICKUP') => {
|
|
const activeChat = chats.find((c) => c.id === activeChatId);
|
|
const name = activeChat ? getNameFromChat(activeChat, contacts) : 'Customer';
|
|
const templates: Record<string, string> = {
|
|
QUOTE: `Hello ${name},\n\nHere is your official iFixKart quotation for repair services. We offer a 6-Month IMEI Warranty & Free Doorstep Return.\n\nThank you for choosing iFixKart! 🔧`,
|
|
REPAIR: `Hello ${name},\n\nYour device diagnosis is complete! ✅ All OEM parts passed our 24-point quality inspection. We are proceeding with the repair now.`,
|
|
PICKUP: `Hello ${name},\n\n🎉 Great news! Your repair is COMPLETED. Your device is ready for doorstep delivery or counter pickup at your convenience.`,
|
|
};
|
|
handleSend(templates[type]);
|
|
};
|
|
|
|
// ── Filter chats ──────────────────────────────────────────────────────────────
|
|
|
|
const filteredChats = chats.filter((c) => {
|
|
const name = getNameFromChat(c, contacts).toLowerCase();
|
|
const matchesSearch = name.includes(searchQuery.toLowerCase()) || c.id.includes(searchQuery);
|
|
if (activeTab === 'UNREAD') return matchesSearch && c.unreadCount > 0;
|
|
if (activeTab === 'GROUPS') return matchesSearch && c.isGroup;
|
|
return matchesSearch;
|
|
});
|
|
|
|
const activeChat = chats.find((c) => c.id === activeChatId);
|
|
const activeName = activeChat ? getNameFromChat(activeChat, contacts) : '';
|
|
|
|
const isConnected = session?.status === 'ready';
|
|
|
|
// ── Render ────────────────────────────────────────────────────────────────────
|
|
|
|
return (
|
|
<>
|
|
<div className="h-[calc(100vh-4rem)] p-4 flex flex-col space-y-3 max-w-[1600px] mx-auto">
|
|
|
|
{/* ── Top Status Bar ── */}
|
|
<div className="bg-card border border-border rounded-xl px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 shadow-xs shrink-0">
|
|
<div className="flex items-center gap-3">
|
|
<div className={`p-2 rounded-lg ${isConnected ? 'bg-emerald-500/10 text-emerald-600' : 'bg-amber-500/10 text-amber-600'}`}>
|
|
<MessageSquare className="w-5 h-5" />
|
|
</div>
|
|
<div>
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<h1 className="font-bold text-base text-foreground">OpenWA Web WhatsApp Suite</h1>
|
|
{sessionLoading ? (
|
|
<span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-muted text-muted-foreground flex items-center gap-1">
|
|
<Loader2 className="w-3 h-3 animate-spin" /> Connecting…
|
|
</span>
|
|
) : isConnected ? (
|
|
<span className="px-2.5 py-0.5 rounded-full text-[10px] font-extrabold uppercase bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 flex items-center gap-1">
|
|
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-ping" />
|
|
LIVE — {session?.pushName || session?.phone || 'Connected'}
|
|
</span>
|
|
) : (
|
|
<span className="px-2.5 py-0.5 rounded-full text-[10px] font-extrabold uppercase bg-amber-500/10 text-amber-600 border border-amber-500/20 flex items-center gap-1">
|
|
<WifiOff className="w-3 h-3" /> DISCONNECTED
|
|
</span>
|
|
)}
|
|
</div>
|
|
<p className="text-xs text-muted-foreground">
|
|
{isConnected
|
|
? `Session: ${session?.name} · Phone: ${session?.phone} · Engine: Baileys`
|
|
: 'OpenWA Gateway (Port 8088) — session not ready'}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
onClick={async () => {
|
|
const sess = await loadSession();
|
|
if (sess?.id) loadChats(sess.id);
|
|
}}
|
|
disabled={sessionLoading || chatsLoading}
|
|
className="p-2 rounded-lg border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors cursor-pointer"
|
|
title="Refresh"
|
|
>
|
|
<RefreshCw className={`w-4 h-4 ${sessionLoading || chatsLoading ? 'animate-spin' : ''}`} />
|
|
</button>
|
|
|
|
<button
|
|
onClick={() => router.push('/notifications-gateway')}
|
|
className="inline-flex items-center gap-1.5 bg-primary text-white hover:bg-primary/90 px-3.5 py-2 rounded-lg text-xs font-bold transition-all shadow-xs cursor-pointer"
|
|
>
|
|
<QrCode className="w-4 h-4" />
|
|
<span>Gateway Dashboard</span>
|
|
<ArrowRight className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* ── Main Pane ── */}
|
|
<div className="flex-1 bg-card border border-border rounded-xl shadow-md overflow-hidden flex flex-col md:flex-row min-h-0">
|
|
|
|
{/* LEFT: Chat List */}
|
|
<div className="w-full md:w-80 lg:w-96 border-r border-border flex flex-col bg-muted/20 shrink-0">
|
|
{/* Search */}
|
|
<div className="p-3 border-b border-border space-y-2.5">
|
|
<div className="relative">
|
|
<Search className="w-4 h-4 absolute left-3 top-2.5 text-muted-foreground" />
|
|
<input
|
|
type="text"
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
placeholder="Search chats…"
|
|
className="w-full bg-background border border-border rounded-lg pl-9 pr-3 py-1.5 text-xs text-foreground focus:outline-hidden"
|
|
/>
|
|
</div>
|
|
{/* Tabs */}
|
|
<div className="grid grid-cols-3 gap-1 bg-muted p-1 rounded-lg text-[10px] font-bold text-center">
|
|
{(['ALL', 'UNREAD', 'GROUPS'] as const).map((tab) => (
|
|
<button
|
|
key={tab}
|
|
onClick={() => setActiveTab(tab)}
|
|
className={`py-1 rounded-md transition-all ${activeTab === tab ? 'bg-card text-primary shadow-2xs' : 'text-muted-foreground'}`}
|
|
>
|
|
{tab === 'ALL' ? 'All' : tab === 'UNREAD' ? 'Unread' : 'Groups'}
|
|
</button>
|
|
))}
|
|
</div>
|
|
<div className="text-[10px] text-muted-foreground px-1">
|
|
{chatsLoading ? (
|
|
<span className="flex items-center gap-1"><Loader2 className="w-3 h-3 animate-spin" /> Loading chats…</span>
|
|
) : (
|
|
<span className="flex items-center gap-1"><Users className="w-3 h-3" /> {filteredChats.length} chats</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Chat Items */}
|
|
<div className="flex-1 overflow-y-auto divide-y divide-border">
|
|
{!isConnected && !sessionLoading && (
|
|
<div className="p-6 text-center text-muted-foreground text-xs space-y-2">
|
|
<WifiOff className="w-8 h-8 mx-auto text-amber-500" />
|
|
<p className="font-semibold">Session Not Connected</p>
|
|
<p>Go to Gateway Dashboard to pair your WhatsApp.</p>
|
|
<button
|
|
onClick={() => router.push('/notifications-gateway')}
|
|
className="mt-2 px-3 py-1.5 bg-primary text-white rounded-lg text-xs font-bold cursor-pointer"
|
|
>
|
|
Open Gateway
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
{filteredChats.map((c) => {
|
|
const name = getNameFromChat(c, contacts);
|
|
const isActive = c.id === activeChatId;
|
|
const timeStr = c.timestamp ? formatTimestamp(c.timestamp) : '';
|
|
|
|
return (
|
|
<button
|
|
key={c.id}
|
|
onClick={() => setActiveChatId(c.id)}
|
|
className={`w-full p-3 text-left flex items-start gap-3 transition-colors cursor-pointer ${isActive ? 'bg-primary/10 border-l-4 border-l-primary' : 'hover:bg-muted/40'
|
|
}`}
|
|
>
|
|
<div className="w-10 h-10 rounded-full bg-primary/20 text-primary font-bold flex items-center justify-center text-sm shrink-0">
|
|
{getInitial(name)}
|
|
</div>
|
|
<div className="flex-1 min-w-0">
|
|
<div className="flex items-center justify-between gap-1">
|
|
<span className="font-semibold text-xs text-foreground truncate">{name}</span>
|
|
<span className="text-[10px] text-muted-foreground shrink-0">{timeStr}</span>
|
|
</div>
|
|
<p className="text-[11px] text-muted-foreground truncate mt-0.5">
|
|
{c.lastMessage || (c.kind === 'channel' ? 'Channel' : c.isGroup ? 'Group' : 'Tap to open chat')}
|
|
</p>
|
|
<div className="flex items-center justify-between gap-1 mt-1">
|
|
<span className="text-[9px] font-bold text-muted-foreground truncate">
|
|
{c.id.replace(/@.*/, '')}
|
|
</span>
|
|
{c.unreadCount > 0 && (
|
|
<span className="px-1.5 rounded-full text-[9px] font-bold bg-emerald-500 text-white shrink-0">
|
|
{c.unreadCount}
|
|
</span>
|
|
)}
|
|
{c.pinned && (
|
|
<span className="text-[9px] text-amber-500 shrink-0">📌</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</button>
|
|
);
|
|
})}
|
|
|
|
{!chatsLoading && isConnected && filteredChats.length === 0 && (
|
|
<div className="p-6 text-center text-muted-foreground text-xs">
|
|
<MessageSquare className="w-8 h-8 mx-auto mb-2 opacity-30" />
|
|
<p>No chats found</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* RIGHT: Conversation */}
|
|
{activeChatId && activeChat ? (
|
|
<div className="flex-1 flex flex-col bg-background min-w-0">
|
|
{/* Header */}
|
|
<div className="p-3 border-b border-border bg-card flex items-center justify-between gap-3 shrink-0">
|
|
<div className="flex items-center gap-3">
|
|
<div className="w-9 h-9 rounded-full bg-primary/20 text-primary font-bold flex items-center justify-center text-sm">
|
|
{getInitial(activeName)}
|
|
</div>
|
|
<div>
|
|
<h2 className="font-bold text-sm text-foreground">{activeName}</h2>
|
|
<p className="text-[11px] text-muted-foreground flex items-center gap-1 font-mono">
|
|
<Phone className="w-3 h-3 text-emerald-600" />
|
|
{activeChatId.replace(/@.*/, '')}
|
|
{activeChat.isGroup && <span className="ml-1 text-blue-500">(Group)</span>}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{isConnected && (
|
|
<span className="text-[10px] text-emerald-600 font-bold bg-emerald-500/10 px-2.5 py-1 rounded-full border border-emerald-500/20 flex items-center gap-1">
|
|
<ShieldCheck className="w-3.5 h-3.5" />
|
|
OpenWA Ready
|
|
</span>
|
|
)}
|
|
<button
|
|
onClick={() => session?.id && loadMessages(session.id, activeChatId)}
|
|
className="p-1.5 rounded-lg border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors cursor-pointer"
|
|
title="Refresh messages"
|
|
>
|
|
<RefreshCw className={`w-3.5 h-3.5 ${messagesLoading ? 'animate-spin' : ''}`} />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Quick Templates */}
|
|
<div className="px-3 py-2 bg-muted/30 border-b border-border flex items-center gap-2 overflow-x-auto text-xs shrink-0">
|
|
<span className="text-[10px] font-bold text-muted-foreground uppercase flex items-center gap-1 shrink-0">
|
|
<Zap className="w-3 h-3 text-amber-500" /> Quick Templates:
|
|
</span>
|
|
<button
|
|
onClick={() => handleTemplate('QUOTE')}
|
|
disabled={!isConnected || isSending}
|
|
className="px-2.5 py-1 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 hover:bg-blue-500/20 font-semibold text-[11px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-40"
|
|
>
|
|
⚡ Send Quotation
|
|
</button>
|
|
<button
|
|
onClick={() => handleTemplate('REPAIR')}
|
|
disabled={!isConnected || isSending}
|
|
className="px-2.5 py-1 rounded-full bg-purple-500/10 text-purple-600 dark:text-purple-400 hover:bg-purple-500/20 font-semibold text-[11px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-40"
|
|
>
|
|
🔧 Repair Update
|
|
</button>
|
|
<button
|
|
onClick={() => handleTemplate('PICKUP')}
|
|
disabled={!isConnected || isSending}
|
|
className="px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 hover:bg-emerald-500/20 font-semibold text-[11px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-40"
|
|
>
|
|
📅 Pickup Ready
|
|
</button>
|
|
</div>
|
|
|
|
{/* Messages */}
|
|
<div className="flex-1 p-4 overflow-y-auto space-y-3 bg-muted/10">
|
|
{messagesLoading && (
|
|
<div className="flex justify-center py-8">
|
|
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
|
</div>
|
|
)}
|
|
|
|
{!messagesLoading && messages.length === 0 && (
|
|
<div className="flex flex-col items-center justify-center h-full text-center text-muted-foreground text-xs space-y-2 opacity-60">
|
|
<MessageSquare className="w-10 h-10" />
|
|
<p>No messages stored yet for this chat.</p>
|
|
<p className="text-[10px]">Messages will appear here as they sync from WhatsApp.</p>
|
|
</div>
|
|
)}
|
|
|
|
{messages.map((m) => {
|
|
const isOut = m.direction === 'outgoing';
|
|
return (
|
|
<div key={m.id} className={`flex flex-col ${isOut ? 'items-end' : 'items-start'}`}>
|
|
<div
|
|
className={`max-w-[80%] rounded-2xl px-4 py-2.5 shadow-2xs text-xs space-y-1 ${isOut
|
|
? 'bg-emerald-600 text-white rounded-br-xs'
|
|
: 'bg-card border border-border text-foreground rounded-bl-xs'
|
|
}`}
|
|
>
|
|
<p className="whitespace-pre-wrap leading-relaxed">
|
|
{m.body || <span className="italic opacity-60">[{m.type}]</span>}
|
|
</p>
|
|
<div className={`flex items-center justify-end gap-1 text-[9px] ${isOut ? 'text-emerald-100' : 'text-muted-foreground'}`}>
|
|
<span>{formatMessageTime(m.timestamp)}</span>
|
|
{isOut && <CheckCheck className="w-3 h-3 text-emerald-200" />}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
<div ref={messagesEndRef} />
|
|
</div>
|
|
|
|
{/* Input */}
|
|
<div className="p-3 bg-card border-t border-border flex items-center gap-2 shrink-0">
|
|
<button
|
|
type="button"
|
|
onClick={() => toast.info('File attachment coming soon!')}
|
|
className="p-2 text-muted-foreground hover:text-foreground rounded-lg hover:bg-muted transition-colors cursor-pointer"
|
|
>
|
|
<Paperclip className="w-4 h-4" />
|
|
</button>
|
|
|
|
<input
|
|
type="text"
|
|
value={inputText}
|
|
onChange={(e) => setInputText(e.target.value)}
|
|
onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleSend()}
|
|
placeholder={isConnected ? 'Type a WhatsApp message…' : 'Connect WhatsApp to send messages'}
|
|
disabled={!isConnected}
|
|
className="flex-1 bg-muted border border-border rounded-xl px-3.5 py-2 text-xs text-foreground focus:outline-hidden font-medium disabled:opacity-50"
|
|
/>
|
|
|
|
<button
|
|
type="button"
|
|
disabled={isSending || !inputText.trim() || !isConnected}
|
|
onClick={() => handleSend()}
|
|
className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold px-4 py-2 rounded-xl text-xs flex items-center gap-1.5 shadow-sm transition-all cursor-pointer disabled:opacity-50"
|
|
>
|
|
{isSending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
|
|
<span>Send</span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-muted-foreground space-y-3">
|
|
{isConnected ? (
|
|
<>
|
|
<MessageSquare className="w-12 h-12 opacity-20" />
|
|
<p className="font-semibold text-sm">Select a chat to start messaging</p>
|
|
<p className="text-xs opacity-60">Real-time WhatsApp via OpenWA Baileys engine</p>
|
|
</>
|
|
) : sessionLoading ? (
|
|
<>
|
|
<Loader2 className="w-10 h-10 animate-spin opacity-30" />
|
|
<p className="text-sm">Connecting to OpenWA…</p>
|
|
</>
|
|
) : (
|
|
<>
|
|
<WifiOff className="w-12 h-12 text-amber-500 opacity-60" />
|
|
<p className="font-semibold text-sm">WhatsApp Not Connected</p>
|
|
<p className="text-xs opacity-60">Pair your device from the Gateway Dashboard</p>
|
|
<button
|
|
onClick={() => router.push('/notifications-gateway')}
|
|
className="mt-2 px-4 py-2 bg-primary text-white rounded-lg text-xs font-bold cursor-pointer"
|
|
>
|
|
Open Gateway Dashboard
|
|
</button>
|
|
</>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* ── Confirm-before-Send Modal ── */}
|
|
{pendingMessage && (
|
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
|
<div className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-md p-6 space-y-4">
|
|
<div className="flex items-start gap-3">
|
|
<div className="p-2.5 bg-amber-500/10 rounded-xl text-amber-500 shrink-0">
|
|
<Send className="w-5 h-5" />
|
|
</div>
|
|
<div>
|
|
<h3 className="font-bold text-base text-foreground">Confirm Send Message</h3>
|
|
<p className="text-xs text-muted-foreground mt-0.5">Double-check recipient before dispatching via WhatsApp</p>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Recipient */}
|
|
<div className="bg-muted/40 border border-border rounded-xl p-3 space-y-1">
|
|
<p className="text-[10px] font-bold text-muted-foreground uppercase">Sending To</p>
|
|
<div className="flex items-center gap-2">
|
|
<div className="w-8 h-8 rounded-full bg-primary/20 text-primary font-bold text-sm flex items-center justify-center shrink-0">
|
|
{pendingMessage.recipientName.charAt(0).toUpperCase()}
|
|
</div>
|
|
<div>
|
|
<p className="text-sm font-bold text-foreground">{pendingMessage.recipientName}</p>
|
|
<p className="text-xs font-mono text-muted-foreground">+{pendingMessage.recipientPhone}</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Message preview */}
|
|
<div className="bg-emerald-600/10 border border-emerald-500/20 rounded-xl p-3 space-y-1">
|
|
<p className="text-[10px] font-bold text-emerald-600 uppercase">Message Preview</p>
|
|
<p className="text-xs text-foreground whitespace-pre-wrap leading-relaxed line-clamp-6">{pendingMessage.text}</p>
|
|
</div>
|
|
|
|
{/* Actions */}
|
|
<div className="flex gap-2 pt-1">
|
|
<button
|
|
onClick={() => setPendingMessage(null)}
|
|
className="flex-1 py-2.5 rounded-xl border border-border text-sm font-bold text-muted-foreground hover:bg-muted transition-colors cursor-pointer"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
onClick={confirmSend}
|
|
disabled={isSending}
|
|
className="flex-1 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold flex items-center justify-center gap-2 transition-all cursor-pointer disabled:opacity-50"
|
|
>
|
|
{isSending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
|
|
Yes, Send
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ─── Page wrapper ─────────────────────────────────────────────────────────────
|
|
|
|
export default function WhatsAppWebPage() {
|
|
return (
|
|
<Suspense fallback={
|
|
<div className="h-screen flex items-center justify-center text-muted-foreground text-sm animate-pulse">
|
|
Loading OpenWA Web WhatsApp…
|
|
</div>
|
|
}>
|
|
<WhatsAppWebContent />
|
|
</Suspense>
|
|
);
|
|
}
|