"use client";

import { useEffect, useRef, useState } from "react";
import { Play, Volume2, VolumeX } from "lucide-react";

type ExperienciaCardProps = {
    imagem: string;
    video: string;
    titulo: string;
};

export default function ExperienciaCard({
    imagem,
    video,
    titulo,
}: ExperienciaCardProps) {
    const videoRef = useRef<HTMLVideoElement | null>(null);
    const containerRef = useRef<HTMLDivElement | null>(null);

    const [iconPlay, setIconPlay] = useState(true);
    const [showVideo, setShowVideo] = useState(false);
    const [isMobile, setIsMobile] = useState(false);
    const [showSoundModal, setShowSoundModal] = useState(false);
    const [pendingPlay, setPendingPlay] = useState(false);
    const [isMuted, setIsMuted] = useState(true);

    // guarda se o usuário já respondeu o modal
    const [hasUserChoice, setHasUserChoice] = useState(false);

    // guarda a preferência escolhida
    const [preferredWithSound, setPreferredWithSound] = useState(false);

    useEffect(() => {
        const checkMobile = () => {
            setIsMobile(window.innerWidth < 768);
        };

        checkMobile();
        window.addEventListener("resize", checkMobile);

        return () => window.removeEventListener("resize", checkMobile);
    }, []);

    const startVideo = async (withSound: boolean) => {
        if (!videoRef.current) return;

        try {
            videoRef.current.currentTime = 0;
            videoRef.current.defaultMuted = !withSound;
            videoRef.current.muted = !withSound;
            videoRef.current.volume = withSound ? 1 : 0;

            setIsMuted(!withSound);
            setShowVideo(true);
            setIconPlay(false);
            setShowSoundModal(false);
            setPendingPlay(false);

            await videoRef.current.play();
        } catch (error) {
            console.error("Erro ao iniciar vídeo:", error);
        }
    };

    useEffect(() => {
        if (!isMobile || !containerRef.current || !videoRef.current) return;

        const currentContainer = containerRef.current;
        const currentVideo = videoRef.current;

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    // ainda não escolheu? abre modal
                    if (!hasUserChoice) {
                        setShowSoundModal(true);
                        setPendingPlay(true);
                        return;
                    }

                    // já escolheu? toca automaticamente com a preferência salva
                    startVideo(preferredWithSound);
                } else {
                    currentVideo.pause();
                    currentVideo.currentTime = 0;
                    setShowVideo(false);
                    setIconPlay(true);
                    setPendingPlay(false);
                    setShowSoundModal(false);
                }
            },
            {
                threshold: 0.5,
            }
        );

        observer.observe(currentContainer);

        return () => {
            observer.unobserve(currentContainer);
            observer.disconnect();
        };
    }, [isMobile, hasUserChoice, preferredWithSound]);

    const handleAllowSound = async () => {
        setHasUserChoice(true);
        setPreferredWithSound(true);
        await startVideo(true);
    };

    const handleStartMuted = async () => {
        setHasUserChoice(true);
        setPreferredWithSound(false);
        await startVideo(false);
    };

    const handleMouseEnter = async () => {
        if (isMobile || !videoRef.current) return;

        try {
            videoRef.current.currentTime = 0;
            videoRef.current.muted = false;
            videoRef.current.volume = 1;
            setIsMuted(false);
            setShowVideo(true);
            setIconPlay(false);

            await videoRef.current.play();
        } catch {
            videoRef.current.muted = true;
            videoRef.current.volume = 0;
            setIsMuted(true);
            await videoRef.current.play();
        }
    };

    const handleMouseLeave = () => {
        if (isMobile || !videoRef.current) return;

        videoRef.current.pause();
        videoRef.current.currentTime = 0;
        setShowVideo(false);
        setIconPlay(true);
    };

    const toggleAudio = () => {
        if (!videoRef.current) return;

        const nextMuted = !videoRef.current.muted;
        videoRef.current.muted = nextMuted;
        videoRef.current.volume = nextMuted ? 0 : 1;
        setIsMuted(nextMuted);
        setPreferredWithSound(!nextMuted);
        setHasUserChoice(true);
    };

    return (
        <>
            <div
                ref={containerRef}
                className="relative overflow-hidden rounded-[1.5rem] aspect-[4/5] bg-[#f8c8dc]/30"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
            >
                <img
                    src={imagem}
                    alt={titulo}
                    className={`absolute inset-0 h-full w-full object-cover transition duration-500 ${showVideo ? "opacity-0 scale-105" : "opacity-100"
                        }`}
                />

                <video
                    ref={videoRef}
                    src={video}
                    loop
                    playsInline
                    preload="auto"
                    muted={isMuted}
                    className={`absolute inset-0 h-full w-full object-cover transition duration-500 ${showVideo ? "opacity-100" : "opacity-0"
                        }`}
                />

                <div className="absolute inset-0 bg-gradient-to-t from-[#57152f]/60 via-[#57152f]/10 to-transparent" />

                <div className="absolute inset-0 flex items-center justify-center transition duration-300">
                    {iconPlay && (
                        <div className="flex h-16 w-16 items-center justify-center rounded-full bg-white/85 text-[#c43d7a] shadow-xl backdrop-blur">
                            <Play className="ml-1 h-6 w-6 fill-current" />
                        </div>
                    )}
                </div>

                {showVideo && (
                    <button
                        type="button"
                        onClick={toggleAudio}
                        className="absolute bottom-4 right-4 z-20 flex h-11 w-11 items-center justify-center rounded-full bg-white/85 text-[#c43d7a] shadow-xl backdrop-blur"
                    >
                        {isMuted ? <VolumeX className="h-5 w-5" /> : <Volume2 className="h-5 w-5" />}
                    </button>
                )}
            </div>

            {showSoundModal && pendingPlay && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-[#2b1020]/55 p-4 backdrop-blur-sm">
                    <div className="w-full max-w-sm rounded-[2rem] border border-white/30 bg-white/90 p-6 shadow-2xl">
                        <h3 className="text-xl font-semibold text-[#57152f]">
                            Deseja assistir com som?
                        </h3>

                        <p className="mt-3 text-sm leading-7 text-[#7a4a61]">
                            Para iniciar o vídeo no celular com áudio, precisamos da sua confirmação.
                        </p>

                        <div className="mt-6 grid gap-3 sm:grid-cols-2">
                            <button
                                type="button"
                                onClick={handleAllowSound}
                                className="rounded-2xl bg-gradient-to-r from-[#e85d9e] to-[#c43d7a] px-5 py-3 text-sm font-semibold text-white shadow-lg shadow-pink-200/70"
                            >
                                Sim, com som
                            </button>

                            <button
                                type="button"
                                onClick={handleStartMuted}
                                className="rounded-2xl border border-[#f2d3e0] bg-white px-5 py-3 text-sm font-semibold text-[#a63b6b]"
                            >
                                Não, sem som
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}