'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { db, callFunction, storage } from '@/lib/firebase';
import { useAuth } from '@/components/auth-provider';
import { useTheme } from '@/hooks/use-theme';
import EffectPicker from '@/components/effect-picker';
import {
  doc,
  onSnapshot,
  collection,
  query,
  orderBy,
  updateDoc,
  increment,
  addDoc,
  deleteDoc,
  setDoc,
  serverTimestamp,
} from 'firebase/firestore';
import {
  ArrowLeft,
  Camera,
  Share2,
  Users,
  Lock,
  Unlock,
  CheckCircle,
  XCircle,
  Heart,
  MapPin,
  MessageCircle,
  QrCode,
  Grid3X3,
  List,
  Image as ImageIcon,
  Download,
  Trophy,
  TrendingUp,
  Sun,
  Moon,
  Globe,
  Hash,
  Award,
  Loader2,
  AlertCircle,
  Sparkles,
  BarChart3,
  Trash2,
  Printer,
  Cloud,
  Film,
} from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { useLanguage } from '@/hooks/use-language';
import { t } from '@/lib/i18n';
import { toast } from '@/hooks/use-toast';

interface PhotoItem {
  id: string;
  url: string;
  guestName: string;
  likes: number;
  comments: number;
  status: string;
  isApproved: boolean;
  approvalStatus?: string;
  isFeatured?: boolean;
  isShareable?: boolean;
  uploadedBy: string;
}

interface EventData {
  id: string;
  name: string;
  eventType: string;
  status: string;
  isPrivate: boolean;
  allowGuestSharing: boolean;
  requireHostApproval: boolean;
  guests?: number;
  photos?: number;
  hostId: string;
  revealDate?: string;
  revealedAt?: string;
}

const mockChallenges: any[] = [];

