import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import Logo from '../../assets/chowman-bg-logo.avif';
import Waiting from '../../assets/waiting.avif';
import SpinningAlpona from '@/components/ui/spinning-alpona';
import { router } from '@inertiajs/react';
import { QuizRouteGuard } from '@/features/quiz/components';
import { useQuizFlow } from '@/features/quiz/hooks';

// Mascot width cap. The text column is padded by the same amount (+ a small gap)
// on BOTH sides, so text stays centred and can never run under the mascot.
const MASCOT_MAX_W = 'min(22vw,140px)';

/** Mascot that slides in from the left edge of the screen and stays there. */
const SlideInMascot = () => {
    const ref = useRef<HTMLImageElement>(null);

    useLayoutEffect(() => {
        const el = ref.current;
        if (!el) return;
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        const animation = el.animate(
            [{ transform: 'translateX(-100%)' }, { transform: 'translateX(0)' }],
            {
                duration: 1000,
                delay: 300,
                easing: 'cubic-bezier(0.22, 1, 0.36, 1)', // fast start, soft landing
                fill: 'backwards', // stay off-screen during the delay
            },
        );

        return () => animation.cancel();
    }, []);

    return (
        <img
            ref={ref}
            src={Waiting}
            alt=""
            className="pointer-events-none absolute bottom-0 left-0 h-full max-h-[300px] w-auto object-contain object-left-bottom select-none"
            style={{ maxWidth: MASCOT_MAX_W }}
        />
    );
};

const Loading = () => {
    const { fetchSession } = useQuizFlow();
    const isStandalonePreview =
        import.meta.env.DEV &&
        new URLSearchParams(window.location.search).get('preview') === '1';
    const hasStartedEvaluation = useRef(false);
    const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
    const [isRetrying, setIsRetrying] = useState(false);

    useEffect(() => {
        if (isStandalonePreview) return;
        if (hasStartedEvaluation.current) return;
        hasStartedEvaluation.current = true;
        let cancelled = false;
        const minimumDisplay = new Promise((resolve) =>
            setTimeout(resolve, 3000),
        );

        const fetchFinalScore = async (): Promise<void> => {
            try {
                // Do not leave this screen until both the three-second brand
                // moment and the server-finalised score are ready.
                await Promise.all([fetchSession(), minimumDisplay]);
                if (!cancelled) router.visit('/score');
            } catch {
                if (!cancelled) {
                    setIsRetrying(true);
                    retryTimerRef.current = setTimeout(() => {
                        void fetchFinalScore();
                    }, 2000);
                }
            }
        };
        void fetchFinalScore();
        return () => {
            cancelled = true;
            if (retryTimerRef.current) clearTimeout(retryTimerRef.current);
        };
        // This screen owns one evaluation cycle. `fetchSession` is recreated
        // when context updates with the fetched score, so it must not restart
        // (and cancel) the active cycle.
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isStandalonePreview]);

    return (
        <QuizRouteGuard
            allowedStates={isStandalonePreview ? undefined : ['completed']}
            requireAuth={!isStandalonePreview}
        >
            {/* overflow-x-hidden: the mascot slides in from off-screen without causing sideways scroll */}
            <main className="flex min-h-[100dvh] flex-col overflow-x-hidden py-8">
                {/* Top block: logo, banner, heading */}
                <div className="mx-auto flex w-full max-w-full shrink-0 flex-col items-center px-4 sm:px-8 lg:px-12">
                    {/* Logo */}
                    <div className="relative z-10 flex justify-center">
                        <img
                            src={Logo}
                            alt="Chowman Logo"
                            className="h-10 w-auto sm:h-12 sm:w-auto"
                        />
                    </div>

                    {/* Banner */}
                    <div>
                        <SpinningAlpona
                            firstLine="Tallying your"
                            secondLine="Pujo gyaan"
                        />
                    </div>

                    {/* Heading */}
                    <div className="relative z-10 -mt-2 text-center sm:-mt-8 lg:-mt-10">
                        <h1 className="font-amethyst text-4xl leading-none text-[#FFF8EA] sm:text-[62px] lg:text-[76px]">
                            <span className='tracking-wider'>Evaluating your</span>
                        </h1>

                        <h2 className="font-amethyst text-4xl leading-none text-[#E7B95E] italic sm:text-[68px] lg:text-[82px] -mt-1">
                            <span className="tracking-wider">answers</span>
                        </h2>
                    </div>
                </div>

                {/* Lower zone: full width so the mascot can hug the screen's left edge.
                    It takes the leftover height; the mascot fills it from the bottom. */}
                <div className="relative min-h-[150px] w-full flex-1">
                    <SlideInMascot />

                    {/* Text column: same padding both sides = mascot width, so nothing overlaps */}
                    <div
                        className="mx-auto flex h-full w-full max-w-full flex-col items-center"
                        style={{
                            paddingLeft: `calc(${MASCOT_MAX_W} + 8px)`,
                            paddingRight: `calc(${MASCOT_MAX_W} + 8px)`,
                        }}
                    >
                        {/* Description */}
                        <p className="mt-12 max-w-[500px] text-center font-montserrat text-xs leading-[1.35] text-[#C5A98B] sm:mt-14 sm:text-[19px] lg:mt-16 lg:text-[21px]">
                            {isRetrying
                                ? 'Still finalising your score. Reconnecting…'
                                : 'Just a festive moment while we check '}
                            
                            your answers.
                        </p>

                        {/* Loading diamonds */}
                        <div className="mt-12 flex items-center gap-7 sm:mt-14 sm:gap-9">
                            {[0, 1, 2].map((item) => (
                                <span
                                    key={item}
                                    className="h-2.5 w-2.5 rotate-0 animate-[loadingDiamond_1.2s_ease-in-out_infinite] bg-[#D4A24E]"
                                    style={{
                                        animationDelay: `${item * 0.2}s`,
                                    }}
                                />
                            ))}
                        </div>
                    </div>
                </div>

                <style>{`
                @keyframes loadingDiamond {
                    0%, 60%, 100% {
                        transform: rotate(45deg) scale(0.65);
                        opacity: 0.35;
                    }

                    30% {
                        transform: rotate(45deg) scale(1.15);
                        opacity: 1;
                    }
                }
            `}</style>
            </main>
        </QuizRouteGuard>
    );
};

export default Loading;
