344 lines
12 KiB
TypeScript
344 lines
12 KiB
TypeScript
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<ViewMode>('guest');
|
|
const [guest, setGuest] = useState<Guest | null>(null);
|
|
const [stats, setStats] = useState<AggregatedStats | null>(null);
|
|
const [photos, setPhotos] = useState<WeddingPhoto[]>([]);
|
|
const [urlTicket, setUrlTicket] = useState<string>('');
|
|
const [urlRole, setUrlRole] = useState<UserRole | undefined>(undefined);
|
|
const [urlName, setUrlName] = useState<string>('');
|
|
const [urlTeam, setUrlTeam] = useState<string>('');
|
|
|
|
// Live Flash Overlays
|
|
const [kissAlert, setKissAlert] = useState<KissAlertOverlay | null>(null);
|
|
const [toastAlert, setToastAlert] = useState<ToastAlertOverlay | null>(null);
|
|
|
|
const wsRef = useRef<WebSocket | null>(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 (
|
|
<div className="min-h-screen bg-[#0a0a0a] text-[#e0e0e0] selection:bg-[#d4af37] selection:text-black relative">
|
|
{/* Subtle Ambient Gold Dot Pattern */}
|
|
<div className="fixed inset-0 gold-dot-pattern opacity-[0.07] pointer-events-none z-0" />
|
|
|
|
{/*
|
|
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 && (
|
|
<div className="fixed top-3 right-3 z-50 flex items-center gap-1 bg-[#141414]/95 backdrop-blur-md p-1.5 rounded-2xl border border-[#d4af37]/30 shadow-2xl print:hidden text-xs">
|
|
{/* Guest View Tab */}
|
|
<button
|
|
onClick={() => setCurrentView('guest')}
|
|
className={`px-3 py-1.5 rounded-xl font-bold transition-all flex items-center gap-1.5 ${
|
|
currentView === 'guest'
|
|
? 'bg-[#d4af37] text-black shadow-md shadow-[#d4af37]/20'
|
|
: 'text-gray-400 hover:text-white'
|
|
}`}
|
|
>
|
|
<Smartphone className="w-3.5 h-3.5" />
|
|
<span>Хаб Гостя</span>
|
|
</button>
|
|
|
|
{/* Projector Screen Tab */}
|
|
<button
|
|
onClick={() => setCurrentView('screen')}
|
|
className={`px-3 py-1.5 rounded-xl font-bold transition-all flex items-center gap-1.5 ${
|
|
currentView === 'screen'
|
|
? 'bg-[#d4af37] text-black shadow-md shadow-[#d4af37]/20'
|
|
: 'text-gray-400 hover:text-white'
|
|
}`}
|
|
>
|
|
<Tv className="w-3.5 h-3.5" />
|
|
<span>Экран зала</span>
|
|
</button>
|
|
|
|
{/* Host / Admin Panel Tab */}
|
|
{(isHostRole || isCoupleRole || isAdminRole) && (
|
|
<button
|
|
onClick={() => setCurrentView('admin')}
|
|
className={`px-3 py-1.5 rounded-xl font-bold transition-all flex items-center gap-1.5 ${
|
|
currentView === 'admin'
|
|
? 'bg-[#d4af37] text-black shadow-md shadow-[#d4af37]/20'
|
|
: 'text-gray-400 hover:text-white'
|
|
}`}
|
|
>
|
|
{isAdminRole ? <Crown className="w-3.5 h-3.5" /> : <Mic className="w-3.5 h-3.5" />}
|
|
<span>{isAdminRole ? 'Админка' : 'Ведущий'}</span>
|
|
</button>
|
|
)}
|
|
|
|
{/* QR Generator Tab (Admin only) */}
|
|
{isAdminRole && (
|
|
<button
|
|
onClick={() => setCurrentView('qr')}
|
|
className={`px-3 py-1.5 rounded-xl font-bold transition-all flex items-center gap-1.5 ${
|
|
currentView === 'qr'
|
|
? 'bg-[#d4af37] text-black shadow-md shadow-[#d4af37]/20'
|
|
: 'text-gray-400 hover:text-white'
|
|
}`}
|
|
>
|
|
<QrCode className="w-3.5 h-3.5" />
|
|
<span>QR-билеты</span>
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Main Content Area */}
|
|
<div className="relative z-10">
|
|
{currentView === 'screen' ? (
|
|
<ScreenView
|
|
stats={stats}
|
|
photos={photos}
|
|
kissAlert={kissAlert}
|
|
toastAlert={toastAlert}
|
|
onCloseKissAlert={() => setKissAlert(null)}
|
|
onCloseToastAlert={() => setToastAlert(null)}
|
|
onSwitchToGuest={() => setCurrentView('guest')}
|
|
onOpenAdmin={() => setCurrentView('admin')}
|
|
/>
|
|
) : currentView === 'admin' ? (
|
|
<AdminView
|
|
stats={stats}
|
|
currentRole={userRole}
|
|
onBack={() => setCurrentView('guest')}
|
|
onOpenQRGenerator={() => setCurrentView('qr')}
|
|
onOpenScreen={() => setCurrentView('screen')}
|
|
/>
|
|
) : currentView === 'qr' ? (
|
|
<QRGenerator
|
|
couplesNames={stats?.couples_names || 'Анна & Дмитрий'}
|
|
onBack={() => setCurrentView('guest')}
|
|
/>
|
|
) : (
|
|
<>
|
|
{/* Guest View or Onboarding */}
|
|
{guest ? (
|
|
<GuestView
|
|
guest={guest}
|
|
stats={stats}
|
|
onLogout={handleLogout}
|
|
onOpenScreen={!isGuestRole ? () => setCurrentView('screen') : undefined}
|
|
onOpenAdmin={!isGuestRole ? () => setCurrentView('admin') : undefined}
|
|
/>
|
|
) : (
|
|
<OnboardingModal
|
|
initialTicketId={urlTicket}
|
|
initialRole={urlRole}
|
|
initialGuestName={urlName}
|
|
initialTeamId={urlTeam}
|
|
onRegistered={(registeredGuest) => setGuest(registeredGuest)}
|
|
/>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|