export default function EventContent() {
  const router = useRouter();
  const params = useParams();
  const eventId = params.id as string;
  const { user } = useAuth();
  const { lang } = useLanguage();
  const { theme, toggleTheme } = useTheme();
  const [view, setView] = useState<'grid' | 'list'>('grid');
  const [showQR, setShowQR] = useState(false);
  const [activeTab, setActiveTab] = useState<'all' | 'pending' | 'yours' | 'social'>('all');
  const [selectedPhoto, setSelectedPhoto] = useState<string | null>(null);
  const [showEffectsFor, setShowEffectsFor] = useState<string | null>(null);
  const [event, setEvent] = useState<EventData | null>(null);
  const [photos, setPhotos] = useState<PhotoItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);
  const [curating, setCurating] = useState(false);
  const [analyticsData, setAnalyticsData] = useState<any>(null);
  const [showAnalytics, setShowAnalytics] = useState(false);
  const [driveLoading, setDriveLoading] = useState(false);
  const [reelLoading, setReelLoading] = useState(false);
  const [reelResult, setReelResult] = useState<{ url: string; photoCount: number } | null>(null);
  const [likedPhotos, setLikedPhotos] = useState<Set<string>>(new Set());
  const [commentText, setCommentText] = useState('');
  const [photoComments, setPhotoComments] = useState<Record<string, any[]>>({});
  const [photoReactions, setPhotoReactions] = useState<Record<string, Record<string, number>>>({});
  const [batchUploading, setBatchUploading] = useState(false);
  const [messages, setMessages] = useState<any[]>([]);
  const [messageText, setMessageText] = useState('');

  // Fetch event and photos from Firestore
  useEffect(() => {
    if (!eventId) return;

    const unsubEvent = onSnapshot(
      doc(db, 'events', eventId),
      (docSnap) => {
        if (docSnap.exists()) {
          setEvent({ id: docSnap.id, ...docSnap.data() } as EventData);
        } else {
          setError(t(lang, 'eventNotFound'));
        }
        setLoading(false);
      },
      (err) => {
        console.error('Event fetch error:', err);
        setError(t(lang, 'failedToLoadEvent') || 'Failed to load event');
        setLoading(false);
      }
    );

    const q = query(
      collection(db, 'events', eventId, 'photos'),
      orderBy('createdAt', 'desc')
    );

    const unsubPhotos = onSnapshot(
      q,
      (snapshot) => {
        const photoData = snapshot.docs.map((d) => ({
          id: d.id,
          ...d.data(),
        })) as PhotoItem[];
        setPhotos(photoData);
      },
      (err) => {
        console.error('Photos fetch error:', err);
      }
    );

    return () => {
      unsubEvent();
      unsubPhotos();
    };
  }, [eventId]);

  // Fetch comments for selected photo
  useEffect(() => {
    if (!selectedPhoto || !eventId) return;
    const commentsRef = collection(db, 'events', eventId, 'photos', selectedPhoto, 'comments');
    const q = query(commentsRef, orderBy('createdAt', 'desc'));
    const unsub = onSnapshot(q, (snap) => {
      const comments = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
      setPhotoComments((prev) => ({ ...prev, [selectedPhoto]: comments }));
    });
    return () => unsub();
  }, [selectedPhoto, eventId]);

  // Fetch photo reactions
  useEffect(() => {
    if (!eventId || !selectedPhoto) return;
    const reactionsRef = collection(db, 'events', eventId, 'photos', selectedPhoto, 'reactions');
    const q = query(reactionsRef);
    const unsub = onSnapshot(q, (snap) => {
      const counts: Record<string, number> = {};
      snap.docs.forEach((d) => {
        const data = d.data();
        counts[data.emoji || '❤️'] = (counts[data.emoji || '❤️'] || 0) + 1;
      });
      setPhotoReactions((prev) => ({ ...prev, [selectedPhoto]: counts }));
    });
    return () => unsub();
  }, [selectedPhoto, eventId]);

  // Fetch guestbook messages
  useEffect(() => {
    if (!eventId) return;
    const messagesRef = collection(db, 'events', eventId, 'messages');
    const q = query(messagesRef, orderBy('createdAt', 'desc'));
    const unsub = onSnapshot(q, (snap) => {
      setMessages(snap.docs.map((d) => ({ id: d.id, ...d.data() })));
    });
    return () => unsub();
  }, [eventId]);

  const handleSubmitMessage = async () => {
    if (!user || !messageText.trim()) return;
    try {
      await addDoc(collection(db, 'events', eventId, 'messages'), {
        text: messageText.trim(),
        userId: user.uid,
        userName: user.displayName || 'Guest',
        createdAt: serverTimestamp(),
      });
      setMessageText('');
    } catch (err) {
      console.error('Message error:', err);
    }
  };

  const handleLike = async (photoId: string) => {
    if (!user) {
      toast({ title: t(lang, 'signInFirst') || 'Please sign in first', variant: 'destructive' });
      return;
    }
    const alreadyLiked = likedPhotos.has(photoId);
    try {
      await updateDoc(doc(db, 'events', eventId, 'photos', photoId), {
        likes: increment(alreadyLiked ? -1 : 1),
      });
      setLikedPhotos((prev) => {
        const next = new Set(prev);
        if (alreadyLiked) next.delete(photoId);
        else next.add(photoId);
        return next;
      });
    } catch (err) {
      console.error('Like error:', err);
    }
  };

  const handleReaction = async (photoId: string, emoji: string) => {
    if (!user) {
      toast({ title: t(lang, 'signInFirst') || 'Please sign in first', variant: 'destructive' });
      return;
    }
    const reactionId = `${user.uid}_${emoji}`;
    const reactionRef = doc(db, 'events', eventId, 'photos', photoId, 'reactions', reactionId);
    const existing = photoReactions[photoId]?.[emoji];
    try {
      if (existing) {
        await deleteDoc(reactionRef);
      } else {
        await setDoc(reactionRef, {
          emoji,
          userId: user.uid,
          userName: user.displayName || 'Guest',
          createdAt: serverTimestamp(),
        });
      }
    } catch (err) {
      console.error('Reaction error:', err);
    }
  };

  const handleAddComment = async (photoId: string) => {
    if (!user || !commentText.trim()) return;
    try {
      await addDoc(collection(db, 'events', eventId, 'photos', photoId, 'comments'), {
        text: commentText.trim(),
        userId: user.uid,
        userName: user.displayName || 'Guest',
        createdAt: serverTimestamp(),
      });
      await updateDoc(doc(db, 'events', eventId, 'photos', photoId), {
        comments: increment(1),
      });
      setCommentText('');
    } catch (err) {
      console.error('Comment error:', err);
    }
  };

  const handleApprove = async (photoId: string) => {
    try {
      const reviewFn = callFunction('reviewPhoto');
      await reviewFn({ eventId, photoId, action: 'approve' });
    } catch (err: any) {
      console.error('Approve error:', err);
      toast({ title: err.message || 'Failed to approve photo', variant: 'destructive' });
    }
  };

  const handleReject = async (photoId: string) => {
    try {
      const reviewFn = callFunction('reviewPhoto');
      await reviewFn({ eventId, photoId, action: 'reject' });
    } catch (err: any) {
      console.error('Reject error:', err);
      toast({ title: err.message || 'Failed to reject photo', variant: 'destructive' });
    }
  };

  const handleDownloadAlbum = async () => {
    setDownloading(true);
    try {
      const downloadFn = callFunction('downloadAlbum');
      const result = await downloadFn({ eventId });
      const { downloadUrl } = result.data as any;
      window.open(downloadUrl, '_blank');
    } catch (error: any) {
      console.error('Download error:', error);
      toast({ title: error.message || t(lang, 'failedGenerateAlbum'), variant: 'destructive' });
    } finally {
      setDownloading(false);
    }
  };

  const handleDeleteEvent = async () => {
    if (!confirm(t(lang, 'confirmDelete') || 'Are you sure you want to delete this event?')) return;
    try {
      const deleteFn = callFunction('deleteEvent');
      await deleteFn({ eventId });
      toast({ title: t(lang, 'eventDeleted') || 'Event deleted', variant: 'success' });
      router.push('/dashboard');
    } catch (error: any) {
      console.error('Delete error:', error);
      toast({ title: error.message || t(lang, 'failedDeleteEvent'), variant: 'destructive' });
    }
  };

  const handleBatchUpload = async (files: FileList | null) => {
    if (!files || !files.length || !user || !eventId) return;
    setBatchUploading(true);
    const total = files.length;
    let uploaded = 0;
    for (const file of Array.from(files)) {
      try {
        const mediaId = `${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
        const { ref: storageRef, uploadBytes, getDownloadURL } = await import('firebase/storage');
        const isVideo = file.type.startsWith('video/');
        const extension = isVideo ? 'mp4' : 'jpg';
        const sRef = storageRef(storage, `events/${eventId}/photos/${mediaId}.${extension}`);
        await uploadBytes(sRef, file);
        const downloadUrl = await getDownloadURL(sRef);
        await addDoc(collection(db, 'events', eventId, 'photos'), {
          url: downloadUrl,
          storagePath: `events/${eventId}/photos/${mediaId}.${extension}`,
          uploadedBy: user.uid,
          guestName: user.displayName || 'Guest',
          eventId: eventId,
          isApproved: false,
          approvalStatus: 'pending',
          likes: 0,
          comments: 0,
          aiAnalyzed: false,
          mediaType: isVideo ? 'video' : 'photo',
          createdAt: serverTimestamp(),
        });
        uploaded++;
      } catch (err) {
        console.error('Batch upload error:', err);
      }
    }
    setBatchUploading(false);
    toast({ title: `${uploaded}/${total} media uploaded`, variant: 'success' });
  };

  const handleLoadAnalytics = async () => {
    try {
      const analyticsFn = callFunction('getEventAnalytics');
      const result = await analyticsFn({ eventId });
      setAnalyticsData(result.data);
      setShowAnalytics(true);
    } catch (error: any) {
      console.error('Analytics error:', error);
      toast({ title: error.message || t(lang, 'failedLoadAnalytics'), variant: 'destructive' });
    }
  };

  const handleSmartCuration = async () => {
    setCurating(true);
    try {
      const curateFn = callFunction('smartCuration');
      await curateFn({ eventId });
      toast({ title: t(lang, 'aiCurationComplete') || 'AI curation complete!', variant: 'success' });
    } catch (error: any) {
      console.error('Curation error:', error);
      toast({ title: error.message || t(lang, 'aiCurationFailed'), variant: 'destructive' });
    } finally {
      setCurating(false);
    }
  };

  const handleDriveBackup = async () => {
    setDriveLoading(true);
    try {
      const backupFn = callFunction('backupEventToDrive');
      const result = await backupFn({ eventId });
      const { folderUrl, photoCount } = result.data as any;
      toast({ title: `Backed up ${photoCount} photos to Drive`, variant: 'success' });
      if (folderUrl) window.open(folderUrl, '_blank');
    } catch (error: any) {
      const msg = error?.message || '';
      if (msg.includes('not connected') || msg.includes('not configured')) {
        // Start OAuth flow
        try {
          const authUrlFn = callFunction('getDriveAuthUrl');
          const authRes = await authUrlFn({ eventId });
          const { url } = authRes.data as any;
          if (url) {
            const popup = window.open(url, 'drive-oauth', 'width=600,height=700');
            if (!popup) toast({ title: t(lang, 'allowPopups'), variant: 'destructive' });
          }
        } catch (e: any) {
          toast({ title: e?.message || 'Failed to start Google Drive OAuth', variant: 'destructive' });
        }
      } else {
        toast({ title: msg || 'Drive backup failed', variant: 'destructive' });
      }
    } finally {
      setDriveLoading(false);
    }
  };

  const handleHighlightReel = async () => {
    setReelLoading(true);
    try {
      const reelFn = callFunction('generateHighlightReel');
      const result = await reelFn({ eventId });
      const { url, photoCount } = result.data as any;
      setReelResult({ url, photoCount });
      toast({ title: `Highlight reel ready (${photoCount} photos)`, variant: 'success' });
    } catch (error: any) {
      console.error('Reel error:', error);
      toast({ title: error.message || t(lang, 'failedGenerateReel'), variant: 'destructive' });
    } finally {
      setReelLoading(false);
    }
  };

  // Listen for Drive OAuth success from popup
  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data?.type === 'drive-oauth-success') {
        toast({ title: 'Google Drive connected! You can now backup.', variant: 'success' });
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  const isHost = user?.uid === event?.hostId;

  const isRevealed = event?.status === 'revealed' || (event?.revealDate ? new Date(event.revealDate) <= new Date() : true);

  const filteredPhotos = activeTab === 'pending'
    ? photos.filter((p) => p.status === 'pending' || p.approvalStatus === 'pending')
    : activeTab === 'yours'
    ? photos.filter((p) => p.uploadedBy === user?.uid)
    : photos;

  const handleShare = async (photoId: string) => {
    const shareUrl = `${window.location.origin}/event/${eventId}/photo/${photoId}`;
    if (navigator.share) {
      await navigator.share({
        title: event?.name || 'Event',
        text: t(lang, 'checkOutPhoto') || 'Check out this photo from our event!',
        url: shareUrl,
      });
    } else {
      await navigator.clipboard.writeText(shareUrl);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-zinc-500" />
      </div>
    );
  }

  if (error || !event) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
          <h2 className="text-lg font-semibold mb-2">{error || t(lang, 'eventNotFound')}</h2>
          <Link href="/dashboard" className="text-sm text-zinc-400 hover:text-white">
            {t(lang, 'backToDashboard') || 'Back to Dashboard'}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="sticky top-0 z-50 border-b border-zinc-900 bg-background/80 backdrop-blur-md">
        <div className="max-w-3xl mx-auto px-4 h-14 flex items-center justify-between">
          <Link href="/dashboard" className="inline-flex items-center gap-2 text-zinc-500 hover:text-zinc-300 text-sm" aria-label="Back to dashboard">
            <ArrowLeft className="h-4 w-4" />
          </Link>
          <h1 className="text-sm font-semibold truncate max-w-[200px]">{event.name}</h1>
          <div className="flex items-center gap-2">
            <button onClick={toggleTheme} className="text-zinc-500 hover:text-zinc-300" aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}>
              {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
            </button>
            <button onClick={() => setShowQR(!showQR)} className="text-zinc-500 hover:text-zinc-300" aria-label="Show QR code" aria-expanded={showQR}>
              <QrCode className="h-5 w-5" />
            </button>
          </div>
        </div>
      </header>

      {/* Event Info */}
      <div className="max-w-3xl mx-auto px-4 py-6">
        <div className="flex items-center gap-3 mb-4">
          <div className="h-14 w-14 rounded-2xl bg-zinc-800 flex items-center justify-center text-3xl">
            {event.eventType === 'wedding' && '💍'}
            {event.eventType === 'party' && '🎉'}
            {event.eventType === 'birthday' && '🎂'}
            {event.eventType === 'trip' && '✈️'}
            {event.eventType === 'corporate' && '🏢'}
            {event.eventType === 'other' && '📸'}
          </div>
          <div className="flex-1">
            <h2 className="text-xl font-bold">{event.name}</h2>
            <div className="flex items-center gap-2 text-xs text-zinc-500 mt-1">
              <span className="flex items-center gap-1">
                <Users className="h-3 w-3" />
                {event.guests || 0} {t(lang, 'guests')}
              </span>
              <span className="flex items-center gap-1">
                <ImageIcon className="h-3 w-3" />
                {event.photos || 0} {t(lang, 'photos')}
              </span>
              {event.isPrivate ? (
                <span className="flex items-center gap-1 text-amber-400">
                  <Lock className="h-3 w-3" />
                  {t(lang, 'privateEvent')}
                </span>
              ) : (
                <span className="flex items-center gap-1 text-emerald-400">
                  <Unlock className="h-3 w-3" />
                  {t(lang, 'publicEvent')}
                </span>
              )}
            </div>
          </div>
          {isHost && (
            <>
              <Link
                href={`/event/${eventId}/slideshow`}
                target="_blank"
                className="h-10 w-10 rounded-full bg-amber-900/50 text-amber-300 flex items-center justify-center hover:bg-amber-900/70 transition-colors"
                title="Live Slideshow"
              >
                <Sparkles className="h-5 w-5" />
              </Link>
              <Link
                href={`/event/${eventId}/print`}
                target="_blank"
                className="h-10 w-10 rounded-full bg-emerald-900/50 text-emerald-300 flex items-center justify-center hover:bg-emerald-900/70 transition-colors"
                title="Print Station"
              >
                <Printer className="h-5 w-5" />
              </Link>
              <button
                onClick={handleLoadAnalytics}
                className="h-10 w-10 rounded-full bg-blue-900/50 text-blue-300 flex items-center justify-center hover:bg-blue-900/70 transition-colors"
                title="Analytics"
              >
                <BarChart3 className="h-5 w-5" />
              </button>
              <button
                onClick={handleSmartCuration}
                disabled={curating}
                className="h-10 w-10 rounded-full bg-violet-900/50 text-violet-300 flex items-center justify-center hover:bg-violet-900/70 transition-colors disabled:opacity-50"
                title="Auto Highlight Reel"
              >
                {curating ? <Loader2 className="h-5 w-5 animate-spin" /> : <Sparkles className="h-5 w-5" />}
              </button>
              <button
                onClick={handleDownloadAlbum}
                disabled={downloading}
                className="h-10 w-10 rounded-full bg-zinc-800 text-white flex items-center justify-center hover:bg-zinc-700 transition-colors disabled:opacity-50"
                title={t(lang, 'download')}
              >
                {downloading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Download className="h-5 w-5" />}
              </button>
              <button
                onClick={handleDriveBackup}
                disabled={driveLoading}
                className="h-10 w-10 rounded-full bg-green-900/50 text-green-300 flex items-center justify-center hover:bg-green-900/70 transition-colors disabled:opacity-50"
                title="Backup to Google Drive"
              >
                {driveLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Cloud className="h-5 w-5" />}
              </button>
              <button
                onClick={handleHighlightReel}
                disabled={reelLoading}
                className="h-10 w-10 rounded-full bg-rose-900/50 text-rose-300 flex items-center justify-center hover:bg-rose-900/70 transition-colors disabled:opacity-50"
                title="Generate Highlight Reel"
              >
                {reelLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Film className="h-5 w-5" />}
              </button>
              <button
                onClick={handleDeleteEvent}
                className="h-10 w-10 rounded-full bg-red-900/50 text-red-300 flex items-center justify-center hover:bg-red-900/70 transition-colors"
                title={t(lang, 'delete')}
              >
                <Trash2 className="h-5 w-5" />
              </button>
            </>
          )}
          <label className="h-10 w-10 rounded-full bg-zinc-800 text-white flex items-center justify-center hover:bg-zinc-700 transition-colors cursor-pointer disabled:opacity-50">
            <input
              type="file"
              accept="image/*"
              multiple
              className="hidden"
              onChange={(e) => handleBatchUpload(e.target.files)}
              disabled={batchUploading}
            />
            {batchUploading ? <Loader2 className="h-5 w-5 animate-spin" /> : <ImageIcon className="h-5 w-5" />}
          </label>
          <Link
            href={`/camera?event=${eventId}`}
            className="h-10 w-10 rounded-full bg-gradient-to-r from-indigo-500 to-purple-600 text-white flex items-center justify-center hover:from-indigo-600 hover:to-purple-700 transition-all shadow-md shadow-indigo-500/20"
          >
            <Camera className="h-5 w-5" />
          </Link>
        </div>

        {/* QR Modal */}
        {showQR && (
          <div className="mb-6 p-6 rounded-2xl border border-zinc-800 bg-zinc-900/50 text-center">
            <p className="text-sm text-zinc-400 mb-3">{t(lang, 'scanToJoin')}</p>
            <div className="inline-block p-4 bg-white rounded-xl">
              <QRCodeSVG value={`${typeof window !== 'undefined' ? window.location.origin : ''}/event/${eventId}/upload`} size={180} />
            </div>
            <p className="text-xs text-zinc-500 mt-3">{t(lang, 'eventCode')}: <span className="font-mono text-white">{eventId}</span></p>
            {/* WhatsApp share */}
            <div className="mt-4 flex flex-col sm:flex-row items-center justify-center gap-2">
              <a
                href={`https://wa.me/?text=${encodeURIComponent(
                  lang === 'ar'
                    ? `حياكم الله في مناسبة ${event?.name || ''} 🌷\n\nشاركونا صوركم وفيديوهاتكم من خلال الرابط:\n${typeof window !== 'undefined' ? window.location.origin : ''}/event/${eventId}/upload`
                    : `You're invited to share photos at ${event?.name || ''}!\nUpload here: ${typeof window !== 'undefined' ? window.location.origin : ''}/event/${eventId}/upload`
                )}`}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 h-9 px-4 rounded-full bg-emerald-500/20 border border-emerald-500/30 text-emerald-400 text-sm hover:bg-emerald-500/30 transition-colors"
              >
                <Share2 className="h-4 w-4" />
                {lang === 'ar' ? 'مشاركة عبر واتساب' : 'Share via WhatsApp'}
              </a>
              <button
                onClick={() => navigator.clipboard.writeText(`${typeof window !== 'undefined' ? window.location.origin : ''}/event/${eventId}/upload`)}
                className="inline-flex items-center gap-2 h-9 px-4 rounded-full bg-zinc-800 text-zinc-300 text-sm hover:bg-zinc-700 transition-colors"
              >
                <Hash className="h-4 w-4" />
                {lang === 'ar' ? 'نسخ رابط الرفع' : 'Copy upload link'}
              </button>
            </div>
          </div>
        )}

        {/* Tabs */}
        <div className="flex items-center gap-1 mb-4 border-b border-zinc-800 overflow-x-auto">
          {[
            { id: 'all', label: t(lang, 'allPhotos'), count: event.photos || 0 },
            ...(event.requireHostApproval ? [{ id: 'pending', label: t(lang, 'pending'), count: photos.filter((p) => p.approvalStatus === 'pending').length }] : []),
            { id: 'yours', label: t(lang, 'yours'), count: photos.filter((p) => p.uploadedBy === user?.uid).length },
            { id: 'social', label: t(lang, 'social'), count: mockChallenges.length },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                activeTab === tab.id
                  ? 'border-white text-white'
                  : 'border-transparent text-zinc-500 hover:text-zinc-300'
              }`}
            >
              {tab.label}
              <span className="ml-1.5 text-xs text-zinc-600">{tab.count}</span>
            </button>
          ))}
        </div>

        {/* Social Tab Content */}
        {activeTab === 'social' && (
          <div className="space-y-4 mb-6">
            {/* Share Event */}
            <div className="p-5 rounded-2xl border border-zinc-800 bg-zinc-900/30">
              <h3 className="font-semibold mb-1 flex items-center gap-2">
                <Globe className="h-4 w-4 text-blue-400" />
                {t(lang, 'shareThisEvent')}
              </h3>
              <p className="text-sm text-zinc-500 mb-4">{t(lang, 'spreadTheWord')}</p>

              {/* QR Code with decorative frame */}
              <div className="flex justify-center mb-5">
                <div className="relative p-1 rounded-3xl bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500">
                  <div className="bg-zinc-950 rounded-[20px] p-5 flex flex-col items-center">
                    <div className="bg-white rounded-2xl p-4 shadow-lg shadow-purple-500/10">
                      <QRCodeSVG
                        value={`${typeof window !== 'undefined' ? window.location.origin : ''}/event/${eventId}/upload`}
                        size={180}
                        level="H"
                        includeMargin={false}
                      />
                    </div>
                    <p className="mt-3 text-xs text-zinc-400 text-center">{lang === 'ar' ? 'امسح للمشاركة' : 'Scan to share photos'}</p>
                    <div className="mt-2 px-3 py-1.5 rounded-lg bg-zinc-800/80 border border-zinc-700/50">
                      <p className="text-[11px] font-mono text-zinc-300 select-all">{typeof window !== 'undefined' ? window.location.origin : 'once.film'}/event/{eventId}/upload</p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <input
                  type="text"
                  readOnly
                  value={`${typeof window !== 'undefined' ? window.location.origin : 'once.film'}/event/${eventId}`}
                  className="flex-1 h-10 px-3 bg-zinc-900 border border-zinc-800 rounded-xl text-sm text-zinc-400"
                />
                <button
                  onClick={() => { navigator.clipboard.writeText(`${window.location.origin}/event/${eventId}`); toast({ title: lang === 'ar' ? 'تم النسخ' : 'Copied!' }); }}
                  className="h-10 px-4 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-sm font-medium hover:from-indigo-600 hover:to-purple-700 transition-all"
                >
                  Copy Link
                </button>
              </div>
              {/* Email Invite */}
              {isHost && (
                <div className="mt-4 pt-4 border-t border-zinc-800">
                  <label className="block text-xs font-medium mb-2 text-zinc-400">{lang === 'ar' ? 'دعوة بالبريد الإلكتروني (يتم إرسال QR + رابط)' : 'Invite by Email (sends QR + link)'}</label>
                  <div className="flex items-center gap-2">
                    <input
                      id="invite-email-input"
                      type="email"
                      placeholder="friend@example.com"
                      className="flex-1 h-10 px-3 bg-zinc-900 border border-zinc-800 rounded-xl text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-zinc-600"
                      onKeyDown={async (e) => {
                        if (e.key === 'Enter') {
                          const email = (e.target as HTMLInputElement).value.trim();
                          if (email) {
                            try {
                              await callFunction('sendInvite')({ eventId, channel: 'email', to: email });
                              toast({ title: lang === 'ar' ? `تم إرسال الدعوة إلى ${email}` : `Invite sent to ${email}` });
                              (e.target as HTMLInputElement).value = '';
                            } catch (err: any) {
                              toast({ title: err?.message || 'Failed to send', variant: 'destructive' });
                            }
                          }
                        }
                      }}
                    />
                    <button
                      onClick={async () => {
                        const input = document.getElementById('invite-email-input') as HTMLInputElement;
                        const email = input?.value?.trim();
                        if (!email) return;
                        try {
                          await callFunction('sendInvite')({ eventId, channel: 'email', to: email });
                          toast({ title: lang === 'ar' ? `تم إرسال الدعوة إلى ${email}` : `Invite sent to ${email}` });
                          input.value = '';
                        } catch (err: any) {
                          toast({ title: err?.message || 'Failed to send', variant: 'destructive' });
                        }
                      }}
                      className="h-10 px-4 rounded-xl bg-emerald-900/50 text-emerald-300 text-sm font-medium hover:bg-emerald-900/70 transition-colors"
                    >
                      {lang === 'ar' ? 'إرسال' : 'Send'}
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Photo Challenges */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold flex items-center gap-2">
                  <Trophy className="h-4 w-4 text-amber-400" />
                  {t(lang, 'photoChallenges')}
                </h3>
              </div>
              {mockChallenges.length === 0 ? (
                <div className="p-8 rounded-2xl border border-zinc-800 bg-zinc-900/30 text-center">
                  <Trophy className="h-8 w-8 text-zinc-600 mx-auto mb-3" />
                  <p className="text-sm text-zinc-400">{t(lang, 'noChallengesYet') || 'No challenges yet'}</p>
                  <p className="text-xs text-zinc-600 mt-1">{t(lang, 'hostCanCreate') || 'Host can create photo challenges'}</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {mockChallenges.map((challenge: any) => (
                    <div key={challenge.id} className="p-4 rounded-2xl border border-zinc-800 bg-zinc-900/30">
                      <div className="flex items-start justify-between">
                        <div>
                          <h4 className="font-medium">{challenge.title}</h4>
                          <p className="text-sm text-zinc-500 mt-1">{challenge.description}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Viral Stats */}
            <div className="grid grid-cols-3 gap-3">
              {[
                { label: t(lang, 'shares'), value: event.allowGuestSharing ? (event.photos || 0) * 3 : 0, icon: Share2 },
                { label: t(lang, 'reach'), value: ((event.guests || 0) * 15 + (event.photos || 0) * 8), icon: Users },
                { label: t(lang, 'engagement'), value: event.photos && event.guests ? Math.min(100, Math.round((event.photos / Math.max(1, event.guests)) * 12)) + '%' : '0%', icon: TrendingUp },
              ].map((stat) => (
                <div key={stat.label} className="p-4 rounded-2xl border border-zinc-800 bg-zinc-900/30 text-center">
                  <stat.icon className="h-4 w-4 text-zinc-500 mx-auto mb-2" />
                  <div className="text-lg font-bold">{typeof stat.value === 'number' ? stat.value.toLocaleString() : stat.value}</div>
                  <div className="text-xs text-zinc-500">{stat.label}</div>
                </div>
              ))}
            </div>

            {/* Guestbook */}
            <div className="p-5 rounded-2xl border border-zinc-800 bg-zinc-900/30">
              <h3 className="font-semibold mb-1 flex items-center gap-2">
                <MessageCircle className="h-4 w-4 text-emerald-400" />
                {t(lang, 'guestbook') || 'Guestbook'}
              </h3>
              <p className="text-sm text-zinc-500 mb-4">{t(lang, 'leaveAMessage') || 'Leave a message for the host'}</p>
              {messages.length > 0 && (
                <div className="space-y-3 mb-4 max-h-60 overflow-y-auto">
                  {messages.map((msg) => (
                    <div key={msg.id} className="flex items-start gap-2 p-3 rounded-xl bg-zinc-800/30">
                      <div className="h-7 w-7 rounded-full bg-zinc-700 flex items-center justify-center text-[10px] font-medium shrink-0">
                        {(msg.userName || 'G').charAt(0)}
                      </div>
                      <div>
                        <span className="text-xs font-medium">{msg.userName || 'Guest'}</span>
                        <p className="text-sm text-zinc-300">{msg.text}</p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {user && (
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={messageText}
                    onChange={(e) => setMessageText(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleSubmitMessage()}
                    placeholder={t(lang, 'writeMessage') || 'Write a message...'}
                    className="flex-1 h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-500"
                  />
                  <button
                    onClick={handleSubmitMessage}
                    disabled={!messageText.trim()}
                    className="h-9 px-3 rounded-lg bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-medium disabled:opacity-30"
                  >
                    {t(lang, 'send') || 'Send'}
                  </button>
                </div>
              )}
            </div>
          </div>
        )}

        {/* View Toggle - only show for photo tabs */}
        {activeTab !== 'social' && (
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-1 p-0.5 rounded-lg bg-zinc-900 border border-zinc-800">
            <button
              onClick={() => setView('grid')}
              className={`h-8 w-8 rounded-md flex items-center justify-center transition-colors ${
                view === 'grid' ? 'bg-zinc-800 text-white' : 'text-zinc-500'
              }`}
            >
              <Grid3X3 className="h-4 w-4" />
            </button>
            <button
              onClick={() => setView('list')}
              className={`h-8 w-8 rounded-md flex items-center justify-center transition-colors ${
                view === 'list' ? 'bg-zinc-800 text-white' : 'text-zinc-500'
              }`}
            >
              <List className="h-4 w-4" />
            </button>
          </div>
          <Link
            href={`/event/${eventId}/map`}
            className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg border border-zinc-800 text-xs text-zinc-400 hover:text-white hover:border-zinc-600 transition-colors"
          >
            <MapPin className="h-3.5 w-3.5" />
            Map
          </Link>
        </div>
        )}

        {/* Reveal Banner */}
        {activeTab !== 'social' && !isRevealed && (
          <div className="mb-4 p-4 rounded-2xl border border-amber-800/50 bg-amber-950/30 text-center">
            <Lock className="h-5 w-5 text-amber-400 mx-auto mb-2" />
            <p className="text-sm text-amber-200 font-medium">{t(lang, 'albumLocked')}</p>
            {event?.revealDate && (
              <p className="text-xs text-amber-400/70 mt-1">
                {t(lang, 'revealsOn')}: {new Date(event.revealDate).toLocaleString()}
              </p>
            )}
          </div>
        )}

        {/* Photos Grid - hide on social tab */}
        {activeTab !== 'social' && filteredPhotos.length === 0 ? (
          <div className="text-center py-16">
            <ImageIcon className="h-12 w-12 text-zinc-700 mx-auto mb-4" />
            <p className="text-zinc-500 text-sm">{t(lang, 'noPhotosYet')}</p>
            <Link href={`/camera?event=${eventId}`} className="inline-flex items-center gap-2 mt-4 h-10 px-6 rounded-full bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-sm font-medium hover:from-indigo-600 hover:to-purple-700 transition-all shadow-md shadow-indigo-500/20">
              <Camera className="h-4 w-4" /> {t(lang, 'takeFirstPhoto')}
            </Link>
          </div>
        ) : activeTab !== 'social' && view === 'grid' ? (
          <div className="grid grid-cols-3 gap-1" role="grid">
            {filteredPhotos.map((photo) => (
              <button
                key={photo.id}
                onClick={() => setSelectedPhoto(photo.id)}
                className="relative aspect-square group"
                aria-label={`View photo by ${photo.guestName}`}
                role="gridcell"
              >
                <img
                  src={photo.url}
                  alt={`Photo by ${photo.guestName}`}
                  className="w-full h-full object-cover rounded-lg"
                  loading="lazy"
                />
                {photo.isFeatured && (
                  <div className="absolute top-1 right-1 bg-violet-500/80 backdrop-blur-sm text-white text-[9px] font-bold px-1.5 py-0.5 rounded-full">
                    AI Pick
                  </div>
                )}
                {photo.status === 'pending' && (
                  <div className="absolute inset-0 bg-black/60 rounded-lg flex items-center justify-center">
                    <span className="text-xs text-amber-400 font-medium">{t(lang, 'pending')}</span>
                  </div>
                )}
                <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors rounded-lg flex items-end justify-between p-2 opacity-0 group-hover:opacity-100">
                  <span className="text-xs text-white">{photo.guestName}</span>
                  <div className="flex items-center gap-1">
                    <Heart className="h-3 w-3 text-white" />
                    <span className="text-xs text-white">{photo.likes}</span>
                  </div>
                </div>
              </button>
            ))}
          </div>
        ) : activeTab !== 'social' && (
          <div className="space-y-3">
            {filteredPhotos.map((photo) => (
              <div key={photo.id} className="flex gap-3 p-3 rounded-xl border border-zinc-800 bg-zinc-900/30">
                <img src={photo.url} alt="" className="h-20 w-20 object-cover rounded-lg shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-sm font-medium">{photo.guestName}</span>
                    {photo.status === 'pending' && (
                      <span className="text-[10px] px-2 py-0.5 rounded-full bg-amber-950/50 text-amber-400 border border-amber-800">{t(lang, 'pending')}</span>
                    )}
                  </div>
                  <div className="flex items-center gap-3 text-xs text-zinc-500">
                    <span className="flex items-center gap-1">
                      <Heart className="h-3 w-3" /> {photo.likes}
                    </span>
                    <span className="flex items-center gap-1">
                      <MessageCircle className="h-3 w-3" /> {photo.comments}
                    </span>
                  </div>
                  {isHost && photo.approvalStatus === 'pending' && (
                    <div className="flex items-center gap-2 mt-2">
                      <button
                        onClick={() => handleApprove(photo.id)}
                        className="h-7 px-3 rounded-lg bg-emerald-950/50 text-emerald-400 text-xs border border-emerald-800 flex items-center gap-1 hover:bg-emerald-900/30 transition-colors"
                      >
                        <CheckCircle className="h-3 w-3" /> {t(lang, 'approve')}
                      </button>
                      <button
                        onClick={() => handleReject(photo.id)}
                        className="h-7 px-3 rounded-lg bg-red-950/50 text-red-400 text-xs border border-red-800 flex items-center gap-1 hover:bg-red-900/30 transition-colors"
                      >
                        <XCircle className="h-3 w-3" /> {t(lang, 'reject')}
                      </button>
                    </div>
                  )}
                </div>
                <button
                  onClick={() => handleShare(photo.id)}
                  className="shrink-0 text-zinc-500 hover:text-white transition-colors"
                >
                  <Share2 className="h-4 w-4" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Photo Detail Modal */}
      {selectedPhoto && (
        <div
          className="fixed inset-0 z-[100] bg-black/90 flex items-center justify-center p-4"
          onClick={() => setSelectedPhoto(null)}
        >
          <div className="max-w-lg w-full" onClick={(e) => e.stopPropagation()}>
            {(() => {
              const photo = photos.find((p) => p.id === selectedPhoto);
              if (!photo) return null;
              return (
                <>
                  <div className="relative">
                    <img src={photo.url} alt="" className="w-full rounded-2xl" />
                    <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 to-transparent rounded-b-2xl">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-sm font-medium">{photo.guestName}</p>
                          <div className="flex items-center gap-3 text-xs text-zinc-400 mt-1">
                            <button
                              onClick={() => handleLike(photo.id)}
                              className={`flex items-center gap-1 transition-colors ${likedPhotos.has(photo.id) ? 'text-red-400' : 'hover:text-white'}`}
                            >
                              <Heart className={`h-3 w-3 ${likedPhotos.has(photo.id) ? 'fill-current' : ''}`} /> {photo.likes}
                            </button>
                            <span className="flex items-center gap-1">
                              <MessageCircle className="h-3 w-3" /> {photo.comments}
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => handleLike(photo.id)}
                            className={`h-9 w-9 rounded-full backdrop-blur-sm flex items-center justify-center transition-colors ${likedPhotos.has(photo.id) ? 'bg-red-500/40 text-red-200' : 'bg-white/20 hover:bg-white/30 text-white'}`}
                          >
                            <Heart className={`h-4 w-4 ${likedPhotos.has(photo.id) ? 'fill-current' : ''}`} />
                          </button>
                          <button
                            onClick={() => setShowEffectsFor(photo.id)}
                            className="h-9 w-9 rounded-full bg-amber-300/30 backdrop-blur-sm flex items-center justify-center hover:bg-amber-300/50 transition-colors"
                            aria-label="Apply AI effects"
                            title="AI Effects"
                          >
                            <Sparkles className="h-4 w-4 text-amber-100" />
                          </button>
                          <button
                            onClick={() => handleShare(photo.id)}
                            className="h-9 w-9 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center hover:bg-white/30 transition-colors"
                          >
                            <Share2 className="h-4 w-4 text-white" />
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  {/* Reactions */}
                  <div className="mt-3 flex items-center gap-1">
                    {['❤️', '🔥', '😂'].map((emoji) => {
                      const count = photoReactions[photo.id]?.[emoji] || 0;
                      return (
                        <button
                          key={emoji}
                          onClick={() => handleReaction(photo.id, emoji)}
                          className={`h-8 px-2 rounded-lg text-xs flex items-center gap-1 transition-colors border ${count > 0 ? 'bg-zinc-800 border-zinc-600 text-white' : 'bg-transparent border-zinc-800 text-zinc-500 hover:border-zinc-600'}`}
                        >
                          <span>{emoji}</span>
                          {count > 0 && <span>{count}</span>}
                        </button>
                      );
                    })}
                  </div>

                  {photoComments[photo.id] && photoComments[photo.id].length > 0 && (
                    <div className="mt-4 max-h-40 overflow-y-auto space-y-2">
                      {photoComments[photo.id].map((c) => (
                        <div key={c.id} className="flex items-start gap-2 text-sm">
                          <div className="h-6 w-6 rounded-full bg-zinc-700 flex items-center justify-center text-[10px] font-medium shrink-0">
                            {(c.userName || 'G').charAt(0)}
                          </div>
                          <div>
                            <span className="font-medium text-xs">{c.userName || 'Guest'}</span>
                            <p className="text-zinc-400 text-xs">{c.text}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  {user && (
                    <div className="mt-3 flex items-center gap-2">
                      <input
                        type="text"
                        value={commentText}
                        onChange={(e) => setCommentText(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && handleAddComment(photo.id)}
                        placeholder={t(lang, 'addComment') || 'Add a comment...'}
                        className="flex-1 h-9 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-500"
                      />
                      <button
                        onClick={() => handleAddComment(photo.id)}
                        disabled={!commentText.trim()}
                        className="h-9 px-3 rounded-lg bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-medium disabled:opacity-30"
                      >
                        {t(lang, 'post') || 'Post'}
                      </button>
                    </div>
                  )}
                </>
              );
            })()}
          </div>
        </div>
      )}

      {/* Analytics Modal */}
      {showAnalytics && analyticsData && (
        <div className="fixed inset-0 z-[100] bg-black/80 flex items-center justify-center p-4" onClick={() => setShowAnalytics(false)}>
          <div className="max-w-md w-full bg-zinc-900 border border-zinc-800 rounded-2xl p-6" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-bold mb-4">{t(lang, 'analytics') || 'Event Analytics'}</h3>
            <div className="grid grid-cols-2 gap-4 mb-6">
              <div className="p-4 rounded-xl bg-zinc-800/50 text-center">
                <div className="text-2xl font-bold">{analyticsData.totalGuests}</div>
                <div className="text-xs text-zinc-400">{t(lang, 'totalGuests') || 'Guests'}</div>
              </div>
              <div className="p-4 rounded-xl bg-zinc-800/50 text-center">
                <div className="text-2xl font-bold">{analyticsData.totalPhotos}</div>
                <div className="text-xs text-zinc-400">{t(lang, 'totalPhotos') || 'Photos'}</div>
              </div>
              <div className="p-4 rounded-xl bg-zinc-800/50 text-center">
                <div className="text-2xl font-bold text-emerald-400">{analyticsData.approvedPhotos}</div>
                <div className="text-xs text-zinc-400">{t(lang, 'approved') || 'Approved'}</div>
              </div>
              <div className="p-4 rounded-xl bg-zinc-800/50 text-center">
                <div className="text-2xl font-bold text-amber-400">{analyticsData.pendingPhotos}</div>
                <div className="text-xs text-zinc-400">{t(lang, 'pending') || 'Pending'}</div>
              </div>
            </div>
            {analyticsData.topUploaders && analyticsData.topUploaders.length > 0 && (
              <div>
                <h4 className="text-sm font-medium mb-3">{t(lang, 'topUploaders') || 'Top Uploaders'}</h4>
                <div className="space-y-2">
                  {analyticsData.topUploaders.map((u: any, i: number) => (
                    <div key={i} className="flex items-center justify-between p-2 rounded-lg bg-zinc-800/30">
                      <span className="text-sm">{u.name || 'Guest'}</span>
                      <span className="text-xs text-zinc-400">{u.photos} {t(lang, 'photos')}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
            <button onClick={() => setShowAnalytics(false)} className="mt-6 w-full h-10 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium text-sm hover:from-indigo-600 hover:to-purple-700 transition-all">
              {t(lang, 'close')}
            </button>
          </div>
        </div>
      )}

      {/* Highlight Reel Result Modal */}
      {reelResult && (
        <div className="fixed inset-0 z-[100] bg-black/90 flex items-center justify-center p-4" onClick={() => setReelResult(null)}>
          <div className="max-w-lg w-full" onClick={(e) => e.stopPropagation()}>
            <p className="text-sm text-emerald-300 font-medium mb-2">🎬 Highlight reel ready!</p>
            <div className="rounded-xl overflow-hidden bg-black border border-zinc-800">
              <video src={reelResult.url} controls autoPlay className="w-full" />
            </div>
            <div className="flex gap-2 mt-3">
              <a
                href={reelResult.url}
                target="_blank"
                rel="noopener noreferrer"
                download
                className="flex-1 h-10 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center justify-center gap-2 hover:bg-amber-200"
              >
                <Download className="h-4 w-4" /> Download
              </a>
              <button
                onClick={() => setReelResult(null)}
                className="flex-1 h-10 rounded-lg border border-zinc-700 text-white text-sm hover:bg-zinc-800"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {showEffectsFor && (() => {
        const targetPhoto = photos.find((p) => p.id === showEffectsFor);
        if (!targetPhoto) return null;
        return (
          <EffectPicker
            eventId={eventId}
            photoId={targetPhoto.id}
            photoUrl={targetPhoto.url}
            onClose={() => setShowEffectsFor(null)}
          />
        );
      })()}
    </div>
  );
}
