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

// --- MODEL KOTA (bez zmian) ---
interface DetailedKittyProps { isGameOver: boolean; }
const DetailedKitty: React.FC<DetailedKittyProps> = ({ isGameOver }) => {
    const mainColor = isGameOver ? '#cbd5e1' : '#f472b6';
    const stripeColor = '#ec4899';
    const earColor = '#fbcfe8';
    return (
        <div className="relative w-20 h-14">
            <div className="absolute -left-4 top-4 w-8 h-3 rounded-full origin-right rotate-[-20deg]" style={{ backgroundColor: mainColor }} />
            <div className="absolute inset-0 rounded-[2rem] overflow-hidden shadow-sm" style={{ backgroundColor: mainColor }}>
                <div className="absolute top-0 left-1/4 w-2 h-4 rounded-full opacity-30" style={{ backgroundColor: stripeColor }} />
            </div>
            <div className="absolute -right-4 -top-6 w-14 h-13 rounded-full shadow-sm" style={{ backgroundColor: mainColor }}>
                <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>
                <div className={`absolute top-5 left-3 w-2.5 h-2.5 rounded-full ${isGameOver ? 'bg-slate-500 flex items-center justify-center text-[10px]' : '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 flex items-center justify-center text-[10px]' : '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-8 left-1/2 -translate-x-1/2 w-2 h-1.5 bg-pink-400 rounded-full" />
            </div>
        </div>
    );
};

// --- KONFIGURACJA STABILNA ---
const FPS_LIMIT = 60;
const FRAME_MIN_TIME = 1000 / FPS_LIMIT; // ok. 16.67ms

const GAP_SIZE = 180;
const PIPE_WIDTH = 70;
const PIPE_SPEED = 180;
const PIPE_SPAWN_RATE = 2.0;
const GRAVITY = 1200;
const FLAP_STRENGTH = -380;
const CANVAS_HEIGHT = 450;

export const FlappyCat: 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('flappyKittyHighScore');
        return saved ? parseInt(saved, 10) : 0;
    });

    const [displayKittyY, setDisplayKittyY] = useState(150);
    const [displayPipes, setDisplayPipes] = useState<{ x: number; topHeight: number; id: number }[]>([]);
    const [rotation, setRotation] = useState(0);

    const kittyYRef = useRef(150);
    const velocityRef = useRef(0);
    const pipesRef = useRef<{ x: number; topHeight: number; id: number; passed?: boolean }[]>([]);
    const scoreRef = useRef(0);
    const requestRef = useRef<number>(0);
    const lastTimeRef = useRef<number>(0);
    const lastFrameTimestampRef = useRef<number>(0); // Do pilnowania FPS
    const spawnTimerRef = useRef<number>(0);

    const endGame = useCallback(() => {
        setGameOver(true);
        setIsPlaying(false);
        if (scoreRef.current > highScore) {
            setHighScore(scoreRef.current);
            localStorage.setItem('flappyKittyHighScore', scoreRef.current.toString());
        }
    }, [highScore]);

    const startGame = useCallback(() => {
        setIsPlaying(true);
        setGameOver(false);
        setScore(0);
        scoreRef.current = 0;
        kittyYRef.current = 150;
        velocityRef.current = 0;
        pipesRef.current = [];
        spawnTimerRef.current = 0;
        lastTimeRef.current = performance.now();
        lastFrameTimestampRef.current = performance.now();
        setDisplayKittyY(150);
        setDisplayPipes([]);
    }, []);

    const flap = useCallback(() => {
        if (isPlaying && !gameOver) velocityRef.current = FLAP_STRENGTH;
    }, [isPlaying, gameOver]);

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

            // --- MECHANIZM FPS CAP ---
            const elapsedSinceLastFrame = currentTime - lastFrameTimestampRef.current;

            // Jeśli klatka przyszła za szybko (np. na monitorze 144Hz), pomijamy update
            if (elapsedSinceLastFrame < FRAME_MIN_TIME) {
                requestRef.current = requestAnimationFrame(update);
                return;
            }

            // Obliczamy dt na podstawie rzeczywistego czasu, który upłynął
            const dt = (currentTime - lastTimeRef.current) / 1000;
            lastTimeRef.current = currentTime;
            lastFrameTimestampRef.current = currentTime; // Aktualizujemy znacznik klatki

            const frameTime = Math.min(dt, 0.1);

            velocityRef.current += GRAVITY * frameTime;
            kittyYRef.current += velocityRef.current * frameTime;
            setRotation(Math.min(Math.max(velocityRef.current * 0.12, -20), 70));

            if (kittyYRef.current > CANVAS_HEIGHT - 40 || kittyYRef.current < -40) {
                endGame();
                return;
            }

            spawnTimerRef.current += frameTime;
            if (spawnTimerRef.current >= PIPE_SPAWN_RATE) {
                const topHeight = Math.random() * (220 - 70) + 70;
                pipesRef.current.push({ x: 650, topHeight, id: Date.now() });
                spawnTimerRef.current = 0;
            }

            const updatedPipes = [];
            for (const p of pipesRef.current) {
                p.x -= PIPE_SPEED * frameTime;
                if (p.x < 100 && p.x + PIPE_WIDTH > 50) {
                    if (kittyYRef.current < p.topHeight || kittyYRef.current > p.topHeight + GAP_SIZE - 45) {
                        endGame();
                        return;
                    }
                }
                if (p.x < 50 && !p.passed) {
                    p.passed = true;
                    scoreRef.current += 1;
                    setScore(scoreRef.current);
                }
                if (p.x > -PIPE_WIDTH) updatedPipes.push(p);
            }
            pipesRef.current = updatedPipes;

            setDisplayKittyY(kittyYRef.current);
            setDisplayPipes([...pipesRef.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 flap();
            }
        };
        window.addEventListener('keydown', handleKey);
        return () => window.removeEventListener('keydown', handleKey);
    }, [isPlaying, gameOver, startGame, flap]);

    return (
        <div className="flex flex-col items-center justify-center min-h-[75vh] p-4 font-sans">
            <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 Menu
            </button>

            <div
                className="relative w-full max-w-[600px] h-[450px] bg-sky-100 rounded-[3rem] shadow-2xl border-4 border-white overflow-hidden cursor-pointer select-none"
                onClick={() => { if (!isPlaying || gameOver) startGame(); else flap(); }}
            >
                <div className="absolute top-10 left-10 text-white/40"><Sparkles size={40} /></div>
                <div className="absolute top-40 right-20 text-white/30"><Sparkles size={60} /></div>

                <div className="absolute top-6 right-8 text-right z-30 font-black">
                    <div className="text-pink-500 text-4xl">Score: {score}</div>
                    <div className="text-pink-300 text-sm flex items-center justify-end gap-1"><Trophy size={14} /> Record: {highScore}</div>
                </div>

                <div className="absolute left-10 z-20" style={{ top: `${displayKittyY}px`, transform: `rotate(${rotation}deg)`, transition: 'transform 0.1s linear' }}>
                    <DetailedKitty isGameOver={gameOver} />
                </div>

                {displayPipes.map(p => (
                    <React.Fragment key={p.id}>
                        <div className="absolute bg-[#e5c29f] border-x-4 border-b-8 border-[#d4ac87] rounded-b-3xl" style={{ left: p.x, top: 0, width: PIPE_WIDTH, height: p.topHeight }} />
                        <div className="absolute bg-[#e5c29f] border-x-4 border-t-8 border-[#d4ac87] rounded-t-3xl" style={{ left: p.x, top: p.topHeight + GAP_SIZE, width: PIPE_WIDTH, height: CANVAS_HEIGHT - (p.topHeight + GAP_SIZE) }} />
                    </React.Fragment>
                ))}

                {!isPlaying && !gameOver && (
                    <div className="absolute inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-40">
                        <div className="bg-white p-10 rounded-[3rem] shadow-2xl text-center border-4 border-pink-100">
                            <p className="text-3xl font-black text-pink-500 mb-6">Flappy Cat 🎈</p>
                            <button className="bg-pink-500 text-white px-10 py-4 rounded-2xl font-black animate-bounce text-xl shadow-lg">START</button>
                        </div>
                    </div>
                )}

                {gameOver && (
                    <div className="absolute inset-0 bg-pink-50/90 backdrop-blur-md flex flex-col items-center justify-center z-40 text-center">
                        <h3 className="text-5xl font-black text-pink-600 mb-2">Oops! 😿</h3>
                        <p className="font-bold text-3xl text-pink-400 mb-8">Score: {score}</p>
                        <button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-xl">TRY AGAIN</button>
                    </div>
                )}
            </div>
        </div>
    );
};