﻿import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowLeft, Trophy, Sparkles, Moon, Sun } from 'lucide-react';

// --- ZAAWANSOWANY MODEL KOTA (DetailedKitty) ---
interface DetailedKittyProps {
    isJumping: boolean;
    isNight: boolean;
    isGameOver: boolean;
}

const DetailedKitty: React.FC<DetailedKittyProps> = ({ isJumping, isNight, isGameOver }) => {
    const mainColor = isGameOver ? (isNight ? '#475569' : '#cbd5e1') : (isNight ? '#f8fafc' : '#f472b6');
    const stripeColor = isNight ? '#cbd5e1' : '#ec4899';
    const earColor = isNight ? '#334155' : '#fbcfe8';

    return (
        <div className={`relative w-20 h-14 transition-all duration-200 ${isJumping ? '-rotate-6 scale-110' : ''}`}>

            {/* OGON */}
            <div
                className="absolute -left-4 top-4 w-8 h-3 rounded-full origin-right rotate-[-20deg]"
                style={{
                    backgroundColor: mainColor,
                    animation: !isGameOver ? 'tail-wag 0.8s ease-in-out infinite' : 'none'
                }}
            />

            {/* TUŁÓW */}
            <div className="absolute inset-0 rounded-[2rem] overflow-hidden shadow-sm" style={{ backgroundColor: mainColor }}>
                {/* Paski dekoracyjne */}
                <div className="absolute top-0 left-1/4 w-2 h-4 rounded-full opacity-30" style={{ backgroundColor: stripeColor }} />
                <div className="absolute top-0 left-1/2 w-2 h-4 rounded-full opacity-30" style={{ backgroundColor: stripeColor }} />
            </div>

            {/* GŁOWA */}
            <div className="absolute -right-4 -top-6 w-14 h-13 rounded-full shadow-sm" style={{ backgroundColor: mainColor }}>
                {/* Uszy */}
                <div className="absolute -top-2 left-1 w-5 h-6 rounded-t-full rotate-[-15deg]" style={{ backgroundColor: mainColor }}>
                    <div className="absolute inset-1 rounded-t-full" style={{ backgroundColor: earColor }} />
                </div>
                <div className="absolute -top-2 right-1 w-5 h-6 rounded-t-full rotate-[15deg]" style={{ backgroundColor: mainColor }}>
                    <div className="absolute inset-1 rounded-t-full" style={{ backgroundColor: earColor }} />
                </div>

                {/* Oczy */}
                <div className={`absolute top-5 left-3 w-2.5 h-2.5 rounded-full ${isGameOver ? 'bg-slate-500 text-[10px] flex items-center justify-center' : 'bg-slate-900'}`}>
                    {isGameOver ? 'x' : <div className="absolute top-0.5 left-0.5 w-1 h-1 bg-white rounded-full opacity-70" />}
                </div>
                <div className={`absolute top-5 right-3 w-2.5 h-2.5 rounded-full ${isGameOver ? 'bg-slate-500 text-[10px] flex items-center justify-center' : 'bg-slate-900'}`}>
                    {isGameOver ? 'x' : <div className="absolute top-0.5 left-0.5 w-1 h-1 bg-white rounded-full opacity-70" />}
                </div>

                {/* Wąsy */}
                <div className="absolute top-7 -left-2 w-3 h-[1px] bg-slate-300 rotate-[10deg] opacity-40" />
                <div className="absolute top-9 -left-2 w-3 h-[1px] bg-slate-300 rotate-[-10deg] opacity-40" />
                <div className="absolute top-8 left-1/2 -translate-x-1/2 w-2 h-1.5 bg-pink-400 rounded-full" />
            </div>

            {/* ŁAPKI (Animowane) */}
            <div className="absolute bottom-[-10px] left-4 w-3 h-6 rounded-full origin-top"
                style={{
                    backgroundColor: mainColor,
                    animation: !isJumping && !isGameOver ? 'kitty-walk 0.2s infinite' : 'none',
                    transform: isJumping ? 'rotate(45deg)' : 'none'
                }}>
                <div className="absolute bottom-0 w-full h-2 bg-white rounded-full opacity-60" />
            </div>
            <div className="absolute bottom-[-10px] right-5 w-3 h-6 rounded-full origin-top"
                style={{
                    backgroundColor: mainColor,
                    animation: !isJumping && !isGameOver ? 'kitty-walk-alt 0.2s infinite' : 'none',
                    transform: isJumping ? 'rotate(-45deg)' : 'none'
                }}>
                <div className="absolute bottom-0 w-full h-2 bg-white rounded-full opacity-60" />
            </div>
        </div>
    );
};

