Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 

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