add_action('wp_head', 'ultra_smooth_video_preloader', 1);
function ultra_smooth_video_preloader() {

    $favicon_url = "https://pouryawood.com/wp-content/uploads/2026/01/cropped-pouryawood.png";
    $video_url   = "https://pouryawood.com/wp-content/uploads/2026/02/preloader1.mp4";
    $gif_url     = "https://pouryawood.com/wp-content/uploads/2026/02/preloaderg.gif"; // ← همون مسیر گیف واقعی تو

    ?>

    <!-- Favicon -->
    <link rel="icon" href="<?php echo $favicon_url; ?>" type="image/png">
    <link rel="shortcut icon" href="<?php echo $favicon_url; ?>" type="image/png">
    <link rel="preload" href="<?php echo $favicon_url; ?>" as="image">

    <style>
    #preloader-container{
        position:fixed;
        inset:0;
        background:#fff;
        z-index:99999;
        display:flex;
        align-items:center;
        justify-content:center;
        overflow:hidden;
        transition:opacity .6s ease;
    }

    #preloader-container video,
    #preloader-container img{
        width:100%;
        height:100%;
        object-fit:cover;
    }
    </style>

    <div id="preloader-container">
        <!-- Desktop video -->
        <video id="preloadVideo" muted playsinline autoplay preload="auto">
            <source src="<?php echo $video_url; ?>" type="video/mp4">
        </video>

        <!-- Mobile GIF -->
        <img id="preloadGif" src="<?php echo $gif_url; ?>" alt="preloader" style="display:none;">
    </div>

    <script>
    (function(){
        var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
        var preloader = document.getElementById('preloader-container');
        var video = document.getElementById('preloadVideo');
        var gif   = document.getElementById('preloadGif');

        if(isMobile){
            // موبایل → GIF
            video.remove();
            gif.style.display = 'block';

            // مدت نمایش معادل ۵ ثانیه
            setTimeout(function(){
                preloader.style.opacity = 0;
                setTimeout(()=>preloader.remove(),600);
            },1700); // ۵ ثانیه
        } else {
            // دسکتاپ → ویدئو
            var p = video.play();
            if(p){ p.catch(()=>{}); }

            video.addEventListener('ended', function(){
                preloader.style.opacity = 0;
                setTimeout(()=>preloader.remove(),600);
            });
        }
    })();
    </script>
    <?php
}
