'use client';

import { motion, AnimatePresence } from 'motion/react';
import { useEffect, useState } from 'react';
import { JokerCard } from '@/components/joker-card';
import { MatchResult } from '@/components/match-overlay';

interface JokerRevealProps {
  visible: boolean;
  match: any;
  mapsUrl: string;
  sessionCode?: string;
  onNewTable: () => void;
  onLeave: () => void;
}

// Vollbild-Joker-Aufdeckung wie im Mockup: magischer Nebel + sanfter Mega-Zoom
// + 3D-Flip. Vorderseite = Tarot-Karte, Rueckseite = das Joker-Ergebnis
// (identisch zum normalen Ergebnis-Screen, nur mit Joker-Branding). Loest der
// Host aus; alle anderen sehen das Ergebnis synchron ueber den Poll.
export function JokerReveal({ visible, match, mapsUrl, sessionCode, onNewTable, onLeave }: JokerRevealProps) {
  const [flipped, setFlipped] = useState(false);
  const [surging, setSurging] = useState(false);

  useEffect(() => {
    if (!visible) {
      setFlipped(false);
      setSurging(false);
      return;
    }
    const surgeTimer = setTimeout(() => setSurging(true), 120);
    const flipTimer = setTimeout(() => setFlipped(true), 650);
    return () => {
      clearTimeout(surgeTimer);
      clearTimeout(flipTimer);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          className="fixed inset-0 z-50 overflow-hidden bg-black"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          {/* Magischer Nebel (zwei driftende Schichten) */}
          <motion.div
            aria-hidden
            className="absolute pointer-events-none"
            style={{
              width: '200%',
              height: '200%',
              left: '-50%',
              top: '-50%',
              background:
                'radial-gradient(circle at 50% 50%, rgba(245,158,11,0.18) 0%, rgba(180,83,9,0.12) 35%, transparent 70%)',
              filter: 'blur(28px)',
            }}
            animate={{ x: ['-5%', '4%', '-3%'], y: ['-5%', '6%', '4%'], rotate: [0, 8, -6], scale: [0.95, 1.08, 1.02] }}
            transition={{ duration: 14, repeat: Infinity, repeatType: 'mirror', ease: 'easeInOut' }}
          />
          <motion.div
            aria-hidden
            className="absolute pointer-events-none"
            style={{
              width: '180%',
              height: '180%',
              left: '-40%',
              top: '-40%',
              background:
                'radial-gradient(circle at 60% 40%, rgba(254,240,138,0.14) 0%, rgba(217,119,6,0.10) 40%, transparent 65%)',
              filter: 'blur(36px)',
            }}
            animate={{ x: ['-3%', '5%', '-2%'], y: ['4%', '-3%', '5%'], rotate: [-6, 4, 7] }}
            transition={{ duration: 9, repeat: Infinity, repeatType: 'mirror', ease: 'easeInOut' }}
          />
          {/* Surge-Schicht beim Aufdecken */}
          <motion.div
            aria-hidden
            className="absolute pointer-events-none"
            style={{
              width: '200%',
              height: '200%',
              left: '-50%',
              top: '-50%',
              background:
                'radial-gradient(circle at 50% 50%, rgba(245,158,11,0.38) 0%, rgba(180,83,9,0.22) 40%, transparent 75%)',
              filter: 'blur(28px)',
            }}
            animate={{ opacity: surging ? 1 : 0 }}
            transition={{ duration: 0.7 }}
          />

          {/* 3D-Flipper */}
          <div className="absolute inset-0" style={{ perspective: 1400 }}>
            <motion.div
              className="absolute inset-0"
              style={{ transformStyle: 'preserve-3d' }}
              animate={{ rotateY: flipped ? 180 : 0 }}
              transition={{ duration: 1.05, ease: [0.2, 0.85, 0.25, 1] }}
            >
              {/* Front: Tarot-Karte mit Mega-Zoom */}
              <div
                className="absolute inset-0 flex items-center justify-center"
                style={{ backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden' }}
              >
                <motion.div
                  className="w-64 h-[360px] sm:w-72 sm:h-96"
                  animate={{ scale: surging ? 2.05 : 1, y: surging ? -4 : 0 }}
                  transition={{ duration: 0.85, ease: [0.22, 1, 0.36, 1] }}
                >
                  <motion.div
                    className="w-full h-full"
                    animate={{ y: [0, -4, 2, -2, 0], rotate: [0, -1, 0.6, 1, 0] }}
                    transition={{ duration: 5, repeat: Infinity, ease: 'easeInOut' }}
                  >
                    <JokerCard />
                  </motion.div>
                </motion.div>
              </div>

              {/* Rückseite: Joker-Ergebnis */}
              <div
                className="absolute inset-0"
                style={{ backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}
              >
                <MatchResult
                  restaurantId={match?.restaurant_id}
                  restaurantName={match?.restaurant_name || ''}
                  matchPercentage={match?.match_percentage || 0}
                  imageUrl={match?.restaurant_image_url}
                  isSymbolImage={match?.restaurant_is_symbol_image}
                  address={match?.restaurant_address}
                  city={match?.restaurant_city}
                  postalCode={match?.restaurant_postal_code}
                  suburb={match?.restaurant_suburb}
                  phone={match?.restaurant_phone}
                  website={match?.restaurant_website}
                  openingHoursRaw={match?.restaurant_opening_hours_raw}
                  cuisine={match?.restaurant_cuisine}
                  lat={match?.restaurant_lat}
                  lon={match?.restaurant_lon}
                  isJokerResult
                  isForcedChoice={match?.isForcedChoice}
                  reservationUrl={match?.restaurant_reservation_url}
                  lieferandoUrl={match?.restaurant_lieferando_url}
                  mapsUrl={mapsUrl}
                  poolCount={match?.pool_count}
                  onLeaveSession={onLeave}
                  onNewTable={onNewTable}
                  sessionCode={sessionCode}
                />
              </div>
            </motion.div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
