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.
 
 

867 regels
44 KiB

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