import React, { useState, useEffect, useRef } from 'react'; import { Guest, AggregatedStats, WeddingPhoto, KissAlertOverlay, ToastAlertOverlay, UserRole, } from './types.ts'; import { OnboardingModal } from './components/OnboardingModal.tsx'; import { GuestView } from './components/GuestView.tsx'; import { ScreenView } from './components/ScreenView.tsx'; import { AdminView } from './components/AdminView.tsx'; import { QRGenerator } from './components/QRGenerator.tsx'; import { Crown, Mic, HeartHandshake, ShieldCheck, QrCode, Tv, Smartphone } from 'lucide-react'; type ViewMode = 'guest' | 'screen' | 'admin' | 'qr'; export default function App() { const [currentView, setCurrentView] = useState('guest'); const [guest, setGuest] = useState(null); const [stats, setStats] = useState(null); const [photos, setPhotos] = useState([]); const [urlTicket, setUrlTicket] = useState(''); const [urlRole, setUrlRole] = useState(undefined); const [urlName, setUrlName] = useState(''); const [urlTeam, setUrlTeam] = useState(''); // Live Flash Overlays const [kissAlert, setKissAlert] = useState(null); const [toastAlert, setToastAlert] = useState(null); const wsRef = useRef(null); // Initialize from URL search parameters & localStorage useEffect(() => { const params = new URLSearchParams(window.location.search); const modeParam = params.get('mode'); const ticketParam = params.get('ticket'); const roleParam = params.get('role') as UserRole | null; const nameParam = params.get('name'); const teamParam = params.get('team'); // Route checks if (window.location.pathname === '/screen' || modeParam === 'screen') { setCurrentView('screen'); } else if (window.location.pathname === '/admin' || modeParam === 'admin') { setCurrentView('admin'); } else if (window.location.pathname === '/qr' || modeParam === 'qr') { setCurrentView('qr'); } if (ticketParam) { setUrlTicket(ticketParam.toUpperCase()); } if (roleParam && ['guest', 'host', 'admin', 'couple'].includes(roleParam)) { setUrlRole(roleParam); } if (nameParam) { setUrlName(nameParam); } if (teamParam) { setUrlTeam(teamParam); } // Check localStorage guest session const savedTicket = ticketParam || localStorage.getItem('wedding_ticket_id'); const savedGuestRaw = localStorage.getItem('wedding_guest_data'); if (savedTicket && savedGuestRaw) { try { const parsedGuest: Guest = JSON.parse(savedGuestRaw); setGuest(parsedGuest); } catch { // Fallback fetch fetch(`/api/guest/${savedTicket}`) .then((res) => (res.ok ? res.json() : null)) .then((data) => { if (data?.guest) { setGuest(data.guest); localStorage.setItem('wedding_guest_data', JSON.stringify(data.guest)); } }) .catch(() => {}); } } }, []); // Fetch initial global state const fetchGlobalState = async () => { try { const res = await fetch('/api/state'); if (res.ok) { const data = await res.json(); setStats(data); if (data.photos) { setPhotos(data.photos); } } } catch (e) { console.warn('Initial state fetch error:', e); } }; useEffect(() => { fetchGlobalState(); }, []); // Real-time WebSocket connection useEffect(() => { let reconnectTimeout: any; function connectWs() { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${protocol}//${window.location.host}/ws`; const ws = new WebSocket(wsUrl); wsRef.current = ws; ws.onopen = () => { console.log('WebSocket connected to Wedding Hub'); }; ws.onmessage = (event) => { try { const msg = JSON.parse(event.data); switch (msg.event) { case 'STATE_SYNC': case 'SETTINGS_UPDATED': setStats(msg.data); break; case 'KISS_ROUND_START': if (msg.data.stats) { setStats(msg.data.stats); } if (msg.data.first_catcher) { setKissAlert({ id: `kiss-${Date.now()}`, guest_name: msg.data.first_catcher.guest_name, team_name: msg.data.first_catcher.team_name || 'Команда Гостей', points: msg.data.points || 3, is_golden: true, timestamp: Date.now(), }); } break; case 'KISS_CATCH': if (msg.data.stats) { setStats(msg.data.stats); } break; case 'PHOTO_UPLOADED': if (msg.data.photo) { setPhotos((prev) => [msg.data.photo, ...prev.slice(0, 49)]); } if (msg.data.stats) { setStats(msg.data.stats); } if (msg.data.photo?.is_toast) { setToastAlert({ id: `toast-${Date.now()}`, guest_name: msg.data.photo.guest_name || 'Гость', team_name: msg.data.photo.team_name || 'Команда', photo_url: msg.data.photo.url, toast_phrase: msg.data.photo.toast_phrase || 'Горько! За счастье молодых!', timestamp: Date.now(), }); } break; } } catch (err) { console.error('WS parse error:', err); } }; ws.onerror = (err) => { console.warn('WS Error:', err); }; ws.onclose = () => { console.log('WS connection lost, retrying in 3s...'); reconnectTimeout = setTimeout(connectWs, 3000); }; } connectWs(); // Fallback polling for high reliability const pollTimer = setInterval(() => { fetchGlobalState(); }, 5000); return () => { clearTimeout(reconnectTimeout); clearInterval(pollTimer); if (wsRef.current) { wsRef.current.close(); } }; }, []); const handleLogout = () => { localStorage.removeItem('wedding_ticket_id'); localStorage.removeItem('wedding_guest_data'); setGuest(null); }; const userRole: UserRole = guest?.role || 'guest'; const isGuestRole = userRole === 'guest'; const isHostRole = userRole === 'host'; const isCoupleRole = userRole === 'couple'; const isAdminRole = userRole === 'admin'; return (
{/* Subtle Ambient Gold Dot Pattern */}
{/* Role-Based Navigation Bar: - Regular guests ONLY see the guest PWA (other tabs are completely hidden per instructions). - Host & Couple see Guest View + Host Controls + Projector Screen (no API keys, no QR manager). - Admin sees full suite (Guest View, Screen, Admin panel with API keys & users, QR generator). */} {!isGuestRole && (
{/* Guest View Tab */} {/* Projector Screen Tab */} {/* Host / Admin Panel Tab */} {(isHostRole || isCoupleRole || isAdminRole) && ( )} {/* QR Generator Tab (Admin only) */} {isAdminRole && ( )}
)} {/* Main Content Area */}
{currentView === 'screen' ? ( setKissAlert(null)} onCloseToastAlert={() => setToastAlert(null)} onSwitchToGuest={() => setCurrentView('guest')} onOpenAdmin={() => setCurrentView('admin')} /> ) : currentView === 'admin' ? ( setCurrentView('guest')} onOpenQRGenerator={() => setCurrentView('qr')} onOpenScreen={() => setCurrentView('screen')} /> ) : currentView === 'qr' ? ( setCurrentView('guest')} /> ) : ( <> {/* Guest View or Onboarding */} {guest ? ( setCurrentView('screen') : undefined} onOpenAdmin={!isGuestRole ? () => setCurrentView('admin') : undefined} /> ) : ( setGuest(registeredGuest)} /> )} )}
); }