import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Share2, Sparkles, Trophy, Users, TrendingUp, Heart, Image as ImageIcon } 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 { Switch } from '@tamagui/switch';
import { MobileShell } from './components/MobileShell';
import { MobileCard, CTAButton, PillBadge, SkeletonCard } from './components/Primitives';
import { LegalConsentSheet } from './components/LegalConsentSheet';
import { DataExportsPanel } from './DataExportsPage';
import {
  getEvent,
  getEventStats,
  getEventQrInvites,
  getEventEngagement,
  updateEvent,
  TenantEvent,
  EventStats,
  EventQrInvite,
  EventEngagement,
  EventAddonCatalogItem,
  getAddonCatalog,
  createEventAddonCheckout,
} from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage, isApiError } from '../lib/apiError';
import { adminPath } from '../constants';
import toast from 'react-hot-toast';
import { useBackNavigation } from './hooks/useBackNavigation';
import { useAdminTheme } from './theme';

type GalleryCounts = {
  photos: number;
  likes: number;
  pending: number;
};

export default function MobileEventRecapPage() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { t, i18n } = useTranslation('management');
  const { textStrong, text, muted, border, primary, danger } = useAdminTheme();
  const locale = i18n.language;

  const [activeTab, setActiveTab] = React.useState<'overview' | 'engagement' | 'compliance'>('overview');
  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [stats, setEventStats] = React.useState<EventStats | null>(null);
  const [invites, setInvites] = React.useState<EventQrInvite[]>([]);
  const [addons, setAddons] = React.useState<EventAddonCatalogItem[]>([]);
  const [engagement, setEngagement] = React.useState<EventEngagement | null>(null);
  const [engagementLoading, setEngagementLoading] = React.useState(false);
  const [engagementError, setEngagementError] = React.useState<string | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [consentOpen, setConsentOpen] = React.useState(false);
  const [busyScope, setBusyScope] = React.useState<string | null>(null);
  const back = useBackNavigation(slug ? adminPath(`/mobile/events/${slug}`) : adminPath('/mobile/events'));

  const load = React.useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    try {
      const [eventData, statsData, invitesData, addonsData] = await Promise.all([
        getEvent(slug),
        getEventStats(slug),
        getEventQrInvites(slug),
        getAddonCatalog(),
      ]);
      setEvent(eventData);
      setEventStats(statsData);
      setInvites(invitesData);
      setAddons(addonsData);
      setError(null);
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('events.errors.loadFailed', 'Recap konnte nicht geladen werden.')));
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t]);

  React.useEffect(() => {
    void load();
  }, [load]);

  React.useEffect(() => {
    if (event?.status && event.status !== 'published') {
      setEngagement(null);
      setEngagementError(null);
      setEngagementLoading(false);
      return;
    }

    const token = invites.find((invite) => invite.is_active)?.token ?? invites[0]?.token ?? '';
    if (!token) {
      setEngagement(null);
      setEngagementError(null);
      setEngagementLoading(false);
      return;
    }

    const controller = new AbortController();
    setEngagementLoading(true);
    setEngagementError(null);
    getEventEngagement(token, { locale: i18n.language, signal: controller.signal })
      .then((payload) => {
        setEngagement(payload);
      })
      .catch((err) => {
        if (err?.name === 'AbortError') {
          return;
        }
        if (isApiError(err) && (err.status === 403 || err.status === 404)) {
          setEngagement(null);
          setEngagementError(null);
          return;
        }
        setEngagement(null);
        setEngagementError(getApiErrorMessage(err, t('events.recap.engagementError', 'Engagement konnte nicht geladen werden.')));
      })
      .finally(() => {
        setEngagementLoading(false);
      });

    return () => {
      controller.abort();
    };
  }, [event?.status, i18n.language, invites, t]);

  const handleCheckout = async (addonKey: string) => {
    if (!slug || busyScope) return;
    setBusyScope(addonKey);
    try {
      const { checkout_url } = await createEventAddonCheckout(slug, {
        addon_key: addonKey,
        success_url: window.location.href,
        cancel_url: window.location.href,
      });
      if (checkout_url) {
        window.location.href = checkout_url;
      }
    } catch (err) {
      toast.error(getApiErrorMessage(err, t('events.errors.checkoutFailed', 'Bezahlvorgang konnte nicht gestartet werden.')));
      setBusyScope(null);
    }
  };

  const handleConsentConfirm = async (consents: { acceptedTerms: boolean }) => {
    if (!slug || !busyScope) return;
    try {
      const { checkout_url } = await createEventAddonCheckout(slug, {
        addon_key: busyScope,
        success_url: window.location.href,
        cancel_url: window.location.href,
        accepted_terms: consents.acceptedTerms,
      } as any);
      if (checkout_url) {
        window.location.href = checkout_url;
      }
    } catch (err) {
      toast.error(getApiErrorMessage(err, t('events.errors.checkoutFailed', 'Bezahlvorgang konnte nicht gestartet werden.')));
      setBusyScope(null);
      setConsentOpen(false);
    }
  };

  if (loading) {
    return (
      <MobileShell activeTab="home" title={t('events.recap.title', 'Event Recap')} onBack={back}>
        <YStack space="$3">
          <SkeletonCard height={120} />
          <SkeletonCard height={200} />
          <SkeletonCard height={150} />
        </YStack>
      </MobileShell>
    );
  }

  if (error || !event) {
    return (
      <MobileShell activeTab="home" title={t('events.recap.title', 'Event Recap')} onBack={back}>
        <MobileCard>
          <Text fontWeight="700" color={danger}>
            {error || t('common.error', 'Ein Fehler ist aufgetreten.')}
          </Text>
          <CTAButton label={t('common.retry', 'Erneut versuchen')} onPress={load} tone="ghost" />
        </MobileCard>
      </MobileShell>
    );
  }

  const galleryCounts: GalleryCounts = {
    photos: stats?.total ?? 0,
    likes: stats?.likes ?? 0,
    pending: stats?.pending_photos ?? 0,
  };

  const activeInvite = invites.find((i) => i.is_active) ?? invites[0] ?? null;
  const guestLink = activeInvite?.url ?? '';

  return (
    <MobileShell
      activeTab="home"
      title={t('events.recap.title', 'Event Recap')}
      onBack={back}
    >
      <YStack space="$4">
        <XStack space="$2">
          <TabButton
            label={t('events.recap.tabs.overview', 'Overview')}
            active={activeTab === 'overview'}
            onPress={() => setActiveTab('overview')}
          />
          <TabButton
            label={t('events.recap.tabs.engagement', 'Engagement')}
            active={activeTab === 'engagement'}
            onPress={() => setActiveTab('engagement')}
          />
          <TabButton
            label={t('events.recap.tabs.compliance', 'Compliance')}
            active={activeTab === 'compliance'}
            onPress={() => setActiveTab('compliance')}
          />
        </XStack>

        {activeTab === 'overview' ? (
          <YStack space="$4">
            <MobileCard space="$3">
              <XStack alignItems="center" justifyContent="space-between">
                <YStack space="$1">
                  <Text fontSize="$xl" fontWeight="800" color={textStrong}>
                    {t('events.recap.completedTitle', 'Event abgeschlossen')}
                  </Text>
                  <Text fontSize="$sm" color={muted}>
                    {formatDate(event.event_date, locale)}
                  </Text>
                </YStack>
                <PillBadge tone="success">{t('events.recap.statusClosed', 'Archiviert')}</PillBadge>
              </XStack>

              <XStack flexWrap="wrap" gap="$2" marginTop="$1">
                <Stat label={t('events.stats.uploads', 'Uploads')} value={formatCount(galleryCounts.photos, locale)} />
                <Stat label={t('events.stats.pending', 'Offen')} value={formatCount(galleryCounts.pending, locale)} />
                <Stat label={t('events.stats.likes', 'Likes')} value={formatCount(galleryCounts.likes, locale)} />
              </XStack>
            </MobileCard>

            <MobileCard space="$3">
              <XStack alignItems="center" space="$2">
                <Share2 size={18} color={primary} />
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.recap.shareGuests', 'Gäste-Galerie teilen')}
                </Text>
              </XStack>
              <Text fontSize="$sm" color={text}>
                {t('events.recap.shareBody', 'Deine Gäste können die Galerie auch nach dem Event weiterhin ansehen.')}
              </Text>

              {guestLink ? (
                <YStack space="$2" marginTop="$1">
                  <XStack
                    backgroundColor={border}
                    padding="$3"
                    borderRadius={12}
                    alignItems="center"
                    justifyContent="space-between"
                  >
                    <Text fontSize="$xs" color={muted} numberOfLines={1} flex={1}>
                      {guestLink}
                    </Text>
                    <CTAButton
                      label={t('events.recap.copyLink', 'Link kopieren')}
                      tone="ghost"
                      onPress={() => copyToClipboard(guestLink, t)}
                    />
                  </XStack>
                  {typeof navigator !== 'undefined' && !!navigator.share && (
                    <CTAButton
                      label={t('events.recap.qrShare', 'Link/QR teilen')}
                      tone="ghost"
                      onPress={() => shareLink(guestLink, event, t)}
                    />
                  )}
                </YStack>
              ) : (
                <Text fontSize="$sm" color={muted} marginTop="$1">
                  {t('events.recap.noPublicUrl', 'Kein Gäste-Link gesetzt. Lege den öffentlichen Link im Event-Setup fest.')}
                </Text>
              )}

              {guestLink && activeInvite?.qr_code_data_url ? (
                <YStack alignItems="center" space="$2" marginTop="$2">
                  <YStack
                    padding="$2"
                    backgroundColor="white"
                    borderRadius={12}
                    borderWidth={1}
                    borderColor={border}
                  >
                    <img
                      src={activeInvite.qr_code_data_url}
                      alt={t('events.recap.qrAlt', 'QR-Code zur Gäste-Galerie')}
                      style={{ width: 120, height: 120 }}
                    />
                  </YStack>
                  <CTAButton
                    label={t('events.recap.qrDownload', 'QR-Code herunterladen')}
                    tone="ghost"
                    onPress={() => downloadQr(activeInvite.qr_code_data_url!)}
                  />
                </YStack>
              ) : null}
            </MobileCard>

            <MobileCard space="$3">
              <XStack alignItems="center" space="$2">
                <Users size={18} color={primary} />
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.recap.settings', 'Nachlauf-Optionen')}
                </Text>
              </XStack>

              <YStack space="$1.5">
                <ToggleOption
                  label={t('events.recap.allowDownloads', 'Gäste dürfen Fotos laden')}
                  value={Boolean(event.settings?.guest_downloads_enabled)}
                  onToggle={(value) => updateSetting(event, setEvent, slug, 'guest_downloads_enabled', value, setError, t as any)}
                />
                <ToggleOption
                  label={t('events.recap.allowSharing', 'Gäste dürfen Fotos teilen')}
                  value={Boolean(event.settings?.guest_sharing_enabled)}
                  onToggle={(value) => updateSetting(event, setEvent, slug, 'guest_sharing_enabled', value, setError, t as any)}
                />
              </YStack>
            </MobileCard>

            <MobileCard space="$3">
              <XStack alignItems="center" space="$2">
                <Sparkles size={18} color={primary} />
                <Text fontSize="$md" fontWeight="800" color={textStrong}>
                  {t('events.recap.addons', 'Galerie verlängern')}
                </Text>
              </XStack>
              <Text fontSize="$sm" color={text}>
                {t('events.recap.addonBody', 'Die Online-Zeit deiner Galerie neigt sich dem Ende? Hier kannst du sie verlängern.')}
              </Text>

              <YStack space="$2">
                {addons
                  .filter((a) => a.key === 'gallery_extension')
                  .map((addon) => (
                    <CTAButton
                      key={addon.key}
                      label={t('events.recap.buyExtension', 'Galerie um 30 Tage verlängern')}
                      onPress={() => handleCheckout(addon.key)}
                      loading={busyScope === addon.key}
                    />
                  ))}
              </YStack>
            </MobileCard>
          </YStack>
        ) : null}

        {activeTab === 'engagement' ? (
          <YStack space="$4">
            {engagementLoading ? (
              <YStack space="$2">
                <SkeletonCard height={140} />
                <SkeletonCard height={180} />
                <SkeletonCard height={180} />
              </YStack>
            ) : engagementError ? (
              <MobileCard>
                <Text fontWeight="700" color={danger}>
                  {engagementError}
                </Text>
              </MobileCard>
            ) : !engagement ? (
              <MobileCard>
                <Text fontWeight="700" color={muted}>
                  {activeInvite
                    ? t('events.recap.engagement.empty', 'No engagement data yet.')
                    : t('events.recap.engagement.noInvite', 'No active guest link available yet.')}
                </Text>
              </MobileCard>
            ) : (
              <YStack space="$4">
                <MobileCard space="$3">
                  <XStack alignItems="center" space="$2">
                    <TrendingUp size={18} color={primary} />
                    <Text fontSize="$md" fontWeight="800" color={textStrong}>
                      {t('events.recap.engagement.title', 'Guest engagement')}
                    </Text>
                  </XStack>
                  <Text fontSize="$sm" color={text}>
                    {t('events.recap.engagement.subtitle', 'Highlights, leaderboards, and milestones from your guests.')}
                  </Text>
                  <XStack flexWrap="wrap" gap="$2" marginTop="$1">
                    <Stat
                      label={t('events.recap.engagement.summary.photos', 'Photos')}
                      value={formatCount(engagement.summary.totalPhotos, locale)}
                    />
                    <Stat
                      label={t('events.recap.engagement.summary.guests', 'Guests')}
                      value={formatCount(engagement.summary.uniqueGuests, locale)}
                    />
                    <Stat
                      label={t('events.recap.engagement.summary.tasks', 'Tasks solved')}
                      value={formatCount(engagement.summary.tasksSolved, locale)}
                    />
                    <Stat
                      label={t('events.recap.engagement.summary.likes', 'Likes')}
                      value={formatCount(engagement.summary.likesTotal, locale)}
                    />
                  </XStack>
                </MobileCard>

                <MobileCard space="$3">
                  <XStack alignItems="center" space="$2">
                    <Trophy size={18} color={primary} />
                    <Text fontSize="$md" fontWeight="800" color={textStrong}>
                      {t('events.recap.engagement.leaderboards.uploadsTitle', 'Top contributors')}
                    </Text>
                  </XStack>
                  {engagement.leaderboards.uploads.length === 0 ? (
                    <Text fontSize="$sm" color={muted}>
                      {t('events.recap.engagement.leaderboards.uploadsEmpty', 'No uploads yet.')}
                    </Text>
                  ) : (
                    <YStack space="$1.5" marginTop="$1">
                      {engagement.leaderboards.uploads.slice(0, 5).map((entry, index) => (
                        <LeaderboardRow
                          key={`${entry.guest}-${entry.photos}-${index}`}
                          rank={index + 1}
                          name={entry.guest || t('events.recap.engagement.guestFallback', 'Guest')}
                          value={`${formatCount(entry.photos, locale)} · ${formatCount(entry.likes, locale)} ${t('events.recap.engagement.likesLabel', 'Likes')}`}
                        />
                      ))}
                    </YStack>
                  )}
                </MobileCard>

                <MobileCard space="$3">
                  <XStack alignItems="center" space="$2">
                    <Heart size={18} color={primary} />
                    <Text fontSize="$md" fontWeight="800" color={textStrong}>
                      {t('events.recap.engagement.leaderboards.likesTitle', 'Most liked')}
                    </Text>
                  </XStack>
                  {engagement.leaderboards.likes.length === 0 ? (
                    <Text fontSize="$sm" color={muted}>
                      {t('events.recap.engagement.leaderboards.likesEmpty', 'No likes yet.')}
                    </Text>
                  ) : (
                    <YStack space="$1.5" marginTop="$1">
                      {engagement.leaderboards.likes.slice(0, 5).map((entry, index) => (
                        <LeaderboardRow
                          key={`${entry.guest}-${entry.likes}-${index}`}
                          rank={index + 1}
                          name={entry.guest || t('events.recap.engagement.guestFallback', 'Guest')}
                          value={`${formatCount(entry.likes, locale)} ${t('events.recap.engagement.likesLabel', 'Likes')}`}
                        />
                      ))}
                    </YStack>
                  )}
                </MobileCard>

                <MobileCard space="$3">
                  <XStack alignItems="center" space="$2">
                    <Sparkles size={18} color={primary} />
                    <Text fontSize="$md" fontWeight="800" color={textStrong}>
                      {t('events.recap.engagement.highlightsTitle', 'Highlights')}
                    </Text>
                  </XStack>
                  <YStack space="$2" marginTop="$1">
                    <XStack space="$2" alignItems="center">
                      <YStack
                        width={72}
                        height={72}
                        borderRadius={12}
                        backgroundColor={border}
                        alignItems="center"
                        justifyContent="center"
                        overflow="hidden"
                      >
                        {engagement.highlights.topPhoto?.thumbnail ? (
                          <img
                            src={engagement.highlights.topPhoto.thumbnail}
                            alt={t('events.recap.engagement.topPhoto', 'Top photo')}
                            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                          />
                        ) : (
                          <ImageIcon size={24} color={muted} />
                        )}
                      </YStack>
                      <YStack flex={1}>
                        <Text fontSize="$sm" fontWeight="700" color={textStrong}>
                          {t('events.recap.engagement.topPhoto', 'Top photo')}
                        </Text>
                        <Text fontSize="$xs" color={muted}>
                          {engagement.highlights.topPhoto
                            ? `${engagement.highlights.topPhoto.guest || t('events.recap.engagement.guestFallback', 'Guest')} · ${formatCount(engagement.highlights.topPhoto.likes, locale)} ${t('events.recap.engagement.likesLabel', 'Likes')}`
                            : t('events.recap.engagement.topPhotoEmpty', 'No photo highlights yet.')}
                        </Text>
                      </YStack>
                    </XStack>

                    <XStack alignItems="center" justifyContent="space-between">
                      <Text fontSize="$sm" fontWeight="600" color={textStrong}>
                        {t('events.recap.engagement.trendingEmotion', 'Trending emotion')}
                      </Text>
                      <Text fontSize="$sm" color={muted}>
                        {engagement.highlights.trendingEmotion
                          ? `${engagement.highlights.trendingEmotion.name} · ${formatCount(engagement.highlights.trendingEmotion.count, locale)}`
                          : t('events.recap.engagement.trendingEmpty', 'No trends yet.')}
                      </Text>
                    </XStack>

                    <YStack space="$1">
                      <Text fontSize="$sm" fontWeight="600" color={textStrong}>
                        {t('events.recap.engagement.timeline', 'Uploads over time')}
                      </Text>
                      {engagement.highlights.timeline.length === 0 ? (
                        <Text fontSize="$xs" color={muted}>
                          {t('events.recap.engagement.timelineEmpty', 'No timeline data yet.')}
                        </Text>
                      ) : (
                        <YStack space="$1">
                          {engagement.highlights.timeline.slice(-5).map((point) => (
                            <XStack key={point.date} alignItems="center" justifyContent="space-between">
                              <Text fontSize="$xs" color={muted}>
                                {formatShortDate(point.date, locale)}
                              </Text>
                              <Text fontSize="$xs" color={muted}>
                                {t('events.recap.engagement.timelineRow', '{{photos}} photos · {{guests}} guests', {
                                  photos: formatCount(point.photos, locale),
                                  guests: formatCount(point.guests, locale),
                                })}
                              </Text>
                            </XStack>
                          ))}
                        </YStack>
                      )}
                    </YStack>
                  </YStack>
                </MobileCard>
              </YStack>
            )}
          </YStack>
        ) : null}

        {activeTab === 'compliance' ? (
          <YStack space="$4">
            <DataExportsPanel variant="recap" event={event} />
          </YStack>
        ) : null}
      </YStack>

      <LegalConsentSheet
        open={consentOpen}
        onClose={() => {
          setConsentOpen(false);
          setBusyScope(null);
        }}
        onConfirm={handleConsentConfirm}
        busy={Boolean(busyScope)}
        t={t as any}
      />
    </MobileShell>
  );
}

