/** 
 *  @author Nityanand Ojha
 *
 */

var _title;
var activityFrame;
var count = 0;
var _leftPannel;
var _rightPannel;
var _main;
var cell;
var wrd;
var audio = null;
var isRecording = false;

var sourceOGG = ""
var sourceMP3 = ""
var scorm = pipwerks.SCORM;
scorm.version = "1.2";
var audioPlaybackStatus = new Array(data.contents.length).fill(false);
init();

// or "2004" based on LMS

function initSCORM() {
    var result = scorm.init();
    if (result) {
        console.log("SCORM initialized successfully.");
    } else {
        console.error("Failed to initialize SCORM.");
    }
}
window.onload = initSCORM;
function init() {
    _main = document.getElementById("main");

    _title = document.getElementById("titleTxt");
    _title.innerHTML = data.title;

    _leftPannel = document.getElementById("leftPannel");
    _rightPannel = document.getElementById("rightPannel");
    audio = document.createElement("audio");

    _main.appendChild(audio);
    sourceMP3 = document.createElement("source");
    audio.appendChild(sourceMP3)
    sourceOGG = document.createElement("source");
    audio.appendChild(sourceOGG)


    constructElement();

    var platform = navigator.userAgent;
    // console.log(platform, " platform");
    // if(platform.indexOf("Android") > -1){
    // 	addAppRecorder();
    // 	return;
    // }
    // addingIrecord();
    
    if (data.irecord) {
        addingIrecord();
        // document.getElementById("rightPannel").style.display = "none";
        console.log("irecord true");
    }else{
        document.getElementById("rightPannel").style.display = "none";
        console.log("irecord false");
    }

    window.addEventListener("blur", stopAudio);
}

function stopAudio(e) {
    if (audio) {
        audio.pause();

        for (var i = 0; i < data.contents.length; i++) {
            var getChild = document.getElementById("soundBtn" + i).childNodes[0]
            getChild.src = "../__images/sndIcon1.png";
        }
    }
}

function constructElement() {

    // if(!data.contents.irecord){
    //     document.getElementById("rightPannel").style.display = "none";
    // }

    var divForScroll = document.createElement("div");
    divForScroll.style.position = "relative";
    _leftPannel.appendChild(divForScroll);

    divForScroll.className = "flexcroll";
    divForScroll.style.overflow = "scroll";
    divForScroll.style.overflow = "auto";
    divForScroll.style.overflowX = "hidden";

    for (let i = 0; i < data.contents.length; i++) {
        // Create the accordion wrapper
        var cell = document.createElement("div");
        cell.style.marginBottom = "30px";
        cell.style.backgroundColor = "#E1F4FD";
        divForScroll.appendChild(cell);

        // Create the header for the accordion
        var accordionHeader = document.createElement("h3");
        accordionHeader.style.display = "flex";
        accordionHeader.style.alignItems = "center";
        accordionHeader.style.justifyContent = "space-between";
        cell.appendChild(accordionHeader);

        // Add the sound button
        var soundBtn = document.createElement("div");
        soundBtn.style.cursor = "pointer";
        soundBtn.style.marginRight = "10px";
        soundBtn.style.display = "flex";
        soundBtn.style.alignItems = "center";

        var soundImg = new Image();
        soundImg.src = "../__images/sndIcon1.png"; // Ensure this image path is correct
        soundImg.style.width = "24px"; // Adjust the size of the sound button
        soundImg.style.height = "24px";
        soundBtn.appendChild(soundImg);
        soundBtn.id = "soundBtn" + i;
        soundBtn.classList.add("soundBtn");

        // Attach click listener to the sound button
        soundBtn.addEventListener("click", function (e) {
            e.stopPropagation(); // Prevents the accordion toggle
            playWrdSound(i); // Plays the word sound for the clicked button
        });

        accordionHeader.appendChild(soundBtn);

        // Add the word text to the header
        var headerText = document.createElement("span");
        headerText.textContent = data.contents[i].word;
        headerText.style.flexGrow = "1";
        headerText.style.textAlign = "left";
        accordionHeader.appendChild(headerText);

        // Create the content for the accordion
        var accordionContent = document.createElement("div");
        accordionContent.innerHTML = generateAccordionContent(data.contents[i]); // Generate dynamic content
        cell.appendChild(accordionContent);

        // Initialize the accordion
        $(cell).accordion({
            collapsible: true,
            heightStyle: "content",
            active: false,
            activate: function (event, ui) {
                if (ui.newHeader.length) {
                    playAccordionAudio(data.contents[i]); // Play audio for the opened panel
                } else {
                    stopAudio(); // Stop audio when panel is closed
                }
            },
        });
    }
}

