Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

684 строки
35 KiB

  1. 'use client';
  2. import { useState, useEffect } from 'react';
  3. import { Card, Portal, MediaItem } from '@/types';
  4. const isVideoUrl = (url: string) => /\.(mp4|webm|mov|m4v|ogv)(\?|$)/i.test(url);
  5. const isPdfFile = (file: File) =>
  6. file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
  7. const isVideoFile = (file: File) =>
  8. file.type.startsWith('video/') || /\.(mp4|webm|mov|m4v|ogv)$/i.test(file.name);
  9. async function uploadBlobAsImage(blob: Blob, name: string): Promise<string | null> {
  10. const formData = new FormData();
  11. formData.append('file', new File([blob], name, { type: blob.type || 'image/png' }));
  12. const res = await fetch('/api/upload', { method: 'POST', body: formData });
  13. const data = await res.json();
  14. return data.url || null;
  15. }
  16. async function extractVideoFrame(file: File): Promise<Blob | null> {
  17. const url = URL.createObjectURL(file);
  18. try {
  19. const video = document.createElement('video');
  20. video.muted = true;
  21. video.playsInline = true;
  22. video.preload = 'metadata';
  23. video.src = url;
  24. await new Promise<void>((resolve, reject) => {
  25. video.addEventListener('loadedmetadata', () => resolve(), { once: true });
  26. video.addEventListener('error', () => reject(new Error('video load error')), { once: true });
  27. });
  28. // Seek slightly past 0 — at exactly 0 some codecs return a black frame
  29. video.currentTime = Math.min(0.1, Math.max(0, video.duration / 10));
  30. await new Promise<void>((resolve, reject) => {
  31. video.addEventListener('seeked', () => resolve(), { once: true });
  32. video.addEventListener('error', () => reject(new Error('video seek error')), { once: true });
  33. });
  34. const canvas = document.createElement('canvas');
  35. canvas.width = video.videoWidth;
  36. canvas.height = video.videoHeight;
  37. const ctx = canvas.getContext('2d');
  38. if (!ctx) return null;
  39. ctx.drawImage(video, 0, 0);
  40. return await new Promise<Blob | null>((resolve) =>
  41. canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.85)
  42. );
  43. } finally {
  44. URL.revokeObjectURL(url);
  45. }
  46. }
  47. async function pdfToImageItems(
  48. file: File,
  49. onProgress: (page: number, total: number) => void
  50. ): Promise<MediaItem[]> {
  51. const pdfjs = await import('pdfjs-dist');
  52. // Worker file is copied to /public via the postinstall script
  53. pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';
  54. const arrayBuffer = await file.arrayBuffer();
  55. const pdf = await pdfjs.getDocument({ data: arrayBuffer }).promise;
  56. const baseName = file.name.replace(/\.pdf$/i, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  57. const items: MediaItem[] = [];
  58. for (let i = 1; i <= pdf.numPages; i++) {
  59. onProgress(i, pdf.numPages);
  60. const page = await pdf.getPage(i);
  61. const viewport = page.getViewport({ scale: 1.5 });
  62. const canvas = document.createElement('canvas');
  63. canvas.width = viewport.width;
  64. canvas.height = viewport.height;
  65. const ctx = canvas.getContext('2d');
  66. if (!ctx) continue;
  67. await page.render({ canvasContext: ctx, viewport }).promise;
  68. const blob: Blob = await new Promise((resolve, reject) => {
  69. canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
  70. });
  71. const url = await uploadBlobAsImage(blob, `${baseName}-page${i}.png`);
  72. if (url) items.push({ url });
  73. }
  74. return items;
  75. }
  76. export default function AdminDashboard() {
  77. const [activeTab, setActiveTab] = useState<'cards' | 'settings'>('cards');
  78. // Card State
  79. const [cards, setCards] = useState<Card[]>([]);
  80. const [isEditing, setIsEditing] = useState<Partial<Card> | null>(null);
  81. // Portal State
  82. const [portal, setPortal] = useState<Partial<Portal>>({});
  83. const [savingPortal, setSavingPortal] = useState(false);
  84. const [uploading, setUploading] = useState<{ [key: string]: boolean }>({});
  85. // NEW UI STATES: Toast and Confirm Dialog
  86. const [toast, setToast] = useState<string | null>(null);
  87. const [confirmDialog, setConfirmDialog] = useState<{ message: string, onConfirm: () => void } | null>(null);
  88. const [pdfProgress, setPdfProgress] = useState<{ name: string; page: number; total: number } | null>(null);
  89. // Helper to show auto-dismissing toast
  90. const showToast = (message: string) => {
  91. setToast(message);
  92. setTimeout(() => setToast(null), 3000);
  93. };
  94. useEffect(() => {
  95. fetch('/api/cards').then(res => res.json()).then(setCards);
  96. fetch('/api/portals').then(res => res.json()).then(data => data && setPortal(data));
  97. }, []);
  98. const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: string, isPortal = false) => {
  99. if (!e.target.files?.[0]) return;
  100. setUploading(prev => ({ ...prev, [field]: true }));
  101. const formData = new FormData();
  102. formData.append('file', e.target.files[0]);
  103. const res = await fetch('/api/upload', { method: 'POST', body: formData });
  104. const data = await res.json();
  105. if (data.url) {
  106. if (isPortal) {
  107. setPortal(prev => ({ ...prev, [field]: data.url }));
  108. } else {
  109. setIsEditing(prev => ({ ...prev, [field]: data.url }));
  110. }
  111. }
  112. setUploading(prev => ({ ...prev, [field]: false }));
  113. };
  114. const handleUploadExtraMedia = async (e: React.ChangeEvent<HTMLInputElement>) => {
  115. const files = e.target.files;
  116. if (!files || files.length === 0) return;
  117. setUploading(prev => ({ ...prev, extraMedia: true }));
  118. const startedWithoutCover = !isEditing?.imageUrl;
  119. let pendingCover: string | null = null;
  120. const canPromote = () => startedWithoutCover && !pendingCover;
  121. const uploaded: MediaItem[] = [];
  122. for (const file of Array.from(files)) {
  123. try {
  124. if (isPdfFile(file)) {
  125. const items = await pdfToImageItems(file, (page, total) =>
  126. setPdfProgress({ name: file.name, page, total })
  127. );
  128. setPdfProgress(null);
  129. if (items.length > 0 && canPromote()) {
  130. // Promote the first PDF page to cover; skip it from the gallery to avoid duplication.
  131. pendingCover = items[0].url;
  132. uploaded.push(...items.slice(1));
  133. } else {
  134. uploaded.push(...items);
  135. }
  136. } else {
  137. const formData = new FormData();
  138. formData.append('file', file);
  139. const res = await fetch('/api/upload', { method: 'POST', body: formData });
  140. const data = await res.json();
  141. if (!data.url) continue;
  142. if (isVideoFile(file)) {
  143. // Video always goes to the gallery so users can play it.
  144. uploaded.push({ url: data.url });
  145. // If no cover yet, extract the first frame and use it as the cover.
  146. if (canPromote()) {
  147. try {
  148. const blob = await extractVideoFrame(file);
  149. if (blob) {
  150. const baseName = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  151. const posterUrl = await uploadBlobAsImage(blob, `${baseName}-poster.jpg`);
  152. if (posterUrl) pendingCover = posterUrl;
  153. }
  154. } catch (err) {
  155. console.warn('Could not extract video poster for', file.name, err);
  156. }
  157. }
  158. } else {
  159. // Plain image
  160. if (canPromote()) {
  161. // Promote to cover; skip the gallery to avoid duplication.
  162. pendingCover = data.url;
  163. } else {
  164. uploaded.push({ url: data.url });
  165. }
  166. }
  167. }
  168. } catch (err) {
  169. console.error('Upload failed for', file.name, err);
  170. showToast(`Failed to process "${file.name}".`);
  171. setPdfProgress(null);
  172. }
  173. }
  174. setIsEditing(prev => ({
  175. ...prev,
  176. imageUrl: (startedWithoutCover && pendingCover) ? pendingCover : (prev?.imageUrl || ''),
  177. extraMedia: [...(prev?.extraMedia || []), ...uploaded],
  178. }));
  179. setUploading(prev => ({ ...prev, extraMedia: false }));
  180. e.target.value = '';
  181. };
  182. const removeExtraMedia = (index: number) => {
  183. setIsEditing(prev => ({
  184. ...prev,
  185. extraMedia: (prev?.extraMedia || []).filter((_, i) => i !== index),
  186. }));
  187. };
  188. const toggleAutoplay = (index: number) => {
  189. setIsEditing(prev => ({
  190. ...prev,
  191. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  192. i === index ? { ...m, autoplay: !m.autoplay } : m
  193. ),
  194. }));
  195. };
  196. const toggleMuted = (index: number) => {
  197. setIsEditing(prev => ({
  198. ...prev,
  199. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  200. i === index ? { ...m, muted: !m.muted } : m
  201. ),
  202. }));
  203. };
  204. const handleSaveCard = async () => {
  205. if (!isEditing) return;
  206. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  207. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  208. await fetch('/api/cards', {
  209. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  210. });
  211. setCards(prev => {
  212. const exists = prev.find(c => c.id === newCard.id);
  213. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  214. });
  215. setIsEditing(null);
  216. };
  217. const handleDeleteCard = (id: string) => {
  218. // Replace window.confirm with our custom dialog
  219. setConfirmDialog({
  220. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  221. onConfirm: async () => {
  222. await fetch(`/api/cards?id=${id}`, { method: 'DELETE' });
  223. setCards(prev => prev.filter(c => c.id !== id));
  224. setConfirmDialog(null);
  225. showToast('Card successfully deleted.');
  226. }
  227. });
  228. };
  229. const moveCard = async (index: number, direction: 'up' | 'down') => {
  230. const newCards = [...cards];
  231. if (direction === 'up' && index > 0) {
  232. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  233. } else if (direction === 'down' && index < newCards.length - 1) {
  234. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  235. } else {
  236. return; // Do nothing if trying to move out of bounds
  237. }
  238. // Recalculate displayOrder for the whole array
  239. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  240. // Optimistically update the UI
  241. setCards(updatedCards);
  242. // Persist the new order to the backend
  243. await fetch('/api/cards', {
  244. method: 'PUT',
  245. headers: { 'Content-Type': 'application/json' },
  246. body: JSON.stringify(updatedCards)
  247. });
  248. };
  249. const handleSavePortal = async () => {
  250. setSavingPortal(true);
  251. await fetch('/api/portals', {
  252. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  253. });
  254. setSavingPortal(false);
  255. showToast('Portal settings saved successfully!'); // Replaced window.alert
  256. };
  257. // Shared Input Classes for high contrast
  258. const inputClasses = "w-full border border-gray-300 p-2.5 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900 placeholder-gray-400";
  259. return (
  260. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  261. {/* Top Header */}
  262. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  263. <div className="max-w-5xl mx-auto flex justify-between items-center">
  264. <div>
  265. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  266. <p className="text-sm text-blue-200">Local Administration</p>
  267. </div>
  268. <a href="/" target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  269. View Live Portal ↗
  270. </a>
  271. </div>
  272. </div>
  273. <div className="max-w-5xl mx-auto mt-8 px-4">
  274. {/* Tab Navigation */}
  275. <div className="flex space-x-2 mb-6">
  276. <button onClick={() => setActiveTab('cards')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'cards' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  277. Manage Cards
  278. </button>
  279. <button onClick={() => setActiveTab('settings')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'settings' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  280. Portal Settings
  281. </button>
  282. </div>
  283. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  284. {/* TAB: CARDS */}
  285. {activeTab === 'cards' && (
  286. <div className="p-6 md:p-8">
  287. <div className="flex justify-between items-center mb-8 border-b pb-4">
  288. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  289. <button onClick={() => setIsEditing({ title: '', cardType: 'INFO_PAGE', displayOrder: cards.length })} className="bg-blue-600 text-white px-5 py-2.5 rounded-lg shadow-sm hover:bg-blue-700 font-medium">
  290. + Add New Card
  291. </button>
  292. </div>
  293. <div className="space-y-3 mb-8">
  294. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  295. {cards.map((card, idx) => (
  296. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  297. <div key={card.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 border rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors gap-4">
  298. <div className="flex items-center gap-4">
  299. {(() => {
  300. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  301. if (!previewUrl) {
  302. return <div className="w-16 h-16 bg-gray-200 rounded-md shadow-sm flex items-center justify-center text-gray-400 text-xs shrink-0">No Image</div>;
  303. }
  304. return isVideoUrl(previewUrl)
  305. ? <video src={previewUrl} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" muted playsInline preload="metadata" />
  306. : <img src={previewUrl} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" alt="" />;
  307. })()}
  308. <div>
  309. <span className="font-semibold text-gray-800 block">{card.title}</span>
  310. <span className="text-xs text-gray-500 uppercase tracking-wider">{card.cardType}</span>
  311. </div>
  312. </div>
  313. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  314. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  315. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  316. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  317. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  318. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  319. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  320. </div>
  321. </div>
  322. ))}
  323. </div>
  324. </div>
  325. )}
  326. {/* TAB: SETTINGS */}
  327. {activeTab === 'settings' && (
  328. <div className="p-6 md:p-8">
  329. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  330. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  331. <div className="space-y-6">
  332. <div>
  333. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  334. <input type="text" value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  335. </div>
  336. <div>
  337. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  338. <textarea value={portal.welcomeText || ''} onChange={e => setPortal({...portal, welcomeText: e.target.value})} className={`${inputClasses} h-32 resize-none`} />
  339. </div>
  340. <div className="flex gap-8">
  341. <div>
  342. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  343. <div className="flex items-center gap-4">
  344. <input type="color" value={portal.themeColor || '#1e3a8a'} onChange={e => setPortal({...portal, themeColor: e.target.value})} className="h-12 w-12 rounded cursor-pointer border-0 p-0" />
  345. <span className="text-gray-900 font-mono font-medium">{portal.themeColor || '#1e3a8a'}</span>
  346. </div>
  347. </div>
  348. {/* NEW: Max Columns Setting updated for 3 */}
  349. <div className="flex-1">
  350. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  351. <input
  352. type="range"
  353. min="3"
  354. max="8"
  355. value={portal.maxGridColumns || 5}
  356. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  357. className="w-full mt-3 accent-blue-600"
  358. />
  359. <div className="flex justify-between text-xs text-gray-400 mt-1">
  360. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  361. </div>
  362. </div>
  363. </div>
  364. </div>
  365. <div className="space-y-6">
  366. {/* Logo Upload with Remove Button */}
  367. <div>
  368. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  369. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'logoUrl', true)} className="block w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-gray-100 cursor-pointer" />
  370. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  371. {portal.logoUrl && (
  372. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  373. <img src={portal.logoUrl} className="h-16 object-contain" alt="Logo Preview" />
  374. <button onClick={() => setPortal({...portal, logoUrl: ''})} className="absolute -top-2 -right-2 bg-red-500 text-white w-6 h-6 rounded-full text-xs font-bold hover:bg-red-600 shadow">✕</button>
  375. </div>
  376. )}
  377. </div>
  378. {/* Hero Upload with Remove Button */}
  379. <div>
  380. <label className="block text-sm font-semibold text-gray-700 mb-1">Hero Background Image</label>
  381. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'heroImageUrl', true)} className="block w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-gray-100 cursor-pointer" />
  382. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  383. {portal.heroImageUrl && (
  384. <div className="mt-2 relative rounded shadow border inline-block w-full">
  385. <img src={portal.heroImageUrl} className="h-32 w-full object-cover rounded" alt="Hero Preview" />
  386. <button onClick={() => setPortal({...portal, heroImageUrl: ''})} className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 flex items-center justify-center rounded-full text-sm font-bold hover:bg-red-600 shadow-lg">✕</button>
  387. </div>
  388. )}
  389. </div>
  390. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
  391. <label className="flex items-center gap-3 cursor-pointer">
  392. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  393. <div>
  394. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  395. <span className="block text-xs text-gray-600">Creates a smooth gradient from the top of the image into the solid theme color at the bottom.</span>
  396. </div>
  397. </label>
  398. </div>
  399. </div>
  400. </div>
  401. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  402. <button onClick={handleSavePortal} disabled={savingPortal} className="bg-blue-600 text-white px-10 py-3 rounded-lg hover:bg-blue-700 font-bold shadow disabled:opacity-50 transition-colors">
  403. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  404. </button>
  405. </div>
  406. </div>
  407. )}
  408. </div>
  409. </div>
  410. {/* MODAL FOR EDITING/CREATING CARDS */}
  411. {isEditing && (
  412. <div
  413. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  414. onClick={() => setIsEditing(null)} // Click outside to close
  415. >
  416. <div
  417. className="bg-white rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl p-6 md:p-8 relative animate-in fade-in zoom-in-95 duration-200"
  418. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  419. >
  420. <button
  421. onClick={() => setIsEditing(null)}
  422. className="absolute top-6 right-6 text-gray-400 hover:text-gray-900 bg-gray-100 hover:bg-gray-200 rounded-full w-8 h-8 flex items-center justify-center transition-colors"
  423. >
  424. </button>
  425. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  426. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  427. </h3>
  428. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  429. <div className="space-y-5">
  430. <div>
  431. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  432. <input type="text" value={isEditing.title || ''} onChange={e => setIsEditing({...isEditing, title: e.target.value})} className={inputClasses} placeholder="e.g., Local History" />
  433. </div>
  434. <div>
  435. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  436. <select value={isEditing.cardType || 'INFO_PAGE'} onChange={e => setIsEditing({...isEditing, cardType: e.target.value as any})} className={inputClasses}>
  437. <option value="INFO_PAGE">Info Page</option>
  438. <option value="IMAGE_GALLERY">Image Gallery</option>
  439. <option value="EXTERNAL_LINK">External Link</option>
  440. </select>
  441. </div>
  442. <div>
  443. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  444. <textarea value={isEditing.shortDescription || ''} onChange={e => setIsEditing({...isEditing, shortDescription: e.target.value})} className={`${inputClasses} h-24 resize-none`} placeholder="Brief summary..." />
  445. </div>
  446. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200 space-y-3">
  447. <label className="flex items-start gap-3 cursor-pointer">
  448. <input
  449. type="checkbox"
  450. checked={!!isEditing.autoFullscreen}
  451. onChange={e => setIsEditing({ ...isEditing, autoFullscreen: e.target.checked })}
  452. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  453. />
  454. <div>
  455. <span className="block text-sm font-semibold text-gray-900">Auto fullscreen</span>
  456. <span className="block text-xs text-gray-600">Open the gallery in fullscreen immediately when the user clicks this card.</span>
  457. </div>
  458. </label>
  459. <label className="flex items-start gap-3 cursor-pointer">
  460. <input
  461. type="checkbox"
  462. checked={!!isEditing.skipPreview}
  463. onChange={e => setIsEditing({ ...isEditing, skipPreview: e.target.checked })}
  464. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  465. />
  466. <div>
  467. <span className="block text-sm font-semibold text-gray-900">Skip preview</span>
  468. <span className="block text-xs text-gray-600">Don&rsquo;t show the cover as a slide in the gallery. The cover stays as the card thumbnail only. Combine with &ldquo;Auto fullscreen&rdquo; to jump straight into the gallery items.</span>
  469. </div>
  470. </label>
  471. </div>
  472. </div>
  473. <div className="space-y-5">
  474. {/* Cover Image */}
  475. <div>
  476. <label className="block text-sm font-semibold text-gray-800 mb-1">
  477. Cover Image <span className="text-gray-400 font-normal text-xs">(shown in grid)</span>
  478. </label>
  479. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  480. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'imageUrl')} className="block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer" />
  481. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading...</p>}
  482. </div>
  483. {isEditing.imageUrl && (
  484. <div className="mt-3 relative rounded-lg overflow-hidden border border-gray-200 group">
  485. <img src={isEditing.imageUrl} className="w-full h-32 object-cover" alt="Cover preview" />
  486. <button
  487. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  488. className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 rounded-full text-sm font-bold shadow opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
  489. title="Remove cover image"
  490. >✕</button>
  491. </div>
  492. )}
  493. </div>
  494. {/* Gallery Media (images + videos + PDFs) */}
  495. <div>
  496. <label className="block text-sm font-semibold text-gray-800 mb-1">
  497. Gallery Media <span className="text-gray-400 font-normal text-xs">(images, videos or PDFs — PDF pages become slides)</span>
  498. </label>
  499. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  500. <input
  501. type="file"
  502. accept="image/*,video/*,application/pdf,.pdf"
  503. multiple
  504. onChange={handleUploadExtraMedia}
  505. className="block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100 cursor-pointer"
  506. />
  507. {uploading['extraMedia'] && !pdfProgress && <p className="mt-2 text-sm text-purple-600 font-medium">Uploading...</p>}
  508. {pdfProgress && (
  509. <p className="mt-2 text-sm text-purple-600 font-medium">
  510. Processing &ldquo;{pdfProgress.name}&rdquo;: page {pdfProgress.page} of {pdfProgress.total}
  511. </p>
  512. )}
  513. </div>
  514. {(isEditing.extraMedia || []).length > 0 && (
  515. <div className="mt-3 space-y-2">
  516. {(isEditing.extraMedia || []).map((item, i) => {
  517. const video = isVideoUrl(item.url);
  518. return (
  519. <div key={item.url + i} className="flex items-center gap-3 p-2 bg-gray-50 border border-gray-200 rounded-lg">
  520. <div className="relative w-16 h-16 rounded-md overflow-hidden bg-black shrink-0">
  521. {video ? (
  522. <>
  523. <video src={item.url} className="w-full h-full object-cover" muted preload="metadata" />
  524. <div className="absolute inset-0 flex items-center justify-center bg-black/30 text-white text-xl">▶</div>
  525. </>
  526. ) : (
  527. <img src={item.url} className="w-full h-full object-cover" alt="" />
  528. )}
  529. <span className="absolute bottom-0 left-0 right-0 text-center text-white text-[10px] bg-black/60">{i + 1}</span>
  530. </div>
  531. <div className="flex-1 min-w-0">
  532. <div className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
  533. {video ? 'Video' : 'Image'}
  534. </div>
  535. {video && (
  536. <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
  537. <label className="flex items-center gap-2 cursor-pointer">
  538. <input
  539. type="checkbox"
  540. checked={!!item.autoplay}
  541. onChange={() => toggleAutoplay(i)}
  542. className="w-4 h-4 text-blue-600 rounded"
  543. />
  544. <span className="text-sm text-gray-700">Autoplay</span>
  545. </label>
  546. <label className="flex items-center gap-2 cursor-pointer">
  547. <input
  548. type="checkbox"
  549. checked={!!item.muted}
  550. onChange={() => toggleMuted(i)}
  551. className="w-4 h-4 text-blue-600 rounded"
  552. />
  553. <span className="text-sm text-gray-700">Muted</span>
  554. </label>
  555. </div>
  556. )}
  557. </div>
  558. <button
  559. onClick={() => removeExtraMedia(i)}
  560. className="bg-red-500 hover:bg-red-600 text-white w-8 h-8 rounded-full text-sm font-bold shrink-0"
  561. title="Remove"
  562. >✕</button>
  563. </div>
  564. );
  565. })}
  566. </div>
  567. )}
  568. </div>
  569. </div>
  570. </div>
  571. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  572. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  573. Cancel
  574. </button>
  575. <button onClick={handleSaveCard} className="bg-green-600 text-white px-8 py-2.5 rounded-lg hover:bg-green-700 font-medium shadow-sm transition-colors">
  576. Save Card
  577. </button>
  578. </div>
  579. </div>
  580. </div>
  581. )}
  582. {/* CUSTOM CONFIRM DIALOG */}
  583. {confirmDialog && (
  584. <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
  585. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  586. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  587. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  588. <div className="flex justify-end gap-3">
  589. <button
  590. onClick={() => setConfirmDialog(null)}
  591. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  592. >
  593. Cancel
  594. </button>
  595. <button
  596. onClick={confirmDialog.onConfirm}
  597. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  598. >
  599. Delete
  600. </button>
  601. </div>
  602. </div>
  603. </div>
  604. )}
  605. {/* CUSTOM TOAST NOTIFICATION */}
  606. {toast && (
  607. <div className="fixed bottom-6 right-6 z-[70] bg-gray-900 text-white px-6 py-4 rounded-lg shadow-2xl flex items-center gap-3 animate-in slide-in-from-bottom-5 fade-in duration-300">
  608. <div className="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-gray-900 font-bold text-sm">
  609. </div>
  610. <span className="font-medium">{toast}</span>
  611. </div>
  612. )}
  613. </div>
  614. );
  615. }