/**
 * @author Acacia Dynamic
 *  @copyright 2024 Acacia Dynamic
 *  @license   private
 */
var DS4AtFirstSight = true;
const observer = new MutationObserver(mutationsList => {
    observer.disconnect();
    set_DS4();
    observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
});
observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });

document.addEventListener('DOMContentLoaded', () => {
    set_DS4();
});

function getCommonParts(strings) {
    if (strings.length === 0) return { prefix: '', suffix: '' };
    if (strings.length === 1) return { prefix: strings[0], suffix: '' };
    let first = strings[0];
    let prefixEnd = 0;
    while (prefixEnd < first.length) {
        let char = first[prefixEnd];
        if (strings.every(str => str[prefixEnd] === char)) {
            prefixEnd++;
        } else {
            break;
        }
    }
    let prefix = first.slice(0, prefixEnd);
    let reversed = strings.map(str => str.split('').reverse().join(''));
    let firstRev = reversed[0];
    let suffixEnd = 0;
    while (suffixEnd < firstRev.length) {
        let char = firstRev[suffixEnd];
        if (reversed.every(str => str[suffixEnd] === char)) {
            suffixEnd++;
        } else {
            break;
        }
    }
    let suffix = first.slice(first.length - suffixEnd);
    return { prefix, suffix };
}

function get_DS4_img() {
    let imgList = Array.from([...document.querySelectorAll('img[src$=".jpg"]')].filter(img => /\/DS4-tmp[\w-]*\.jpg$/.test(img.src)));
    if (imgList.length == 0) {
        return imgList;
    }
    let srcList = imgList.map(img => img.src);
    let { prefix, suffix } = getCommonParts(srcList);
    function escapeRegex(str) {
        return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }
    let fullRegexp = new RegExp(
        escapeRegex(prefix) + '.*' + escapeRegex(suffix)
    );
    let allImgs = Array.from(document.querySelectorAll('img'));
    allImgs.forEach(img => {
        if (fullRegexp.test(img.src) && !imgList.includes(img)) {
            imgList.push(img);
        }
    });
    return imgList;
}

function sleep(seconds) {
    const end = Date.now() + seconds * 1000;
    while (Date.now() < end) {
        // boucle vide, bloque tout
    }
}

