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

701 строка
36 KiB

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