import { AlertCircle, ArrowDownUp, Bell, BellRing, BookOpen, Check, Clock, Download, ExternalLink, Eye, FileText, Gift, History, Loader2, RotateCcw, Send, Settings, Sparkles, Timer, Users, } from "lucide-react"; import { YoutubeIcon } from "@/components/BrandIcons"; import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useShowNotification } from "@/components/NotificationCenter"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import { useTranslation } from "@/hooks/useTranslation"; import { bilingual } from "@/lib/i18n"; import { trpc } from "@/providers/trpc"; // ═══════════════════════════════════════════════════════════════════════════════ // Types // ═══════════════════════════════════════════════════════════════════════════════ /** * ✅ ROOT FIX (dashboard audit): the old composer offered "enrollment" / * "update" / "custom" notification types — the backend `admin.sendBroadcast` * z.enum REJECTS all three ("promo" | "system" | "lesson" | "file" | * "software" | "youtube"), which is exactly why Admin.tsx used to hardcode * `type: "promo"` and silently ignore whatever the admin picked. The composer * now speaks the SERVER's vocabulary, so the selected type actually lands in * the stored notification. */ type NotificationType = | "promo" | "system" | "lesson" | "file" | "software" | "youtube"; export interface AdminNotificationPanelProps { /** * Ship the composed notification to the server. ROOT FIX: this is now * awaited — the success toast / history refresh only happen once the * backend CONFIRMS the broadcast. The old panel showed "sent successfully" * immediately, even when the mutation failed. */ readonly onSend?: (notification: { readonly type: NotificationType; readonly title: string; readonly message: string; /** Optional click-through target (relative path or http(s) URL). */ readonly url?: string; readonly titleAr?: string; readonly titleEn?: string; readonly messageAr?: string; readonly messageEn?: string; }) => Promise | undefined; } /** One broadcast row as stored by the server (notifications table). */ interface BroadcastRecord { readonly id: string; readonly type: NotificationType; readonly titleAr: string; readonly titleEn: string; readonly messageAr: string; readonly messageEn: string; readonly url: string | null; readonly sentAt: number; } interface FormErrors { titleEn?: string; titleAr?: string; messageEn?: string; messageAr?: string; url?: string; } // ═══════════════════════════════════════════════════════════════════════════════ // Constants // ═══════════════════════════════════════════════════════════════════════════════ const TITLE_MIN = 3; const TITLE_MAX = 120; const MESSAGE_MIN = 10; const MESSAGE_MAX = 500; /** Mirrors the server's `url` refine: relative path or http(s) only. */ const URL_MAX = 700; const DEFAULT_COOLDOWN = 60; const NOTIFICATION_TYPE_CONFIG: Record< NotificationType, { icon: ReactNode; color: string; bg: string; labelEn: string; labelAr: string; descriptionEn: string; descriptionAr: string; toastType: "enrollment" | "promo" | "update" | "info"; } > = { promo: { icon: , color: "text-[#f59e0b]", bg: "bg-[rgba(245,158,11,0.1)]", labelEn: "Promo / Announcement", labelAr: "عرض / إعلان", descriptionEn: "Promotional offers and general announcements", descriptionAr: "العروض الترويجية والإعلانات العامة", toastType: "promo", }, system: { icon: , color: "text-[#10b981]", bg: "bg-[rgba(16,185,129,0.1)]", labelEn: "System Notice", labelAr: "إشعار نظامي", descriptionEn: "Platform updates, maintenance windows, new features", descriptionAr: "تحديثات المنصة أو الصيانة أو الميزات الجديدة", toastType: "update", }, lesson: { icon: , color: "text-[#06b6d4]", bg: "bg-[rgba(6,182,212,0.1)]", labelEn: "New Lesson", labelAr: "درس جديد", descriptionEn: "New course episode just landed", descriptionAr: "إضافة درس جديد لأحد الكورسات", toastType: "enrollment", }, file: { icon: , color: "text-[#818cf8]", bg: "bg-[rgba(129,140,248,0.1)]", labelEn: "New File", labelAr: "ملف جديد", descriptionEn: "New reference / library file available", descriptionAr: "توافر ملف أو مرجع جديد في المكتبة", toastType: "info", }, software: { icon: , color: "text-[#a78bfa]", bg: "bg-[rgba(167,139,250,0.1)]", labelEn: "New Software", labelAr: "برنامج جديد", descriptionEn: "New software entry in the downloads section", descriptionAr: "إضافة برنامج جديد في قسم التحميلات", toastType: "info", }, youtube: { icon: , color: "text-[#f87171]", bg: "bg-[rgba(248,113,113,0.1)]", labelEn: "YouTube Video", labelAr: "فيديو يوتيوب", descriptionEn: "New episode detected on the YouTube channel", descriptionAr: "فيديو جديد على قناة يوتيوب", toastType: "info", }, }; const NOTIFICATION_TYPES = Object.keys(NOTIFICATION_TYPE_CONFIG) as NotificationType[]; function isNotificationType(value: unknown): value is NotificationType { return typeof value === "string" && (NOTIFICATION_TYPES as string[]).includes(value); } // ═══════════════════════════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════════════════════════ function formatDateTime(iso: string | number, lang: "en" | "ar"): string { try { const d = new Date(iso); return d.toLocaleDateString(lang === "ar" ? "ar-EG" : "en-US", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } catch { return String(iso); } } /** * Map a server broadcast row (admin.broadcastHistory → notifications table) * into the component's record shape. Arabic is the primary display (matches * pushNotification: `title`/`message` are Arabic-first, English lives in * data.en). */ function mapServerBroadcast(row: { eventId: string; type: unknown; title: string; message: string; url: string | null; en: { title?: string; message?: string } | null; createdAt: string | Date; }): BroadcastRecord | null { if (!isNotificationType(row.type)) return null; return { id: row.eventId, type: row.type, titleAr: row.title, titleEn: row.en?.title || row.title, messageAr: row.message, messageEn: row.en?.message || "", url: row.url ?? null, sentAt: row.createdAt instanceof Date ? row.createdAt.getTime() : new Date(row.createdAt).getTime(), }; } /** Server-side validation twin: relative path or http(s) URL. */ function isValidLinkUrl(value: string): boolean { return value.startsWith("/") || /^https?:\/\//i.test(value); } /** Bilingual validation labels for a title field (EN or AR side). */ function titleFieldLabels(requiredAr: string, requiredEn: string, isRTL: boolean) { return { required: isRTL ? requiredAr : requiredEn, tooShort: isRTL ? `يجب أن يكون العنوان ${TITLE_MIN} أحرف على الأقل` : `Title must be at least ${TITLE_MIN} characters`, tooLong: isRTL ? `يجب ألا يتجاوز العنوان ${TITLE_MAX} حرفًا` : `Title must not exceed ${TITLE_MAX} characters`, }; } /** Bilingual validation labels for a message field (EN or AR side). */ function messageFieldLabels(requiredAr: string, requiredEn: string, isRTL: boolean) { return { required: isRTL ? requiredAr : requiredEn, tooShort: isRTL ? `يجب أن تكون الرسالة ${MESSAGE_MIN} أحرف على الأقل` : `Message must be at least ${MESSAGE_MIN} characters`, tooLong: isRTL ? `يجب ألا تتجاوز الرسالة ${MESSAGE_MAX} حرفًا` : `Message must not exceed ${MESSAGE_MAX} characters`, }; } /** Optional-link validation — mirrors the server's z.refine exactly so the * admin never hits a server rejection the form could have caught locally. * Returns the field error, or null when the URL is acceptable. */ function validateLinkUrl(rawUrl: string, isRTL: boolean): string | null { const trimmedUrl = rawUrl.trim(); if (!trimmedUrl) return null; if (trimmedUrl.length > URL_MAX) { return isRTL ? `يجب ألا يتجاوز الرابط ${URL_MAX} حرفًا` : `Link must not exceed ${URL_MAX} characters`; } if (!isValidLinkUrl(trimmedUrl)) { return isRTL ? "الرابط يجب أن يكون مسارًا داخليًا يبدأ بـ / أو رابط http(s)" : "Link must be a relative path starting with / or an http(s) URL"; } return null; } // ═══════════════════════════════════════════════════════════════════════════════ // Sub-components // ═══════════════════════════════════════════════════════════════════════════════ /** Character counter that turns red when limit is approached. */ function CharCounter({ current, min, max, }: { readonly current: number; readonly min: number; readonly max: number; }) { const isOver = current > max; const isUnder = current > 0 && current < min; const innerColor = isUnder ? "text-[#f59e0b]" : "text-[#64748b]"; const color = isOver ? "text-[#f87171]" : innerColor; return ( {current}/{max} ); } /** Inline validation message. */ function FieldError({ message }: { readonly message?: string }) { if (!message) return null; return (

