import { useState, useEffect } from "@wordpress/element";
import apiFetch from "@wordpress/api-fetch";

export default function ServerTimeClock() {
    const [time, setTime] = useState("—");
    const [tz, setTz] = useState("UTC");
    const [serverEpochAtSync, setServerEpochAtSync] = useState(null);
    const [clientMsAtSync, setClientMsAtSync] = useState(null);

    const syncServerTime = () => {
        apiFetch({ path: "/ekesto-cache-warmup/v1/server-time" })
            .then((response) => {
                setServerEpochAtSync(response.epoch);
                setClientMsAtSync(Date.now());
                setTz(response.tz || "UTC");
            })
            .catch(console.error);
    };

    useEffect(() => {
        syncServerTime();
        const resyncInterval = setInterval(syncServerTime, 5 * 60 * 1000); // Re-sync every 5 minutes
        return () => clearInterval(resyncInterval);
    }, []);

    useEffect(() => {
        if (!serverEpochAtSync || !clientMsAtSync) return;

        const fmt = new Intl.DateTimeFormat("sv-SE", {
            timeZone: tz,
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            hour12: false,
        });

        const tick = () => {
            const elapsedSec = Math.floor((Date.now() - clientMsAtSync) / 1000);
            const d = new Date((serverEpochAtSync + elapsedSec) * 1000);
            setTime(fmt.format(d) + " (" + tz + ")");
        };

        tick();
        const tickInterval = setInterval(tick, 1000);
        return () => clearInterval(tickInterval);
    }, [serverEpochAtSync, clientMsAtSync, tz]);

    return <span className="ecw-clock-counter">{time}</span>;
}