function set_DS4(){
    let imgList = get_DS4_img();
    if (imgList.length > 0) {
        imgList.forEach(img => {
            let next = img.nextElementSibling;
            if (next instanceof HTMLVideoElement) {
                /*if(next.style.display == 'none') {
                    next.style.display = next.getAttribute('data-display');
                    img.style.display = 'none';
                }*/
            } else {
                // si pas le cas on l'ajoute avec les dimensions de l'image
                // quand clic sur la vidéo, on lance le clic sur l'image
                const video = document.querySelector('.DS4-product-player-block video');
                [...video.attributes].forEach(attr => video.removeAttribute(attr));
                let tmpMaxVideoHeight = 98;
                let tmpMaxVideoWidth = 98;
                if(parseFloat(window.getComputedStyle(img).getPropertyValue('height'))<50) {
                    // image cassée
                    tmpMaxVideoHeight = img.getAttribute('height');
                    tmpMaxVideoWidth = img.getAttribute('width');
                } else {
                    tmpMaxVideoHeight = parseFloat(window.getComputedStyle(img).getPropertyValue('height'));
                    tmpMaxVideoWidth = parseFloat(window.getComputedStyle(img).getPropertyValue('width'));
                }
                const isBadNumber = v => v == null || Number.isNaN(v);
                if (isBadNumber(tmpMaxVideoWidth) && img.parentElement && img.parentElement.tagName.toLowerCase() === 'li') {
                    // Trouver le <li> suivant
                    const nextLi = img.parentElement.nextElementSibling;
                    if (nextLi) {
                        // Trouver une image dans ce <li>
                        const nextImg = nextLi.querySelector('img');
                        if (nextImg) {
                            tmpMaxVideoHeight = parseFloat(window.getComputedStyle(nextImg).getPropertyValue('height'));
                            tmpMaxVideoWidth = parseFloat(window.getComputedStyle(nextImg).getPropertyValue('width'));
                            if (isBadNumber(tmpMaxVideoHeight) || tmpMaxVideoHeight < 10) {
                                tmpMaxVideoHeight = tmpMaxVideoWidth;
                            }
                        }
                    }
                }

                if(tmpMaxVideoWidth == 0 || tmpMaxVideoHeight == 0) {

                        const imgs = document.querySelectorAll('img');
                        imgs.forEach(img => {
                            if (img.src.includes(ds4_first_image)) {
                                const ds4rect = img.getBoundingClientRect();
                                tmpMaxVideoWidth = window.getComputedStyle(img).getPropertyValue('width');//ds4rect.width;
                                tmpMaxVideoHeight = window.getComputedStyle(img).getPropertyValue('height');//ds4rect.height;
                            }
                        });

                }

                let newAttributes = [
                    'class="DS4video ' + img.className + '"',
                    'autoplay',
                    'loop',
                    'muted',
                    'playsinline',
                    'style="max-width:' + tmpMaxVideoWidth + 'px;max-height:' + tmpMaxVideoHeight + 'px;cursor:' + window.getComputedStyle(img).getPropertyValue('cursor') + ';display:' + window.getComputedStyle(img).getPropertyValue('display') + '"',
                    'data-display="' + window.getComputedStyle(img).getPropertyValue('display') + '"'
                ];
                newAttributes.forEach(attrString => {
                    const [name, value] = attrString.split('=');
                    if (value !== undefined) {
                        const cleanValue = value.replace(/^["']|["']$/g, '');
                        video.setAttribute(name.trim(), cleanValue);
                    } else {
                        video.setAttribute(name.trim(), '');
                    }
                });

                if (img.closest("li") || img.closest("ul")) {
                    console.log('closest');
                    video.removeAttribute("controls");
                }

                img.insertAdjacentHTML('afterend', document.querySelector('.DS4-product-player-block').innerHTML);

            }
        });
    }
    // pour repasser sur l'image normal pour l'affichage en grand
    let videoList = document.querySelectorAll('.DS4video');
    if (videoList.length > 0) {
        videoList.forEach(video => {
            let prev = video.previousElementSibling;
            if (prev instanceof HTMLImageElement) {
                if(!imgList.includes(prev)) {
                    video.style.display = 'none';
                    prev.style.display = video.getAttribute('data-display');
                }
            }
            video.removeAttribute('alt');
            video.removeAttribute('title');
            video.removeAttribute('src');
            if (video.closest('ul')) {
                video.removeAttribute('controls');
            }
        });
    }
}

document.body.addEventListener('click', function(event) {
    if (event.target && event.target.tagName.toLowerCase() === 'video' && event.target.classList.contains('DS4video')) {
        event.target.previousElementSibling.click();
    }
});

function DS4_cover() {
    let imgList = get_DS4_img();//document.querySelectorAll('img[alt="DS4-special-image"]');
    if (imgList.length > 0) {
        imgList.forEach(img => {
            //si l'image est dans un li alors c'est les preview, on clic dessus la première fois
            if (DS4AtFirstSight) {
                let liParent = img.closest('li');
                if (liParent) {
                    let parent = img.parentElement;
                    img.click();
                    DS4AtFirstSight = false;
                }
            }
        });
    }
}

// une fois le dom chargé et les scripts executés pour remplacer la cover
window.onload = function() {
    DS4_cover();
}
// pour les produits avec combinaisons, on écoute les fetch/ajax pour mettre la vidéo en cover
// fetch
const originalFetch = window.fetch;
window.fetch = function(...args) {
    return originalFetch(...args).then(response => {
        if (response.ok && response.headers.get('content-type').includes('application/json')) {
            return response.json().then(data => {
                if (data.hasOwnProperty('product_has_combinations')) {
                    DS4AtFirstSight=true;
                    DS4_cover();
                }
                return data;
            });
        } else {
            return response;
        }
    });
};
// XMLHttpRequest
const originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(...args) {
    this.addEventListener('load', function() {
        if (this.status === 200 && this.getResponseHeader('Content-Type').includes('application/json')) {
            const data = JSON.parse(this.responseText);
            if (data.hasOwnProperty('product_has_combinations')) {
                DS4AtFirstSight=true;
                DS4_cover();
            }
        }
    });
    originalSend.apply(this, args);
};

window.addEventListener('load', () => {
    const imgs = Array.from(
        document.querySelectorAll('img[src$=".jpg"]')
    ).filter(img => /\/DS4-tmp[\w-]*\.jpg$/.test(img.src));

    imgs.forEach(async (img) => {
        img.src = img.src.split("wp-content")[0] +
            "wp-content/plugins/digitalsignage4/assets/DS4-tmp.jpg";
        img.removeAttribute("srcset");

        // Attendre que l'image soit décodée (plus fiable que 'load')
        try { await img.decode(); } catch(e) { /* ignore decoding error */ }

        // Laisser le navigateur faire un layout (frame suivante)
        await new Promise(r => requestAnimationFrame(() => r()));

        // Si l’élément (ou un parent) est display:none, tout restera à 0
        const hidden = !img.isConnected ||
            img.offsetParent === null; // approximatif: null si display:none (hors fixed)

        const rect = img.getBoundingClientRect();
        const w = rect.width;
        const h = rect.height;

        if (w > 0 && h > 0) {
            const videos = Array.from(img.parentElement.querySelectorAll('video'));
            videos.forEach(async (video) => {
                video.style.maxWidth = w + 'px';
                video.style.maxHeight = h + 'px';
            });
        }
        img.style.display = 'none';
    });
});