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

var imagesBinary;
    
window.onload = (event) => {
    loadBin();
}

async function loadFrames() {
    const res = await fetch('imagepack.gz')
    const buffer = await res.arrayBuffer();
    return buffer;
}

const GZIP_MAGIC = [0x1f, 0x8b];

function parseFrames(arrayBuffer) {
    // ---- detect gzip ---------------------------------------
    const isGzip = arrayBuffer.byteLength >= 2 &&
        new Uint8Array(arrayBuffer).subarray(0, 2)
            .every((v,i)=> v===GZIP_MAGIC[i]);
    let buffer = arrayBuffer;
    if (isGzip) {
        const decompressed = pako.inflate(new Uint8Array(arrayBuffer));
        buffer = decompressed.buffer;
    }
    const view   = new DataView(buffer);
    let offset   = 0;
    const magic = String.fromCharCode(...new Uint8Array(buffer.slice(offset, offset + 5)));
    if (magic !== 'IMGPK') throw new Error('Invalid image pack');
    offset += 5;
    const count = view.getUint32(offset, true); // little‑endian
    offset += 4;
    const entries = [];
    for (let i = 0; i < count; i++) {
        const imgOffset = Number(view.getBigUint64(offset, true)); offset += 8;
        const imgLength = Number(view.getBigUint64(offset, true)); offset += 8;
        entries.push({offset: imgOffset, length: imgLength});
    }
    return {arrayBuffer: buffer, entries};
}

async function loadBin() {
    const frames = await loadFrames();
    const parsedFrames = parseFrames(frames);
    document.getElementById('logo').style.animation = 'fadeOut 1s forwards'
    document.getElementById('spinner').style.display = 'none'
    imagesBinary = parsedFrames;   
    setTimeout(() => {
        const loader = document.getElementById('loading-screen');
        loader.style.display = 'none'; }, 1000);
}

function getImageBlob(pack, index) {
    const entry = pack.entries[index];
    if (!entry) throw new Error('Index out of range');
    // Slice the ArrayBuffer to get just this image's bytes
    const slice = pack.arrayBuffer.slice(entry.offset, entry.offset + entry.length);
    return new Blob([slice], {type: 'image/jpg'});
}

function getImageURL(pack, index) {
    return URL.createObjectURL(getImageBlob(pack, index));
}

async function showLine(index) {
    if (index < 0 || index >= lines.length) return;
    const line = lines[index];
    console.log(index);
    // Update image
    const image = getImageURL(imagesBinary, index);
    sceneImg.src = 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);
    }
}

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));


function start() {
    document.getElementById('start').style.display = 'none';
    document.removeEventListener('keydown', event);
    document.removeEventListener('click', start)
    document.getElementById('main').style.display = 'block';
    document.addEventListener('keydown', e => {
        if (e.code === 'Space') {
            if (!event.repeat) {
                e.preventDefault();
                next();
                console.log('press');
            }
        }
    }, { once: true } );
    document.addEventListener('click', e => {
        if (!event.repeat) {
            e.preventDefault();
            next();
            console.log('click');
        }
    });
}
    
// Prevent spacebar from scrolling the page
document.addEventListener('keydown', e => {
    if (e.code === 'Space') {
        e.preventDefault();
        start();
    }
});
    
// Advance on click anywhere in the document
document.addEventListener('click', start);