function Stat({ label, value, pill }: { label: string; value: string; pill?: boolean }) {
  const { textStrong, muted, accentSoft, border } = useAdminTheme();
  return (
    <YStack
      paddingHorizontal="$3"
      paddingVertical="$2"
      borderRadius={12}
      borderWidth={1}
      borderColor={border}
      backgroundColor={pill ? accentSoft : 'transparent'}
      minWidth={80}
    >
      <Text fontSize="$xs" color={muted}>
        {label}
      </Text>
      <Text fontSize="$md" fontWeight="800" color={textStrong}>
        {value}
      </Text>
    </YStack>
  );
}

function ToggleOption({ label, value, onToggle }: { label: string; value: boolean; onToggle: (val: boolean) => void }) {
  const { textStrong } = useAdminTheme();
  return (
    <XStack alignItems="center" justifyContent="space-between" paddingVertical="$1">
      <Text fontSize="$sm" color={textStrong} fontWeight="600">
        {label}
      </Text>
      <Switch size="$4" checked={value} onCheckedChange={onToggle} aria-label={label}>
        <Switch.Thumb />
      </Switch>
    </XStack>
  );
}

function TabButton({ label, active, onPress }: { label: string; active: boolean; onPress: () => void }) {
  const { primary, surfaceMuted, border, surface, textStrong } = useAdminTheme();
  return (
    <Pressable onPress={onPress} style={{ flex: 1 }}>
      <XStack
        alignItems="center"
        justifyContent="center"
        paddingVertical="$2.5"
        borderRadius={12}
        backgroundColor={active ? primary : surfaceMuted}
        borderWidth={1}
        borderColor={active ? primary : border}
      >
        <Text fontSize="$sm" color={active ? surface : textStrong} fontWeight="700">
          {label}
        </Text>
      </XStack>
    </Pressable>
  );
}

