"use client";
import { useEffect, useRef, useState } from "react";
import Link from "next/link";

type Config = {
  imageUrl: string;
  musicUrl: string;
  durationSeconds: number;
  glowSize: number;
  glowColor: string;
  imageOpacity: number;
  overlayColor: string;
  overlayOpacity: number;
  imageSize: number;
  welcomeText: string;
  siteName: string;
  textStrokeWidth?: number;
  textStrokeColor?: string;
};

function hexToRgba(hex: string, alphaPct: number) {
  const clean = hex.replace("#", "");
  const r = parseInt(clean.substring(0, 2), 16) || 0;
  const g = parseInt(clean.substring(2, 4), 16) || 0;
  const b = parseInt(clean.substring(4, 6), 16) || 0;
  return `rgba(${r},${g},${b},${alphaPct / 100})`;
}

// Background twinkling starfield — fixed, blinking in place.
function useBackgroundStars(count: number) {
  const [stars] = useState(() =>
    Array.from({ length: count }).map(() => ({
      left: Math.random() * 100,
      top: Math.random() * 100,
      size: 2 + Math.random() * 3,
      delay: Math.random() * 3,
      duration: 1.5 + Math.random() * 2,
    }))
  );
  return stars;
}

// Stars that orbit around the image on individual elliptical paths, giving a
// pseudo-3D "moving around" effect rather than just sitting still.
function useOrbitingStars(count: number) {
  const [stars] = useState(() =>
    Array.from({ length: count }).map((_, i) => ({
      radius: 90 + Math.random() * 60,
      duration: 6 + Math.random() * 6,
      delay: -(Math.random() * 10),
      size: 3 + Math.random() * 4,
      reverse: i % 2 === 0,
    }))
  );
  return stars;
}

