<?php
// File: /single/part-bible-slideout.php
if (!defined('ABSPATH')) exit;
?>

<div class="dd-sermon-bible-panel" id="ddSermonBiblePanel">
    <div class="dd-bible-panel-header">
        <div style="display: flex; gap: 8px; flex: 1;">
            <select id="ddBBook" style="flex: 2;" onchange="ddLoadBiblePanel()"></select>
            <select id="ddBChapter" style="flex: 1;" onchange="ddLoadBiblePanel()"></select>
            
            <select id="ddBVerse" style="width: 70px;" onchange="ddScrollToVerse()">
                <option value="">V.</option>
            </select>
        </div>
        <button onclick="ddToggleBiblePanel()" style="background: transparent; border: none; font-size: 24px; color: #8E8E93; cursor: pointer; padding: 0 8px; margin-left: 10px;">&times;</button>
    </div>
    
    <div class="dd-bible-panel-content" id="ddBiblePanelContent">
        <div style="text-align:center; padding: 80px 20px; color: #8E8E93; font-family: -apple-system, sans-serif;">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="opacity: 0.5; margin-bottom: 10px;"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg><br>
            Fetching scriptures...
        </div>
    </div>
</div>

<script>
    const ddBooks = ["Genesis","Exodus","Leviticus","Numbers","Deuteronomy","Joshua","Judges","Ruth","1 Samuel","2 Samuel","1 Kings","2 Kings","1 Chronicles","2 Chronicles","Ezra","Nehemiah","Esther","Job","Psalm","Proverbs","Ecclesiastes","Song of Solomon","Isaiah","Jeremiah","Lamentations","Ezekiel","Daniel","Hosea","Joel","Amos","Obadiah","Jonah","Micah","Nahum","Habakkuk","Zephaniah","Haggai","Zechariah","Malachi","Matthew","Mark","Luke","John","Acts","Romans","1 Corinthians","2 Corinthians","Galatians","Ephesians","Philippians","Colossians","1 Thessalonians","2 Thessalonians","1 Timothy","2 Timothy","Titus","Philemon","Hebrews","James","1 Peter","2 Peter","1 John","2 John","3 John","Jude","Revelation"];
    
    const ddAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
    let isBibleLoaded = false;

    function ddToggleBiblePanel() {
        const wrapper = document.getElementById('ddSermonLayoutWrapper');
        wrapper.classList.toggle('bible-open');
        
        if (wrapper.classList.contains('bible-open') && !isBibleLoaded) {
            ddInitBibleControls();
            ddLoadBiblePanel("<?php echo esc_js($init_book); ?>", <?php echo $init_chap; ?>, <?php echo $init_verse; ?>);
            isBibleLoaded = true;
        }
    }

    function ddInitBibleControls() {
        const bookSel = document.getElementById('ddBBook');
        const chapSel = document.getElementById('ddBChapter');
        
        ddBooks.forEach(b => {
            let opt = document.createElement('option');
            opt.value = b; opt.innerText = b;
            bookSel.appendChild(opt);
        });

        for(let i=1; i<=150; i++) {
            let opt = document.createElement('option');
            opt.value = i; opt.innerText = i; 
            chapSel.appendChild(opt);
        }
    }

    function ddLoadBiblePanel(forceBook = null, forceChap = null, forceVerse = null) {
        const bookSel = document.getElementById('ddBBook');
        const chapSel = document.getElementById('ddBChapter');
        const vSelect = document.getElementById('ddBVerse');
        const contentBox = document.getElementById('ddBiblePanelContent');

        let b = forceBook || bookSel.value;
        let c = forceChap || chapSel.value;
        let v = forceVerse || vSelect.value;

        bookSel.value = b;
        chapSel.value = c;

        contentBox.innerHTML = '<div style="text-align:center; padding: 60px; color: #8E8E93;">Loading...</div>';

        const formData = new FormData();
        formData.append('action', 'dd_app_read');
        formData.append('book', b);
        formData.append('chapter', c);

        fetch(ddAjaxUrl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(res => {
            if (res.success) {
                // BULLETPROOF DOM SCRUBBER
                // We create a temporary invisible div to manipulate the HTML directly before it ever hits the screen
                let tempDiv = document.createElement('div');
                tempDiv.innerHTML = res.data.html;
                
                // 1. Physically delete all SVG icons, reading titles, and cross-reference spans
                let junkNodes = tempDiv.querySelectorAll('.dd-apple-note-icon, .dd-apple-xref-wrapper, .dd-apple-xref-sup, .dd-apple-reading-title, .dd-apple-strongs');
                junkNodes.forEach(node => node.remove());
                
                // 2. Unwrap the <a> tags so the text is no longer a clickable link with purple styling
                let links = tempDiv.querySelectorAll('a.dd-apple-has-note');
                links.forEach(link => {
                    let parent = link.parentNode;
                    while(link.firstChild) {
                        parent.insertBefore(link.firstChild, link);
                    }
                    parent.removeChild(link);
                });

                // 3. Strip out the leftover Strong's numbers using Regex just in case any bled through as plain text
                let cleanHtml = tempDiv.innerHTML;
                cleanHtml = cleanHtml.replace(/([a-zA-Z]+)[HG]\d{1,5}\b/gi, '$1');
                
                // Inject the pristine HTML
                contentBox.innerHTML = cleanHtml;

                // DYNAMIC VERSE POPULATOR
                let verseWrappers = contentBox.querySelectorAll('.dd-verse-wrap');
                let verseCount = verseWrappers.length;
                
                vSelect.innerHTML = '<option value="">V.</option>';
                for(let i=1; i<=verseCount; i++) {
                    let opt = document.createElement('option');
                    opt.value = i; opt.innerText = i;
                    vSelect.appendChild(opt);
                }

                // Scroll targeting
                if (v && v > 0 && v <= verseCount) {
                    vSelect.value = v;
                    ddScrollToVerse(v);
                } else {
                    contentBox.scrollTop = 0;
                }
            } else {
                contentBox.innerHTML = '<div style="text-align:center; color:#FF3B30; padding:40px;">' + res.data + '</div>';
            }
        })
        .catch(err => {
            contentBox.innerHTML = '<div style="text-align:center; color:#FF3B30; padding:40px;">Connection error.</div>';
        });
    }

    function ddScrollToVerse(overrideVerse = null) {
        let v = overrideVerse || document.getElementById('ddBVerse').value;
        if (v && v > 0) {
            const targetVerse = document.getElementById('dd-verse-' + v);
            if (targetVerse) {
                // Scroll specifically inside the bible panel
                document.getElementById('ddBiblePanelContent').scrollTo({
                    top: targetVerse.offsetTop - 40,
                    behavior: 'smooth'
                });
                
                targetVerse.style.backgroundColor = '#FFF0B3';
                targetVerse.style.borderRadius = '8px';
                targetVerse.style.padding = '4px 8px';
                targetVerse.style.transition = 'background-color 1s ease';
                
                setTimeout(() => {
                    targetVerse.style.backgroundColor = 'transparent';
                    targetVerse.style.padding = '0';
                }, 2500);
            }
        }
    }
</script>