# SPDX-FileCopyrightText: 2025 HongKongukah.com
# SPDX-License-Identifier: MIT

"""PyScript module for performing the countdown on the main screen."""

from datetime import datetime, timedelta, timezone
import time

from pyscript import document, window, fetch  # type: ignore
from pyscript.ffi import create_proxy  # type: ignore

EVENT_DELTA = -8

response = await fetch("/api/latest_event")  # type: ignore
EVENT_DATA = await response.json()  # type: ignore

def update_countdown():
    """Update the countdown text dynamically."""
    tz = timezone(timedelta(hours=-4))
    current = datetime.now(tz)
    target_str = EVENT_DATA["event_start"]
    year, month, day = target_str.split("-")
    target = datetime(
        year=int(year),
        month=int(month),
        day=int(day),
        tzinfo=tz,
    )
    delta = target - current
    if delta.days < EVENT_DELTA:
        announcement = "See you next year!\n\U0001f62d"
    elif delta < timedelta():
        day_number = -int(delta.days)
        announcement = f"Day {day_number}!\n\U0001f389\U0001f3a4\U0001f37b"
    else:
        days = delta.days
        hours = delta.seconds // 3600
        minutes = (delta.seconds // 60) % 60
        seconds = delta.seconds % 60
        announcement = f"Starting in {days} days, {hours} hours, {minutes} minutes, {seconds} seconds\n\U0001f440"
    countdown = document.querySelector("#countdown-header")
    countdown.innerText = str(announcement)
    window.setTimeout(create_proxy(update_countdown), 100)  # type: ignore


update_countdown()
