'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { toast } from 'sonner';
import { Copy, Check } from 'lucide-react';
import { HoverRollingText } from '@/components/hover-rolling-text';
import { motion } from 'motion/react';
import { ScreenshotLightbox } from '@/components/screenshot-lightbox';

const screenshots = [
    '/2023-11-23_21.00.17.png',
    '/2025-07-13_12.59.13.png',
    '/2025-07-13_13.01.28.png',
    '/2025-10-22_17.07.42.png',
    '/backgroundimg.avif',
];

export function Hero() {
    const [copied, setCopied] = useState(false);
    const [currentImage, setCurrentImage] = useState(0);
    const [lightboxOpen, setLightboxOpen] = useState(false);
    const [lightboxIndex, setLightboxIndex] = useState(0);
    const [imagesLoaded, setImagesLoaded] = useState(false);
    const serverAddress = 'minecraft.biohazardvfx.com';

    useEffect(() => {
        const interval = setInterval(() => {
            setCurrentImage((prev) => (prev + 1) % screenshots.length);
        }, 5000); // Change image every 5 seconds

        // Mark images as loaded after a short delay (they load progressively)
        const loadTimer = setTimeout(() => setImagesLoaded(true), 500);

        return () => {
            clearInterval(interval);
            clearTimeout(loadTimer);
        };
    }, []);

    const copyServerAddress = async () => {
        try {
            await navigator.clipboard.writeText(serverAddress);
            setCopied(true);
            toast.success('Server address copied to clipboard!');
            setTimeout(() => setCopied(false), 2000);
        } catch (error) {
            console.error(error);
            toast.error('Failed to copy address');
        }
    };

    return (
        <div className="w-full max-w-xl space-y-6 min-w-0">
            <motion.div
                className="flex flex-col gap-6 text-foreground min-w-0"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.1 }}
            >
                <motion.span
                    className="inline-flex w-fit items-center gap-2 rounded-full border border-primary/30 bg-primary/10 px-5 py-2 text-xs font-bold uppercase tracking-[0.25em] text-primary shadow-sm"
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ duration: 0.4, delay: 0.2 }}
                >
                    Biohazard SMP
                </motion.span>
                <motion.h1
                    className="text-6xl font-bold leading-[1.1] break-words overflow-wrap-anywhere sm:text-7xl lg:text-8xl"
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.3 }}
                >
                    <span className="block text-primary break-words tracking-tighter text-shadow-md">
                        <HoverRollingText
                            text="Build."
                            transition={{ duration: 0.6, delay: 0.05 }}
                        />
                    </span>
                    <span className="block text-secondary break-words tracking-normal text-shadow-sm">
                        <HoverRollingText
                            text="Explore."
                            transition={{ duration: 0.6, delay: 0.05 }}
                        />
                    </span>
                    <span className="block text-accent break-words tracking-normal text-shadow-sm">
                        <HoverRollingText
                            text="Survive."
                            transition={{ duration: 0.6, delay: 0.05 }}
                        />
                    </span>
                </motion.h1>
                <motion.p
                    className="max-w-md text-base leading-relaxed text-muted-foreground sm:text-lg break-words"
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.5 }}
                >
                    A vanilla-first Minecraft experience for VFX artists and creatives.
                </motion.p>
            </motion.div>

            {/* Server Address */}
            <motion.div
                className="space-y-4"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.7 }}
            >
                <div className="group rounded-2xl border border-border/50 bg-card/50 p-6 shadow-xl backdrop-blur backdrop-saturate-150 transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/30 hover:shadow-2xl noise-texture">
                    <span className="text-xs font-bold uppercase tracking-[0.2em] text-muted-foreground">
                        Server IP
                    </span>
                    <div className="mt-4 flex items-center justify-between gap-4 rounded-xl border border-border/50 bg-background/90 px-5 py-4 shadow-sm min-w-0">
                        <code className="text-base font-mono font-bold text-foreground sm:text-lg break-all min-w-0">
                            {serverAddress}
                        </code>
                        <Button
                            onClick={copyServerAddress}
                            size="icon-sm"
                            variant="outline"
                            className="shrink-0 border-primary/30 bg-primary/10 transition-all duration-200 ease-out hover:bg-primary/20 hover:border-primary/50 hover:shadow-lg hover:shadow-primary/20 active:scale-[0.98]"
                            aria-label={copied ? 'Server address copied' : 'Copy server address'}
                        >
                            {copied ? <Check className="h-4 w-4 text-primary" /> : <Copy className="h-4 w-4 text-primary" />}
                        </Button>
                    </div>
                </div>
            </motion.div>

            {/* Screenshot Showcase */}
            <motion.div
                className="group relative aspect-video overflow-hidden rounded-3xl border-2 border-white/10 bg-card/50 shadow-2xl backdrop-blur-xl backdrop-saturate-150 transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/50 hover:shadow-2xl hover:shadow-primary/20 cursor-pointer noise-texture"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.9, ease: [0.33, 1, 0.68, 1] }}
                style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)" }}
                onClick={() => {
                    setLightboxIndex(currentImage);
                    setLightboxOpen(true);
                }}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        setLightboxIndex(currentImage);
                        setLightboxOpen(true);
                    }
                }}
                aria-label="View screenshots in lightbox"
            >
                {!imagesLoaded && (
                    <div className="absolute inset-0">
                        <Skeleton className="h-full w-full" />
                    </div>
                )}
                {screenshots.map((screenshot, index) => (
                    <div
                        key={screenshot}
                        className={`absolute inset-0 transition-opacity duration-1000 ${index === currentImage ? 'opacity-100' : 'opacity-0'
                            }`}
                    >
                        <Image
                            src={screenshot}
                            alt={`Minecraft server screenshot ${index + 1}`}
                            fill
                            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                            className="object-cover transition-transform duration-700 group-hover:scale-105"
                            priority={index === 0}
                        />
                    </div>
                ))}

                {/* Image overlay gradient */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-black/10 to-transparent" />

                {/* Carousel indicators */}
                <div className="absolute bottom-5 left-1/2 -translate-x-1/2 flex gap-2.5 rounded-full border border-white/20 bg-black/40 px-4 py-2.5 shadow-lg backdrop-blur-md">
                    {screenshots.map((_, index) => (
                        <button
                            key={index}
                            onClick={() => setCurrentImage(index)}
                            className={`h-2 rounded-full transition-all duration-300 ${index === currentImage
                                ? 'w-8 bg-white shadow-lg shadow-primary/50'
                                : 'w-2 bg-white/40 hover:bg-white/70 hover:w-3'
                                }`}
                            aria-label={`View screenshot ${index + 1}`}
                        />
                    ))}
                </div>
            </motion.div>

            {/* Lightbox */}
            <ScreenshotLightbox
                images={screenshots}
                isOpen={lightboxOpen}
                initialIndex={lightboxIndex}
                onClose={() => setLightboxOpen(false)}
            />
        </div>
    );
}
