'use client';

import { useEffect, useState } from 'react';
import Image from "next/image";
import { motion } from "motion/react";

import { Button } from "@/components/ui/button";
import { Hero } from "@/components/hero";
import { ServerStatus } from "@/components/server-status";
import { Leaderboard } from "@/components/leaderboard";
import { MinecraftServerStructuredData } from "@/components/structured-data";
import { ThemeToggle } from "@/components/theme-toggle";
import { MessageCircle } from "lucide-react";

interface ServerData {
    online: boolean;
    players: {
        online: number;
        playerList?: string[];
    };
    uptime?: {
        days: number;
        hours: number;
        minutes: number;
        formatted: string;
    } | null;
    stats?: {
        totalPlayers: number;
        uniquePlayers7d: number;
        averageTps: string;
    };
    error?: string;
}

export default function Home() {
    const [serverData, setServerData] = useState<ServerData | null>(null);

    useEffect(() => {
        const fetchServerData = async () => {
            try {
                const response = await fetch('/api/server-status');
                if (!response.ok) {
                    throw new Error('Failed to fetch server status');
                }
                const data = await response.json() as ServerData;
                setServerData(data);
            } catch (err) {
                console.error('Error fetching server data for structured data:', err);
            }
        };

        fetchServerData();

        // Refresh every 30 seconds to keep structured data updated
        const interval = setInterval(fetchServerData, 30000);
        return () => clearInterval(interval);
    }, []);

    const structuredDataProps = serverData ? {
        playersOnline: serverData.players.online,
        maxPlayers: 20, // Assuming max players is 20, you can adjust this
        version: "1.21.x",
        status: serverData.online ? "Online" : "Offline"
    } : undefined;

    return (
        <>
            <MinecraftServerStructuredData serverData={structuredDataProps} />
            <div className="relative min-h-screen min-h-svh overflow-hidden">
                <div className="absolute inset-0">
                    {/* Light mode background */}
                    <Image
                        src="/backgroundimg.avif"
                        alt="Minecraft background"
                        fill
                        sizes="100vw"
                        className="object-cover dark:hidden"
                        priority
                    />
                    {/* Dark mode background */}
                    <Image
                        src="/backgroundimg-dark.avif"
                        alt="Minecraft background dark"
                        fill
                        sizes="100vw"
                        className="hidden dark:block object-cover"
                        priority
                    />
                    <div className="absolute inset-0 bg-gradient-to-br from-black/52 via-black/28 to-black/10 backdrop-blur-[1.5px]" />
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_left,_rgba(255,255,255,0.32),_transparent_60%)] dark:bg-[radial-gradient(circle_at_top_left,_rgba(255,255,255,0.15),_transparent_60%)]" />
                </div>

                <div className="relative z-10 flex min-h-screen min-h-svh flex-col font-sans overflow-x-hidden">
                    <main className="flex flex-1 items-center justify-center px-6 py-16 sm:px-10 lg:px-14 overflow-x-hidden">
                        <div className="w-full max-w-7xl mx-auto">
                            <div className="flex gap-6 items-stretch relative">
                                {/* Leaderboard - Left Side (separate card) */}
                                <section className="hidden lg:flex lg:flex-shrink-0 w-[300px] rounded-3xl border-2 border-white/10 bg-background/96 p-6 shadow-2xl backdrop-blur-xl backdrop-saturate-150 overflow-hidden card-depth-2 noise-texture" style={{ maxHeight: '650px' }}>
                                    <Leaderboard className="h-full" />
                                </section>

                                {/* Main Card - Centered */}
                                <div className="flex-1 flex justify-center min-w-0">
                                    <section className="w-full max-w-6xl rounded-3xl border-2 border-white/10 bg-background/96 p-8 shadow-2xl backdrop-blur-xl backdrop-saturate-150 sm:p-10 lg:p-12 overflow-hidden relative card-depth-2 noise-texture" id="main-card">
                                    {/* Theme Toggle - Top Right */}
                                    <div className="absolute top-6 right-6 z-10">
                                        <ThemeToggle />
                                    </div>
                                    <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
                                        <Hero />

                                        <div className="flex flex-col gap-6 border-t border-white/10 pt-6 lg:border-t-0 lg:pt-0 lg:border-l lg:pl-8" id="server-status">
                                            <div className="rounded-3xl border border-border/40 bg-background p-6 shadow-lg backdrop-blur-sm card-depth-1 noise-texture">
                                                <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between text-foreground mb-6">
                                                    <div>
                                                        <p className="text-xs uppercase tracking-[0.35em] text-muted-foreground">
                                                            Live snapshot
                                                        </p>
                                                        <h2 className="text-2xl font-semibold tracking-tight mt-1">
                                                            Server Pulse
                                                        </h2>
                                                    </div>
                                                    <span className="text-xs uppercase tracking-[0.3em] text-muted-foreground">
                                                        Auto refresh • 30s
                                                    </span>
                                                </div>
                                                <ServerStatus className="h-full" />
                                            </div>

                                        <motion.div
                                            className="rounded-3xl border border-border/50 bg-background/50 p-6 shadow-xl backdrop-blur backdrop-saturate-150 transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/50 card-depth-1 noise-texture"
                                            initial={{ opacity: 0, y: 20 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            transition={{ duration: 0.5, delay: 1.2, ease: [0.33, 1, 0.68, 1] }}
                                            style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)" }}
                                        >
                                            <motion.div
                                                className="flex items-center justify-between"
                                                initial={{ opacity: 0 }}
                                                animate={{ opacity: 1 }}
                                                transition={{ duration: 0.4, delay: 1.3 }}
                                            >
                                                <p className="text-xs font-bold uppercase tracking-[0.15em] text-muted-foreground">
                                                    Quick Facts
                                                </p>
                                                <span className="text-[11px] font-medium text-muted-foreground/70">
                                                    Join-ready snapshot
                                                </span>
                                            </motion.div>
                                            <motion.dl
                                                className="mt-6 grid gap-3 text-sm text-muted-foreground sm:grid-cols-2"
                                                initial={{ opacity: 0 }}
                                                animate={{ opacity: 1 }}
                                                transition={{ duration: 0.4, delay: 1.4, ease: [0.33, 1, 0.68, 1] }}
                                                style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden" }}
                                            >
                                                {[
                                                    { label: "Version", value: "1.21.x Survival" },
                                                    { label: "Difficulty", value: "Hard + Vanilla Tweaks" },
                                                    { label: "Region", value: "United States" },
                                                    { label: "Community", value: "Discord & Whitelist" },
                                                ].map((item, index) => (
                                                    <motion.div
                                                        key={item.label}
                                                        className="group rounded-xl border border-border/50 bg-background/95 p-4 shadow-md transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/30 hover:shadow-lg"
                                                        initial={{ opacity: 0, y: 20 }}
                                                        animate={{ opacity: 1, y: 0 }}
                                                        transition={{ duration: 0.4, delay: 1.5 + index * 0.1, ease: [0.33, 1, 0.68, 1] }}
                                                        style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)" }}
                                                    >
                                                        <dt className="text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                                                            {item.label}
                                                        </dt>
                                                        <dd className="mt-2 text-base font-bold text-foreground">
                                                            {item.value}
                                                        </dd>
                                                    </motion.div>
                                                ))}
                                            </motion.dl>
                                            <motion.div
                                                initial={{ opacity: 0, y: 20 }}
                                                animate={{ opacity: 1, y: 0 }}
                                                transition={{ duration: 0.4, delay: 1.9, ease: "easeOut" }}
                                                style={{ willChange: "opacity, transform" }}
                                            >
                                                <Button 
                                                    size="lg" 
                                                    className="mt-6 w-full font-bold shadow-lg transition-all duration-200 ease-out hover:scale-[1.02] hover:shadow-xl hover:shadow-primary/20 active:scale-[0.98]"
                                                    asChild
                                                >
                                                    <a 
                                                        href="https://discord.gg/58FnVzmzrS" 
                                                        target="_blank" 
                                                        rel="noopener noreferrer"
                                                        className="flex items-center justify-center gap-2"
                                                    >
                                                        <MessageCircle className="h-5 w-5" />
                                                        Join Discord
                                                    </a>
                                                </Button>
                                            </motion.div>
                                        </motion.div>
                                        </div>
                                    </div>
                                    </section>
                                </div>
                            </div>
                            
                            {/* Leaderboard Section - Mobile */}
                            <section className="mt-12 lg:hidden rounded-3xl border-2 border-white/10 bg-background/96 p-8 shadow-2xl backdrop-blur-xl backdrop-saturate-150 sm:p-10 lg:p-12 card-depth-2 noise-texture">
                                <Leaderboard />
                            </section>
                        </div>
                    </main>
                </div>
            </div>
        </>
    );
}
