"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTimeSync = useTimeSync;
const lucide_react_native_1 = require("lucide-react-native");
const react_1 = require("react");
const react_native_1 = require("react-native");
const streamplace_1 = require("streamplace");
const toast_1 = require("../components/ui/toast");
const streamplace_store_1 = require("../streamplace-store/streamplace-store");
const time_sync_1 = require("./time-sync");
function useTimeSync() {
    const url = (0, streamplace_store_1.useUrl)();
    const t = (0, toast_1.useToast)();
    const hasShownWarning = (0, react_1.useRef)(false);
    (0, react_1.useEffect)(() => {
        const checkTime = async () => {
            if (react_native_1.Platform.OS !== "web") {
                return;
            }
            try {
                const agent = new streamplace_1.StreamplaceAgent(url);
                const start = new Date().getTime();
                const response = await agent.place.stream.server.getServerTime();
                const roundTripLatency = new Date().getTime() - start;
                const serverTime = response.data.serverTime;
                // always sync with server time
                (0, time_sync_1.syncTimeWithServer)(serverTime, roundTripLatency / 2);
                const driftInfo = (0, time_sync_1.checkClockDrift)(serverTime);
                // only show warning if drift is significant
                if (driftInfo.hasDrift && !hasShownWarning.current) {
                    hasShownWarning.current = true;
                    t.show("Clock drift detected!", `Your device clock is ${driftInfo.driftSeconds}s off from server time. Please sync your system clock to avoid issues.`, {
                        variant: "info",
                        iconLeft: lucide_react_native_1.TriangleAlert,
                        duration: 25,
                    });
                    console.log(`time sync applied: offset ${driftInfo.driftMs}ms. Date() calls will now use server time.`);
                }
            }
            catch (error) {
                console.error("failed to sync time with server:", error);
            }
        };
        checkTime();
        const interval = setInterval(checkTime, 1800000); // every 30m
        return () => clearInterval(interval);
    }, [url, t]);
}
//# sourceMappingURL=useTimeSync.js.map