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.
 
 

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