import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { Activity, Bell, CalendarDays, Camera, CheckCircle2, ChevronDown, Download, Image as ImageIcon, Layout, ListTodo, MapPin, Megaphone, MessageCircle, Pencil, QrCode, Settings, ShieldCheck, Smartphone, Sparkles, TrendingUp, Tv, Users, ArrowRight, Play, Clock, AlertCircle } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { Image } from '@tamagui/image';
import { isSameDay, isPast, isFuture, parseISO, differenceInDays, startOfDay } from 'date-fns';
import { MobileShell } from './components/MobileShell';
import { ADMIN_EVENTS_PATH, adminPath } from '../constants';
import { useEventContext } from '../context/EventContext';
import { getEventStats, EventStats, TenantEvent, getEventPhotos, TenantPhoto } from '../api';
import { formatEventDate, resolveEventDisplayName } from '../lib/events';
import { useAuth } from '../auth/context';
import { useAdminTheme } from './theme';
import { buildLimitWarnings } from '../lib/limitWarnings';
import { withAlpha } from './components/colors';
import { useEventReadiness } from './hooks/useEventReadiness';
import { SetupChecklist } from './components/SetupChecklist';
import { KpiStrip } from './components/Primitives';
// --- HELPERS ---
function translateLimits(t: any) {
return (key: string, options?: any) => t(`management:limits.${key}`, key, options);
}
// --- MODERN PRIMITIVES ---
function ModernCard({ children, style, ...rest }: any) {
const theme = useAdminTheme();
return (
{children}
);
}
function ModernButton({ label, onPress, tone = 'primary', fullWidth = true, icon, style }: any) {
const theme = useAdminTheme();
const isPrimary = tone === 'primary';
const isGhost = tone === 'ghost';
const isAccent = tone === 'accent';
const bg = isPrimary ? theme.primary : isAccent ? theme.accent : isGhost ? 'transparent' : theme.surface;
const text = isPrimary || isAccent ? 'white' : isGhost ? theme.text : theme.textStrong;
const border = isPrimary || isAccent || isGhost ? 'transparent' : theme.border;
return (
{icon}
{label}
);
}
function StatusBadge({ status }: { status: string }) {
const theme = useAdminTheme();
const { t } = useTranslation('management');
const config = {
published: { bg: '#DCFCE7', text: '#166534', label: t('events.status.published', 'Live') },
draft: { bg: '#FEF3C7', text: '#92400E', label: t('events.status.draft', 'Draft') },
archived: { bg: '#F1F5F9', text: '#475569', label: t('events.status.archived', 'Archived') },
}[status] || { bg: theme.surfaceMuted, text: theme.muted, label: status };
return (
{config.label}
);
}
// --- MAIN PAGE COMPONENT ---
export default function MobileDashboardPage() {
const navigate = useNavigate();
const { slug: slugParam } = useParams<{ slug?: string }>();
const { t, i18n } = useTranslation(['management', 'dashboard', 'mobile']);
const { events, activeEvent, hasEvents, hasMultipleEvents, isLoading, selectEvent } = useEventContext();
const { user } = useAuth();
const isMember = user?.role === 'member';
// --- LOGIC ---
const memberPermissions = React.useMemo(() => {
if (!isMember) return ['*'];
return Array.isArray(activeEvent?.member_permissions) ? activeEvent?.member_permissions ?? [] : [];
}, [activeEvent?.member_permissions, isMember]);
function allowPermission(permissions: string[], permission: string): boolean {
if (permissions.includes('*') || permissions.includes(permission)) return true;
if (permission.includes(':')) {
const [prefix] = permission.split(':');
return permissions.includes(`${prefix}:*`);
}
return false;
}
const canManageEvents = React.useMemo(() => allowPermission(memberPermissions, 'events:manage'), [memberPermissions]);
const { data: stats } = useQuery({
queryKey: ['mobile', 'dashboard', 'stats', activeEvent?.slug],
enabled: Boolean(activeEvent?.slug),
queryFn: async () => {
if (!activeEvent?.slug) return null;
return await getEventStats(activeEvent.slug);
},
});
const { data: photoData } = useQuery({
queryKey: ['mobile', 'dashboard', 'recent-photos', activeEvent?.slug],
enabled: Boolean(activeEvent?.slug),
queryFn: async () => {
if (!activeEvent?.slug) return { photos: [] };
return await getEventPhotos(activeEvent.slug, { perPage: 6, sort: 'desc' });
},
});
const locale = i18n.language?.startsWith('en') ? 'en-GB' : 'de-DE';
React.useEffect(() => {
if (!slugParam || slugParam === activeEvent?.slug) return;
selectEvent(slugParam);
}, [activeEvent?.slug, selectEvent, slugParam]);
const shouldRedirectToSelector = !isLoading && !activeEvent && !slugParam;
React.useEffect(() => {
if (!shouldRedirectToSelector) return;
navigate(ADMIN_EVENTS_PATH, { replace: true });
}, [navigate, shouldRedirectToSelector]);
const [eventSwitcherOpen, setEventSwitcherOpen] = React.useState(false);
// --- RENDER ---
if (shouldRedirectToSelector) {
return null;
}
if (isLoading) {
return (
);
}
if (!hasEvents && !events.length) {
return (
navigate(adminPath('/mobile/events/new'))} />
);
}
// Calculate Readiness
const readiness = useEventReadiness(activeEvent, t as any);
const phase = activeEvent ? getEventPhase(activeEvent) : 'setup';
const isCompleted = phase === 'post';
return (
{/* 1. LIFECYCLE HERO */}
setEventSwitcherOpen(true)}
canSwitch={hasMultipleEvents}
readiness={readiness}
/>
{/* 1b. SETUP CHECKLIST */}
{phase === 'setup' && (
)}
{/* 2. PULSE STRIP */}
{/* 3. ALERTS */}
{/* 4. UNIFIED COMMAND GRID */}
{/* 5. RECENT PHOTOS */}
);
}
// --- SUB COMPONENTS ---
type EventPhase = 'setup' | 'live' | 'post';
function getEventPhase(event: TenantEvent): EventPhase {
if (event.status === 'archived') return 'post';
if (!event.event_date) return 'setup';
const today = startOfDay(new Date());
const eventDate = parseISO(event.event_date);
if (isSameDay(today, eventDate)) return 'live';
if (isPast(eventDate)) return 'post';
return 'setup';
}
function LifecycleHero({ event, stats, locale, navigate, onSwitch, canSwitch, readiness }: any) {
const theme = useAdminTheme();
const { t } = useTranslation(['management', 'dashboard']);
if (!event) return null;
const phase = getEventPhase(event);
const pendingPhotos = stats?.pending_photos ?? event.pending_photo_count ?? 0;
// Header Row
const Header = () => (
{formatEventDate(event.event_date, locale)}
);
if (phase === 'live') {
return (
{t('dashboard:liveNow.status', 'Happening Now')}
{pendingPhotos > 0 ? `${pendingPhotos} ${t('management:photos.filters.pending', 'Pending')}` : t('dashboard:liveNow.description', 'Event is Running')}
{pendingPhotos > 0 && (
navigate(adminPath(`/mobile/events/${event.slug}/control-room`))}>
{t('management:photos.openModeration', 'Review')}
)}
);
}
const daysToGo = event.event_date ? differenceInDays(parseISO(event.event_date), new Date()) : 0;
if (phase === 'post') {
return (
{t('events.recap.completedTitle', 'Event completed')}
{t('events.recap.galleryOpen', 'Gallery online')}
}
onPress={() => navigate(adminPath(`/mobile/exports`))}
/>
}
onPress={() => navigate(adminPath(`/mobile/events/${event.slug}/recap`))}
/>
);
}
// SETUP
const nextStep = readiness.nextStep;
const ctaLabel = nextStep ? nextStep.ctaLabel : t('dashboard:onboarding.hero.cta', 'Setup Complete');
const ctaAction = nextStep ? () => navigate(adminPath(nextStep.targetPath)) : undefined;
return (
{t('dashboard:upcoming.status.planning', 'Countdown')}
{daysToGo} {t('management:galleryStatus.daysLabel', 'days')}
{/* Main CTA if not ready */}
{!readiness.isReady && (
}
onPress={ctaAction}
/>
)}
{readiness.isReady && (
Ready for Liftoff
)}
);
}
function PulseStrip({ event, stats }: any) {
const theme = useAdminTheme();
const { t } = useTranslation('management');
const uploadCount = stats?.uploads_total ?? event?.photo_count ?? 0;
const guestCount = event?.active_invites_count ?? event?.total_invites_count ?? 0;
const pendingCount = stats?.pending_photos ?? event?.pending_photo_count ?? 0;
return (
0 ? t('management:common.actionNeeded', 'Review') : undefined,
color: pendingCount > 0 ? '#8B5CF6' : theme.textMuted
}
]} />
);
}
function UnifiedToolGrid({ event, navigate, permissions, isMember, isCompleted }: any) {
const theme = useAdminTheme();
const { t } = useTranslation(['management', 'dashboard']);
const slug = event?.slug;
if (!slug) return null;
const experienceItems = [
{ label: t('management:photos.gallery.title', 'Photos'), icon: ImageIcon, path: `/mobile/events/${slug}/control-room`, color: theme.primary },
!isCompleted ? { label: t('management:events.quick.liveShowSettings', 'Slide Show'), icon: Tv, path: `/mobile/events/${slug}/live-show/settings`, color: '#F59E0B' } : null,
!isCompleted ? { label: t('events.tasks.badge', 'Photo tasks'), icon: ListTodo, path: `/mobile/events/${slug}/tasks`, color: theme.accent } : null,
!isCompleted ? { label: t('management:events.quick.photobooth', 'Photobooth'), icon: Camera, path: `/mobile/events/${slug}/photobooth`, color: '#8B5CF6' } : null,
].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));
const operationsItems = [
!isCompleted ? { label: t('management:invites.badge', 'QR Codes'), icon: QrCode, path: `/mobile/events/${slug}/qr`, color: '#10B981' } : null,
{ label: t('management:events.quick.guests', 'Guests'), icon: Users, path: `/mobile/events/${slug}/members`, color: theme.text },
!isCompleted ? { label: t('management:events.quick.guestMessages', 'Messages'), icon: Megaphone, path: `/mobile/events/${slug}/guest-notifications`, color: theme.text } : null,
!isCompleted ? { label: t('events.branding.titleShort', 'Branding'), icon: Layout, path: `/mobile/events/${slug}/branding`, color: theme.text } : null,
].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));
const adminItems = [
{ label: t('management:mobileDashboard.shortcutAnalytics', 'Analytics'), icon: TrendingUp, path: `/mobile/events/${slug}/analytics` },
!isCompleted ? { label: t('events.recap.exportTitleShort', 'Exports'), icon: Download, path: `/mobile/exports` } : null,
{ label: t('management:mobileProfile.settings', 'Settings'), icon: Settings, path: `/mobile/events/${slug}/edit` },
].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));
const sections = [
{
title: t('management:branding.badge', 'Experience'),
items: experienceItems,
},
{
title: t('management:workspace.hero.badge', 'Operations'),
items: operationsItems,
},
{
title: t('management:settings.hero.badge', 'Admin'),
items: adminItems,
}
].filter((section) => section.items.length > 0);
return (
{sections.map((section) => (
{section.title}
{section.items.map((item) => (
navigate(adminPath(item.path))}
style={{ width: '48%', flexGrow: 1 }}
>
{item.label}
))}
))}
);
}
function RecentPhotosSection({ photos, navigate, slug }: { photos: TenantPhoto[], navigate: any, slug: string }) {
const theme = useAdminTheme();
const { t } = useTranslation('management');
if (!photos.length) return null;
return (
{t('photos.recentTitle', 'Latest Uploads')}
navigate(adminPath(`/mobile/events/${slug}/control-room`))}>
{t('common.all', 'See all')}
{photos.map((photo) => (
navigate(adminPath(`/mobile/events/${slug}/control-room`))}>
{photo.thumbnail_url ? (
) : (
)}
))}
);
}
function AlertsSection({ event, stats, t }: any) {
const theme = useAdminTheme();
const limitWarnings = buildLimitWarnings(event?.limits ?? null, translateLimits(t));
if (!limitWarnings.length) return null;
return (
{limitWarnings.map((w: any, idx: number) => {
const isDanger = w.tone === 'danger';
const bg = isDanger ? theme.dangerBg : theme.warningBg;
const border = isDanger ? theme.dangerText : theme.warningBorder;
const text = isDanger ? theme.dangerText : theme.warningText;
const Icon = isDanger ? AlertCircle : Bell;
return (
{w.message}
);
})}
);
}
function EmptyState({ canManage, onCreate }: any) {
const theme = useAdminTheme();
const { t } = useTranslation(['management', 'mobile']);
return (
{t('mobile:header.appName', 'Event Admin')}
{t('mobile:header.noEventsBody', 'Create your first event.')}
{canManage && }
);
}