// Generate content for the accordion
function generateAccordionContent(content) {
    let html = "";

    // Add meaning text
    if (content.meaning && content.meaning.text) {
        html += `<p><strong>Meaning:</strong> ${content.meaning.text}</p>`;
    }

    // Add sentence
    if (content.sentence) {
        html += `<p><strong>Sentence:</strong> ${content.sentence}</p>`;
    }

    // Add image
    if (content.meaning.img) {
        html += `<div><img src="${content.meaning.img}" alt="${content.word}" style="max-width: 100%; height: auto;"></div>`;
    }

    // Add video
    if (content.meaning.vid) {
        html += `
            <div>
                <video controls style="max-width: 100%; height: auto;">
                    <source src="${content.meaning.vid}" type="video/mp4">
                    Your browser does not support the video tag.
                </video>
            </div>
        `;
    }

    return html || "<p>No additional information available.</p>";
}

// Play audio for the opened panel
function playAccordionAudio(content) {
    // Stop the currently playing audio
    stopAudio();

    // Stop all other videos before playing a new video
    document.querySelectorAll("video").forEach(video => {
        video.pause();
    });

    if (content.audio) {
        sourceMP3.src = content.audio;
        sourceOGG.src = content.audio.replace(".mp3", ".ogg");
        audio.load();
        audio.play();
    }
}

document.addEventListener("play", function (event) {
    if (event.target.tagName === "VIDEO") {
        stopAudio();
    }
}, true);


// Stop any currently playing audio
function stopAudio() {
    if (audio) {
        audio.pause();
        audio.currentTime = 0;
    }
}

// Helper function to generate dynamic accordion content
function generateAccordionContent(content) {
    let html = "";

    // Add meaning text
    if (content.meaning && content.meaning.text) {
        html += `<p><strong>Meaning:</strong> ${content.meaning.text}</p>`;
    }

    // Add sentence
    if (content.sentence) {
        html += `<p><strong>Sentence:</strong> ${content.sentence}</p>`;
    }

    // Add image if available
    if (content.meaning.img) {
        html += `<div><img src="${content.meaning.img}" alt="${content.word}" style="max-width: 100%; height: auto;"></div>`;
    }
    // Add video if available
    if (content.meaning.vid) {
        html += `
            <div>
                <video controls style="max-width: 100%; height: auto;">
                    <source src="${content.meaning.vid}" type="video/mp4">
                    Your browser does not support the video tag.
                </video>
            </div>
        `;
    }

    return html || "<p>No additional information available.</p>";
}


function onsoundBtnClicked(e) {
    var cBtnId = e.target.parentNode.id.substr(8);

    playWrdSound(cBtnId);
}

function playWrdSound(cBtnId) {
    // Stop all videos before playing audio
    document.querySelectorAll("video").forEach(video => {
        video.pause();
    });

    for (var i = 0; i < data.contents.length; i++) {
        var getChild = document.getElementById("soundBtn" + i).childNodes[0];
        getChild.src = "../__images/sndIcon1.png";
    }

    var cChild = document.getElementById("soundBtn" + cBtnId).childNodes[0];
    cChild.src = "../__images/sndIcon.png";

    sourceOGG.src = "Assets/mp3/" + data.contents[cBtnId].sound + ".ogg";
    sourceMP3.src = "Assets/mp3/" + data.contents[cBtnId].sound + ".mp3";
    audio.load();

    audio.addEventListener("ended", function () {
        onSoundEnded(cBtnId);
    });

    audio.play();
}

function onSoundEnded(cBtnId) {
    audioPlaybackStatus[cBtnId] = true;

    if (audioPlaybackStatus.every((status) => status)) {
        var completionStatus = scorm.get("cmi.core.lesson_status");
        if (completionStatus !== "completed") {
            scorm.set("cmi.core.lesson_status", "completed");
            scorm.save();
            console.log("SCORM status set to completed.");
        }
    }

    for (var i = 0; i < data.contents.length; i++) {
        var getChild = document.getElementById("soundBtn" + i).childNodes[0];
        getChild.src = "../__images/sndIcon1.png";
    }
}

function addingIrecord() {
    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("id", "iRecorder");
    ifrm.setAttribute("scrolling", "no");
    ifrm.setAttribute("frameborder", "0");
    _rightPannel.appendChild(ifrm);

    ifrm.src = "js/Irecord/index.html";
}
$(window).resize(function () {
    const width = $(window).width();
    if (width < 600) {
        $(".accordion").accordion("option", "collapsible", true);
    }
});
function terminateSCORM() {
    var result = scorm.finish();
    if (result) {
        console.log("SCORM session terminated.");
    } else {
        console.error("Failed to terminate SCORM session.");
    }
}
window.onunload = terminateSCORM;