You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

777 line
39 KiB

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