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

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