Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

1284 linhas
65 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, FACTORY_RESET_ENABLED } from '@/lib/config';
  5. import { CARD_LIMITS, PORTAL_LIMITS } from '@/lib/validation';
  6. import { withBasePath } from '@/lib/url';
  7. type CharCounterProps = { value: string | undefined; limit: number };
  8. function CharCounter({ value, limit }: CharCounterProps) {
  9. const len = (value ?? '').length;
  10. if (len < limit * 0.8) return null;
  11. const overflow = len > limit;
  12. return (
  13. <p className={`text-xs mt-1 text-right ${overflow ? 'text-red-600 font-semibold' : 'text-gray-500'}`}>
  14. {len} / {limit}
  15. </p>
  16. );
  17. }
  18. function stripTags(html: string): string {
  19. if (typeof window === 'undefined' || !html) return '';
  20. return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? '';
  21. }
  22. type RichTextMiniProps = {
  23. value: string;
  24. onChange: (html: string) => void;
  25. limit: number;
  26. className?: string;
  27. };
  28. function RichTextMini({ value, onChange, limit, className }: RichTextMiniProps) {
  29. const ref = useRef<HTMLDivElement>(null);
  30. // Sync iniziale soltanto. Aggiornare innerHTML durante l'editing perderebbe la
  31. // posizione del cursore, quindi confidiamo che onInput tenga value e DOM allineati.
  32. useEffect(() => {
  33. if (ref.current && ref.current.innerHTML !== value) {
  34. ref.current.innerHTML = value || '';
  35. }
  36. // eslint-disable-next-line react-hooks/exhaustive-deps
  37. }, []);
  38. const exec = (cmd: 'bold' | 'italic') => {
  39. ref.current?.focus();
  40. document.execCommand(cmd);
  41. onChange(ref.current?.innerHTML || '');
  42. };
  43. return (
  44. <div>
  45. <div className="flex gap-1 mb-1">
  46. <button
  47. type="button"
  48. onClick={() => exec('bold')}
  49. className="font-bold w-8 h-8 border border-gray-300 rounded hover:bg-gray-100"
  50. title="Grassetto"
  51. >B</button>
  52. <button
  53. type="button"
  54. onClick={() => exec('italic')}
  55. className="italic w-8 h-8 border border-gray-300 rounded hover:bg-gray-100"
  56. title="Corsivo"
  57. >I</button>
  58. </div>
  59. <div
  60. ref={ref}
  61. contentEditable
  62. suppressContentEditableWarning
  63. onInput={(e) => onChange((e.target as HTMLDivElement).innerHTML)}
  64. className={className ?? 'w-full border border-gray-300 rounded-lg p-2.5 min-h-[8rem] bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500'}
  65. />
  66. <CharCounter value={stripTags(value)} limit={limit} />
  67. </div>
  68. );
  69. }
  70. function StyledSelect<T extends string>({
  71. value,
  72. onChange,
  73. options,
  74. }: {
  75. value: T;
  76. onChange: (v: T) => void;
  77. options: { value: T; label: string; style?: React.CSSProperties }[];
  78. }) {
  79. const [open, setOpen] = useState(false);
  80. const ref = useRef<HTMLDivElement>(null);
  81. useEffect(() => {
  82. if (!open) return;
  83. const onClick = (e: MouseEvent) => {
  84. if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
  85. };
  86. const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
  87. document.addEventListener('mousedown', onClick);
  88. document.addEventListener('keydown', onKey);
  89. return () => {
  90. document.removeEventListener('mousedown', onClick);
  91. document.removeEventListener('keydown', onKey);
  92. };
  93. }, [open]);
  94. const current = options.find(o => o.value === value);
  95. // Fallback: se il value non matcha nessuna opzione (es. tipo disattivato dalla flag), mostra il valore raw prettificato
  96. const displayLabel = current?.label
  97. ?? (typeof value === 'string' && value.length > 0
  98. ? value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, c => c.toUpperCase())
  99. : '');
  100. 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";
  101. return (
  102. <div ref={ref} className="relative">
  103. <button
  104. type="button"
  105. onClick={() => setOpen(o => !o)}
  106. className={`${inputBase} text-left flex items-center justify-between cursor-pointer`}
  107. >
  108. <span className={displayLabel ? '' : 'text-gray-400'} style={current?.style}>{displayLabel || 'Seleziona…'}</span>
  109. <span className={`text-gray-500 transition-transform ${open ? 'rotate-180' : ''}`}>▾</span>
  110. </button>
  111. {open && (
  112. <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">
  113. {options.map(o => (
  114. <button
  115. key={o.value}
  116. type="button"
  117. onClick={() => { onChange(o.value); setOpen(false); }}
  118. 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'}`}
  119. style={o.style}
  120. >
  121. {o.label}
  122. </button>
  123. ))}
  124. </div>
  125. )}
  126. </div>
  127. );
  128. }
  129. 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';
  130. // Sottoinsieme di formati video davvero riproducibili dai browser moderni
  131. const PLAYBACK_SUPPORTED_VIDEO = 'mp4|m4v|webm|mov|qt|ogv|ogg';
  132. const PLAYBACK_SUPPORTED_LABEL = 'MP4, M4V, WebM, MOV, OGV';
  133. const isVideoUrl = (url: string) => new RegExp(`\\.(${VIDEO_EXTENSIONS})(\\?|$)`, 'i').test(url);
  134. const isPdfFile = (file: File) =>
  135. file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
  136. const isVideoFile = (file: File) =>
  137. file.type.startsWith('video/') || new RegExp(`\\.(${VIDEO_EXTENSIONS})$`, 'i').test(file.name);
  138. const isPlayableVideoFile = (file: File) =>
  139. new RegExp(`\\.(${PLAYBACK_SUPPORTED_VIDEO})$`, 'i').test(file.name);
  140. const previewFontFamily = (filename: string): string =>
  141. `PortalPreview-${filename.replace(/[^A-Za-z0-9]/g, '_')}`;
  142. const fontFormatFromName = (filename: string): string => {
  143. const ext = filename.match(/\.([^.]+)$/)?.[1].toLowerCase() ?? 'woff2';
  144. return ({ woff2: 'woff2', woff: 'woff', ttf: 'truetype', otf: 'opentype' } as Record<string, string>)[ext] ?? 'woff2';
  145. };
  146. const extractFileName = (url: string): string => {
  147. const match = url.match(/[?&]name=([^&]+)/);
  148. if (match) return decodeURIComponent(match[1]);
  149. const seg = url.split('/').pop() || 'download';
  150. return seg.split('?')[0];
  151. };
  152. async function uploadBlobAsImage(blob: Blob, name: string): Promise<string | null> {
  153. const formData = new FormData();
  154. formData.append('file', new File([blob], name, { type: blob.type || 'image/png' }));
  155. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  156. const data = await res.json();
  157. return data.url || null;
  158. }
  159. async function extractVideoFrame(file: File): Promise<Blob | null> {
  160. const url = URL.createObjectURL(file);
  161. try {
  162. const video = document.createElement('video');
  163. video.muted = true;
  164. video.playsInline = true;
  165. video.preload = 'metadata';
  166. video.src = url;
  167. await new Promise<void>((resolve, reject) => {
  168. video.addEventListener('loadedmetadata', () => resolve(), { once: true });
  169. video.addEventListener('error', () => reject(new Error('video load error')), { once: true });
  170. });
  171. // Seek slightly past 0 — at exactly 0 some codecs return a black frame
  172. video.currentTime = Math.min(0.1, Math.max(0, video.duration / 10));
  173. await new Promise<void>((resolve, reject) => {
  174. video.addEventListener('seeked', () => resolve(), { once: true });
  175. video.addEventListener('error', () => reject(new Error('video seek error')), { once: true });
  176. });
  177. const canvas = document.createElement('canvas');
  178. canvas.width = video.videoWidth;
  179. canvas.height = video.videoHeight;
  180. const ctx = canvas.getContext('2d');
  181. if (!ctx) return null;
  182. ctx.drawImage(video, 0, 0);
  183. return await new Promise<Blob | null>((resolve) =>
  184. canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.85)
  185. );
  186. } finally {
  187. URL.revokeObjectURL(url);
  188. }
  189. }
  190. async function pdfToImageItems(
  191. file: File,
  192. onProgress: (page: number, total: number) => void
  193. ): Promise<MediaItem[]> {
  194. const pdfjs = await import('pdfjs-dist');
  195. // Worker file is copied to /public via the postinstall script
  196. pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';
  197. const arrayBuffer = await file.arrayBuffer();
  198. const pdf = await pdfjs.getDocument({ data: arrayBuffer }).promise;
  199. const baseName = file.name.replace(/\.pdf$/i, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  200. const items: MediaItem[] = [];
  201. for (let i = 1; i <= pdf.numPages; i++) {
  202. onProgress(i, pdf.numPages);
  203. const page = await pdf.getPage(i);
  204. const viewport = page.getViewport({ scale: 1.5 });
  205. const canvas = document.createElement('canvas');
  206. canvas.width = viewport.width;
  207. canvas.height = viewport.height;
  208. const ctx = canvas.getContext('2d');
  209. if (!ctx) continue;
  210. await page.render({ canvasContext: ctx, viewport }).promise;
  211. const blob: Blob = await new Promise((resolve, reject) => {
  212. canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
  213. });
  214. const url = await uploadBlobAsImage(blob, `${baseName}-page${i}.png`);
  215. if (url) items.push({ url });
  216. }
  217. return items;
  218. }
  219. export default function AdminDashboard() {
  220. const [activeTab, setActiveTab] = useState<'cards' | 'settings'>('cards');
  221. // Card State
  222. const [cards, setCards] = useState<Card[]>([]);
  223. const [isEditing, setIsEditing] = useState<Partial<Card> | null>(null);
  224. // Portal State
  225. const [portal, setPortal] = useState<Partial<Portal>>({});
  226. const [savingPortal, setSavingPortal] = useState(false);
  227. const [uploading, setUploading] = useState<{ [key: string]: boolean }>({});
  228. // NEW UI STATES: Toast and Confirm Dialog
  229. const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
  230. const [confirmDialog, setConfirmDialog] = useState<{ message: string, onConfirm: () => void } | null>(null);
  231. const [pdfProgress, setPdfProgress] = useState<{ name: string; page: number; total: number } | null>(null);
  232. const [availableFonts, setAvailableFonts] = useState<string[]>([]);
  233. // Map: expected URL of the future-transcoded file → job state.
  234. // We key by URL (not jobId) so the rendering layer can look it up cheaply.
  235. const [transcodeJobs, setTranscodeJobs] = useState<Record<string, { jobId: string; status: string; progress: number }>>({});
  236. // External Link feature flag: priorità al setting del portale, fallback alla costante in lib/config.
  237. const externalLinksOn = portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT;
  238. // Helper to show auto-dismissing toast
  239. const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  240. setToast({ message, type });
  241. setTimeout(() => setToast(null), type === 'error' ? 6000 : 3000);
  242. };
  243. useEffect(() => {
  244. fetch(withBasePath('/api/cards')).then(res => res.json()).then(setCards);
  245. fetch(withBasePath('/api/portals')).then(res => res.json()).then(data => data && setPortal(data));
  246. fetch(withBasePath('/api/fonts')).then(res => res.json()).then(setAvailableFonts).catch(() => setAvailableFonts([]));
  247. }, []);
  248. // Poll pending transcode jobs every 2s. On 'done' we drop the entry from the
  249. // map; on 'failed' we additionally pull the media URL out of the editor so the
  250. // admin doesn't try to save a broken reference.
  251. useEffect(() => {
  252. const pendingEntries = Object.entries(transcodeJobs).filter(
  253. ([, j]) => j.status === 'queued' || j.status === 'running'
  254. );
  255. if (pendingEntries.length === 0) return;
  256. let cancelled = false;
  257. const tick = async () => {
  258. for (const [url, j] of pendingEntries) {
  259. if (cancelled) return;
  260. try {
  261. const res = await fetch(withBasePath(`/api/transcode/${j.jobId}`));
  262. if (!res.ok) continue;
  263. const data = await res.json();
  264. if (cancelled) return;
  265. if (data.status === 'done') {
  266. setTranscodeJobs(prev => {
  267. const next = { ...prev };
  268. delete next[url];
  269. return next;
  270. });
  271. } else if (data.status === 'failed' || data.status === 'cancelled') {
  272. setTranscodeJobs(prev => {
  273. const next = { ...prev };
  274. delete next[url];
  275. return next;
  276. });
  277. setIsEditing(prev => prev ? {
  278. ...prev,
  279. extraMedia: (prev.extraMedia || []).filter(m => m.url !== url),
  280. imageUrl: prev.imageUrl === url ? '' : prev.imageUrl,
  281. } : prev);
  282. const msg = data.status === 'failed'
  283. ? `Trascodifica fallita${data.error ? `: ${String(data.error).split('\n')[0]}` : ''}`
  284. : 'Trascodifica annullata';
  285. showToast(msg, 'error');
  286. } else {
  287. setTranscodeJobs(prev => prev[url] ? ({ ...prev, [url]: { ...prev[url], status: data.status, progress: data.progress ?? 0 } }) : prev);
  288. }
  289. } catch {
  290. // ignore network glitches; will retry next tick
  291. }
  292. }
  293. };
  294. void tick();
  295. const id = window.setInterval(() => { void tick(); }, 2000);
  296. return () => { cancelled = true; window.clearInterval(id); };
  297. // eslint-disable-next-line react-hooks/exhaustive-deps
  298. }, [Object.keys(transcodeJobs).join('|')]);
  299. const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: string, isPortal = false) => {
  300. if (!e.target.files?.[0]) return;
  301. setUploading(prev => ({ ...prev, [field]: true }));
  302. const formData = new FormData();
  303. formData.append('file', e.target.files[0]);
  304. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  305. const data = await res.json();
  306. if (data.url) {
  307. if (isPortal) {
  308. setPortal(prev => ({ ...prev, [field]: data.url }));
  309. } else {
  310. setIsEditing(prev => ({ ...prev, [field]: data.url }));
  311. }
  312. }
  313. setUploading(prev => ({ ...prev, [field]: false }));
  314. };
  315. const handleUploadExtraMedia = async (e: React.ChangeEvent<HTMLInputElement>) => {
  316. const files = e.target.files;
  317. if (!files || files.length === 0) return;
  318. setUploading(prev => ({ ...prev, extraMedia: true }));
  319. const startedWithoutCover = !isEditing?.imageUrl;
  320. let pendingCover: string | null = null;
  321. const canPromote = () => startedWithoutCover && !pendingCover;
  322. // Pre-filtro: scarta video con formati non riproducibili nei browser
  323. const rejected: string[] = [];
  324. const acceptedFiles: File[] = [];
  325. for (const file of Array.from(files)) {
  326. if (isVideoFile(file) && !isPlayableVideoFile(file)) {
  327. rejected.push(file.name);
  328. } else {
  329. acceptedFiles.push(file);
  330. }
  331. }
  332. if (rejected.length > 0) {
  333. const list = rejected.length <= 3
  334. ? rejected.join(', ')
  335. : `${rejected.slice(0, 3).join(', ')} e altri ${rejected.length - 3}`;
  336. showToast(
  337. `Formato non supportato! I formati supportati sono: ${PLAYBACK_SUPPORTED_LABEL}. File ignorati: ${list}`,
  338. 'error'
  339. );
  340. }
  341. if (acceptedFiles.length === 0) {
  342. setUploading(prev => ({ ...prev, extraMedia: false }));
  343. e.target.value = '';
  344. return;
  345. }
  346. const uploaded: MediaItem[] = [];
  347. for (const file of acceptedFiles) {
  348. try {
  349. if (isPdfFile(file)) {
  350. const items = await pdfToImageItems(file, (page, total) =>
  351. setPdfProgress({ name: file.name, page, total })
  352. );
  353. setPdfProgress(null);
  354. if (items.length > 0 && canPromote()) {
  355. // Promote the first PDF page to cover; skip it from the gallery to avoid duplication.
  356. pendingCover = items[0].url;
  357. uploaded.push(...items.slice(1));
  358. } else {
  359. uploaded.push(...items);
  360. }
  361. } else {
  362. const formData = new FormData();
  363. formData.append('file', file);
  364. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  365. const data = await res.json();
  366. if (!data.url) continue;
  367. if (data?.transcoding?.jobId) {
  368. const { jobId, status } = data.transcoding;
  369. setTranscodeJobs(prev => ({ ...prev, [data.url]: { jobId, status, progress: 0 } }));
  370. }
  371. if (isVideoFile(file)) {
  372. // Video always goes to the gallery so users can play it.
  373. uploaded.push({ url: data.url });
  374. // If no cover yet, extract the first frame and use it as the cover.
  375. if (canPromote()) {
  376. try {
  377. const blob = await extractVideoFrame(file);
  378. if (blob) {
  379. const baseName = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  380. const posterUrl = await uploadBlobAsImage(blob, `${baseName}-poster.jpg`);
  381. if (posterUrl) pendingCover = posterUrl;
  382. }
  383. } catch (err) {
  384. console.warn('Could not extract video poster for', file.name, err);
  385. }
  386. }
  387. } else {
  388. // Plain image
  389. if (canPromote()) {
  390. // Promote to cover; skip the gallery to avoid duplication.
  391. pendingCover = data.url;
  392. } else {
  393. uploaded.push({ url: data.url });
  394. }
  395. }
  396. }
  397. } catch (err) {
  398. console.error('Upload failed for', file.name, err);
  399. showToast(`Failed to process "${file.name}".`);
  400. setPdfProgress(null);
  401. }
  402. }
  403. setIsEditing(prev => ({
  404. ...prev,
  405. imageUrl: (startedWithoutCover && pendingCover) ? pendingCover : (prev?.imageUrl || ''),
  406. extraMedia: [...(prev?.extraMedia || []), ...uploaded],
  407. }));
  408. setUploading(prev => ({ ...prev, extraMedia: false }));
  409. e.target.value = '';
  410. };
  411. const removeExtraMedia = (index: number) => {
  412. setIsEditing(prev => ({
  413. ...prev,
  414. extraMedia: (prev?.extraMedia || []).filter((_, i) => i !== index),
  415. }));
  416. };
  417. const moveExtraMedia = (index: number, direction: 'up' | 'down') => {
  418. setIsEditing(prev => {
  419. const items = [...(prev?.extraMedia || [])];
  420. if (direction === 'up' && index > 0) {
  421. [items[index - 1], items[index]] = [items[index], items[index - 1]];
  422. } else if (direction === 'down' && index < items.length - 1) {
  423. [items[index + 1], items[index]] = [items[index], items[index + 1]];
  424. } else {
  425. return prev;
  426. }
  427. return { ...prev, extraMedia: items };
  428. });
  429. };
  430. const toggleAutoplay = (index: number) => {
  431. setIsEditing(prev => ({
  432. ...prev,
  433. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  434. i === index ? { ...m, autoplay: !m.autoplay } : m
  435. ),
  436. }));
  437. };
  438. const toggleMuted = (index: number) => {
  439. setIsEditing(prev => ({
  440. ...prev,
  441. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  442. i === index ? { ...m, muted: !m.muted } : m
  443. ),
  444. }));
  445. };
  446. const handleSaveCard = async () => {
  447. if (!isEditing) return;
  448. // External Link: URL obbligatorio (feedback immediato, ribadito anche lato server)
  449. if (isEditing.cardType === 'EXTERNAL_LINK' && !isEditing.actionUrl?.trim()) {
  450. showToast("L'URL è obbligatorio per le card External Link", 'error');
  451. return;
  452. }
  453. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  454. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  455. const res = await fetch(withBasePath('/api/cards'), {
  456. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  457. });
  458. if (!res.ok) {
  459. let message = 'Errore di salvataggio';
  460. try {
  461. const body = await res.json();
  462. if (res.status === 400 && Array.isArray(body?.errors) && body.errors.length > 0) {
  463. const first = body.errors[0];
  464. message = first.limit != null
  465. ? `${first.field}: ${first.message} (${first.actual} / ${first.limit})`
  466. : `${first.field}: ${first.message}`;
  467. } else if (body?.error) {
  468. message = body.error;
  469. }
  470. } catch {}
  471. showToast(message, 'error');
  472. return; // keep the editor open so the admin can fix
  473. }
  474. setCards(prev => {
  475. const exists = prev.find(c => c.id === newCard.id);
  476. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  477. });
  478. setIsEditing(null);
  479. };
  480. const handleDeleteCard = (id: string) => {
  481. // Replace window.confirm with our custom dialog
  482. setConfirmDialog({
  483. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  484. onConfirm: async () => {
  485. await fetch(withBasePath(`/api/cards?id=${id}`), { method: 'DELETE' });
  486. setCards(prev => prev.filter(c => c.id !== id));
  487. setConfirmDialog(null);
  488. showToast('Card successfully deleted.');
  489. }
  490. });
  491. };
  492. const moveCard = async (index: number, direction: 'up' | 'down') => {
  493. const newCards = [...cards];
  494. if (direction === 'up' && index > 0) {
  495. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  496. } else if (direction === 'down' && index < newCards.length - 1) {
  497. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  498. } else {
  499. return; // Do nothing if trying to move out of bounds
  500. }
  501. // Recalculate displayOrder for the whole array
  502. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  503. // Optimistically update the UI
  504. setCards(updatedCards);
  505. // Persist the new order to the backend
  506. await fetch(withBasePath('/api/cards'), {
  507. method: 'PUT',
  508. headers: { 'Content-Type': 'application/json' },
  509. body: JSON.stringify(updatedCards)
  510. });
  511. };
  512. const handleSavePortal = async () => {
  513. setSavingPortal(true);
  514. await fetch(withBasePath('/api/portals'), {
  515. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  516. });
  517. setSavingPortal(false);
  518. showToast('Portal settings saved successfully!'); // Replaced window.alert
  519. };
  520. const handleBackupDownload = () => {
  521. window.location.href = withBasePath('/api/admin/backup');
  522. };
  523. const [restoring, setRestoring] = useState(false);
  524. const handleRestoreUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  525. const file = e.target.files?.[0];
  526. e.target.value = '';
  527. if (!file) return;
  528. if (!window.confirm('Il ripristino sovrascriverà tutti i dati attuali (card, portale, media, font). Continuare?')) return;
  529. setRestoring(true);
  530. try {
  531. const fd = new FormData();
  532. fd.append('file', file);
  533. const res = await fetch(withBasePath('/api/admin/restore'), { method: 'POST', body: fd });
  534. const data = await res.json().catch(() => ({}));
  535. if (!res.ok) {
  536. showToast(data?.error || `Errore ripristino (${res.status})`, 'error');
  537. return;
  538. }
  539. showToast(`Ripristino completato: ${data.restored?.cards ?? 0} card, ${data.restored?.portals ?? 0} portali. Ricarico…`);
  540. setTimeout(() => window.location.reload(), 1200);
  541. } catch (err) {
  542. showToast(`Errore di rete: ${(err as Error).message}`, 'error');
  543. } finally {
  544. setRestoring(false);
  545. }
  546. };
  547. // Factory preset (developer): UI visibile solo se FACTORY_RESET_ENABLED.
  548. const [factoryPreset, setFactoryPreset] = useState<{ exists: boolean; sizeBytes?: number; modifiedAt?: string } | null>(null);
  549. const [savingPreset, setSavingPreset] = useState(false);
  550. const [factoryResetting, setFactoryResetting] = useState(false);
  551. const refreshFactoryPreset = async () => {
  552. try {
  553. const res = await fetch(withBasePath('/api/admin/factory-preset'));
  554. if (res.ok) setFactoryPreset(await res.json());
  555. } catch { /* ignore */ }
  556. };
  557. useEffect(() => {
  558. if (FACTORY_RESET_ENABLED) void refreshFactoryPreset();
  559. }, []);
  560. const handleSaveFactoryPreset = async () => {
  561. const msg = factoryPreset?.exists
  562. ? 'Sovrascrivere il factory preset esistente con lo stato attuale?'
  563. : 'Salvare lo stato attuale come factory preset?';
  564. if (!window.confirm(msg)) return;
  565. setSavingPreset(true);
  566. try {
  567. const res = await fetch(withBasePath('/api/admin/factory-preset'), { method: 'POST' });
  568. const data = await res.json().catch(() => ({}));
  569. if (!res.ok) {
  570. showToast(data?.error || `Errore (${res.status})`, 'error');
  571. return;
  572. }
  573. showToast('Factory preset aggiornato.');
  574. await refreshFactoryPreset();
  575. } catch (err) {
  576. showToast(`Errore di rete: ${(err as Error).message}`, 'error');
  577. } finally {
  578. setSavingPreset(false);
  579. }
  580. };
  581. const handleFactoryReset = async () => {
  582. if (!window.confirm('FACTORY RESET — tutti i dati attuali verranno sostituiti col factory preset. Continuare?')) return;
  583. setFactoryResetting(true);
  584. try {
  585. const res = await fetch(withBasePath('/api/admin/factory-reset'), { method: 'POST' });
  586. const data = await res.json().catch(() => ({}));
  587. if (!res.ok) {
  588. showToast(data?.error || `Errore (${res.status})`, 'error');
  589. return;
  590. }
  591. showToast(`Factory reset eseguito: ${data.restored?.cards ?? 0} card, ${data.restored?.portals ?? 0} portali. Ricarico…`);
  592. setTimeout(() => window.location.reload(), 1200);
  593. } catch (err) {
  594. showToast(`Errore di rete: ${(err as Error).message}`, 'error');
  595. } finally {
  596. setFactoryResetting(false);
  597. }
  598. };
  599. // Shared Input Classes for high contrast
  600. 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";
  601. return (
  602. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  603. {/* Top Header */}
  604. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  605. <div className="max-w-5xl mx-auto flex justify-between items-center">
  606. <div>
  607. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  608. <p className="text-sm text-blue-200">Local Administration</p>
  609. </div>
  610. <a href={withBasePath('/')} target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  611. View Live Portal ↗
  612. </a>
  613. </div>
  614. </div>
  615. <div className="max-w-5xl mx-auto mt-8 px-4">
  616. {/* Tab Navigation */}
  617. <div className="flex space-x-2 mb-6">
  618. <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'}`}>
  619. Manage Cards
  620. </button>
  621. <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'}`}>
  622. Portal Settings
  623. </button>
  624. </div>
  625. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  626. {/* TAB: CARDS */}
  627. {activeTab === 'cards' && (
  628. <div className="p-6 md:p-8">
  629. <div className="flex justify-between items-center mb-8 border-b pb-4">
  630. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  631. <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">
  632. + Add New Card
  633. </button>
  634. </div>
  635. <div className="space-y-3 mb-8">
  636. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  637. {cards.map((card, idx) => (
  638. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  639. <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">
  640. <div className="flex items-center gap-4">
  641. {(() => {
  642. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  643. if (!previewUrl) {
  644. 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>;
  645. }
  646. return isVideoUrl(previewUrl)
  647. ? <video src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" muted playsInline preload="metadata" />
  648. : <img src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" alt="" />;
  649. })()}
  650. <div>
  651. <span className="font-semibold text-gray-800 block">{card.title}</span>
  652. <span className="text-xs text-gray-500 uppercase tracking-wider">
  653. {card.cardType}
  654. {card.extraMedia && card.extraMedia.length > 0 && (
  655. <span className="text-gray-400 normal-case tracking-normal ml-2">[{card.extraMedia.length}]</span>
  656. )}
  657. {card.cardType === 'FULLSCREEN_LOCK' && (
  658. <span className="ml-2 bg-red-100 text-red-700 px-2 py-0.5 rounded font-bold text-[10px] tracking-wider">LOCK ATTIVA</span>
  659. )}
  660. </span>
  661. </div>
  662. </div>
  663. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  664. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  665. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  666. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  667. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  668. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  669. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  670. </div>
  671. </div>
  672. ))}
  673. </div>
  674. </div>
  675. )}
  676. {/* TAB: SETTINGS */}
  677. {activeTab === 'settings' && (
  678. <div className="p-6 md:p-8">
  679. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  680. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  681. <div className="space-y-6">
  682. <div>
  683. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  684. <input type="text" maxLength={PORTAL_LIMITS.title} value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  685. <CharCounter value={portal.title} limit={PORTAL_LIMITS.title} />
  686. </div>
  687. <div>
  688. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  689. <RichTextMini
  690. value={portal.welcomeText || ''}
  691. onChange={html => setPortal({ ...portal, welcomeText: html })}
  692. limit={PORTAL_LIMITS.welcomeText}
  693. />
  694. </div>
  695. <div className="flex gap-8">
  696. <div>
  697. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  698. <div className="flex items-center gap-4">
  699. <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" />
  700. <span className="text-gray-900 font-mono font-medium">{portal.themeColor || '#1e3a8a'}</span>
  701. </div>
  702. </div>
  703. {/* NEW: Max Columns Setting updated for 3 */}
  704. <div className="flex-1">
  705. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  706. <input
  707. type="range"
  708. min="3"
  709. max="8"
  710. value={portal.maxGridColumns || 5}
  711. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  712. className="w-full mt-3 accent-blue-600"
  713. />
  714. <div className="flex justify-between text-xs text-gray-400 mt-1">
  715. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  716. </div>
  717. </div>
  718. </div>
  719. <div>
  720. <label className="block text-sm font-semibold text-gray-700 mb-1">Font del portale</label>
  721. <style dangerouslySetInnerHTML={{ __html: availableFonts.map(f => `
  722. @font-face {
  723. font-family: '${previewFontFamily(f)}';
  724. src: url('${withBasePath('/api/fonts?name=' + encodeURIComponent(f))}') format('${fontFormatFromName(f)}');
  725. font-display: swap;
  726. }`).join('') }} />
  727. <StyledSelect<string>
  728. value={portal.fontFamily ?? ''}
  729. onChange={(v) => setPortal({ ...portal, fontFamily: v })}
  730. options={[
  731. { value: '', label: 'Sistema (Arial)' },
  732. ...availableFonts.map(f => ({
  733. value: f,
  734. label: f.replace(/\.(woff2?|ttf|otf)$/i, ''),
  735. style: { fontFamily: `'${previewFontFamily(f)}', Arial, Helvetica, sans-serif` },
  736. })),
  737. ]}
  738. />
  739. </div>
  740. </div>
  741. <div className="space-y-6">
  742. {/* Logo Upload with Remove Button */}
  743. <div>
  744. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  745. <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" />
  746. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  747. {portal.logoUrl && (
  748. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  749. <img src={withBasePath(portal.logoUrl)} className="h-16 object-contain" alt="Logo Preview" />
  750. <a href={withBasePath(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>
  751. <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>
  752. </div>
  753. )}
  754. </div>
  755. {/* Hero Upload with Remove Button */}
  756. <div>
  757. <label className="block text-sm font-semibold text-gray-700 mb-1">Hero Background Image</label>
  758. <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" />
  759. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  760. {portal.heroImageUrl && (
  761. <div className="mt-2 relative rounded shadow border inline-block w-full">
  762. <img src={withBasePath(portal.heroImageUrl)} className="h-32 w-full object-cover rounded" alt="Hero Preview" />
  763. <a href={withBasePath(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>
  764. <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>
  765. </div>
  766. )}
  767. </div>
  768. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 space-y-3">
  769. <label className="flex items-center gap-3 cursor-pointer">
  770. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  771. <div>
  772. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  773. <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>
  774. </div>
  775. </label>
  776. <label className="flex items-center gap-3 cursor-pointer">
  777. <input
  778. type="checkbox"
  779. checked={portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT}
  780. onChange={e => setPortal({...portal, externalLinkEnabled: e.target.checked})}
  781. className="w-5 h-5 text-blue-600 rounded"
  782. />
  783. <div>
  784. <span className="block text-sm font-semibold text-gray-900">Abilita &ldquo;External Link&rdquo;</span>
  785. <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>
  786. </div>
  787. </label>
  788. </div>
  789. </div>
  790. </div>
  791. <div className="mt-10 pt-6 border-t border-gray-200">
  792. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Backup &amp; Restore</h3>
  793. <p className="text-xs text-gray-500 mb-4">
  794. Il backup contiene card, configurazione portale, media (immagini, video, PDF) e font caricati. Il ripristino sovrascrive lo stato attuale; la cartella precedente viene conservata come <code>data.bak-&lt;timestamp&gt;</code> per sicurezza.
  795. </p>
  796. <div className="flex flex-wrap gap-3">
  797. <button
  798. type="button"
  799. onClick={handleBackupDownload}
  800. className="bg-gray-800 text-white px-5 py-2.5 rounded-lg hover:bg-gray-900 font-medium shadow-sm"
  801. >
  802. ⬇ Scarica backup ZIP
  803. </button>
  804. <label className={`cursor-pointer inline-flex items-center bg-amber-600 text-white px-5 py-2.5 rounded-lg hover:bg-amber-700 font-medium shadow-sm ${restoring ? 'opacity-60 cursor-not-allowed' : ''}`}>
  805. <input
  806. type="file"
  807. accept=".zip,application/zip,application/x-zip-compressed"
  808. onChange={handleRestoreUpload}
  809. disabled={restoring}
  810. hidden
  811. />
  812. {restoring ? 'Ripristino in corso…' : '⤴ Ripristina da ZIP…'}
  813. </label>
  814. </div>
  815. </div>
  816. {FACTORY_RESET_ENABLED && (
  817. <div className="mt-8 pt-6 border-t border-gray-200">
  818. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Factory Preset <span className="text-[10px] bg-gray-200 text-gray-600 px-1.5 py-0.5 rounded ml-1 tracking-normal">developer</span></h3>
  819. <p className="text-xs text-gray-500 mb-2">
  820. Stato &ldquo;di fabbrica&rdquo; sempre ripristinabile con un click. Utile per preparare preset standard da distribuire alle macchine MajorNet:
  821. configura il portale come vuoi, salvalo come preset, poi copia <code>factory/preset.zip</code> sulle altre macchine.
  822. </p>
  823. <p className="text-xs text-gray-700 mb-4">
  824. Preset attuale: {factoryPreset === null ? '…'
  825. : factoryPreset.exists
  826. ? <span className="text-green-700 font-medium">presente · {((factoryPreset.sizeBytes ?? 0) / (1024 * 1024)).toFixed(1)} MB · {factoryPreset.modifiedAt ? new Date(factoryPreset.modifiedAt).toLocaleString('it-IT') : '?'}</span>
  827. : <span className="text-gray-400 italic">nessun preset configurato</span>}
  828. </p>
  829. <div className="flex flex-wrap gap-3">
  830. <button
  831. type="button"
  832. onClick={handleSaveFactoryPreset}
  833. disabled={savingPreset}
  834. className="bg-emerald-700 text-white px-5 py-2.5 rounded-lg hover:bg-emerald-800 font-medium shadow-sm disabled:opacity-60"
  835. >
  836. {savingPreset ? 'Salvataggio…' : '💾 Salva stato attuale come Factory Preset'}
  837. </button>
  838. <button
  839. type="button"
  840. onClick={handleFactoryReset}
  841. disabled={factoryResetting || !factoryPreset?.exists}
  842. title={factoryPreset?.exists ? undefined : 'Nessun preset configurato'}
  843. className="bg-red-700 text-white px-5 py-2.5 rounded-lg hover:bg-red-800 font-medium shadow-sm disabled:opacity-60 disabled:cursor-not-allowed"
  844. >
  845. {factoryResetting ? 'Reset in corso…' : '🏭 Factory Reset'}
  846. </button>
  847. </div>
  848. </div>
  849. )}
  850. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  851. <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">
  852. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  853. </button>
  854. </div>
  855. </div>
  856. )}
  857. </div>
  858. </div>
  859. {/* MODAL FOR EDITING/CREATING CARDS */}
  860. {isEditing && (
  861. <div
  862. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  863. onClick={() => setIsEditing(null)} // Click outside to close
  864. >
  865. <div
  866. 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"
  867. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  868. >
  869. <button
  870. onClick={() => setIsEditing(null)}
  871. 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"
  872. >
  873. </button>
  874. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  875. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  876. </h3>
  877. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  878. <div className="space-y-5">
  879. <div>
  880. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  881. <input type="text" maxLength={CARD_LIMITS.title} value={isEditing.title || ''} onChange={e => setIsEditing({...isEditing, title: e.target.value})} className={inputClasses} placeholder="e.g., Local History" />
  882. <CharCounter value={isEditing.title} limit={CARD_LIMITS.title} />
  883. </div>
  884. <div>
  885. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  886. <StyledSelect<CardType>
  887. value={(isEditing.cardType || 'INFO_PAGE') as CardType}
  888. onChange={(v) => setIsEditing({ ...isEditing, cardType: v })}
  889. options={[
  890. { value: 'INFO_PAGE', label: 'Info Page' },
  891. { value: 'IMAGE_GALLERY', label: 'Image Gallery' },
  892. { value: 'BOOK', label: 'Flip-Book' },
  893. { value: 'FULLSCREEN_LOCK', label: 'Fullscreen Lock (kiosk)' },
  894. ...(externalLinksOn ? [{ value: 'EXTERNAL_LINK' as CardType, label: 'External Link' }] : []),
  895. ]}
  896. />
  897. </div>
  898. {isEditing.cardType === 'FULLSCREEN_LOCK' && (
  899. <div className="bg-red-50 border border-red-200 rounded-lg p-4">
  900. <p className="text-sm font-semibold text-red-800">⚠ Modalità Kiosk Lock</p>
  901. <p className="text-xs text-red-700 mt-1">
  902. Questa card prenderà il controllo totale del portale pubblico. Tutte le altre card saranno nascoste finché non rimuovi questa.
  903. Carica un&apos;immagine o un video come &quot;Contenuto a schermo intero&quot; nella sezione a destra.
  904. </p>
  905. </div>
  906. )}
  907. {isEditing.cardType !== 'FULLSCREEN_LOCK' && (isEditing.cardType === 'EXTERNAL_LINK' ? (
  908. <>
  909. <div>
  910. <label className="block text-sm font-semibold text-gray-800 mb-1">URL <span className="text-red-600">*</span></label>
  911. <input
  912. type="url"
  913. maxLength={CARD_LIMITS.actionUrl}
  914. value={isEditing.actionUrl || ''}
  915. onChange={e => setIsEditing({ ...isEditing, actionUrl: e.target.value })}
  916. className={inputClasses}
  917. placeholder="https://esempio.it/pagina"
  918. />
  919. <CharCounter value={isEditing.actionUrl} limit={CARD_LIMITS.actionUrl} />
  920. </div>
  921. <div>
  922. <label className="block text-sm font-semibold text-gray-800 mb-1">Testo del link</label>
  923. <input
  924. type="text"
  925. maxLength={CARD_LIMITS.shortDescription}
  926. value={isEditing.shortDescription || ''}
  927. onChange={e => setIsEditing({ ...isEditing, shortDescription: e.target.value })}
  928. className={inputClasses}
  929. placeholder="es. Visita il sito ufficiale"
  930. />
  931. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  932. <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>
  933. </div>
  934. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200">
  935. <label className="flex items-start gap-3 cursor-pointer">
  936. <input
  937. type="checkbox"
  938. checked={!!isEditing.redirectOnClick}
  939. onChange={e => setIsEditing({ ...isEditing, redirectOnClick: e.target.checked })}
  940. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  941. />
  942. <div>
  943. <span className="block text-sm font-semibold text-gray-900">Redirect on click</span>
  944. <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>
  945. </div>
  946. </label>
  947. </div>
  948. </>
  949. ) : (
  950. <div>
  951. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  952. <textarea maxLength={CARD_LIMITS.shortDescription} value={isEditing.shortDescription || ''} onChange={e => setIsEditing({ ...isEditing, shortDescription: e.target.value })} className={`${inputClasses} h-24 resize-none`} placeholder="Brief summary..." />
  953. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  954. </div>
  955. ))}
  956. {isEditing.cardType !== 'BOOK' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  957. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200 space-y-3">
  958. <label className="flex items-start gap-3 cursor-pointer">
  959. <input
  960. type="checkbox"
  961. checked={!!isEditing.autoFullscreen}
  962. onChange={e => setIsEditing({ ...isEditing, autoFullscreen: e.target.checked })}
  963. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  964. />
  965. <div>
  966. <span className="block text-sm font-semibold text-gray-900">Auto fullscreen</span>
  967. <span className="block text-xs text-gray-600">Open the gallery in fullscreen immediately when the user clicks this card.</span>
  968. </div>
  969. </label>
  970. <label className="flex items-start gap-3 cursor-pointer">
  971. <input
  972. type="checkbox"
  973. checked={!!isEditing.skipPreview}
  974. onChange={e => setIsEditing({ ...isEditing, skipPreview: e.target.checked })}
  975. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  976. />
  977. <div>
  978. <span className="block text-sm font-semibold text-gray-900">Cover not in the gallery</span>
  979. <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>
  980. </div>
  981. </label>
  982. </div>
  983. )}
  984. </div>
  985. <div className="space-y-5">
  986. {/* Cover Image — per FULLSCREEN_LOCK è il contenuto kiosk a tutto schermo e accetta anche video */}
  987. <div>
  988. <label className="block text-sm font-semibold text-gray-800 mb-1">
  989. {isEditing.cardType === 'FULLSCREEN_LOCK'
  990. ? <>Contenuto a schermo intero <span className="text-gray-400 font-normal text-xs">(immagine o video)</span></>
  991. : <>Cover Image <span className="text-gray-400 font-normal text-xs">(shown in grid)</span></>}
  992. </label>
  993. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  994. <input
  995. type="file"
  996. accept={isEditing.cardType === 'FULLSCREEN_LOCK' ? 'image/*,video/mp4,video/webm,.mp4,.webm,.mov,.m4v' : 'image/*'}
  997. onChange={e => handleUpload(e, 'imageUrl')}
  998. 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"
  999. />
  1000. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading...</p>}
  1001. </div>
  1002. {isEditing.imageUrl && (
  1003. <div className="mt-3 relative rounded-lg overflow-hidden border border-gray-200 group">
  1004. {isVideoUrl(isEditing.imageUrl) ? (
  1005. <video src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" muted playsInline />
  1006. ) : (
  1007. <img src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" alt="Cover preview" />
  1008. )}
  1009. <a
  1010. href={withBasePath(isEditing.imageUrl)}
  1011. download={extractFileName(isEditing.imageUrl)}
  1012. 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"
  1013. title="Scarica"
  1014. aria-label="Scarica cover"
  1015. >⬇</a>
  1016. <button
  1017. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  1018. 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"
  1019. title="Remove cover image"
  1020. >✕</button>
  1021. </div>
  1022. )}
  1023. </div>
  1024. {/* Gallery Media (images + videos + PDFs) — nascosta per INFO_PAGE (solo cover ammessa) e FULLSCREEN_LOCK (solo contenuto kiosk) */}
  1025. {isEditing.cardType !== 'INFO_PAGE' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  1026. <div>
  1027. <label className="block text-sm font-semibold text-gray-800 mb-1">
  1028. Gallery Media <span className="text-gray-400 font-normal text-xs">(images, videos or PDFs — PDF pages become images)</span>
  1029. </label>
  1030. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  1031. <input
  1032. type="file"
  1033. 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"
  1034. multiple
  1035. onChange={handleUploadExtraMedia}
  1036. 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"
  1037. />
  1038. {uploading['extraMedia'] && !pdfProgress && <p className="mt-2 text-sm text-purple-600 font-medium">Uploading...</p>}
  1039. {pdfProgress && (
  1040. <p className="mt-2 text-sm text-purple-600 font-medium">
  1041. Processing &ldquo;{pdfProgress.name}&rdquo;: page {pdfProgress.page} of {pdfProgress.total}
  1042. </p>
  1043. )}
  1044. </div>
  1045. {(isEditing.extraMedia || []).length > 0 && (
  1046. <div className="mt-3 space-y-2">
  1047. {(isEditing.extraMedia || []).map((item, i) => {
  1048. const video = isVideoUrl(item.url);
  1049. const tc = transcodeJobs[item.url];
  1050. const isTranscoding = !!tc && (tc.status === 'queued' || tc.status === 'running');
  1051. return (
  1052. <div key={item.url + i} className="flex items-center gap-3 p-2 bg-gray-50 border border-gray-200 rounded-lg">
  1053. <div className="relative w-16 h-16 rounded-md overflow-hidden bg-black shrink-0">
  1054. {video ? (
  1055. <>
  1056. <video src={withBasePath(item.url)} className="w-full h-full object-cover" muted preload="metadata" />
  1057. <div className="absolute inset-0 flex items-center justify-center bg-black/30 text-white text-xl">▶</div>
  1058. </>
  1059. ) : (
  1060. <img src={withBasePath(item.url)} className="w-full h-full object-cover" alt="" />
  1061. )}
  1062. {isTranscoding && (
  1063. <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/75 text-white text-[10px] font-semibold leading-tight gap-0.5">
  1064. <span>Transcoding</span>
  1065. <span>{Math.round((tc.progress || 0) * 100)}%</span>
  1066. </div>
  1067. )}
  1068. <span className="absolute bottom-0 left-0 right-0 text-center text-white text-[10px] bg-black/60">{i + 1}</span>
  1069. </div>
  1070. <div className="flex-1 min-w-0">
  1071. <div className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
  1072. {video ? 'Video' : 'Image'}
  1073. </div>
  1074. {video && (
  1075. <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
  1076. <label className="flex items-center gap-2 cursor-pointer">
  1077. <input
  1078. type="checkbox"
  1079. checked={!!item.autoplay}
  1080. onChange={() => toggleAutoplay(i)}
  1081. className="w-4 h-4 text-blue-600 rounded"
  1082. />
  1083. <span className="text-sm text-gray-700">Autoplay</span>
  1084. </label>
  1085. <label className="flex items-center gap-2 cursor-pointer">
  1086. <input
  1087. type="checkbox"
  1088. checked={!!item.muted}
  1089. onChange={() => toggleMuted(i)}
  1090. className="w-4 h-4 text-blue-600 rounded"
  1091. />
  1092. <span className="text-sm text-gray-700">Muted</span>
  1093. </label>
  1094. </div>
  1095. )}
  1096. </div>
  1097. <button
  1098. onClick={() => moveExtraMedia(i, 'up')}
  1099. 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"
  1100. title="Sposta su"
  1101. aria-label="Sposta su"
  1102. disabled={i === 0}
  1103. >↑</button>
  1104. <button
  1105. onClick={() => moveExtraMedia(i, 'down')}
  1106. 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"
  1107. title="Sposta giù"
  1108. aria-label="Sposta giù"
  1109. disabled={i === (isEditing.extraMedia || []).length - 1}
  1110. >↓</button>
  1111. <a
  1112. href={withBasePath(item.url)}
  1113. download={extractFileName(item.url)}
  1114. 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"
  1115. title="Scarica"
  1116. aria-label="Scarica"
  1117. >⬇</a>
  1118. <button
  1119. onClick={() => removeExtraMedia(i)}
  1120. className="bg-red-500 hover:bg-red-600 text-white w-8 h-8 rounded-full text-sm font-bold shrink-0"
  1121. title="Remove"
  1122. >✕</button>
  1123. </div>
  1124. );
  1125. })}
  1126. </div>
  1127. )}
  1128. </div>
  1129. )}
  1130. </div>
  1131. </div>
  1132. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  1133. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  1134. Cancel
  1135. </button>
  1136. <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">
  1137. Save Card
  1138. </button>
  1139. </div>
  1140. </div>
  1141. </div>
  1142. )}
  1143. {/* CUSTOM CONFIRM DIALOG */}
  1144. {confirmDialog && (
  1145. <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">
  1146. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  1147. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  1148. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  1149. <div className="flex justify-end gap-3">
  1150. <button
  1151. onClick={() => setConfirmDialog(null)}
  1152. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  1153. >
  1154. Cancel
  1155. </button>
  1156. <button
  1157. onClick={confirmDialog.onConfirm}
  1158. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  1159. >
  1160. Delete
  1161. </button>
  1162. </div>
  1163. </div>
  1164. </div>
  1165. )}
  1166. {/* CUSTOM TOAST NOTIFICATION */}
  1167. {toast && (
  1168. <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 ${
  1169. toast.type === 'error' ? 'bg-red-700' : 'bg-gray-900'
  1170. }`}>
  1171. <div className={`w-6 h-6 rounded-full flex items-center justify-center font-bold text-sm shrink-0 mt-0.5 ${
  1172. toast.type === 'error' ? 'bg-white text-red-700' : 'bg-green-500 text-gray-900'
  1173. }`}>
  1174. {toast.type === 'error' ? '!' : '✓'}
  1175. </div>
  1176. <span className="font-medium leading-snug">{toast.message}</span>
  1177. </div>
  1178. )}
  1179. </div>
  1180. );
  1181. }