'use client';

/**
 * Stories Mode — Instagram-style auto-advancing story viewer for the most
 * recent 24h of approved photos in the event.
 */

import { useEffect, useState, useRef } from 'react';
import Link from 'next/link';
import { ChevronLeft, ChevronRight, X, Pause, Play } from 'lucide-react';
import { db } from '@/lib/firebase';
import { collection, query, where, onSnapshot } from 'firebase/firestore';

interface Photo {
  id: string;
  url: string;
  guestName?: string;
  uploadedAt?: any;
  isApproved?: boolean;
}

const SLIDE_MS = 5000;

export default function StoriesClient({ eventId }: { eventId: string }) {
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);
  const progressRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const cutoff = Date.now() - 24 * 60 * 60 * 1000;
    const q = query(collection(db, 'events', eventId, 'photos'), where('isApproved', '==', true));
    const unsub = onSnapshot(q, (snap) => {
      const list: Photo[] = snap.docs
        .map((d) => ({ id: d.id, ...(d.data() as any) }))
        .filter((p: any) => {
          const t = p.uploadedAt?.toMillis?.() ?? 0;
          return t >= cutoff;
        })
        .sort((a: any, b: any) => (a.uploadedAt?.toMillis?.() ?? 0) - (b.uploadedAt?.toMillis?.() ?? 0));
      setPhotos(list);
    });
    return () => unsub();
  }, [eventId]);

  useEffect(() => {
    if (paused || photos.length === 0) return;
    const start = Date.now();
    if (progressRef.current) progressRef.current.style.width = '0%';
    const interval = setInterval(() => {
      const pct = Math.min(100, ((Date.now() - start) / SLIDE_MS) * 100);
      if (progressRef.current) progressRef.current.style.width = `${pct}%`;
    }, 50);
    const timer = setTimeout(() => {
      setIndex((i) => (i + 1 >= photos.length ? 0 : i + 1));
    }, SLIDE_MS);
    return () => { clearInterval(interval); clearTimeout(timer); };
  }, [index, paused, photos.length]);

  if (photos.length === 0) {
    return (
      <div className="min-h-screen bg-black text-white flex flex-col items-center justify-center p-6 gap-4">
        <p className="text-zinc-400">No photos in the last 24 hours.</p>
        <Link href={`/event/${eventId}`} className="text-amber-300 underline text-sm">Back to event</Link>
      </div>
    );
  }

  const photo = photos[index];

  return (
    <div className="min-h-screen bg-black text-white flex items-center justify-center">
      <div className="relative max-w-md w-full aspect-[9/16] bg-zinc-950 rounded-2xl overflow-hidden">
        {/* Progress bars */}
        <div className="absolute top-2 left-2 right-2 flex gap-1 z-20">
          {photos.map((_, i) => (
            <div key={i} className="flex-1 h-0.5 bg-white/30 rounded-full overflow-hidden">
              <div
                ref={i === index ? progressRef : null}
                className="h-full bg-white"
                style={{ width: i < index ? '100%' : '0%' }}
              />
            </div>
          ))}
        </div>

        {/* Header */}
        <div className="absolute top-6 left-3 right-3 flex items-center justify-between z-20">
          <div className="flex items-center gap-2">
            <div className="h-8 w-8 rounded-full bg-gradient-to-br from-amber-300 to-amber-600 flex items-center justify-center text-xs font-bold text-zinc-950">
              {(photo.guestName || 'G').charAt(0)}
            </div>
            <div>
              <p className="text-xs font-medium">{photo.guestName || 'Guest'}</p>
              <p className="text-[10px] text-zinc-400">24h story</p>
            </div>
          </div>
          <Link
            href={`/event/${eventId}`}
            className="h-8 w-8 rounded-full bg-black/50 flex items-center justify-center"
            aria-label="Close"
          >
            <X className="h-4 w-4" />
          </Link>
        </div>

        {/* Image */}
        <img src={photo.url} alt="" className="absolute inset-0 w-full h-full object-cover" />

        {/* Tap zones */}
        <button
          className="absolute top-0 bottom-0 left-0 w-1/3 z-10"
          onClick={() => setIndex((i) => (i - 1 + photos.length) % photos.length)}
          aria-label="Previous"
        >
          <ChevronLeft className="absolute left-2 top-1/2 -translate-y-1/2 h-8 w-8 text-white/50" />
        </button>
        <button
          className="absolute top-0 bottom-0 right-0 w-1/3 z-10"
          onClick={() => setIndex((i) => (i + 1) % photos.length)}
          aria-label="Next"
        >
          <ChevronRight className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 text-white/50" />
        </button>
        <button
          className="absolute bottom-3 left-1/2 -translate-x-1/2 h-10 w-10 rounded-full bg-black/50 flex items-center justify-center z-20"
          onClick={() => setPaused((p) => !p)}
          aria-label={paused ? 'Play' : 'Pause'}
        >
          {paused ? <Play className="h-5 w-5" /> : <Pause className="h-5 w-5" />}
        </button>
      </div>
    </div>
  );
}