// --- GŁÓWNY KOMPONENT GRY ---
export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [gameOver, setGameOver] = useState(false);
    const [score, setScore] = useState(0);
    const [highScore, setHighScore] = useState<number>(() => {
        const saved = localStorage.getItem('kittyHighScore');
        return saved ? parseInt(saved, 10) : 0;
    });

    const [displayKittyY, setDisplayKittyY] = useState(0);
    const [displayObstacleX, setDisplayObstacleX] = useState(600);

    const isNight = Math.floor(score / 10) % 2 === 1;

    const kittyYRef = useRef(0);
    const obstacleXRef = useRef(600);
    const velocityRef = useRef(0);
    const scoreRef = useRef(0);
    const requestRef = useRef<number>(0);

    const GRAVITY = 0.6;
    const JUMP_STRENGTH = -11;
    const GROUND_Y = 0;

    const endGame = useCallback(() => {
        setGameOver(true);
        setIsPlaying(false);
        const currentHighScore = parseInt(localStorage.getItem('kittyHighScore') || '0', 10);
        if (scoreRef.current > currentHighScore) {
            setHighScore(scoreRef.current);
            localStorage.setItem('kittyHighScore', scoreRef.current.toString());
        }
    }, []);

    const startGame = useCallback(() => {
        setIsPlaying(true);
        setGameOver(false);
        setScore(0);
        scoreRef.current = 0;
        kittyYRef.current = 0;
        obstacleXRef.current = 600;
        velocityRef.current = 0;
        setDisplayKittyY(0);
        setDisplayObstacleX(600);
    }, []);

    const jump = useCallback(() => {
        if (kittyYRef.current <= GROUND_Y && !gameOver && isPlaying) {
            velocityRef.current = JUMP_STRENGTH;
        }
    }, [gameOver, isPlaying]);

    useEffect(() => {
        const update = () => {
            if (gameOver || !isPlaying) return;

            velocityRef.current += GRAVITY;
            kittyYRef.current -= velocityRef.current;
            if (kittyYRef.current <= GROUND_Y) {
                kittyYRef.current = GROUND_Y;
                velocityRef.current = 0;
            }

            obstacleXRef.current -= 5 + (scoreRef.current * 0.2);
            if (obstacleXRef.current < -50) {
                obstacleXRef.current = 650;
                scoreRef.current += 1;
                setScore(scoreRef.current);
            }

            // DOSTOSOWANA KOLIZJA: Uwzględnia większy model kota
            if (obstacleXRef.current < 110 && obstacleXRef.current > 30 && kittyYRef.current < 45) {
                endGame();
                return;
            }

            setDisplayKittyY(kittyYRef.current);
            setDisplayObstacleX(obstacleXRef.current);
            requestRef.current = requestAnimationFrame(update);
        };

        if (isPlaying && !gameOver) {
            requestRef.current = requestAnimationFrame(update);
        }
        return () => cancelAnimationFrame(requestRef.current);
    }, [isPlaying, gameOver, endGame]);

    useEffect(() => {
        const handleKey = (e: KeyboardEvent) => {
            if (e.code === 'Space') {
                e.preventDefault();
                if (!isPlaying || gameOver) startGame(); else jump();
            }
        };
        window.addEventListener('keydown', handleKey);
        return () => window.removeEventListener('keydown', handleKey);
    }, [isPlaying, gameOver, startGame, jump]);

    return (
        <div className="flex flex-col items-center justify-center min-h-[70vh] p-4">
            <button onClick={onBack} className="mb-6 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none">
                <ArrowLeft size={20} /> Back to Home
            </button>

            <div
                className={`relative w-full max-w-[650px] h-[320px] rounded-[3.5rem] shadow-2xl border-4 transition-colors duration-1000 overflow-hidden cursor-pointer select-none
          ${isNight ? 'bg-slate-950 border-indigo-500 shadow-indigo-500/20' : 'bg-white border-pink-100 shadow-pink-200/50'}`}
                onClick={() => { if (!isPlaying || gameOver) startGame(); else jump(); }}
            >
                {/* Niebo */}
                <div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? 'translate-y-0 opacity-100' : '-translate-y-20 opacity-0'}`}>
                    <Moon className="text-indigo-200 fill-indigo-100" size={48} />
                </div>
                <div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? '-translate-y-20 opacity-0' : 'translate-y-0 opacity-100'}`}>
                    <Sun className="text-yellow-400 fill-yellow-200 animate-spin-slow" size={48} />
                </div>

                {/* Wyniki */}
                <div className={`absolute top-6 right-8 text-right z-10 font-black transition-colors duration-1000 ${isNight ? 'text-indigo-100' : 'text-pink-500'}`}>
                    <div className="text-3xl tracking-tighter">Score: {score}</div>
                    <div className={`text-sm flex items-center justify-end gap-1 ${isNight ? 'text-indigo-400' : 'text-pink-300'}`}>
                        <Trophy size={14} /> High: {highScore}
                    </div>
                </div>

                {/* KOTEK */}
                <div className="absolute left-10" style={{ bottom: `${displayKittyY + 48}px` }}>
                    <DetailedKitty isJumping={displayKittyY > 2} isNight={isNight} isGameOver={gameOver} />
                </div>

                {/* PRZESZKODA (Kłębek wełny) */}
                <div
                    className={`absolute bottom-12 w-12 h-12 rounded-full border-2 flex items-center justify-center animate-spin transition-colors duration-1000
            ${isNight ? 'bg-indigo-900 border-indigo-400 shadow-lg shadow-indigo-500/30' : 'bg-pink-200 border-pink-400'}`}
                    style={{ left: `${displayObstacleX}px` }}
                >
                    <div className={`w-8 h-1 border-t-2 rotate-45 ${isNight ? 'border-indigo-300' : 'border-pink-400'}`}></div>
                </div>

                {/* Ziemia */}
                <div className={`absolute bottom-0 w-full h-12 border-t-4 transition-colors duration-1000 flex items-center justify-around
          ${isNight ? 'bg-slate-900 border-indigo-900 text-indigo-900' : 'bg-pink-50 border-pink-100 text-pink-200'}`}>
                    {[...Array(9)].map((_, i) => <span key={i} className="text-2xl">🐾</span>)}
                </div>

                {/* Ekrany informacyjne */}
                {!isPlaying && !gameOver && (
                    <div className="absolute inset-0 bg-white/20 backdrop-blur-[4px] flex items-center justify-center">
                        <div className="bg-white p-10 rounded-[3rem] shadow-2xl flex flex-col items-center border-4 border-pink-100">
                            <Sparkles className="text-yellow-400 mb-2 animate-bounce" size={40} />
                            <button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-lg hover:scale-105 transition-all">
                                START GAME
                            </button>
                        </div>
                    </div>
                )}

                {gameOver && (
                    <div className={`absolute inset-0 backdrop-blur-md flex flex-col items-center justify-center text-center p-6 transition-colors duration-1000
            ${isNight ? 'bg-slate-950/90' : 'bg-pink-50/90'}`}>
                        <h3 className={`text-5xl font-black mb-4 ${isNight ? 'text-white' : 'text-pink-600'}`}>Meow! 😿</h3>
                        <p className={`font-bold mb-8 text-2xl ${isNight ? 'text-indigo-300' : 'text-pink-400'}`}>Score: {score}</p>
                        <button className="bg-pink-500 text-white border-4 border-white px-12 py-4 rounded-2xl font-black text-xl hover:bg-pink-600 transition-all shadow-xl">
                            TRY AGAIN
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};