// Fetch text data and handle interaction
const textEl = document.getElementById('text');
const sceneImg = document.getElementById('image');
let lines = [];
let currentIndex = 0;

function showLine(index) {
    if (index < 0 || index >= lines.length) return;
    const line = lines[index];
    // Update image
    sceneImg.src = line.image;
    // Append or set text with alignment per line
    const lineEl = document.createElement('p');
    lineEl.textContent = line.text;
    // Alignment: left, centre, right
    if (line.align === '0') {
        lineEl.style.textAlign = 'left';
    } else if (line.align === '1') {
        lineEl.style.textAlign = 'center';
    } else if (line.align === '2') {
        lineEl.style.textAlign = 'right';
    }
    textEl.appendChild(lineEl);
    // Auto‑scroll to keep the newest line visible
    textEl.scrollTop = textEl.scrollHeight;
}

function next() {
    if (currentIndex < lines.length - 1) {
        currentIndex++;
        showLine(currentIndex);
    }
}

// Prevent spacebar from scrolling the page
document.addEventListener('keydown', e => {
    if (e.code === 'Space') {
        e.preventDefault();
        next();
    }
});

// Advance on click anywhere in the document
document.addEventListener('click', next);

fetch('text.json')
    .then(r => r.json())
    .then(data => {
        lines = data;
        if (lines.length > 0) {
            showLine(0);
        }
    })
    .catch(err => console.error('Failed to load text:', err));