import { getFontClass } from '@/lib/fonts';
import { cn } from '@/lib/utils';
import React, { useCallback, useEffect, useRef } from 'react';

interface HeroSectionProps {
    appName: string;
    heroBackgroundUrl?: string | null;
    heroBackgroundWebP?: string | null;
    heroHeight?: number;
    smokeEnabled: boolean;
    newsSparksEnabled: boolean;
    appFont?: string;
    appNameColor?: string;
    buttonText?: string;
    serverStartTime?: string | null;
    heroUseLogo?: boolean;
    heroLogoUrl?: string | null;
    heroLogoSize?: number;
}

export const HeroSection = React.memo(function HeroSection({
    appName,
    heroBackgroundUrl,
    heroBackgroundWebP,
    heroHeight,
    smokeEnabled,
    newsSparksEnabled,
    appFont,
    appNameColor,
    buttonText = 'Play Now',
    serverStartTime,
    heroUseLogo,
    heroLogoUrl,
    heroLogoSize = 300,
}: HeroSectionProps) {
    const logoRef = useRef<HTMLDivElement>(null);

    const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
        const el = logoRef.current;
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        const centerX = rect.width / 2;
        const centerY = rect.height / 2;
        const rotateX = ((y - centerY) / centerY) * -12;
        const rotateY = ((x - centerX) / centerX) * 12;
        el.style.transform = `perspective(800px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.05, 1.05, 1.05)`;
    }, []);

    const handleMouseLeave = useCallback(() => {
        const el = logoRef.current;
        if (!el) return;
        el.style.transform = 'perspective(800px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
    }, []);

    // Reduce effects on mobile for better performance
    const [isMobile, setIsMobile] = React.useState(false);
    const [countdown, setCountdown] = React.useState({
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
    });
    const [isServerRunning, setIsServerRunning] = React.useState(true);

    useEffect(() => {
        const checkMobile = () => setIsMobile(window.innerWidth < 768);
        checkMobile();
        window.addEventListener('resize', checkMobile);
        return () => window.removeEventListener('resize', checkMobile);
    }, []);

    useEffect(() => {
        if (!serverStartTime) return;

        const calculateCountdown = () => {
            const start = new Date(serverStartTime).getTime();
            const now = new Date().getTime();
            const diff = now - start;

            // Check if server start time is in the future (Development mode)
            if (diff < 0) {
                setIsServerRunning(false);
                // Calculate countdown to server start (absolute value of diff)
                const absDiff = Math.abs(diff);
                const days = Math.floor(absDiff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((absDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((absDiff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((absDiff % (1000 * 60)) / 1000);

                setCountdown({ days, hours, minutes, seconds });
                return;
            }

            // Server is running - count up from start time
            setIsServerRunning(true);
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diff % (1000 * 60)) / 1000);

            setCountdown({ days, hours, minutes, seconds });
        };

        calculateCountdown();
        const interval = setInterval(calculateCountdown, 1000);

        return () => clearInterval(interval);
    }, [serverStartTime]);

    const shouldShowEffects = newsSparksEnabled && !isMobile;

    return (
        <section
            id="hero"
            className="youplay-banner banner-top youplay-banner-parallax small relative overflow-visible"
            style={{ minHeight: `${heroHeight || 40}vh` }}
        >
            {/* Hero Effect - Only on desktop for better mobile performance */}
            {!isMobile && (
                <div className="hero-effect">
                    <div className="hero-rocks"></div>
                    <div className="hero-sparkles-1"></div>
                    <div className="hero-sparkles-2"></div>
                </div>
            )}

            {heroBackgroundUrl ? (
                heroBackgroundUrl.endsWith('.mp4') ? (
                    <div className="absolute inset-0">
                        <video src={heroBackgroundUrl} className="h-full w-full object-cover" autoPlay loop muted playsInline />
                    </div>
                ) : (
                    <div className="image absolute inset-0" data-speed="0.4">
                        <picture>
                            {heroBackgroundWebP && <source srcSet={heroBackgroundWebP} type="image/webp" />}
                            <img
                                src={heroBackgroundUrl}
                                alt={appName}
                                className="jarallax-img h-full w-full object-cover"
                                fetchPriority="high"
                                loading="eager"
                                decoding="sync"
                                onError={(e) => {
                                    e.currentTarget.style.display = 'none';
                                    const fallback = document.createElement('div');
                                    fallback.className = 'absolute inset-0 bg-gradient-to-br from-background via-background to-muted/20';
                                    e.currentTarget.parentElement?.appendChild(fallback);
                                }}
                            />
                        </picture>
                    </div>
                )
            ) : (
                <div className="from-background via-background to-muted/20 absolute inset-0 bg-gradient-to-br" />
            )}

            {/* Smoke Effect - Controlled by smokeEnabled setting */}
            {smokeEnabled && (
                <div className={`pointer-events-none absolute inset-0 overflow-hidden ${isMobile ? 'opacity-20' : 'opacity-40'}`}>
                    <div className="smoke-layer-1 absolute h-full w-full"></div>
                    <div className="smoke-layer-2 absolute h-full w-full"></div>
                </div>
            )}

            {/* Spark Effects - Desktop only */}
            {shouldShowEffects && (
                <div className="pointer-events-none absolute inset-0 overflow-hidden">
                    <div className="sparks-spark-1"></div>
                    <div className="sparks-spark-2"></div>
                    <div className="sparks-spark-3"></div>
                    <div className="sparks sparks_2">
                        <div className="spark_1"></div>
                        <div className="spark_2"></div>
                        <div className="spark_3"></div>
                        <div className="spark_4 spark-big"></div>
                        <div className="spark_5 spark-big"></div>
                    </div>
                </div>
            )}

            <div
                className="absolute inset-0"
                style={{
                    background:
                        'radial-gradient(circle at 50% 35%, rgba(168,85,247,0.16), transparent 32%), linear-gradient(180deg, rgba(5,0,14,0.35) 0%, rgba(5,0,14,0.72) 62%, rgba(5,0,14,0.96) 100%)',
                }}
            />

            {/* Bottom blur transition */}
            <div
                className="pointer-events-none absolute bottom-0 h-32 w-full overflow-hidden sm:h-40 md:h-48"
                style={{ left: '50%', transform: 'translateX(-50%)' }}
            >
                <img
                    src="/img/animations/blur-bottom.svg"
                    alt=""
                    className="h-full min-w-full object-cover object-top"
                    style={{
                        opacity: 0.85,
                        maskImage: 'linear-gradient(to bottom, transparent 0%, black 20%)',
                        WebkitMaskImage: 'linear-gradient(to bottom, transparent 0%, black 20%)',
                    }}
                />
            </div>

            <div className="info absolute inset-0 z-10 flex items-center">
                <div className="container mx-auto px-4">
                    <div className="flex translate-y-10 flex-col items-center gap-0 text-center">
                        <div
                            className="flex max-w-5xl flex-col items-center gap-6 overflow-visible px-6 py-12 md:px-12 md:py-16"
                            style={{ filter: 'drop-shadow(0 10px 15px rgba(0,0,0,0.3))' }}
                        >

                            {heroUseLogo && heroLogoUrl ? (
                                <>
                                    <style
                                        dangerouslySetInnerHTML={{
                                            __html: `
                                            .hero-logo {
                                                max-height: ${Math.round(heroLogoSize * 0.6)}px;
                                            }
                                            @media (min-width: 768px) {
                                                .hero-logo {
                                                    max-height: ${heroLogoSize}px;
                                                }
                                            }
                                            .hero-logo-wrapper {
                                                position: relative;
                                                cursor: pointer;
                                                transition: transform 0.15s ease-out;
                                                will-change: transform;
                                            }
                                            .hero-logo-wrapper::before {
                                                content: '';
                                                position: absolute;
                                                inset: -30%;
                                                background: radial-gradient(circle at 50% 50%, rgba(168,85,247,0.22) 0%, transparent 60%);
                                                opacity: 0;
                                                transition: opacity 0.3s ease;
                                                pointer-events: none;
                                                z-index: -1;
                                            }
                                            .hero-logo-wrapper:hover::before {
                                                opacity: 1;
                                            }
                                        `,
                                        }}
                                    />
                                    <div ref={logoRef} className="hero-logo-wrapper" onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave}>
                                        <img
                                            src={heroLogoUrl}
                                            alt={appName}
                                            className="hero-logo relative z-1 w-auto object-contain"
                                            style={{
                                                filter: 'drop-shadow(0 4px 24px rgba(0,0,0,0.55)) drop-shadow(0 0 30px rgba(168,85,247,0.22))',
                                                transition: 'filter 0.3s ease',
                                            }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.filter =
                                                    'drop-shadow(0 4px 30px rgba(168,85,247,0.35)) drop-shadow(0 0 70px rgba(217,70,239,0.22))';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.filter =
                                                    'drop-shadow(0 4px 24px rgba(0,0,0,0.55)) drop-shadow(0 0 30px rgba(168,85,247,0.22))';
                                            }}
                                        />
                                    </div>
                                </>
                            ) : (
                                <div
                                    ref={logoRef}
                                    className="hero-logo-wrapper inline-block"
                                    onMouseMove={handleMouseMove}
                                    onMouseLeave={handleMouseLeave}
                                >
                                    <h1
                                        className={cn(
                                            'bg-clip-text text-center text-[36px] leading-relaxed font-bold text-transparent md:text-9xl',
                                            getFontClass(appFont),
                                        )}
                                        style={{
                                            backgroundImage: appNameColor
                                                ? `linear-gradient(to bottom, #ffffff 0%, ${appNameColor} 100%)`
                                                : 'linear-gradient(to bottom, #ffffff 0%, #e9d5ff 45%, #a855f7 100%)',
                                            textShadow: '0 0 48px rgba(168,85,247,0.45), 0 8px 28px rgba(0,0,0,0.85)',
                                        }}
                                    >
                                        {appName || 'Perfect World'}
                                    </h1>
                                </div>
                            )}


                            {/* Server Running Countdown - directly under app name */}
                            {serverStartTime && (
                                <div className="flex flex-col items-center gap-3">
                                    {isServerRunning ? (
                                        <>
                                            <div
                                                className="text-base font-semibold tracking-widest text-purple-100 uppercase md:text-lg"
                                                style={{ textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}
                                            >
                                                Server is Running:
                                            </div>
                                            <div className="flex gap-2 md:gap-3">
                                                {/* Days */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.days.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">Days</div>
                                                </div>

                                                {/* Hours */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.hours.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">Hours</div>
                                                </div>

                                                {/* Minutes */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.minutes.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">
                                                        Minutes
                                                    </div>
                                                </div>

                                                {/* Seconds */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.seconds.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">
                                                        Seconds
                                                    </div>
                                                </div>
                                            </div>
                                        </>
                                    ) : (
                                        <>
                                            <div
                                                className="text-base font-semibold tracking-widest text-purple-100 uppercase md:text-lg"
                                                style={{ textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}
                                            >
                                                Server Launching In:
                                            </div>
                                            <div className="flex gap-2 md:gap-3">
                                                {/* Days */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.days.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">Days</div>
                                                </div>

                                                {/* Hours */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.hours.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">Hours</div>
                                                </div>

                                                {/* Minutes */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.minutes.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">
                                                        Minutes
                                                    </div>
                                                </div>

                                                {/* Seconds */}
                                                <div className="flex flex-col items-center">
                                                    <div className="min-w-[60px] rounded-lg border border-purple-400/20 bg-purple-950/40 px-3 py-2 backdrop-blur-sm md:min-w-[80px] md:px-5 md:py-3">
                                                        <div
                                                            className="text-center font-mono text-2xl font-bold text-fuchsia-300 tabular-nums md:text-4xl"
                                                            style={{ textShadow: '0 0 20px rgba(217,70,239,0.55)' }}
                                                        >
                                                            {countdown.seconds.toString().padStart(2, '0')}
                                                        </div>
                                                    </div>
                                                    <div className="mt-1.5 text-xs tracking-wider text-purple-100/80 uppercase md:text-sm">
                                                        Seconds
                                                    </div>
                                                </div>
                                            </div>
                                        </>
                                    )}
                                </div>
                            )}
                        </div>

                        <div className="relative inline-flex flex-col items-center gap-4 sm:flex-row">
                            {/* Spark Effects around Play Now button - Desktop only */}
                            {shouldShowEffects && (
                                <>
                                    <div className="absolute -top-4 -left-4 h-4 w-4 animate-pulse rounded-full bg-purple-400 blur-sm"></div>
                                    <div
                                        className="absolute -top-2 -right-6 h-3 w-3 animate-pulse rounded-full bg-fuchsia-400 blur-sm"
                                        style={{ animationDelay: '0.2s' }}
                                    ></div>
                                    <div
                                        className="absolute -bottom-3 left-1/4 h-3 w-3 animate-pulse rounded-full bg-violet-400 blur-sm"
                                        style={{ animationDelay: '0.4s' }}
                                    ></div>
                                    <div
                                        className="absolute -right-4 -bottom-2 h-4 w-4 animate-pulse rounded-full bg-pink-400 blur-sm"
                                        style={{ animationDelay: '0.6s' }}
                                    ></div>
                                    <div
                                        className="absolute top-1/2 -left-8 h-2 w-2 animate-ping rounded-full bg-purple-300 blur-sm"
                                        style={{ animationDelay: '0.1s' }}
                                    ></div>
                                    <div
                                        className="absolute top-1/2 -right-8 h-2 w-2 animate-ping rounded-full bg-fuchsia-300 blur-sm"
                                        style={{ animationDelay: '0.3s' }}
                                    ></div>
                                </>
                            )}
                            <a
                                href="/#download"
                                className="relative z-10 inline-block cursor-pointer transition-transform duration-200 hover:scale-105"
                            >
                                <img src="/img/button/4.webp" alt={buttonText} width={547} height={220} className="h-auto w-auto" />
                                <span className="pointer-events-none absolute inset-0 flex items-center justify-center text-2xl font-bold text-white drop-shadow-lg">
                                    {buttonText}
                                </span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
});