export default function WelcomeAnimation({
  previewConfig,
  onClosePreview,
}: {
  previewConfig?: Config;
  onClosePreview?: () => void;
}) {
  const [config, setConfig] = useState<Config | null>(previewConfig || null);
  const [visible, setVisible] = useState(!!previewConfig);
  const audioRef = useRef<HTMLAudioElement>(null);
  const bgStars = useBackgroundStars(40);
  const orbitStars = useOrbitingStars(8);

  useEffect(() => {
    if (previewConfig) return;

    let cancelled = false;
    async function checkAndLoad() {
      try {
        // Single round trip instead of two sequential ones — every
        // millisecond between mount and the audio.play() call reduces the
        // odds that strict mobile browsers allow audible autoplay.
        const res = await fetch("/api/welcome-animation/check-and-load");
        const data = await res.json();
        if (!data.show || cancelled) return;

        setConfig(data.config);
        setVisible(true);
        fetch("/api/welcome-animation/mark-seen", { method: "POST" }).catch(() => {});
      } catch {}
    }
    checkAndLoad();
    return () => {
      cancelled = true;
    };
  }, [previewConfig]);

  useEffect(() => {
    if (!visible || !config) return;
    if (config.musicUrl && audioRef.current) {
      audioRef.current.volume = 0.5;
      // Try real, audible autoplay first — logging in is a genuine user
      // gesture, which most browsers extend for the rest of the page visit.
      // If the browser genuinely blocks it, fall back to a silent muted
      // autoplay with no visible prompt at all — better to occasionally play
      // without sound than to interrupt the moment asking for permission.
      audioRef.current.muted = false;
      audioRef.current.play().catch(() => {
        if (audioRef.current) {
          audioRef.current.muted = true;
          audioRef.current.play().catch(() => {});
        }
      });
    }
    const timer = setTimeout(() => close(), config.durationSeconds * 1000);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, config]);

  function close() {
    setVisible(false);
    audioRef.current?.pause();
    if (onClosePreview) onClosePreview();
  }

  if (!visible || !config) return null;

  return (
    <div
      className="fixed inset-0 z-[200] flex items-center justify-center p-4 cursor-pointer"
      style={{ background: hexToRgba(config.overlayColor, config.overlayOpacity) }}
      onClick={close}
    >
      {config.musicUrl && (
        <audio
          ref={audioRef}
          src={config.musicUrl}
          loop
          onError={() => console.error("Welcome animation music failed to load — the file may no longer exist at:", config.musicUrl)}
        />
      )}

      {/* Background twinkling stars */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        {bgStars.map((s, i) => (
          <div
            key={i}
            className="absolute rounded-full bg-white"
            style={{
              left: `${s.left}%`,
              top: `${s.top}%`,
              width: s.size,
              height: s.size,
              animation: `welcome-twinkle ${s.duration}s ease-in-out ${s.delay}s infinite`,
            }}
          />
        ))}
      </div>

      <div className="relative text-center">
        {config.welcomeText && (
          <p
            className="text-white text-lg sm:text-xl font-bold mb-8"
            style={{
              textShadow:
                "0 0 8px rgba(0,0,0,0.9), 0 0 20px rgba(0,0,0,0.8), 0 2px 6px rgba(0,0,0,0.9), 0 4px 16px rgba(0,0,0,0.7)",
              WebkitTextStroke: config.textStrokeWidth ? `${config.textStrokeWidth}px ${config.textStrokeColor || "#000000"}` : undefined,
            }}
          >
            {config.welcomeText}
          </p>
        )}

        {config.imageUrl && (
          <div className="relative mx-auto" style={{ width: config.imageSize, height: config.imageSize }}>
            {/* Orbiting stars — move around the image in elliptical paths for a 3D feel */}
            {orbitStars.map((s, i) => (
              <div
                key={i}
                className="absolute top-1/2 left-1/2 pointer-events-none"
                style={{
                  width: s.radius * 2,
                  height: s.radius * 2,
                  marginLeft: -s.radius,
                  marginTop: -s.radius,
                  animation: `welcome-orbit${s.reverse ? "-reverse" : ""} ${s.duration}s linear ${s.delay}s infinite`,
                }}
              >
                <div
                  className="absolute rounded-full bg-white"
                  style={{
                    width: s.size,
                    height: s.size,
                    top: 0,
                    left: "50%",
                    boxShadow: `0 0 ${s.size * 2}px rgba(255,255,255,0.8)`,
                  }}
                />
              </div>
            ))}

            <img
              src={config.imageUrl}
              alt="Welcome"
              className="w-full h-full object-contain relative z-10"
              style={{
                opacity: config.imageOpacity / 100,
                filter: `drop-shadow(0 0 ${config.glowSize}px ${config.glowColor})`,
                animation: "welcome-float 3s ease-in-out infinite",
              }}
            />
          </div>
        )}

        <div>
          <Link
            href="/community"
            onClick={(e) => {
              e.stopPropagation();
              close();
            }}
            className="inline-block mt-6 px-8 py-3 rounded-full text-sm font-bold text-white bg-gradient-to-r from-amber-500 to-red-600 hover:from-amber-400 hover:to-red-500 transition-all hover:scale-105 active:scale-95"
            style={{ boxShadow: `0 0 30px ${config.glowColor}, 0 0 60px ${hexToRgba(config.glowColor, 40)}` }}
          >
            ✨ Go to Community
          </Link>
        </div>

        <p className="text-white/40 text-xs mt-6">Tap anywhere else to continue</p>
      </div>

      <style jsx global>{`
        @keyframes welcome-twinkle {
          0%, 100% { opacity: 0.2; transform: scale(1); }
          50% { opacity: 1; transform: scale(1.6); }
        }
        @keyframes welcome-float {
          0%, 100% { transform: translateY(0); }
          50% { transform: translateY(-12px); }
        }
        @keyframes welcome-orbit {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        @keyframes welcome-orbit-reverse {
          from { transform: rotate(360deg); }
          to { transform: rotate(0deg); }
        }
      `}</style>
    </div>
  );
}
