/*
Theme Name:   Greyd Child Theme
Theme URI:    https://greyd.io/
Description:  A child theme for the Greyd Theme
Author:       Greyd
Author URI:   http://example.com
Template:     greyd-theme
Version:      1.0.0
License:      GPLv2 or later
License URI:  http://www.gnu.org/licenses/gpl-2.0.html
Tags:         Tags: blog, portfolio, entertainment, site-editing, block-patterns, block-styles
Text Domain:  greyd-child-theme
*/


function svf_enqueue_script() {
    ?>
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            console.log('testing for safari');
            // 1. Detect Safari (macOS) and any browser on iOS
            // We must exclude Chrome/Edge on macOS, but include all browsers on iOS (as they use WebKit)
            var uA = navigator.userAgent;
            var isIOS = /iPad|iPhone|iPod/.test(uA) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
            var isSafari = /^((?!chrome|android).)*safari/i.test(uA);
            
            // If it is Safari Desktop OR any iOS device
            if (isSafari || isIOS) {
                console.log("wir sind in safari unterwegs. iiiih!");
                // 2. Find all video elements on the page
                var videos = document.querySelectorAll('video');

                videos.forEach(function(video) {
                    var currentSrc = video.currentSrc || video.src;
                    
                    // Check internal <source> tags if standard src is empty
                    if (!currentSrc) {
                        var sources = video.querySelectorAll('source');
                        if (sources.length > 0) {
                            currentSrc = sources[0].src;
                        }
                    }

                    // 3. Check if the video is using WebM
                    if (currentSrc && currentSrc.includes('.webm')) {
                        
                        // Create the new MP4 URL
                        var newSrc = currentSrc.replace('.webm', '.mp4');

                        // 4. Swap the source
                        // We clear existing sources and set the direct src attribute for reliability
                        video.innerHTML = ''; // Clear child <source> tags
                        video.src = newSrc;
                        
                        // Force the video to reload with the new source
                        video.load();
                        
                        // Optional: specific fix for transparency rendering glitches in Safari
                        video.style.backgroundColor = "transparent"; 
                    }
                });
            }
        });
    </script>
    <?php
}

// Hook the script into the footer so it runs after HTML is generated
add_action( 'wp_footer', 'svf_enqueue_script' );