{message}

); } /** Inline success message. */ function FieldSuccess({ message }: { readonly message?: string }) { if (!message) return null; return (

{message}

); } /** The cooldown countdown ring/indicator. */ function CooldownIndicator({ remaining, total, isRTL, }: { readonly remaining: number; readonly total: number; readonly isRTL: boolean; }) { const pct = total > 0 ? (remaining / total) * 100 : 0; const circumference = 2 * Math.PI * 16; const offset = circumference - (pct / 100) * circumference; return (
{remaining}

{isRTL ? "يرجى الانتظار" : "Please wait"}

{isRTL ? `ثوانٍ قبل إرسال الإشعار التالي` : "seconds before next notification"}

); } /** Toast preview — mimics the look of NotificationToast. */ function NotificationPreview({ type, title, message, isVisible, }: { readonly type: NotificationType; readonly title: string; readonly message: string; readonly isVisible: boolean; }) { const cfg = NOTIFICATION_TYPE_CONFIG[type]; return (
{/* Icon */}
{cfg.icon}
{/* Content */}

{title || cfg.labelEn}

{message || "Notification preview will appear here..."}

{/* Preview badge */} Preview
); } /** Single row in the history list (server-backed — read-only audit trail). */ function HistoryRow({ record, lang, }: { readonly record: BroadcastRecord; readonly lang: "en" | "ar"; }) { const isRTL = lang === "ar"; const cfg = NOTIFICATION_TYPE_CONFIG[record.type]; return (
{/* Icon */}
{cfg.icon}
{/* Content */}

{isRTL ? record.titleAr : record.titleEn}

{bilingual("تم الإرسال", "Sent", isRTL)}

{isRTL ? record.messageAr : record.messageEn}

{bilingual("جميع المستخدمين", "All Users", isRTL)} • {formatDateTime(record.sentAt, lang)} {record.url && ( <> • {record.url} )}
); } /** Empty state for history. */ function EmptyHistory({ lang, error, }: { readonly lang: "en" | "ar"; readonly error?: boolean; }) { const isRTL = lang === "ar"; let heading: string; let subtext: string; if (error) { heading = isRTL ? "تعذر تحميل السجل من السيرفر" : "Could not load history from the server"; subtext = isRTL ? "تأكد من الاتصال ثم أعد المحاولة" : "Check connectivity and try again"; } else { heading = isRTL ? "لا توجد إشعارات مرسلة" : "No notifications sent"; subtext = isRTL ? "كل إشعار تبثه يظهر هنا مباشرة من السيرفر" : "Every broadcast you send appears here straight from the server"; } return (

{heading}

{subtext}

); } /** History tab body: loading / error / empty / rows. */ function HistoryList({ lang, records, isLoading, isError, onRetry, }: { readonly lang: "en" | "ar"; readonly records: BroadcastRecord[]; readonly isLoading: boolean; readonly isError: boolean; readonly onRetry: () => void; }) { const isRTL = lang === "ar"; if (isLoading) { return (
{isRTL ? "جاري تحميل السجل..." : "Loading history..."}
); } if (isError) { return (
); } if (records.length === 0) { return ; } return (
{records.map((record) => ( ))}
); } // ═══════════════════════════════════════════════════════════════════════════════ // Main Component // ═══════════════════════════════════════════════════════════════════════════════ export default function AdminNotificationPanel({ // NOSONAR — admin broadcast composer; the form state is tightly coupled to the honest-send flow onSend, }: AdminNotificationPanelProps) { const { lang } = useTranslation(); const { showNotification } = useShowNotification(); const isRTL = lang === "ar"; // ─── Form state ─── const [type, setType] = useState("promo"); const [titleEn, setTitleEn] = useState(""); const [titleAr, setTitleAr] = useState(""); const [messageEn, setMessageEn] = useState(""); const [messageAr, setMessageAr] = useState(""); const [url, setUrl] = useState(""); const [previewActive, setPreviewActive] = useState(false); // ─── Cooldown state ─── const [cooldownRemaining, setCooldownRemaining] = useState(0); const [cooldownTotal, setCooldownTotal] = useState(DEFAULT_COOLDOWN); const lastSentRef = useRef(0); const cooldownIntervalRef = useRef | null>(null); // ─── UI state ─── const [errors, setErrors] = useState({}); const [successMessage, setSuccessMessage] = useState(""); const [isSending, setIsSending] = useState(false); const [activeTab, setActiveTab] = useState("compose"); // ─── History state ─── const [historyFilter, setHistoryFilter] = useState("all"); // ─── Settings state ─── const [settingCooldown, setSettingCooldown] = useState(DEFAULT_COOLDOWN); /** * ✅ ROOT FIX: the History tab now reads SERVER truth * (notifications table via admin.broadcastHistory) instead of a * localStorage list that claimed "sent/scheduled" without the backend * ever confirming anything. Broadcasts persist ~30 days server-side. */ const broadcastHistory = trpc.admin.broadcastHistory.useQuery(undefined); const records = useMemo( () => (broadcastHistory.data ?? []) .map(mapServerBroadcast) .filter((r): r is BroadcastRecord => r !== null), [broadcastHistory.data], ); // ═══════════════════════════════════════════════════════════════════════════ // Cooldown timer // ═══════════════════════════════════════════════════════════════════════════ useEffect(() => { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); cooldownIntervalRef.current = null; } if (cooldownRemaining <= 0) return; cooldownIntervalRef.current = setInterval(() => { setCooldownRemaining((prev) => { const newVal = prev - 1; if (newVal <= 0) { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); cooldownIntervalRef.current = null; } return 0; } return newVal; }); }, 1000); return () => { if (cooldownIntervalRef.current) { clearInterval(cooldownIntervalRef.current); cooldownIntervalRef.current = null; } }; }, [cooldownRemaining]); // ═══════════════════════════════════════════════════════════════════════════ // Validation // ═══════════════════════════════════════════════════════════════════════════ const validate = useCallback((): boolean => { const next: FormErrors = {}; let valid = true; const validateTextField = ( value: string, field: keyof FormErrors, labels: { required: string; tooShort: string; tooLong: string }, min: number, max: number, ): void => { const trimmed = value.trim(); if (!trimmed) { next[field] = labels.required; valid = false; } else if (trimmed.length < min) { next[field] = labels.tooShort; valid = false; } else if (value.length > max) { next[field] = labels.tooLong; valid = false; } }; // English title validateTextField(titleEn, "titleEn", titleFieldLabels("العنوان الإنجليزي مطلوب", "English title is required", isRTL), TITLE_MIN, TITLE_MAX); // Arabic title validateTextField(titleAr, "titleAr", titleFieldLabels("العنوان العربي مطلوب", "Arabic title is required", isRTL), TITLE_MIN, TITLE_MAX); // English message validateTextField(messageEn, "messageEn", messageFieldLabels("الرسالة الإنجليزية مطلوبة", "English message is required", isRTL), MESSAGE_MIN, MESSAGE_MAX); // Arabic message validateTextField(messageAr, "messageAr", messageFieldLabels("الرسالة العربية مطلوبة", "Arabic message is required", isRTL), MESSAGE_MIN, MESSAGE_MAX); // Optional link — mirrors the server's z.refine exactly so the admin // never hits a server rejection the form could have caught locally. const urlError = validateLinkUrl(url, isRTL); if (urlError) next.url = urlError; setErrors(next); return valid; }, [titleEn, titleAr, messageEn, messageAr, url, isRTL]); // ═══════════════════════════════════════════════════════════════════════════ // Reset form // ═══════════════════════════════════════════════════════════════════════════ const resetForm = useCallback(() => { setType("promo"); setTitleEn(""); setTitleAr(""); setMessageEn(""); setMessageAr(""); setUrl(""); setErrors({}); setSuccessMessage(""); setPreviewActive(false); }, []); // ═══════════════════════════════════════════════════════════════════════════ // Preview notification // ═══════════════════════════════════════════════════════════════════════════ const handlePreview = useCallback(() => { if (cooldownRemaining > 0) return; const displayTitle = isRTL ? titleAr : titleEn; const displayMessage = isRTL ? messageAr : messageEn; const cfg = NOTIFICATION_TYPE_CONFIG[type]; showNotification({ type: cfg.toastType, title: displayTitle || cfg.labelEn, message: displayMessage || "Preview notification", duration: 4000, }); setPreviewActive(true); setTimeout(() => setPreviewActive(false), 5000); }, [type, titleEn, titleAr, messageEn, messageAr, isRTL, showNotification, cooldownRemaining]); // ═══════════════════════════════════════════════════════════════════════════ // Send notification — HONEST flow: success only after the server confirms // ═══════════════════════════════════════════════════════════════════════════ const handleSend = useCallback(async () => { // NOSONAR — one honest send path: validate → await server → feedback if (cooldownRemaining > 0) return; if (!validate()) return; setIsSending(true); setSuccessMessage(""); const trimmedUrl = url.trim(); const payload = { type, title: isRTL ? titleAr.trim() : titleEn.trim(), message: isRTL ? messageAr.trim() : messageEn.trim(), url: trimmedUrl || undefined, titleAr: titleAr.trim(), titleEn: titleEn.trim(), messageAr: messageAr.trim(), messageEn: messageEn.trim(), }; try { // ✅ ROOT FIX: the send is now genuinely awaited. The old panel fired // "تم الإرسال بنجاح" unconditionally — even when the mutation failed. await onSend?.(payload); // Server confirmed — only NOW is success shown anywhere. const cfg = NOTIFICATION_TYPE_CONFIG[type]; showNotification({ type: cfg.toastType, title: isRTL ? "تم الإرسال بنجاح" : "Notification Sent", message: isRTL ? `تم بث "${payload.titleAr}" لكل المستخدمين المسجلين` : `"${payload.titleEn}" broadcast to all registered users`, duration: 4000, }); // Start cooldown const cooldown = settingCooldown || DEFAULT_COOLDOWN; setCooldownTotal(cooldown); setCooldownRemaining(cooldown); lastSentRef.current = Date.now(); setSuccessMessage( isRTL ? "تم إرسال الإشعار بنجاح!" : "Notification sent successfully!", ); // Refresh the server-backed history so the row appears immediately. void broadcastHistory.refetch(); // Reset form after short delay so user sees the success setTimeout(() => resetForm(), 2000); } catch (err) { const fallbackMessage = isRTL ? "حدث خطأ غير متوقع — لم يتم الإرسال" : "Unexpected error — nothing was sent"; showNotification({ type: "info", title: isRTL ? "فشل إرسال الإشعار" : "Send failed", message: err instanceof Error && err.message ? err.message : fallbackMessage, duration: 6000, }); } finally { setIsSending(false); } }, [ cooldownRemaining, validate, type, titleEn, titleAr, messageEn, messageAr, url, isRTL, onSend, showNotification, settingCooldown, broadcastHistory, resetForm, ]); // ═══════════════════════════════════════════════════════════════════════════ // Save settings // ═══════════════════════════════════════════════════════════════════════════ const handleSaveSettings = useCallback(() => { const cd = Math.max(10, Math.min(300, settingCooldown)); setSettingCooldown(cd); setCooldownTotal(cd); showNotification({ type: "update", title: isRTL ? "تم حفظ الإعدادات" : "Settings Saved", message: isRTL ? `تم ضبط فترة الانتظار على ${cd} ثانية` : `Cooldown set to ${cd} seconds`, duration: 3000, }); }, [settingCooldown, showNotification, isRTL]); // ═══════════════════════════════════════════════════════════════════════════ // Computed values // ═══════════════════════════════════════════════════════════════════════════ const typeConfig = NOTIFICATION_TYPE_CONFIG[type]; const filteredHistory = historyFilter === "all" ? records : records.filter((r) => r.type === historyFilter); const isOnCooldown = cooldownRemaining > 0; const isFormEmpty = !titleEn && !titleAr && !messageEn && !messageAr; const previewTitle = isRTL ? titleAr : titleEn; const previewMessage = isRTL ? messageAr : messageEn; const idleSendIcon = isOnCooldown ? ( ) : ( ); const idleSendLabel = isOnCooldown ? `${cooldownRemaining}s` : bilingual("إرسال الإشعار", "Send Notification", isRTL); const sendingLabel = isRTL ? "جاري الإرسال..." : "Sending..."; const sendButtonLabel = isSending ? sendingLabel : idleSendLabel; const readyStatusBadge = ( {isRTL ? "جاهز" : "Ready"} ); const emptyStatusBadge = isFormEmpty ? ( {isRTL ? "فارغ" : "Empty"} ) : readyStatusBadge; const errorStatusBadge = Object.values(errors).some(Boolean) ? ( {isRTL ? "أخطاء" : "Errors"} ) : emptyStatusBadge; const formStatusBadge = isOnCooldown ? ( {isRTL ? "انتظار" : "Cooldown"} ) : errorStatusBadge; // ═══════════════════════════════════════════════════════════════════════════ // Render // ═══════════════════════════════════════════════════════════════════════════ return (
{/* ─── Header ─── */}

