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.
 
 

1403 lines
71 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, UPLOAD_LIMITS } 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)} over limit` : `${remaining} remaining`}
  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. // Hex input per il theme color: stato locale che resta libero durante la digitazione,
  231. // committa su portal.themeColor solo quando la stringa e' un hex completo valido.
  232. const [hexInput, setHexInput] = useState<string>('#1e3a8a');
  233. useEffect(() => {
  234. if (portal.themeColor) setHexInput(portal.themeColor);
  235. }, [portal.themeColor]);
  236. // NEW UI STATES: Toast and Confirm Dialog
  237. const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
  238. const [confirmDialog, setConfirmDialog] = useState<{ message: string, onConfirm: () => void } | null>(null);
  239. const [pdfProgress, setPdfProgress] = useState<{ name: string; page: number; total: number } | null>(null);
  240. const [availableFonts, setAvailableFonts] = useState<string[]>([]);
  241. // Map: expected URL of the future-transcoded file → job state.
  242. // We key by URL (not jobId) so the rendering layer can look it up cheaply.
  243. const [transcodeJobs, setTranscodeJobs] = useState<Record<string, { jobId: string; status: string; progress: number }>>({});
  244. // External Link feature flag: priorità al setting del portale, fallback alla costante in lib/config.
  245. const externalLinksOn = portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT;
  246. // Helper to show auto-dismissing toast
  247. const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  248. setToast({ message, type });
  249. setTimeout(() => setToast(null), type === 'error' ? 6000 : 3000);
  250. };
  251. const refreshFonts = async () => {
  252. try {
  253. const res = await fetch(withBasePath('/api/fonts'));
  254. if (res.ok) setAvailableFonts(await res.json());
  255. } catch { setAvailableFonts([]); }
  256. };
  257. useEffect(() => {
  258. fetch(withBasePath('/api/cards')).then(res => res.json()).then(setCards);
  259. fetch(withBasePath('/api/portals')).then(res => res.json()).then(data => data && setPortal(data));
  260. void refreshFonts();
  261. }, []);
  262. const [uploadingFont, setUploadingFont] = useState(false);
  263. const handleFontUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  264. const file = e.target.files?.[0];
  265. e.target.value = '';
  266. if (!file) return;
  267. setUploadingFont(true);
  268. try {
  269. const fd = new FormData();
  270. fd.append('file', file);
  271. const res = await fetch(withBasePath('/api/admin/fonts'), { method: 'POST', body: fd });
  272. const data = await res.json().catch(() => ({}));
  273. if (!res.ok) {
  274. showToast(data?.error || `Upload error (${res.status})`, 'error');
  275. return;
  276. }
  277. showToast(`Font uploaded: ${data.name}`);
  278. await refreshFonts();
  279. // Auto-seleziona il font appena caricato
  280. if (data.name) setPortal(p => ({ ...p, fontFamily: data.name }));
  281. } catch (err) {
  282. showToast(`Could not reach the server. Check your network connection and try again. Details: ${(err as Error).message}`, 'error');
  283. } finally {
  284. setUploadingFont(false);
  285. }
  286. };
  287. const handleFontDelete = async (name: string) => {
  288. if (!window.confirm(`Delete font "${name}"? Portals using this font will fall back to the system font.`)) return;
  289. try {
  290. const res = await fetch(withBasePath(`/api/admin/fonts?name=${encodeURIComponent(name)}`), { method: 'DELETE' });
  291. const data = await res.json().catch(() => ({}));
  292. if (!res.ok) {
  293. showToast(data?.error || `Delete error (${res.status})`, 'error');
  294. return;
  295. }
  296. showToast('Font deleted.');
  297. await refreshFonts();
  298. if (portal.fontFamily === name) setPortal(p => ({ ...p, fontFamily: '' }));
  299. } catch (err) {
  300. showToast(`Could not reach the server. Check your network connection and try again. Details: ${(err as Error).message}`, 'error');
  301. }
  302. };
  303. // Poll pending transcode jobs every 2s. On 'done' we drop the entry from the
  304. // map; on 'failed' we additionally pull the media URL out of the editor so the
  305. // admin doesn't try to save a broken reference.
  306. useEffect(() => {
  307. const pendingEntries = Object.entries(transcodeJobs).filter(
  308. ([, j]) => j.status === 'queued' || j.status === 'running'
  309. );
  310. if (pendingEntries.length === 0) return;
  311. let cancelled = false;
  312. const tick = async () => {
  313. for (const [url, j] of pendingEntries) {
  314. if (cancelled) return;
  315. try {
  316. const res = await fetch(withBasePath(`/api/transcode/${j.jobId}`));
  317. if (!res.ok) continue;
  318. const data = await res.json();
  319. if (cancelled) return;
  320. if (data.status === 'done') {
  321. setTranscodeJobs(prev => {
  322. const next = { ...prev };
  323. delete next[url];
  324. return next;
  325. });
  326. } else if (data.status === 'failed' || data.status === 'cancelled') {
  327. setTranscodeJobs(prev => {
  328. const next = { ...prev };
  329. delete next[url];
  330. return next;
  331. });
  332. setIsEditing(prev => prev ? {
  333. ...prev,
  334. extraMedia: (prev.extraMedia || []).filter(m => m.url !== url),
  335. imageUrl: prev.imageUrl === url ? '' : prev.imageUrl,
  336. } : prev);
  337. const msg = data.status === 'failed'
  338. ? `Transcoding failed${data.error ? `: ${String(data.error).split('\n')[0]}` : ''}`
  339. : 'Trascodifica annullata';
  340. showToast(msg, 'error');
  341. } else {
  342. setTranscodeJobs(prev => prev[url] ? ({ ...prev, [url]: { ...prev[url], status: data.status, progress: data.progress ?? 0 } }) : prev);
  343. }
  344. } catch {
  345. // ignore network glitches; will retry next tick
  346. }
  347. }
  348. };
  349. void tick();
  350. const id = window.setInterval(() => { void tick(); }, 2000);
  351. return () => { cancelled = true; window.clearInterval(id); };
  352. // eslint-disable-next-line react-hooks/exhaustive-deps
  353. }, [Object.keys(transcodeJobs).join('|')]);
  354. const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: string, isPortal = false) => {
  355. if (!e.target.files?.[0]) return;
  356. setUploading(prev => ({ ...prev, [field]: true }));
  357. const formData = new FormData();
  358. formData.append('file', e.target.files[0]);
  359. // Il logo è l'unico upload che ammette SVG (sanitizzato lato server).
  360. const endpoint = field === 'logoUrl' ? '/api/upload?context=logo' : '/api/upload';
  361. const res = await fetch(withBasePath(endpoint), { method: 'POST', body: formData });
  362. const data = await res.json();
  363. if (data.url) {
  364. if (isPortal) {
  365. setPortal(prev => ({ ...prev, [field]: data.url }));
  366. } else {
  367. setIsEditing(prev => ({ ...prev, [field]: data.url }));
  368. }
  369. }
  370. setUploading(prev => ({ ...prev, [field]: false }));
  371. };
  372. const handleUploadExtraMedia = async (e: React.ChangeEvent<HTMLInputElement>) => {
  373. const files = e.target.files;
  374. if (!files || files.length === 0) return;
  375. setUploading(prev => ({ ...prev, extraMedia: true }));
  376. const startedWithoutCover = !isEditing?.imageUrl;
  377. let pendingCover: string | null = null;
  378. const canPromote = () => startedWithoutCover && !pendingCover;
  379. // Pre-filtro: scarta video con formati non riproducibili nei browser
  380. const rejected: string[] = [];
  381. const acceptedFiles: File[] = [];
  382. for (const file of Array.from(files)) {
  383. if (isVideoFile(file) && !isPlayableVideoFile(file)) {
  384. rejected.push(file.name);
  385. } else {
  386. acceptedFiles.push(file);
  387. }
  388. }
  389. if (rejected.length > 0) {
  390. const list = rejected.length <= 3
  391. ? rejected.join(', ')
  392. : `${rejected.slice(0, 3).join(', ')} and ${rejected.length - 3} more`;
  393. showToast(
  394. `Unsupported format! Supported formats: ${PLAYBACK_SUPPORTED_LABEL}. Skipped files: ${list}`,
  395. 'error'
  396. );
  397. }
  398. if (acceptedFiles.length === 0) {
  399. setUploading(prev => ({ ...prev, extraMedia: false }));
  400. e.target.value = '';
  401. return;
  402. }
  403. const uploaded: MediaItem[] = [];
  404. for (const file of acceptedFiles) {
  405. try {
  406. if (isPdfFile(file)) {
  407. const items = await pdfToImageItems(file, (page, total) =>
  408. setPdfProgress({ name: file.name, page, total })
  409. );
  410. setPdfProgress(null);
  411. if (items.length > 0 && canPromote()) {
  412. // Promote the first PDF page to cover; skip it from the gallery to avoid duplication.
  413. pendingCover = items[0].url;
  414. uploaded.push(...items.slice(1));
  415. } else {
  416. uploaded.push(...items);
  417. }
  418. } else {
  419. const formData = new FormData();
  420. formData.append('file', file);
  421. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  422. const data = await res.json();
  423. if (!data.url) continue;
  424. if (data?.transcoding?.jobId) {
  425. const { jobId, status } = data.transcoding;
  426. setTranscodeJobs(prev => ({ ...prev, [data.url]: { jobId, status, progress: 0 } }));
  427. }
  428. if (isVideoFile(file)) {
  429. // Video always goes to the gallery so users can play it.
  430. uploaded.push({ url: data.url });
  431. // If no cover yet, extract the first frame and use it as the cover.
  432. if (canPromote()) {
  433. try {
  434. const blob = await extractVideoFrame(file);
  435. if (blob) {
  436. const baseName = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  437. const posterUrl = await uploadBlobAsImage(blob, `${baseName}-poster.jpg`);
  438. if (posterUrl) pendingCover = posterUrl;
  439. }
  440. } catch (err) {
  441. console.warn('Could not extract video poster for', file.name, err);
  442. }
  443. }
  444. } else {
  445. // Plain image
  446. if (canPromote()) {
  447. // Promote to cover; skip the gallery to avoid duplication.
  448. pendingCover = data.url;
  449. } else {
  450. uploaded.push({ url: data.url });
  451. }
  452. }
  453. }
  454. } catch (err) {
  455. console.error('Upload failed for', file.name, err);
  456. showToast(`Failed to process "${file.name}".`);
  457. setPdfProgress(null);
  458. }
  459. }
  460. setIsEditing(prev => ({
  461. ...prev,
  462. imageUrl: (startedWithoutCover && pendingCover) ? pendingCover : (prev?.imageUrl || ''),
  463. extraMedia: [...(prev?.extraMedia || []), ...uploaded],
  464. }));
  465. setUploading(prev => ({ ...prev, extraMedia: false }));
  466. e.target.value = '';
  467. };
  468. const removeExtraMedia = (index: number) => {
  469. setIsEditing(prev => ({
  470. ...prev,
  471. extraMedia: (prev?.extraMedia || []).filter((_, i) => i !== index),
  472. }));
  473. };
  474. const moveExtraMedia = (index: number, direction: 'up' | 'down') => {
  475. setIsEditing(prev => {
  476. const items = [...(prev?.extraMedia || [])];
  477. if (direction === 'up' && index > 0) {
  478. [items[index - 1], items[index]] = [items[index], items[index - 1]];
  479. } else if (direction === 'down' && index < items.length - 1) {
  480. [items[index + 1], items[index]] = [items[index], items[index + 1]];
  481. } else {
  482. return prev;
  483. }
  484. return { ...prev, extraMedia: items };
  485. });
  486. };
  487. const toggleAutoplay = (index: number) => {
  488. setIsEditing(prev => ({
  489. ...prev,
  490. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  491. i === index ? { ...m, autoplay: !m.autoplay } : m
  492. ),
  493. }));
  494. };
  495. const toggleMuted = (index: number) => {
  496. setIsEditing(prev => ({
  497. ...prev,
  498. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  499. i === index ? { ...m, muted: !m.muted } : m
  500. ),
  501. }));
  502. };
  503. const handleSaveCard = async () => {
  504. if (!isEditing) return;
  505. // External Link: URL obbligatorio (feedback immediato, ribadito anche lato server)
  506. if (isEditing.cardType === 'EXTERNAL_LINK' && !isEditing.actionUrl?.trim()) {
  507. showToast('URL is required for External Link cards', 'error');
  508. return;
  509. }
  510. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  511. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  512. const res = await fetch(withBasePath('/api/cards'), {
  513. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  514. });
  515. if (!res.ok) {
  516. let message = 'Save error';
  517. try {
  518. const body = await res.json();
  519. if (res.status === 400 && Array.isArray(body?.errors) && body.errors.length > 0) {
  520. const first = body.errors[0];
  521. message = first.limit != null
  522. ? `${first.field}: ${first.message} (${first.actual} / ${first.limit})`
  523. : `${first.field}: ${first.message}`;
  524. } else if (body?.error) {
  525. message = body.error;
  526. }
  527. } catch {}
  528. showToast(message, 'error');
  529. return; // keep the editor open so the admin can fix
  530. }
  531. setCards(prev => {
  532. const exists = prev.find(c => c.id === newCard.id);
  533. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  534. });
  535. setIsEditing(null);
  536. };
  537. const handleDeleteCard = (id: string) => {
  538. // Replace window.confirm with our custom dialog
  539. setConfirmDialog({
  540. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  541. onConfirm: async () => {
  542. await fetch(withBasePath(`/api/cards?id=${id}`), { method: 'DELETE' });
  543. setCards(prev => prev.filter(c => c.id !== id));
  544. setConfirmDialog(null);
  545. showToast('Card successfully deleted.');
  546. }
  547. });
  548. };
  549. const moveCard = async (index: number, direction: 'up' | 'down') => {
  550. const newCards = [...cards];
  551. if (direction === 'up' && index > 0) {
  552. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  553. } else if (direction === 'down' && index < newCards.length - 1) {
  554. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  555. } else {
  556. return; // Do nothing if trying to move out of bounds
  557. }
  558. // Recalculate displayOrder for the whole array
  559. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  560. // Optimistically update the UI
  561. setCards(updatedCards);
  562. // Persist the new order to the backend
  563. await fetch(withBasePath('/api/cards'), {
  564. method: 'PUT',
  565. headers: { 'Content-Type': 'application/json' },
  566. body: JSON.stringify(updatedCards)
  567. });
  568. };
  569. const handleSavePortal = async () => {
  570. setSavingPortal(true);
  571. await fetch(withBasePath('/api/portals'), {
  572. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  573. });
  574. setSavingPortal(false);
  575. showToast('Portal settings saved successfully!'); // Replaced window.alert
  576. };
  577. const handleBackupDownload = () => {
  578. window.location.href = withBasePath('/api/admin/backup');
  579. };
  580. const [restoring, setRestoring] = useState(false);
  581. const handleRestoreUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  582. const file = e.target.files?.[0];
  583. e.target.value = '';
  584. if (!file) return;
  585. if (!window.confirm('Restore will overwrite all current data (cards, portal, media, fonts). Continue?')) return;
  586. setRestoring(true);
  587. try {
  588. const fd = new FormData();
  589. fd.append('file', file);
  590. const res = await fetch(withBasePath('/api/admin/restore'), { method: 'POST', body: fd });
  591. const data = await res.json().catch(() => ({}));
  592. if (!res.ok) {
  593. showToast(data?.error || `Restore error (${res.status})`, 'error');
  594. return;
  595. }
  596. showToast(`Restore completed: ${data.restored?.cards ?? 0} cards, ${data.restored?.portals ?? 0} portals. Reloading…`);
  597. setTimeout(() => window.location.reload(), 1200);
  598. } catch (err) {
  599. showToast(`Could not reach the server. Check your network connection and try again. Details: ${(err as Error).message}`, 'error');
  600. } finally {
  601. setRestoring(false);
  602. }
  603. };
  604. // Factory preset: la sezione è sempre visibile (per chi accede a /admin); solo
  605. // il bottone "Salva come preset" è gated da FACTORY_PRESET_SAVE_ENABLED.
  606. const [factoryPreset, setFactoryPreset] = useState<{ exists: boolean; sizeBytes?: number; modifiedAt?: string } | null>(null);
  607. const [savingPreset, setSavingPreset] = useState(false);
  608. const [factoryResetting, setFactoryResetting] = useState(false);
  609. const refreshFactoryPreset = async () => {
  610. try {
  611. const res = await fetch(withBasePath('/api/admin/factory-preset'));
  612. if (res.ok) setFactoryPreset(await res.json());
  613. } catch { /* ignore */ }
  614. };
  615. useEffect(() => {
  616. void refreshFactoryPreset();
  617. }, []);
  618. const handleSaveFactoryPreset = async () => {
  619. const msg = factoryPreset?.exists
  620. ? 'Overwrite the existing factory preset with the current state?'
  621. : 'Save the current state as factory preset?';
  622. if (!window.confirm(msg)) return;
  623. setSavingPreset(true);
  624. try {
  625. const res = await fetch(withBasePath('/api/admin/factory-preset'), { method: 'POST' });
  626. const data = await res.json().catch(() => ({}));
  627. if (!res.ok) {
  628. showToast(data?.error || `Error (${res.status})`, 'error');
  629. return;
  630. }
  631. showToast('Factory preset updated.');
  632. await refreshFactoryPreset();
  633. } catch (err) {
  634. showToast(`Could not reach the server. Check your network connection and try again. Details: ${(err as Error).message}`, 'error');
  635. } finally {
  636. setSavingPreset(false);
  637. }
  638. };
  639. const handleFactoryReset = async () => {
  640. if (!window.confirm('FACTORY RESET — all current data will be replaced with the factory preset. Continue?')) return;
  641. setFactoryResetting(true);
  642. try {
  643. const res = await fetch(withBasePath('/api/admin/factory-reset'), { method: 'POST' });
  644. const data = await res.json().catch(() => ({}));
  645. if (!res.ok) {
  646. showToast(data?.error || `Error (${res.status})`, 'error');
  647. return;
  648. }
  649. showToast(`Factory reset completed: ${data.restored?.cards ?? 0} cards, ${data.restored?.portals ?? 0} portals. Reloading…`);
  650. setTimeout(() => window.location.reload(), 1200);
  651. } catch (err) {
  652. showToast(`Could not reach the server. Check your network connection and try again. Details: ${(err as Error).message}`, 'error');
  653. } finally {
  654. setFactoryResetting(false);
  655. }
  656. };
  657. // Shared Input Classes for high contrast
  658. 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";
  659. return (
  660. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  661. {/* Top Header */}
  662. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  663. <div className="max-w-5xl mx-auto flex justify-between items-center">
  664. <div>
  665. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  666. <p className="text-sm text-blue-200">Local Administration</p>
  667. </div>
  668. <a href={withBasePath('/')} target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  669. View Live Portal ↗
  670. </a>
  671. </div>
  672. </div>
  673. <div className="max-w-5xl mx-auto mt-8 px-4">
  674. {/* Tab Navigation */}
  675. <div className="flex space-x-2 mb-6">
  676. <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'}`}>
  677. Manage Cards
  678. </button>
  679. <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'}`}>
  680. Portal Settings
  681. </button>
  682. </div>
  683. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  684. {/* TAB: CARDS */}
  685. {activeTab === 'cards' && (
  686. <div className="p-6 md:p-8">
  687. <div className="flex justify-between items-center mb-8 border-b pb-4">
  688. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  689. <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">
  690. + Add New Card
  691. </button>
  692. </div>
  693. <div className="space-y-3 mb-8">
  694. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  695. {cards.map((card, idx) => (
  696. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  697. <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">
  698. <div className="flex items-center gap-4">
  699. {(() => {
  700. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  701. if (!previewUrl) {
  702. 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>;
  703. }
  704. return isVideoUrl(previewUrl)
  705. ? <video src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" muted playsInline preload="metadata" />
  706. : <img src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" alt="" />;
  707. })()}
  708. <div>
  709. <span className="font-semibold text-gray-800 block">{card.title}</span>
  710. <span className="text-xs text-gray-500 uppercase tracking-wider">
  711. {card.cardType}
  712. {card.extraMedia && card.extraMedia.length > 0 && (
  713. <span className="text-gray-400 normal-case tracking-normal ml-2">[{card.extraMedia.length}]</span>
  714. )}
  715. {card.cardType === 'FULLSCREEN_LOCK' && (
  716. <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>
  717. )}
  718. </span>
  719. </div>
  720. </div>
  721. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  722. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  723. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  724. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  725. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  726. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  727. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  728. </div>
  729. </div>
  730. ))}
  731. </div>
  732. </div>
  733. )}
  734. {/* TAB: SETTINGS */}
  735. {activeTab === 'settings' && (
  736. <div className="p-6 md:p-8">
  737. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  738. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  739. <div className="space-y-6">
  740. <div>
  741. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  742. <input type="text" maxLength={PORTAL_LIMITS.title} value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  743. <CharCounter value={portal.title} limit={PORTAL_LIMITS.title} />
  744. </div>
  745. <div>
  746. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  747. <RichTextMini
  748. value={portal.welcomeText || ''}
  749. onChange={html => setPortal({ ...portal, welcomeText: html })}
  750. limit={PORTAL_LIMITS.welcomeText}
  751. />
  752. </div>
  753. <div className="flex gap-8">
  754. <div>
  755. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  756. <div className="flex items-center gap-4">
  757. <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" />
  758. <input
  759. type="text"
  760. value={hexInput}
  761. onChange={e => {
  762. const v = e.target.value;
  763. setHexInput(v);
  764. // Commit a portal.themeColor solo se la stringa e' un hex pieno e valido.
  765. if (/^#[0-9a-fA-F]{6}$/.test(v)) setPortal({ ...portal, themeColor: v.toLowerCase() });
  766. }}
  767. onBlur={() => {
  768. // Se l'utente esce dal campo con un valore non valido, ripristina l'ultimo valore noto.
  769. if (!/^#[0-9a-fA-F]{6}$/.test(hexInput)) setHexInput(portal.themeColor || '#1e3a8a');
  770. }}
  771. maxLength={7}
  772. spellCheck={false}
  773. placeholder="#RRGGBB"
  774. aria-label="Theme color hex"
  775. className={`font-mono text-sm px-3 py-2 rounded border outline-none focus:ring-2 focus:ring-blue-500 w-32 ${/^#[0-9a-fA-F]{6}$/.test(hexInput) ? 'border-gray-300 text-gray-900' : 'border-red-500 text-red-600'}`}
  776. />
  777. </div>
  778. </div>
  779. {/* NEW: Max Columns Setting updated for 3 */}
  780. <div className="flex-1">
  781. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  782. <input
  783. type="range"
  784. min="3"
  785. max="8"
  786. value={portal.maxGridColumns || 5}
  787. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  788. className="w-full mt-3 accent-blue-600"
  789. />
  790. <div className="flex justify-between text-xs text-gray-400 mt-1">
  791. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  792. </div>
  793. </div>
  794. </div>
  795. <div>
  796. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal font</label>
  797. <style dangerouslySetInnerHTML={{ __html: availableFonts.map(f => `
  798. @font-face {
  799. font-family: '${previewFontFamily(f)}';
  800. src: url('${withBasePath('/api/fonts?name=' + encodeURIComponent(f))}') format('${fontFormatFromName(f)}');
  801. font-display: swap;
  802. }`).join('') }} />
  803. <StyledSelect<string>
  804. value={portal.fontFamily ?? ''}
  805. onChange={(v) => setPortal({ ...portal, fontFamily: v })}
  806. options={[
  807. { value: '', label: 'System (Arial)' },
  808. ...availableFonts.map(f => ({
  809. value: f,
  810. label: f.replace(/\.(woff2?|ttf|otf)$/i, ''),
  811. style: { fontFamily: `'${previewFontFamily(f)}', Arial, Helvetica, sans-serif` },
  812. })),
  813. ]}
  814. />
  815. <div className="flex items-center gap-3 flex-wrap mt-2">
  816. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  817. <input
  818. type="file"
  819. accept=".woff2,.woff,.ttf,.otf,font/woff2,font/woff,font/ttf,font/otf"
  820. onChange={handleFontUpload}
  821. disabled={uploadingFont}
  822. hidden
  823. />
  824. {uploadingFont ? 'Uploading…' : 'Upload font…'}
  825. </label>
  826. {portal.fontFamily && availableFonts.includes(portal.fontFamily) && (
  827. <button
  828. type="button"
  829. onClick={() => handleFontDelete(portal.fontFamily!)}
  830. className="text-xs text-red-600 hover:text-red-700 underline"
  831. title={`Delete font "${portal.fontFamily}"`}
  832. >
  833. Delete selected font
  834. </button>
  835. )}
  836. </div>
  837. <p className="text-xs text-gray-500 mt-1">Supported: <code>.woff2</code>, <code>.woff</code>, <code>.ttf</code>, <code>.otf</code> · max {(UPLOAD_LIMITS.font / (1024 * 1024)).toFixed(0)} MB</p>
  838. </div>
  839. </div>
  840. <div className="space-y-6">
  841. {/* Logo Upload with Remove Button */}
  842. <div>
  843. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  844. <div className="flex items-center gap-3 flex-wrap">
  845. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  846. <input type="file" accept="image/*,.svg,image/svg+xml" onChange={e => handleUpload(e, 'logoUrl', true)} hidden />
  847. Choose image…
  848. </label>
  849. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  850. </div>
  851. {portal.logoUrl && (
  852. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  853. <img src={withBasePath(portal.logoUrl)} className="h-16 object-contain" alt="Logo Preview" />
  854. <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>
  855. <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>
  856. </div>
  857. )}
  858. </div>
  859. {/* Hero Upload with Remove Button */}
  860. <div>
  861. <label className="block text-sm font-semibold text-gray-700 mb-1">Background Image</label>
  862. <div className="flex items-center gap-3 flex-wrap">
  863. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  864. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'heroImageUrl', true)} hidden />
  865. Choose image…
  866. </label>
  867. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  868. </div>
  869. {portal.heroImageUrl && (
  870. <div className="mt-2 relative rounded shadow border inline-block w-full">
  871. <img src={withBasePath(portal.heroImageUrl)} className="h-32 w-full object-cover rounded" alt="Background preview" />
  872. <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 background">⬇</a>
  873. <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>
  874. </div>
  875. )}
  876. </div>
  877. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 space-y-3">
  878. <label className="flex items-center gap-3 cursor-pointer">
  879. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  880. <div>
  881. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  882. <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>
  883. </div>
  884. </label>
  885. <label className="flex items-center gap-3 cursor-pointer">
  886. <input
  887. type="checkbox"
  888. checked={portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT}
  889. onChange={e => setPortal({...portal, externalLinkEnabled: e.target.checked})}
  890. className="w-5 h-5 text-blue-600 rounded"
  891. />
  892. <div>
  893. <span className="block text-sm font-semibold text-gray-900">Enable &ldquo;External Link&rdquo; type in the dropdown menu.</span>
  894. <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>
  895. </div>
  896. </label>
  897. </div>
  898. </div>
  899. </div>
  900. <div className="mt-10 pt-6 border-t border-gray-200">
  901. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Backup &amp; Restore</h3>
  902. <p className="text-xs text-gray-500 mb-4">
  903. 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>interceptor-backup-YYYYMMDD-hhmmss.zip</code>.
  904. </p>
  905. <div className="flex flex-wrap gap-3">
  906. <button
  907. type="button"
  908. onClick={handleBackupDownload}
  909. className="bg-gray-800 text-white px-5 py-2.5 rounded-lg hover:bg-gray-900 font-medium shadow-sm"
  910. >
  911. ⬇ Save backup (ZIP)
  912. </button>
  913. <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' : ''}`}>
  914. <input
  915. type="file"
  916. accept=".zip,application/zip,application/x-zip-compressed"
  917. onChange={handleRestoreUpload}
  918. disabled={restoring}
  919. hidden
  920. />
  921. {restoring ? 'Restoring…' : '⤴ Restore from ZIP'}
  922. </label>
  923. </div>
  924. </div>
  925. <div className="mt-8 pt-6 border-t border-gray-200">
  926. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Factory Preset</h3>
  927. <p className="text-xs text-gray-500 mb-2">
  928. &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.
  929. </p>
  930. <p className="text-xs text-gray-700 mb-4">
  931. Current preset: {factoryPreset === null ? '…'
  932. : factoryPreset.exists
  933. ? <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>
  934. : <span className="text-gray-400 italic">no preset configured</span>}
  935. </p>
  936. <div className="flex flex-wrap gap-3">
  937. <button
  938. type="button"
  939. onClick={handleFactoryReset}
  940. disabled={factoryResetting || !factoryPreset?.exists}
  941. title={factoryPreset?.exists ? undefined : 'No preset configured'}
  942. 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"
  943. >
  944. {factoryResetting ? 'Reset in progress…' : 'Factory Reset'}
  945. </button>
  946. {FACTORY_PRESET_SAVE_ENABLED && (
  947. <button
  948. type="button"
  949. onClick={handleSaveFactoryPreset}
  950. disabled={savingPreset}
  951. title="Developer function: save the current state as a new factory preset"
  952. className="bg-emerald-700 text-white px-5 py-2.5 rounded-lg hover:bg-emerald-800 font-medium shadow-sm disabled:opacity-60"
  953. >
  954. {savingPreset ? 'Saving…' : 'Save as Factory Preset (dev)'}
  955. </button>
  956. )}
  957. </div>
  958. </div>
  959. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  960. <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">
  961. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  962. </button>
  963. </div>
  964. </div>
  965. )}
  966. </div>
  967. </div>
  968. {/* MODAL FOR EDITING/CREATING CARDS */}
  969. {isEditing && (
  970. <div
  971. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  972. onClick={() => setIsEditing(null)} // Click outside to close
  973. >
  974. <div
  975. 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"
  976. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  977. >
  978. <button
  979. onClick={() => setIsEditing(null)}
  980. 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"
  981. >
  982. </button>
  983. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  984. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  985. </h3>
  986. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  987. <div className="space-y-5">
  988. <div>
  989. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  990. <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" />
  991. <CharCounter value={isEditing.title} limit={CARD_LIMITS.title} />
  992. </div>
  993. <div>
  994. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  995. <StyledSelect<CardType>
  996. value={(isEditing.cardType || 'INFO_PAGE') as CardType}
  997. onChange={(v) => setIsEditing({ ...isEditing, cardType: v })}
  998. options={[
  999. { value: 'INFO_PAGE', label: 'Info Page' },
  1000. { value: 'IMAGE_GALLERY', label: 'Image Gallery' },
  1001. { value: 'BOOK', label: 'Flip-Book' },
  1002. { value: 'FULLSCREEN_LOCK', label: 'Fullscreen Lock (kiosk)' },
  1003. ...(externalLinksOn ? [{ value: 'EXTERNAL_LINK' as CardType, label: 'External Link' }] : []),
  1004. ]}
  1005. />
  1006. </div>
  1007. {isEditing.cardType === 'FULLSCREEN_LOCK' && (
  1008. <div className="bg-red-50 border border-red-200 rounded-lg p-4">
  1009. <p className="text-sm font-semibold text-red-800">⚠ Kiosk Lock Mode</p>
  1010. <p className="text-xs text-red-700 mt-1">
  1011. This card will take full control of the public portal. All other cards will be hidden until you remove this one.
  1012. Upload an image or video as &quot;Full-screen content&quot; in the section on the right.
  1013. </p>
  1014. </div>
  1015. )}
  1016. {isEditing.cardType !== 'FULLSCREEN_LOCK' && (isEditing.cardType === 'EXTERNAL_LINK' ? (
  1017. <>
  1018. <div>
  1019. <label className="block text-sm font-semibold text-gray-800 mb-1">URL <span className="text-red-600">*</span></label>
  1020. <input
  1021. type="url"
  1022. maxLength={CARD_LIMITS.actionUrl}
  1023. value={isEditing.actionUrl || ''}
  1024. onChange={e => setIsEditing({ ...isEditing, actionUrl: e.target.value })}
  1025. className={inputClasses}
  1026. placeholder="https://example.com/page"
  1027. />
  1028. <CharCounter value={isEditing.actionUrl} limit={CARD_LIMITS.actionUrl} />
  1029. </div>
  1030. <div>
  1031. <label className="block text-sm font-semibold text-gray-800 mb-1">Link text</label>
  1032. <input
  1033. type="text"
  1034. maxLength={CARD_LIMITS.shortDescription}
  1035. value={isEditing.shortDescription || ''}
  1036. onChange={e => setIsEditing({ ...isEditing, shortDescription: e.target.value })}
  1037. className={inputClasses}
  1038. placeholder="e.g. Visit the official site"
  1039. />
  1040. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  1041. <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>
  1042. </div>
  1043. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200">
  1044. <label className="flex items-start gap-3 cursor-pointer">
  1045. <input
  1046. type="checkbox"
  1047. checked={!!isEditing.redirectOnClick}
  1048. onChange={e => setIsEditing({ ...isEditing, redirectOnClick: e.target.checked })}
  1049. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1050. />
  1051. <div>
  1052. <span className="block text-sm font-semibold text-gray-900">Redirect on click</span>
  1053. <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>
  1054. </div>
  1055. </label>
  1056. </div>
  1057. </>
  1058. ) : (
  1059. <div>
  1060. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  1061. <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..." />
  1062. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  1063. </div>
  1064. ))}
  1065. {isEditing.cardType !== 'BOOK' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  1066. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200 space-y-3">
  1067. <label className="flex items-start gap-3 cursor-pointer">
  1068. <input
  1069. type="checkbox"
  1070. checked={!!isEditing.autoFullscreen}
  1071. onChange={e => setIsEditing({ ...isEditing, autoFullscreen: e.target.checked })}
  1072. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1073. />
  1074. <div>
  1075. <span className="block text-sm font-semibold text-gray-900">Auto fullscreen</span>
  1076. <span className="block text-xs text-gray-600">Open the gallery in fullscreen immediately when the user clicks this card.</span>
  1077. </div>
  1078. </label>
  1079. <label className="flex items-start gap-3 cursor-pointer">
  1080. <input
  1081. type="checkbox"
  1082. checked={!!isEditing.skipPreview}
  1083. onChange={e => setIsEditing({ ...isEditing, skipPreview: e.target.checked })}
  1084. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1085. />
  1086. <div>
  1087. <span className="block text-sm font-semibold text-gray-900">Cover not in the gallery</span>
  1088. <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>
  1089. </div>
  1090. </label>
  1091. </div>
  1092. )}
  1093. </div>
  1094. <div className="space-y-5">
  1095. {/* Cover Image — per FULLSCREEN_LOCK è il contenuto kiosk a tutto schermo e accetta anche video */}
  1096. <div>
  1097. <label className="block text-sm font-semibold text-gray-800 mb-1">
  1098. {isEditing.cardType === 'FULLSCREEN_LOCK'
  1099. ? <>Full-screen content <span className="text-gray-400 font-normal text-xs">(image or video)</span></>
  1100. : <>Cover Image <span className="text-gray-400 font-normal text-xs">(shown in grid)</span></>}
  1101. </label>
  1102. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  1103. <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">
  1104. <input
  1105. type="file"
  1106. accept={isEditing.cardType === 'FULLSCREEN_LOCK' ? 'image/*,video/mp4,video/webm,.mp4,.webm,.mov,.m4v' : 'image/*'}
  1107. onChange={e => handleUpload(e, 'imageUrl')}
  1108. hidden
  1109. />
  1110. {isEditing.cardType === 'FULLSCREEN_LOCK' ? 'Choose image or video…' : 'Choose image…'}
  1111. </label>
  1112. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading...</p>}
  1113. </div>
  1114. {isEditing.imageUrl && (
  1115. <div className="mt-3 relative rounded-lg overflow-hidden border border-gray-200 group">
  1116. {isVideoUrl(isEditing.imageUrl) ? (
  1117. <video src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" muted playsInline />
  1118. ) : (
  1119. <img src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" alt="Cover preview" />
  1120. )}
  1121. <a
  1122. href={withBasePath(isEditing.imageUrl)}
  1123. download={extractFileName(isEditing.imageUrl)}
  1124. 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"
  1125. title="Download"
  1126. aria-label="Download cover"
  1127. >⬇</a>
  1128. <button
  1129. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  1130. 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"
  1131. title="Remove cover image"
  1132. >✕</button>
  1133. </div>
  1134. )}
  1135. </div>
  1136. {/* Gallery Media (images + videos + PDFs) — nascosta per INFO_PAGE (solo cover ammessa) e FULLSCREEN_LOCK (solo contenuto kiosk) */}
  1137. {isEditing.cardType !== 'INFO_PAGE' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  1138. <div>
  1139. <label className="block text-sm font-semibold text-gray-800 mb-1">
  1140. Gallery Media <span className="text-gray-400 font-normal text-xs">(images, videos or PDFs — PDF pages become images)</span>
  1141. </label>
  1142. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  1143. <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">
  1144. <input
  1145. type="file"
  1146. 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"
  1147. multiple
  1148. onChange={handleUploadExtraMedia}
  1149. hidden
  1150. />
  1151. Choose files…
  1152. </label>
  1153. {uploading['extraMedia'] && !pdfProgress && <p className="mt-2 text-sm text-purple-600 font-medium">Uploading...</p>}
  1154. {pdfProgress && (
  1155. <p className="mt-2 text-sm text-purple-600 font-medium">
  1156. Processing &ldquo;{pdfProgress.name}&rdquo;: page {pdfProgress.page} of {pdfProgress.total}
  1157. </p>
  1158. )}
  1159. </div>
  1160. {(isEditing.extraMedia || []).length > 0 && (
  1161. <div className="mt-3 space-y-2">
  1162. {(isEditing.extraMedia || []).map((item, i) => {
  1163. const video = isVideoUrl(item.url);
  1164. const tc = transcodeJobs[item.url];
  1165. const isTranscoding = !!tc && (tc.status === 'queued' || tc.status === 'running');
  1166. return (
  1167. <div key={item.url + i} className="flex items-center gap-3 p-2 bg-gray-50 border border-gray-200 rounded-lg">
  1168. <div className="relative w-16 h-16 rounded-md overflow-hidden bg-black shrink-0">
  1169. {video ? (
  1170. <>
  1171. <video src={withBasePath(item.url)} className="w-full h-full object-cover" muted preload="metadata" />
  1172. <div className="absolute inset-0 flex items-center justify-center bg-black/30 text-white text-xl">▶</div>
  1173. </>
  1174. ) : (
  1175. <img src={withBasePath(item.url)} className="w-full h-full object-cover" alt="" />
  1176. )}
  1177. {isTranscoding && (
  1178. <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">
  1179. <span>Transcoding</span>
  1180. <span>{Math.round((tc.progress || 0) * 100)}%</span>
  1181. </div>
  1182. )}
  1183. <span className="absolute bottom-0 left-0 right-0 text-center text-white text-[10px] bg-black/60">{i + 1}</span>
  1184. </div>
  1185. <div className="flex-1 min-w-0">
  1186. <div className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
  1187. {video ? 'Video' : 'Image'}
  1188. </div>
  1189. {video && (
  1190. <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
  1191. <label className="flex items-center gap-2 cursor-pointer">
  1192. <input
  1193. type="checkbox"
  1194. checked={!!item.autoplay}
  1195. onChange={() => toggleAutoplay(i)}
  1196. className="w-4 h-4 text-blue-600 rounded"
  1197. />
  1198. <span className="text-sm text-gray-700">Autoplay</span>
  1199. </label>
  1200. <label className="flex items-center gap-2 cursor-pointer">
  1201. <input
  1202. type="checkbox"
  1203. checked={!!item.muted}
  1204. onChange={() => toggleMuted(i)}
  1205. className="w-4 h-4 text-blue-600 rounded"
  1206. />
  1207. <span className="text-sm text-gray-700">Muted</span>
  1208. </label>
  1209. </div>
  1210. )}
  1211. </div>
  1212. <button
  1213. onClick={() => moveExtraMedia(i, 'up')}
  1214. 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"
  1215. title="Move up"
  1216. aria-label="Move up"
  1217. disabled={i === 0}
  1218. >↑</button>
  1219. <button
  1220. onClick={() => moveExtraMedia(i, 'down')}
  1221. 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"
  1222. title="Move down"
  1223. aria-label="Move down"
  1224. disabled={i === (isEditing.extraMedia || []).length - 1}
  1225. >↓</button>
  1226. <a
  1227. href={withBasePath(item.url)}
  1228. download={extractFileName(item.url)}
  1229. 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"
  1230. title="Download"
  1231. aria-label="Download"
  1232. >⬇</a>
  1233. <button
  1234. onClick={() => removeExtraMedia(i)}
  1235. className="bg-red-500 hover:bg-red-600 text-white w-8 h-8 rounded-full text-sm font-bold shrink-0"
  1236. title="Remove"
  1237. >✕</button>
  1238. </div>
  1239. );
  1240. })}
  1241. </div>
  1242. )}
  1243. </div>
  1244. )}
  1245. </div>
  1246. </div>
  1247. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  1248. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  1249. Cancel
  1250. </button>
  1251. <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">
  1252. Save Card
  1253. </button>
  1254. </div>
  1255. </div>
  1256. </div>
  1257. )}
  1258. {/* CUSTOM CONFIRM DIALOG */}
  1259. {confirmDialog && (
  1260. <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">
  1261. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  1262. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  1263. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  1264. <div className="flex justify-end gap-3">
  1265. <button
  1266. onClick={() => setConfirmDialog(null)}
  1267. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  1268. >
  1269. Cancel
  1270. </button>
  1271. <button
  1272. onClick={confirmDialog.onConfirm}
  1273. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  1274. >
  1275. Delete
  1276. </button>
  1277. </div>
  1278. </div>
  1279. </div>
  1280. )}
  1281. {/* CUSTOM TOAST NOTIFICATION */}
  1282. {toast && (
  1283. <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 ${
  1284. toast.type === 'error' ? 'bg-red-700' : 'bg-gray-900'
  1285. }`}>
  1286. <div className={`w-6 h-6 rounded-full flex items-center justify-center font-bold text-sm shrink-0 mt-0.5 ${
  1287. toast.type === 'error' ? 'bg-white text-red-700' : 'bg-green-500 text-gray-900'
  1288. }`}>
  1289. {toast.type === 'error' ? '!' : '✓'}
  1290. </div>
  1291. <span className="font-medium leading-snug">{toast.message}</span>
  1292. </div>
  1293. )}
  1294. </div>
  1295. );
  1296. }