function LeaderboardRow({ rank, name, value }: { rank: number; name: string; value: string }) {
  const { textStrong, muted, border, surfaceMuted } = useAdminTheme();
  return (
    <XStack
      alignItems="center"
      justifyContent="space-between"
      paddingHorizontal="$2.5"
      paddingVertical="$2"
      borderRadius={12}
      borderWidth={1}
      borderColor={border}
      backgroundColor={surfaceMuted}
    >
      <XStack alignItems="center" space="$2">
        <Text fontSize="$xs" color={muted} fontWeight="700">
          #{rank}
        </Text>
        <Text fontSize="$sm" color={textStrong} fontWeight="600">
          {name}
        </Text>
      </XStack>
      <Text fontSize="$xs" color={muted}>
        {value}
      </Text>
    </XStack>
  );
}

function formatCount(value: number, locale?: string): string {
  const normalized = Number.isFinite(value) ? value : 0;
  return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(normalized);
}

function formatShortDate(iso: string, locale?: string): string {
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(date);
}

async function updateSetting(
  event: TenantEvent,
  setEvent: (event: TenantEvent) => void,
  slug: string | undefined,
  key: 'guest_downloads_enabled' | 'guest_sharing_enabled',
  value: boolean,
  setError: (message: string | null) => void,
  t: (key: string, fallback?: string) => string,
): Promise<void> {
  if (!slug) return;
  try {
    const updated = await updateEvent(slug, {
      settings: {
        ...(event.settings ?? {}),
        [key]: value,
      },
    });
    setEvent(updated);
  } catch (err) {
    if (!isAuthError(err)) {
      setError(getApiErrorMessage(err, t('events.errors.toggleFailed', 'Einstellung konnte nicht gespeichert werden.')));
    }
  }
}

function copyToClipboard(value: string, t: any) {
  if (typeof window !== 'undefined') {
    void window.navigator.clipboard.writeText(value);
    toast.success(t('events.recap.copySuccess', 'Link kopiert'));
  }
}

async function shareLink(value: string, event: TenantEvent | null, t: any) {
  if (typeof window !== 'undefined' && navigator.share) {
    try {
      await navigator.share({
        title: resolveName(event?.name ?? ''),
        text: t('events.recap.shareText', 'Schau dir die Fotos von unserem Event an!'),
        url: value,
      });
    } catch {
      // silently ignore or fallback to copy
    }
  }
}

function downloadQr(dataUrl: string) {
  const link = document.createElement('a');
  link.href = dataUrl;
  link.download = 'guest-gallery-qr.png';
  link.click();
}

function resolveName(name: TenantEvent['name']): string {
  if (typeof name === 'string') return name;
  if (name && typeof name === 'object') {
    return name.de ?? name.en ?? Object.values(name)[0] ?? 'Event';
  }
  return 'Event';
}

function formatDate(iso?: string | null, locale?: string): string {
  if (!iso) return '';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return date.toLocaleDateString(locale, { day: '2-digit', month: 'short', year: 'numeric' });
}