{isRTL ? "مركز إرسال الإشعارات" : "Notification Center"}

{isRTL ? "بث إشعارات حقيقية لكل المستخدمين — تسجيل من السيرفر" : "Broadcast real notifications to all users — server-backed log"}

{records.length}{" "} {isRTL ? "إشعار مرسل" : "sent"}
{/* ─── Tabs ─── */} {isRTL ? "إرسال جديد" : "Send New"} {isRTL ? "السجل" : "History"} {isRTL ? "الإعدادات" : "Settings"} {/* ═══════════════════════════════════════════════════════════════════ TAB 1 — Compose / Send New ═══════════════════════════════════════════════════════════════════ */}
{/* ── Left Column: Form ── */}
{/* Cooldown indicator */} {isOnCooldown && ( )} {/* Success message */} {successMessage && ( )} {/* ── Notification Type ── */} {isRTL ? "نوع الإشعار" : "Notification Type"} {isRTL ? "النوع يُحفظ في الإشعار نفسه ويحدد شكله عند المستخدم" : "The type is stored on the notification and shapes how users see it"} {NOTIFICATION_TYPES.map((nt) => { const cfg = NOTIFICATION_TYPE_CONFIG[nt]; const isSelected = type === nt; return ( ); })} {/* ── Titles (EN / AR) ── */}
{/* English Title */}
{ const v = e.target.value; if (v.length <= TITLE_MAX) setTitleEn(v); setErrors((prev) => ({ ...prev, titleEn: undefined })); setSuccessMessage(""); }} placeholder={ isRTL ? "أدخل العنوان بالإنجليزية..." : "Enter title in English..." } dir="ltr" className={`border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe] placeholder:text-[#475569] ${ errors.titleEn ? "border-[#f87171] focus-visible:border-[#f87171] focus-visible:ring-[#f87171]/30" : "" }`} />
{/* Arabic Title */}
{ const v = e.target.value; if (v.length <= TITLE_MAX) setTitleAr(v); setErrors((prev) => ({ ...prev, titleAr: undefined })); setSuccessMessage(""); }} placeholder="أدخل العنوان بالعربية..." dir="rtl" className={`border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe] placeholder:text-[#475569] ${ errors.titleAr ? "border-[#f87171] focus-visible:border-[#f87171] focus-visible:ring-[#f87171]/30" : "" }`} />
{/* ── Messages (EN / AR) ── */}
{/* English Message */}