from browser import window, document, console

# Configuration: pixel thresholds for checkpoints.
# We use the index to track which "view" we are on.
checkpoints = [0, 1000, 2000, 3000]

# Create a spacer so the page stays scrollable while content is fixed.
spacer = document.createElement('div')
spacer.style.height = f"{max(checkpoints) + 2000}px"
document.body.appendChild(spacer)

is_programmatic_scroll = False
scroll_timeout = None


def report_scroll(event):
    global is_programmatic_scroll, scroll_timeout

    if is_programmatic_scroll:
        is_programmatic_scroll = False
        return

    current_scroll = window.scrollY
    print(current_scroll)
    
    # Find the nearest checkpoint
    nearest_checkpoint = min(checkpoints, key=lambda cp: abs(cp - current_scroll))
    
    # Only snap if we're more than 100px away from the nearest checkpoint
    distance = abs(nearest_checkpoint - current_scroll)
    if distance > 100:
        return
    
    # Snap to the nearest checkpoint
    if current_scroll != nearest_checkpoint:
        is_programmatic_scroll = True
        window.scrollTo(0, nearest_checkpoint)

    console.log(f"Currently viewing content for checkpoint: {nearest_checkpoint}")


window.bind("scroll", report_scroll)