"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LivestreamProvider = LivestreamProvider;
exports.WebsocketWatcher = WebsocketWatcher;
exports.TeleportWatcher = TeleportWatcher;
exports.PinnedCommentWatcher = PinnedCommentWatcher;
exports.LivestreamPoller = LivestreamPoller;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const hooks_1 = require("../hooks");
const teleport_1 = require("../lib/slash-commands/teleport");
const stream_notifications_1 = require("../lib/stream-notifications");
const livestream_store_1 = require("../livestream-store");
const streamplace_store_1 = require("../streamplace-store");
const websocket_1 = require("./websocket");
function LivestreamProvider({ children, src, onTeleport, ignoreOuterContext = false, }) {
    const context = (0, react_1.useContext)(livestream_store_1.LivestreamContext);
    const store = (0, react_1.useRef)((0, livestream_store_1.makeLivestreamStore)()).current;
    if (context) {
        // this is ok, there's use cases for having one in another
        // like having a player component that's independently usable
        // but can also be embedded within an entire livestream page
        if (!ignoreOuterContext) {
            return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
        }
    }
    window.livestreamStore = store;
    return ((0, jsx_runtime_1.jsx)(livestream_store_1.LivestreamContext.Provider, { value: { store: store }, children: (0, jsx_runtime_1.jsx)(LivestreamPoller, { src: src, onTeleport: onTeleport, children: children }) }));
}
function WebsocketWatcher({ src }) {
    (0, websocket_1.useLivestreamWebsocket)(src);
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {});
}
function TeleportWatcher({ onTeleport, }) {
    const activeTeleport = (0, livestream_store_1.useLivestreamStore)((state) => state.activeTeleport);
    const activeTeleportUri = (0, livestream_store_1.useLivestreamStore)((state) => state.activeTeleportUri);
    const profile = (0, hooks_1.useAvatars)(activeTeleport ? [activeTeleport.streamer] : []);
    const livestreamProfile = (0, livestream_store_1.useLivestreamStore)((state) => state.profile);
    const pdsAgent = (0, streamplace_store_1.usePDSAgent)();
    const userDID = (0, streamplace_store_1.useDID)();
    const prevActiveTeleportRef = (0, react_1.useRef)(activeTeleport);
    (0, react_1.useEffect)(() => {
        if (!activeTeleport || !profile[activeTeleport.streamer])
            return;
        const startsAt = new Date(activeTeleport.startsAt);
        const now = new Date();
        const countdown = Math.max(0, Math.floor((startsAt.getTime() - now.getTime()) / 1000));
        // resolve the DID to a handle for display
        const targetHandle = profile[activeTeleport.streamer]?.handle || activeTeleport.streamer;
        // check if the current user is the streamer of the current livestream
        const canCancel = livestreamProfile?.did === userDID;
        stream_notifications_1.StreamNotifications.teleport({
            targetHandle: targetHandle,
            targetDID: activeTeleport.streamer,
            countdown: countdown,
            canCancel: canCancel,
            onDismiss: async (reason) => {
                console.log("🔍 StreamNotifications.onDismiss called with reason:", reason);
                if (reason === "user" && activeTeleportUri && pdsAgent && userDID) {
                    try {
                        await (0, teleport_1.deleteTeleport)(pdsAgent, userDID, activeTeleportUri);
                    }
                    catch (err) {
                        console.error("Failed to delete teleport:", err);
                    }
                }
                if (reason === "auto" && onTeleport) {
                    console.log("🔍 Calling onTeleport with:", targetHandle, activeTeleport.streamer);
                    onTeleport(targetHandle, activeTeleport.streamer);
                }
                else if (reason === "auto" && !onTeleport) {
                    console.log("🔍 onTeleport is not defined!");
                }
                else if (reason === "auto") {
                    console.log("🔍 Reason is auto but teleport function not called for unknown reason");
                }
            },
        });
    }, [
        activeTeleport,
        activeTeleportUri,
        profile,
        onTeleport,
        pdsAgent,
        userDID,
    ]);
    (0, react_1.useEffect)(() => {
        if (prevActiveTeleportRef.current &&
            !activeTeleport &&
            !activeTeleportUri) {
            stream_notifications_1.StreamNotifications.teleportCancelled();
        }
        prevActiveTeleportRef.current = activeTeleport;
    }, [activeTeleport, activeTeleportUri]);
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {});
}
function PinnedCommentWatcher() {
    const pinnedComment = (0, livestream_store_1.usePinnedComment)();
    const streamerDID = (0, livestream_store_1.useLivestreamStore)((state) => state.profile?.did);
    const unpinChatMessage = (0, livestream_store_1.useUnpinChatMessage)();
    const store = (0, livestream_store_1.getStoreFromContext)();
    const prevPinnedRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        return () => {
            stream_notifications_1.StreamNotifications.pinnedCommentDismiss();
        };
    }, []);
    // Show/hide notification when pinned comment changes
    (0, react_1.useEffect)(() => {
        const currentUri = pinnedComment?.uri ?? null;
        if (currentUri === prevPinnedRef.current)
            return;
        prevPinnedRef.current = currentUri;
        if (pinnedComment) {
            stream_notifications_1.StreamNotifications.pinnedComment({
                pinnedComment,
                onDismiss: () => {
                    store.setState({ pinnedComment: null });
                },
                onUnpin: () => {
                    if (!streamerDID)
                        return;
                    unpinChatMessage(pinnedComment.uri, streamerDID).catch((e) => {
                        console.error("Failed to unpin:", e);
                    });
                },
            });
        }
        else {
            stream_notifications_1.StreamNotifications.pinnedCommentDismiss();
        }
    }, [pinnedComment, streamerDID, unpinChatMessage]);
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {});
}
function LivestreamPoller({ children, src, onTeleport, }) {
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(WebsocketWatcher, { src: src }), (0, jsx_runtime_1.jsx)(TeleportWatcher, { onTeleport: onTeleport }), (0, jsx_runtime_1.jsx)(PinnedCommentWatcher, {}), children] }));
}
//# sourceMappingURL=index.js.map