Spaces:
Running
Running
File size: 69,157 Bytes
50a005c 18afd52 50a005c 18afd52 50a005c 18afd52 50a005c 18afd52 50a005c 18afd52 50a005c 18afd52 50a005c 700d33c 18afd52 50a005c 18afd52 50a005c 18afd52 50a005c 2efd444 50a005c 2efd444 b8b5e61 2efd444 43a1d74 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 700d33c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c caa8f36 50a005c d3a69df 50a005c d3a69df 50a005c d3a69df 50a005c d3a69df 50a005c d3a69df 50a005c 92398e6 50a005c b8b5e61 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 b8b5e61 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c caa8f36 50a005c caa8f36 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c d3a69df 50a005c d3a69df caa8f36 d3a69df caa8f36 d3a69df caa8f36 d3a69df caa8f36 50a005c 2efd444 caa8f36 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 caa8f36 2efd444 caa8f36 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c d3a69df 2efd444 d3a69df 50a005c 2efd444 50a005c 2efd444 50a005c 8054c5d 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 8054c5d 50a005c c7df2b5 50a005c 8054c5d 50a005c c7df2b5 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 8054c5d 50a005c 2efd444 50a005c d3a69df 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c d3a69df 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 caa8f36 50a005c 8054c5d 50a005c c7df2b5 1858532 50a005c 2efd444 50a005c 2efd444 50a005c 2efd444 50a005c c7df2b5 50a005c c7df2b5 50a005c 2efd444 50a005c 2efd444 50a005c c7df2b5 50a005c c7df2b5 50a005c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 | 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<unknown> | 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: <Gift className="h-4 w-4" />,
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: <Sparkles className="h-4 w-4" />,
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: <BookOpen className="h-4 w-4" />,
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: <FileText className="h-4 w-4" />,
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: <Download className="h-4 w-4" />,
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: <YoutubeIcon className="h-4 w-4" />,
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 (
<span className={`text-[11px] tabular-nums ${color}`}>
{current}/{max}
</span>
);
}
/** Inline validation message. */
function FieldError({ message }: { readonly message?: string }) {
if (!message) return null;
return (
<p className="mt-1 flex items-center gap-1 text-[12px] text-[#f87171]">
<AlertCircle className="h-3 w-3 shrink-0" />
{message}
</p>
);
}
/** Inline success message. */
function FieldSuccess({ message }: { readonly message?: string }) {
if (!message) return null;
return (
<p className="mt-1 flex items-center gap-1 text-[12px] text-[#10b981]">
<Check className="h-3 w-3 shrink-0" />
{message}
</p>
);
}
/** 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 (
<div className="flex items-center gap-3 rounded-xl border border-[#1e2d3d] bg-[#0d1420] px-4 py-3">
<div className="relative h-10 w-10 shrink-0">
<svg className="h-10 w-10 -rotate-90" viewBox="0 0 36 36" role="img" aria-hidden="true">
<circle
cx="18"
cy="18"
r="16"
fill="none"
stroke="#1e2d3d"
strokeWidth="2.5"
/>
<circle
cx="18"
cy="18"
r="16"
fill="none"
stroke="#06b6d4"
strokeWidth="2.5"
strokeDasharray={circumference}
strokeDashoffset={offset}
strokeLinecap="round"
className="transition-all duration-1000"
/>
</svg>
<span className="absolute inset-0 flex items-center justify-center text-[10px] font-bold text-[#06b6d4]">
{remaining}
</span>
</div>
<div>
<p className="text-[13px] font-medium text-[#e8f0fe]">
{isRTL ? "يرجى الانتظار" : "Please wait"}
</p>
<p className="text-[11px] text-[#64748b]">
{isRTL
? `ثوانٍ قبل إرسال الإشعار التالي`
: "seconds before next notification"}
</p>
</div>
</div>
);
}
/** 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 (
<div
className={`flex w-full items-start gap-3 rounded-xl border border-[rgba(6,182,212,0.15)] bg-[rgba(7,11,18,0.85)] p-4 shadow-[0_8px_32px_rgba(0,0,0,0.4)] backdrop-blur-xl transition-all duration-300 ${
isVisible
? "translate-y-0 opacity-100"
: "pointer-events-none translate-y-2 opacity-40"
}`}
>
{/* Icon */}
<div
className={`mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${cfg.bg}`}
>
<span className={cfg.color}>{cfg.icon}</span>
</div>
{/* Content */}
<div className="min-w-0 flex-1">
<p className="text-[13px] font-semibold text-[#e8f0fe]">
{title || cfg.labelEn}
</p>
<p className="mt-1 text-[12px] leading-relaxed text-[#94a3b8]">
{message || "Notification preview will appear here..."}
</p>
</div>
{/* Preview badge */}
<Badge
variant="outline"
className="shrink-0 border-[#1e2d3d] text-[10px] text-[#64748b]"
>
Preview
</Badge>
</div>
);
}
/** 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 (
<div className="group flex items-start gap-3 rounded-lg border border-[#1e2d3d] bg-[#0d1420] px-4 py-3 transition-colors hover:border-[#2d3f52]">
{/* Icon */}
<div
className={`mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${cfg.bg}`}
>
<span className={cfg.color}>{cfg.icon}</span>
</div>
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="truncate text-[13px] font-semibold text-[#e8f0fe]">
{isRTL ? record.titleAr : record.titleEn}
</p>
<Badge className="border-0 bg-[rgba(16,185,129,0.12)] text-[10px] text-[#10b981]">
{bilingual("تم الإرسال", "Sent", isRTL)}
</Badge>
</div>
<p className="mt-0.5 line-clamp-1 text-[12px] text-[#64748b]">
{isRTL ? record.messageAr : record.messageEn}
</p>
<div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] text-[#475569]">
<span className="flex items-center gap-1">
<Users className="h-3 w-3" />
{bilingual("جميع المستخدمين", "All Users", isRTL)}
</span>
<span>•</span>
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{formatDateTime(record.sentAt, lang)}
</span>
{record.url && (
<>
<span>•</span>
<span className="flex max-w-[220px] items-center gap-1 truncate" dir="ltr">
<ExternalLink className="h-3 w-3 shrink-0" />
{record.url}
</span>
</>
)}
</div>
</div>
</div>
);
}
/** 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 (
<div className="flex flex-col items-center justify-center py-16 text-center">
<div className="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[rgba(148,163,184,0.06)]">
<History className="h-7 w-7 text-[#475569]" />
</div>
<p className="text-[14px] font-semibold text-[#94a3b8]">{heading}</p>
<p className="mt-1 max-w-[260px] text-[12px] text-[#475569]">{subtext}</p>
</div>
);
}
/** 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 (
<div className="flex items-center justify-center gap-2 rounded-xl border border-[#1e2d3d] bg-[#070b12] py-16 text-[13px] text-[#94a3b8]">
<Loader2 className="h-4 w-4 animate-spin" />
{isRTL ? "جاري تحميل السجل..." : "Loading history..."}
</div>
);
}
if (isError) {
return (
<div className="rounded-xl border border-[rgba(248,113,113,0.3)] bg-[rgba(248,113,113,0.05)]">
<EmptyHistory lang={lang} error />
<div className="flex justify-center pb-6">
<Button
type="button"
size="sm"
variant="outline"
onClick={onRetry}
className="border-[#1e2d3d] text-[#94a3b8] hover:bg-[#1e2d3d]"
>
{isRTL ? "إعادة المحاولة" : "Retry"}
</Button>
</div>
</div>
);
}
if (records.length === 0) {
return <EmptyHistory lang={lang} />;
}
return (
<div className="max-h-[520px] space-y-2 overflow-y-auto rounded-xl border border-[#1e2d3d] bg-[#070b12] p-2">
{records.map((record) => (
<HistoryRow key={record.id} record={record} lang={lang} />
))}
</div>
);
}
// ═══════════════════════════════════════════════════════════════════════════════
// 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<NotificationType>("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<number>(0);
const cooldownIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// ─── UI state ───
const [errors, setErrors] = useState<FormErrors>({});
const [successMessage, setSuccessMessage] = useState("");
const [isSending, setIsSending] = useState(false);
const [activeTab, setActiveTab] = useState("compose");
// ─── History state ───
const [historyFilter, setHistoryFilter] = useState<NotificationType | "all">("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<BroadcastRecord[]>(
() =>
(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 ? (
<Timer className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
) : (
<Send className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
);
const idleSendLabel = isOnCooldown
? `${cooldownRemaining}s`
: bilingual("إرسال الإشعار", "Send Notification", isRTL);
const sendingLabel = isRTL ? "جاري الإرسال..." : "Sending...";
const sendButtonLabel = isSending ? sendingLabel : idleSendLabel;
const readyStatusBadge = (
<Badge className="border-0 bg-[rgba(16,185,129,0.12)] text-[10px] text-[#10b981]">
<Check className={`h-3 w-3 ${isRTL ? "ml-1" : "mr-1"}`} />
{isRTL ? "جاهز" : "Ready"}
</Badge>
);
const emptyStatusBadge = isFormEmpty ? (
<Badge variant="outline" className="border-[#1e2d3d] text-[10px] text-[#64748b]">
{isRTL ? "فارغ" : "Empty"}
</Badge>
) : readyStatusBadge;
const errorStatusBadge = Object.values(errors).some(Boolean) ? (
<Badge className="border-0 bg-[rgba(248,113,113,0.12)] text-[10px] text-[#f87171]">
<AlertCircle className={`h-3 w-3 ${isRTL ? "ml-1" : "mr-1"}`} />
{isRTL ? "أخطاء" : "Errors"}
</Badge>
) : emptyStatusBadge;
const formStatusBadge = isOnCooldown ? (
<Badge className="border-0 bg-[rgba(245,158,11,0.12)] text-[10px] text-[#f59e0b]">
<Timer className={`h-3 w-3 ${isRTL ? "ml-1" : "mr-1"}`} />
{isRTL ? "انتظار" : "Cooldown"}
</Badge>
) : errorStatusBadge;
// ═══════════════════════════════════════════════════════════════════════════
// Render
// ═══════════════════════════════════════════════════════════════════════════
return (
<div
dir={isRTL ? "rtl" : "ltr"}
className="w-full rounded-2xl border border-[#1e2d3d] bg-[#0d1420]"
>
{/* ─── Header ─── */}
<div className="flex items-center gap-3 border-b border-[#1e2d3d] px-6 py-5">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[rgba(6,182,212,0.1)]">
<BellRing className="h-5 w-5 text-[#06b6d4]" />
</div>
<div className="min-w-0 flex-1">
<h2 className="text-lg font-bold text-[#e8f0fe]">
{isRTL ? "مركز إرسال الإشعارات" : "Notification Center"}
</h2>
<p className="text-[13px] text-[#64748b]">
{isRTL
? "بث إشعارات حقيقية لكل المستخدمين — تسجيل من السيرفر"
: "Broadcast real notifications to all users — server-backed log"}
</p>
</div>
<Badge
variant="outline"
className="border-[rgba(6,182,212,0.25)] text-[12px] text-[#06b6d4]"
>
{records.length}{" "}
{isRTL ? "إشعار مرسل" : "sent"}
</Badge>
</div>
{/* ─── Tabs ─── */}
<Tabs
value={activeTab}
onValueChange={setActiveTab}
className="px-6 pb-6"
>
<TabsList className="mt-4 flex w-full border border-[#1e2d3d] bg-[#070b12]">
<TabsTrigger
value="compose"
className="flex-1 data-[state=active]:bg-[#06b6d4] data-[state=active]:text-[#070b12]"
>
<Send className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
{isRTL ? "إرسال جديد" : "Send New"}
</TabsTrigger>
<TabsTrigger
value="history"
className="flex-1 data-[state=active]:bg-[#06b6d4] data-[state=active]:text-[#070b12]"
>
<History className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
{isRTL ? "السجل" : "History"}
</TabsTrigger>
<TabsTrigger
value="settings"
className="flex-1 data-[state=active]:bg-[#06b6d4] data-[state=active]:text-[#070b12]"
>
<Settings className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
{isRTL ? "الإعدادات" : "Settings"}
</TabsTrigger>
</TabsList>
{/* ═══════════════════════════════════════════════════════════════════
TAB 1 — Compose / Send New
═══════════════════════════════════════════════════════════════════ */}
<TabsContent value="compose" className="mt-6">
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr,360px]">
{/* ── Left Column: Form ── */}
<div className="space-y-6">
{/* Cooldown indicator */}
{isOnCooldown && (
<CooldownIndicator
remaining={cooldownRemaining}
total={cooldownTotal}
isRTL={isRTL}
/>
)}
{/* Success message */}
{successMessage && (
<FieldSuccess message={successMessage} />
)}
{/* ── Notification Type ── */}
<Card className="border-[#1e2d3d] bg-[#111827] py-4">
<CardHeader className="pb-0">
<CardTitle className="text-[14px] text-[#e8f0fe]">
{isRTL ? "نوع الإشعار" : "Notification Type"}
</CardTitle>
<CardDescription className="text-[12px]">
{isRTL
? "النوع يُحفظ في الإشعار نفسه ويحدد شكله عند المستخدم"
: "The type is stored on the notification and shapes how users see it"}
</CardDescription>
</CardHeader>
<CardContent className="grid grid-cols-2 gap-2 pt-4 sm:grid-cols-3">
{NOTIFICATION_TYPES.map((nt) => {
const cfg = NOTIFICATION_TYPE_CONFIG[nt];
const isSelected = type === nt;
return (
<button
key={nt}
type="button"
onClick={() => setType(nt)}
data-testid={`notif-type-${nt}`}
className={`flex flex-col items-center gap-2 rounded-xl border px-3 py-3 text-center transition-all ${
isSelected
? "border-[#06b6d4] bg-[rgba(6,182,212,0.08)] ring-1 ring-[rgba(6,182,212,0.2)]"
: "border-[#1e2d3d] bg-[#0d1420] hover:border-[#2d3f52]"
}`}
>
<div
className={`flex h-9 w-9 items-center justify-center rounded-lg ${cfg.bg}`}
>
<span className={cfg.color}>{cfg.icon}</span>
</div>
<span
className={`text-[11px] font-medium ${
isSelected ? "text-[#06b6d4]" : "text-[#94a3b8]"
}`}
>
{isRTL ? cfg.labelAr : cfg.labelEn}
</span>
</button>
);
})}
</CardContent>
</Card>
{/* ── Titles (EN / AR) ── */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{/* English Title */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-[#94a3b8]">
{isRTL ? "العنوان (إنجليزي)" : "Title (English)"}
<span className="ml-1 text-[#f87171]">*</span>
</Label>
<CharCounter
current={titleEn.length}
min={TITLE_MIN}
max={TITLE_MAX}
/>
</div>
<Input
value={titleEn}
onChange={(e) => {
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" : ""
}`}
/>
<FieldError message={errors.titleEn} />
</div>
{/* Arabic Title */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-[#94a3b8]">
{isRTL ? "العنوان (عربي)" : "Title (Arabic)"}
<span className="ml-1 text-[#f87171]">*</span>
</Label>
<CharCounter
current={titleAr.length}
min={TITLE_MIN}
max={TITLE_MAX}
/>
</div>
<Input
value={titleAr}
onChange={(e) => {
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" : ""
}`}
/>
<FieldError message={errors.titleAr} />
</div>
</div>
{/* ── Messages (EN / AR) ── */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{/* English Message */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-[#94a3b8]">
{isRTL ? "الرسالة (إنجليزي)" : "Message (English)"}
<span className="ml-1 text-[#f87171]">*</span>
</Label>
<CharCounter
current={messageEn.length}
min={MESSAGE_MIN}
max={MESSAGE_MAX}
/>
</div>
<Textarea
value={messageEn}
onChange={(e) => {
const v = e.target.value;
if (v.length <= MESSAGE_MAX) setMessageEn(v);
setErrors((prev) => ({ ...prev, messageEn: undefined }));
setSuccessMessage("");
}}
placeholder={
isRTL
? "اكتب الرسالة بالإنجليزية..."
: "Write the message in English..."
}
dir="ltr"
rows={4}
className={`min-h-[100px] border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe] placeholder:text-[#475569] ${
errors.messageEn ? "border-[#f87171] focus-visible:border-[#f87171] focus-visible:ring-[#f87171]/30" : ""
}`}
/>
<FieldError message={errors.messageEn} />
</div>
{/* Arabic Message */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-[#94a3b8]">
{isRTL ? "الرسالة (عربي)" : "Message (Arabic)"}
<span className="ml-1 text-[#f87171]">*</span>
</Label>
<CharCounter
current={messageAr.length}
min={MESSAGE_MIN}
max={MESSAGE_MAX}
/>
</div>
<Textarea
value={messageAr}
onChange={(e) => {
const v = e.target.value;
if (v.length <= MESSAGE_MAX) setMessageAr(v);
setErrors((prev) => ({ ...prev, messageAr: undefined }));
setSuccessMessage("");
}}
placeholder="اكتب الرسالة بالعربية..."
dir="rtl"
rows={4}
className={`min-h-[100px] border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe] placeholder:text-[#475569] ${
errors.messageAr ? "border-[#f87171] focus-visible:border-[#f87171] focus-visible:ring-[#f87171]/30" : ""
}`}
/>
<FieldError message={errors.messageAr} />
</div>
</div>
{/* ── Optional click-through link ── */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-[#94a3b8]">
{isRTL ? "رابط الإشعار (اختياري)" : "Notification Link (optional)"}
</Label>
<CharCounter
current={url.trim().length}
min={0}
max={URL_MAX}
/>
</div>
<Input
value={url}
onChange={(e) => {
setUrl(e.target.value);
setErrors((prev) => ({ ...prev, url: undefined }));
setSuccessMessage("");
}}
placeholder={isRTL ? "/courses/etap أو https://..." : "/courses/etap or https://..."}
dir="ltr"
className={`border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe] placeholder:text-[#475569] ${
errors.url ? "border-[#f87171] focus-visible:border-[#f87171] focus-visible:ring-[#f87171]/30" : ""
}`}
/>
<FieldError message={errors.url} />
<p className="text-[11px] text-[#475569]">
{isRTL
? "عند ضغط المستخدم على الإشعار يفتح هذا الرابط — مسار داخلي يبدأ بـ / أو رابط http(s)"
: "Clicking the notification opens this link — a relative path starting with / or an http(s) URL"}
</p>
</div>
{/* ── Recipients (honest contract) ── */}
<Card className="border-[#1e2d3d] bg-[#111827] py-4">
<CardContent className="pt-0">
<div className="flex items-center gap-3 rounded-lg border border-[rgba(6,182,212,0.15)] bg-[rgba(6,182,212,0.05)] px-3 py-2.5">
<span className="text-[#06b6d4]">
<Users className="h-4 w-4" />
</span>
<span className="text-[12px] text-[#94a3b8]">
{isRTL ? "سيتم البث إلى: " : "Will broadcast to: "}
<span className="font-semibold text-[#06b6d4]">
{isRTL
? "جميع المستخدمين المسجلين"
: "All registered users"}
</span>
<span className="ms-1 text-[#64748b]">
{isRTL
? "— داخل التطبيق + Web Push + قناة تليجرام"
: "— in-app bell + Web Push + Telegram channel"}
</span>
</span>
</div>
</CardContent>
</Card>
{/* ── Action Buttons ── */}
<div className="flex flex-col gap-3 sm:flex-row sm:justify-between">
<Button
type="button"
variant="ghost"
onClick={resetForm}
className="border border-[#1e2d3d] text-[#94a3b8] hover:bg-[#1e2d3d] hover:text-[#e8f0fe]"
>
<RotateCcw className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
{isRTL ? "إعادة تعيين" : "Reset Form"}
</Button>
{/* ✅ MOBILE FIX: flex-wrap — Reset + Preview + Send are
whitespace-nowrap buttons; on a 320px viewport the row
overflowed by ~8px past the card edge. */}
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="outline"
onClick={handlePreview}
disabled={isFormEmpty || isOnCooldown}
className="border-[#1e2d3d] bg-[#111827] text-[#94a3b8] hover:bg-[#1e2d3d] hover:text-[#e8f0fe]"
>
<Eye className={`h-4 w-4 ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
{isRTL ? "معاينة" : "Preview"}
</Button>
<Button
type="button"
onClick={handleSend}
disabled={isOnCooldown || isSending}
data-testid="notif-send"
className="bg-[#06b6d4] text-[#070b12] hover:bg-[#22d3ee] disabled:opacity-50"
>
{isSending ? (
<Loader2 className={`h-4 w-4 animate-spin ${isRTL ? "ml-1.5" : "mr-1.5"}`} />
) : idleSendIcon}
{sendButtonLabel}
</Button>
</div>
</div>
</div>
{/* ── Right Column: Preview ── */}
<div className="space-y-4">
<div className="sticky top-6 space-y-4">
<div className="flex items-center gap-2">
<Eye className="h-4 w-4 text-[#64748b]" />
<h3 className="text-[13px] font-semibold text-[#94a3b8]">
{isRTL ? "معاينة مباشرة" : "Live Preview"}
</h3>
</div>
<NotificationPreview
type={type}
title={previewTitle}
message={previewMessage}
isVisible={previewActive || !isFormEmpty}
/>
{/* Type description */}
<div className="rounded-lg border border-[#1e2d3d] bg-[#070b12] p-3">
<p className="text-[11px] text-[#64748b]">
{isRTL ? typeConfig.descriptionAr : typeConfig.descriptionEn}
</p>
</div>
{/* Notification metadata summary */}
<div className="rounded-lg border border-[#1e2d3d] bg-[#070b12] p-4 space-y-3">
<p className="text-[12px] font-semibold text-[#94a3b8]">
{isRTL ? "ملخص الإشعار" : "Notification Summary"}
</p>
<div className="space-y-2 text-[12px]">
<div className="flex items-center justify-between">
<span className="text-[#64748b]">
{isRTL ? "النوع" : "Type"}
</span>
<Badge
variant="outline"
className="border-[#1e2d3d] text-[10px]"
>
<span
className={`flex items-center gap-1 ${typeConfig.color}`}
>
{typeConfig.icon}
{isRTL ? typeConfig.labelAr : typeConfig.labelEn}
</span>
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-[#64748b]">
{isRTL ? "المستلمون" : "Recipients"}
</span>
<span className="flex items-center gap-1 text-[#94a3b8]">
<Users className="h-3 w-3" />
{isRTL
? "جميع المستخدمين المسجلين"
: "All registered users"}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-[#64748b]">
{isRTL ? "التوقيت" : "Timing"}
</span>
<span className="flex items-center gap-1 text-[#10b981]">
<Clock className="h-3 w-3" />
{bilingual("فوري", "Immediate", isRTL)}
</span>
</div>
<div className="border-t border-[#1e2d3d] pt-2">
<div className="flex items-center justify-between">
<span className="text-[#64748b]">
{isRTL ? "الحالة" : "Status"}
</span>
{formStatusBadge}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</TabsContent>
{/* ═══════════════════════════════════════════════════════════════════
TAB 2 — History (server truth)
═══════════════════════════════════════════════════════════════════ */}
<TabsContent value="history" className="mt-6">
<div className="space-y-4">
{/* Header row */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 className="text-[15px] font-semibold text-[#e8f0fe]">
{isRTL ? "سجل البث (من السيرفر)" : "Broadcast History (server)"}
</h3>
<p className="text-[12px] text-[#64748b]">
{isRTL
? `${records.length} إشعار مُبث — يُحفظ على السيرفر حوالي 30 يومًا`
: `${records.length} broadcasts — stored server-side for ~30 days`}
</p>
</div>
<div className="flex items-center gap-2">
{/* Filter */}
<select
value={historyFilter}
onChange={(e) =>
setHistoryFilter(e.target.value as NotificationType | "all")
}
aria-label={isRTL ? "تصفية حسب النوع" : "Filter by type"}
className="h-9 w-[160px] rounded-md border border-[#1e2d3d] bg-[#111827] px-2 text-[12px] text-[#e8f0fe]"
>
<option value="all">{isRTL ? "الكل" : "All Types"}</option>
{NOTIFICATION_TYPES.map((nt) => (
<option key={nt} value={nt}>
{isRTL
? NOTIFICATION_TYPE_CONFIG[nt].labelAr
: NOTIFICATION_TYPE_CONFIG[nt].labelEn}
</option>
))}
</select>
</div>
</div>
{/* List */}
<HistoryList
lang={lang}
records={filteredHistory}
isLoading={broadcastHistory.isLoading}
isError={broadcastHistory.isError}
onRetry={() => void broadcastHistory.refetch()}
/>
</div>
</TabsContent>
{/* ═══════════════════════════════════════════════════════════════════
TAB 3 — Settings
═══════════════════════════════════════════════════════════════════ */}
<TabsContent value="settings" className="mt-6">
<div className="space-y-6">
{/* Rate Limiting */}
<Card className="border-[#1e2d3d] bg-[#111827] py-4">
<CardHeader className="pb-0">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-[rgba(6,182,212,0.1)]">
<Timer className="h-4 w-4 text-[#06b6d4]" />
</div>
<div>
<CardTitle className="text-[14px] text-[#e8f0fe]">
{isRTL
? "معدل الإرسال المحدود"
: "Rate Limiting / Cooldown"}
</CardTitle>
<CardDescription className="text-[12px]">
{isRTL
? "تحديد الفترة الزمنية بين الإشعارات لمنع الإرسال المتكرر"
: "Set the minimum time between sends to prevent spam"}
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="pt-4">
<div className="space-y-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="space-y-1.5 sm:col-span-2">
<Label className="text-[#94a3b8]">
{isRTL
? "فترة الانتظار (بالثواني)"
: "Cooldown Duration (seconds)"}
</Label>
<Input
type="number"
value={settingCooldown}
min={10}
max={300}
onChange={(e) => {
const val = Number.parseInt(e.target.value, 10);
if (!Number.isNaN(val)) {
setSettingCooldown(val);
}
}}
dir="ltr"
className="w-full border-[#1e2d3d] bg-[#0d1420] text-[#e8f0fe]"
/>
<p className="text-[11px] text-[#475569]">
{isRTL
? "الحد الأدنى: 10 ثوانٍ — الحد الأقصى: 300 ثانية"
: "Min: 10s — Max: 300s"}
</p>
</div>
<div className="flex items-end">
<Button
type="button"
onClick={handleSaveSettings}
className="w-full bg-[#06b6d4] text-[#070b12] hover:bg-[#22d3ee]"
>
{isRTL ? "حفظ" : "Save"}
</Button>
</div>
</div>
{/* Visual presets */}
<div>
<p className="mb-2 text-[11px] text-[#64748b]">
{isRTL ? "اختيارات سريعة:" : "Quick presets:"}
</p>
<div className="flex flex-wrap gap-2">
{[
{ label: isRTL ? "30 ثانية" : "30s", value: 30 },
{ label: isRTL ? "60 ثانية" : "60s", value: 60 },
{ label: isRTL ? "2 دقيقة" : "2 min", value: 120 },
{ label: isRTL ? "5 دقائق" : "5 min", value: 300 },
].map((preset) => (
<button
key={preset.value}
type="button"
onClick={() => setSettingCooldown(preset.value)}
className={`rounded-lg border px-3 py-1.5 text-[12px] font-medium transition-all ${
settingCooldown === preset.value
? "border-[#06b6d4] bg-[rgba(6,182,212,0.1)] text-[#06b6d4]"
: "border-[#1e2d3d] text-[#94a3b8] hover:border-[#2d3f52] hover:text-[#e8f0fe]"
}`}
>
{preset.label}
</button>
))}
</div>
</div>
</div>
</CardContent>
</Card>
{/* Notification Defaults */}
<Card className="border-[#1e2d3d] bg-[#111827] py-4">
<CardHeader className="pb-0">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-[rgba(16,185,129,0.1)]">
<Bell className="h-4 w-4 text-[#10b981]" />
</div>
<div>
<CardTitle className="text-[14px] text-[#e8f0fe]">
{isRTL ? "إعدادات الإشعارات الافتراضية" : "Default Notification Settings"}
</CardTitle>
<CardDescription className="text-[12px]">
{isRTL
? "إعدادات افتراضية عند إنشاء إشعار جديد"
: "Default settings when composing a new notification"}
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="pt-4">
<div className="space-y-3">
{/* Info rows */}
{[
{
icon: <Gift className="h-4 w-4 text-[#f59e0b]" />,
labelEn: "Default Type",
labelAr: "النوع الافتراضي",
valueEn: "Promo / Announcement",
valueAr: "عرض / إعلان",
},
{
icon: <Users className="h-4 w-4 text-[#94a3b8]" />,
labelEn: "Default Recipients",
labelAr: "المستلمون الافتراضيون",
valueEn: "All registered users",
valueAr: "جميع المستخدمين المسجلين",
},
{
icon: <Clock className="h-4 w-4 text-[#f59e0b]" />,
labelEn: "Default Timing",
labelAr: "التوقيت الافتراضي",
valueEn: "Immediate",
valueAr: "فوري",
},
{
icon: <ArrowDownUp className="h-4 w-4 text-[#64748b]" />,
labelEn: "Title Length Limit",
labelAr: "حد طول العنوان",
valueEn: `${TITLE_MIN}–${TITLE_MAX} chars`,
valueAr: `${TITLE_MIN}–${TITLE_MAX} حرف`,
},
{
icon: <ArrowDownUp className="h-4 w-4 text-[#64748b]" />,
labelEn: "Message Length Limit",
labelAr: "حد طول الرسالة",
valueEn: `${MESSAGE_MIN}–${MESSAGE_MAX} chars`,
valueAr: `${MESSAGE_MIN}–${MESSAGE_MAX} حرف`,
},
].map((item) => (
<div
key={item.labelEn || item.labelAr}
className="flex items-center justify-between rounded-lg border border-[#1e2d3d] bg-[#0d1420] px-3 py-2.5"
>
<div className="flex items-center gap-2.5">
{item.icon}
<span className="text-[12px] text-[#94a3b8]">
{isRTL ? item.labelAr : item.labelEn}
</span>
</div>
<span className="text-[12px] font-medium text-[#e8f0fe]">
{isRTL ? item.valueAr : item.valueEn}
</span>
</div>
))}
</div>
</CardContent>
</Card>
{/* Stats */}
<Card className="border-[#1e2d3d] bg-[#111827] py-4">
<CardHeader className="pb-0">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-[rgba(148,163,184,0.08)]">
<History className="h-4 w-4 text-[#94a3b8]" />
</div>
<CardTitle className="text-[14px] text-[#e8f0fe]">
{isRTL ? "إحصائيات الإشعارات" : "Notification Stats"}
</CardTitle>
</div>
</CardHeader>
<CardContent className="pt-4">
<div className="grid grid-cols-2 gap-3">
{[
{
label: isRTL ? "إجمالي المبثق (سيرفر)" : "Total Broadcasts (server)",
value: records.length,
color: "#10b981",
},
{
label: isRTL ? "فترة الانتظار" : "Cooldown",
value: `${settingCooldown}s`,
color: "#06b6d4",
},
].map((stat) => (
<div
key={stat.label}
className="rounded-lg border border-[#1e2d3d] bg-[#0d1420] p-3 text-center"
>
<p
className="text-xl font-bold"
style={{ color: stat.color }}
>
{stat.value}
</p>
<p className="mt-1 text-[11px] text-[#64748b]">
{stat.label}
</p>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
</div>
);
}
|