<?php
    
include_once "Functions/get_content.php";
    
$blocks getPageContentBlocks($dbc'timeline');

    
/* 
        (Label, Image, Title, Text), the three numbers or indexes 
        indicate the position of a certain block type in a "data row" starting from index 0 
    */
    /* $timelineData = [
        '1930-1945' => ['Kindheit (1930-1945)', 3, 1, 4], 
        '1949-1954' => ['Bildungslaufbahn (1949-1954)', 5, 6, 7],                                                          
        'karriere-1958-1964' => ['Karriere (1958-1964)', 8, 9, 10],
        'international-1958-1964' => ['Internationalität (1958-1964)', 17, 11, 12],
        'genie-1980-2000' => ['Genie (1980-2000)', 18, 13, 14],
        'abschluss-2000-2021' => ['Abschluss (2000-2021)', 19, 15, 16]
    ]; */

    // load timeline data from JSON file
    
$timelineData json_decode(file_get_contents('./Scripts/timelineData.json'), true);
?>

<div class='main-timeline-container'>
    <div class='timeline-container'>
        <!-- DEBUGGING - Blocks Array -->
        <script>
            var blocks = <?php echo json_encode($blocks); ?>;
            var timelineData = <?php echo json_encode($timelineData); ?>;
            console.log('Blocks Array:', blocks);
            console.log('Timeline Data Array:', timelineData);
        </script>

        <?php
            
if (isset($blocks[0]) && $blocks[0]['blockType'] === 'header') {
                echo 
"<h1>" htmlspecialchars($blocks[0]['content'] ?? 'No Header') . "</h1>";
                echo 
"<p>" htmlspecialchars($blocks[20]['content'])  . "</p>";
            }
            if (isset(
$blocks[1]) && $blocks[1]['blockType'] === 'text') {
                echo 
"<p>" nl2br(htmlspecialchars($blocks[1]['content'] ?? 'No Text')) . "</p>";
            }
        
?>

        <!-- Timeline Navigation -->
        <div id="timeline">
            <?php echo "<h1 id='timeline-header'>" $blocks[2]['content'] . "</h1>" ?>
            <ul id="dates">
                <!-- Timeline vertical line -->
                <svg class="date-timeline" width="2" height="448" viewBox="0 0 2 448" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 0L1 1230" stroke="white" stroke-dasharray="2 2"/>
                </svg>
                <div class="timeline-progress"></div>
                
                <?php
                    $firstItem 
true;
                    foreach (
$timelineData as $eventId => $data) {
                        
$label $data['Label'];
                        
// Extract year from label for yearLabel if needed
                        
if (preg_match('/^([^(]+)\s*(\([^)]+\))$/'$label$matches)) {
                            
$mainLabel trim($matches[1]);
                            
$yearLabel $matches[2];
                        } else {
                            
$mainLabel $label;
                            
$yearLabel '';
                        }
                        
$isSelected $firstItem 'selected' '';
                        echo 
"<li data-event='$eventId'>
                                <div class='timeline-dot 
$isSelected'></div>
                                <a href='#
$eventId' class='$isSelected' data-event='$eventId'>
                                    <span class='timeline-label'>
$mainLabel
                                        <span class='timeline-year'>
$yearLabel</span>
                                    </span>
                                </a>
                            </li>"
;
                        
$firstItem false;
                    }
                
?>
            </ul>
        </div>
    </div>

    <!-- Timeline Content -->
    <div id='timeline-image-container'>
        <ul id='issues'>
            <?php
                $blockCount 
0;
                foreach (
$timelineData as $eventId => $data) {
                    
$isSelected $blockCount === 'selected' '';
                    
$imageIndex $data['ImageBlockID'];
                    
$titleIndex $data['TitleBlockID'];
                    
$textIndex $data['TextBlockID'];

                    
$imagePath = isset($blocks[$imageIndex]) ? htmlspecialchars($blocks[$imageIndex]['content']) : 'No Image';
                    
$altText 'Image Not Available';
                    if (
$imagePath !== 'No Image') {
                        
$basename basename($imagePath);
                        
$altWithoutExt pathinfo($basenamePATHINFO_FILENAME);
                        
$altText $altWithoutExt "[" . ($imageIndex) . "]";
                    }
                    
$title = isset($blocks[$titleIndex]) ? htmlspecialchars($blocks[$titleIndex]['content']) : 'No Title'
                    
$text = isset($blocks[$textIndex]) ? nl2br(htmlspecialchars($blocks[$textIndex]['content'])) : 'No Text'

                    echo 
"<li id='$eventId' class='$isSelected' data-event='$eventId'>";
                    echo 
"<div class='vertical-image-hanging-line'></div>";
                    echo    
"<img src='$imagePath' alt='$altText'>";
                    echo    
"<h1 class='timeline-image-container-header'>$title</h1>";
                    if (
$blockCount === 0) {
                        echo 
"<p style='padding:0;'>$text</p>";
                    } else {
                        echo 
"<p>$text</p>";
                    }
                    echo 
"</li>";
                    
$blockCount++;
                }
            
?>
        </ul>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const navItems = document.querySelectorAll('#dates li');
        const navLinks = document.querySelectorAll('#dates li a');
        const contentItems = document.querySelectorAll('#issues li');

        function clearSelected() {
            navItems.forEach(item => item.querySelector('.timeline-dot').classList.remove('selected'));
            navLinks.forEach(link => link.classList.remove('selected'));
            contentItems.forEach(item => item.classList.remove('selected'));
        }

        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const eventId = this.getAttribute('data-event');
                const targetId = this.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);

                clearSelected();
                const navLi = document.querySelector(`#dates li[data-event='${eventId}']`);
                if (navLi) navLi.querySelector('.timeline-dot').classList.add('selected');
                this.classList.add('selected');
                const contentLi = document.querySelector(`#issues li[data-event='${eventId}']`);
                if (contentLi) contentLi.classList.add('selected');

                if (targetElement) {
                    targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
        });

        if (navLinks.length && contentItems.length) {
            clearSelected();
            navItems[0].querySelector('.timeline-dot').classList.add('selected');
            navLinks[0].classList.add('selected');
            contentItems[0].classList.add('selected');
        }
    });
</script>