"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModView = void 0;
exports.DeleteButton = DeleteButton;
exports.ReportButton = ReportButton;
const jsx_runtime_1 = require("react/jsx-runtime");
const dropdown_menu_1 = require("@rn-primitives/dropdown-menu");
const react_1 = require("react");
const atoms_1 = require("../../lib/theme/atoms");
const player_store_1 = require("../../player-store");
const block_1 = require("../../streamplace-store/block");
const moderation_1 = require("../../streamplace-store/moderation");
const xrpc_1 = require("../../streamplace-store/xrpc");
const react_native_1 = require("react-native");
const livestream_store_1 = require("../../livestream-store");
const streamplace_store_1 = require("../../streamplace-store");
const format_handle_1 = require("../../utils/format-handle");
const ui_1 = require("../ui");
const BSKY_FRONTEND_DOMAIN = "bsky.app";
exports.ModView = (0, react_1.forwardRef)(() => {
    const triggerRef = (0, react_1.useRef)(null);
    const message = (0, player_store_1.usePlayerStore)((state) => state.modMessage);
    const toast = (0, ui_1.useToast)();
    let agent = (0, xrpc_1.usePDSAgent)();
    let [messageRemoved, setMessageRemoved] = (0, react_1.useState)(false);
    let { createBlock, isLoading: isBlockLoading } = (0, block_1.useCreateBlockRecord)();
    let { createHideChat, isLoading: isHideLoading } = (0, block_1.useCreateHideChatRecord)();
    const pinChatMessage = (0, livestream_store_1.usePinChatMessage)();
    const setReportModalOpen = (0, player_store_1.usePlayerStore)((x) => x.setReportModalOpen);
    const setReportSubject = (0, player_store_1.usePlayerStore)((x) => x.setReportSubject);
    const setModMessage = (0, player_store_1.usePlayerStore)((x) => x.setModMessage);
    const deleteChatMessage = (0, livestream_store_1.useDeleteChatMessage)();
    // Get the streamer's DID from the livestream profile
    const streamerDID = (0, livestream_store_1.useLivestreamStore)((x) => x.profile?.did);
    // Check moderation permissions for the current user on this streamer's channel
    const modPermissions = (0, moderation_1.useCanModerate)(streamerDID);
    // get the channel did
    const channelId = (0, player_store_1.usePlayerStore)((state) => state.src);
    // get the logged in user's identity
    const handle = (0, streamplace_store_1.useStreamplaceStore)((state) => state.handle);
    const cleanup = () => {
        setModMessage(null);
    };
    // Effect must be called unconditionally (before any early returns)
    (0, react_1.useEffect)(() => {
        if (message) {
            setMessageRemoved(false);
            triggerRef.current?.open();
        }
        else {
            triggerRef.current?.close();
        }
    }, [message]);
    // Check if any moderation actions are actually available for this message
    // This must match the individual action checks inside the DropdownMenuGroup
    const hasAvailableActions = !!(message &&
        agent?.did &&
        ((modPermissions.canHide && message.author.did !== streamerDID) ||
            (modPermissions.canPin && message.author.did !== streamerDID) ||
            modPermissions.canBan));
    return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsxs)(ui_1.DropdownMenu, { style: [ui_1.layout.flex.row, ui_1.layout.flex.alignCenter, atoms_1.gap.all[2], atoms_1.w[80]], onOpenChange: (isOpen) => {
                if (!isOpen) {
                    cleanup();
                }
            }, children: [(0, jsx_runtime_1.jsx)(ui_1.DropdownMenuTrigger, { ref: triggerRef, children: (0, jsx_runtime_1.jsx)(ui_1.View, {}) }), (0, jsx_runtime_1.jsx)(ui_1.ResponsiveDropdownMenuContent, { children: message && ((0, jsx_runtime_1.jsx)(ModViewContent, { message: message, modPermissions: modPermissions, agent: agent, streamerDID: streamerDID, hasAvailableActions: hasAvailableActions, isHideLoading: isHideLoading, isBlockLoading: isBlockLoading, messageRemoved: messageRemoved, setMessageRemoved: setMessageRemoved, createHideChat: createHideChat, createBlock: createBlock, pinChatMessage: pinChatMessage, toast: toast, setReportModalOpen: setReportModalOpen, setReportSubject: setReportSubject, deleteChatMessage: deleteChatMessage })) })] }) }));
});
function ModViewContent({ message, modPermissions, agent, streamerDID, hasAvailableActions, isHideLoading, isBlockLoading, messageRemoved, setMessageRemoved, createHideChat, createBlock, pinChatMessage, toast, setReportModalOpen, setReportSubject, deleteChatMessage, }) {
    const { onOpenChange } = (0, dropdown_menu_1.useRootContext)();
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(ui_1.DropdownMenuGroup, { children: (0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { children: (0, jsx_runtime_1.jsx)(ui_1.View, { style: [ui_1.layout.flex.column, atoms_1.mr[5], { gap: 6, maxWidth: "100%" }], children: (0, jsx_runtime_1.jsxs)(ui_1.Text, { style: {
                                fontVariant: ["tabular-nums"],
                                color: ui_1.atoms.colors.gray[300],
                            }, children: [new Date(message.record.createdAt).toLocaleTimeString([], {
                                    hour: "2-digit",
                                    minute: "2-digit",
                                    hour12: false,
                                }), " ", (0, format_handle_1.formatHandleWithAt)(message.author), ": ", message.record.text] }) }) }) }, "message-display"), hasAvailableActions && ((0, jsx_runtime_1.jsxs)(ui_1.DropdownMenuGroup, { title: `Moderation actions`, children: [modPermissions.canHide && message.author.did !== streamerDID && ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { disabled: isHideLoading || messageRemoved, onPress: () => {
                            if (isHideLoading || messageRemoved)
                                return;
                            createHideChat(message.uri, streamerDID ?? undefined)
                                .then((r) => setMessageRemoved(true))
                                .catch((e) => console.error(e));
                        }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: isHideLoading || messageRemoved ? "muted" : "warning", children: isHideLoading
                                ? "Hiding..."
                                : messageRemoved
                                    ? "Message hidden"
                                    : "Hide this message" }) })), modPermissions.canPin && ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuGroup, { children: (0, jsx_runtime_1.jsxs)(ui_1.DropdownMenuSub, { children: [(0, jsx_runtime_1.jsx)(ui_1.DropdownMenuSubTrigger, { subMenuTitle: "Pin message", style: { padding: 0, margin: 0 }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "primary", children: "Pin this message" }) }), (0, jsx_runtime_1.jsx)(ui_1.DropdownMenuSubContent, { children: (0, jsx_runtime_1.jsxs)(ui_1.DropdownMenuGroup, { title: "Pin duration", children: [(0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { onPress: () => {
                                                    if (!streamerDID)
                                                        return;
                                                    pinChatMessage(message.uri, streamerDID)
                                                        .then(() => {
                                                        toast.show("Comment pinned", "", { duration: 3 });
                                                        onOpenChange?.(false);
                                                    })
                                                        .catch((e) => {
                                                        toast.show("Error pinning comment", e instanceof Error ? e.message : "Failed to pin", { duration: 5 });
                                                    });
                                                }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "primary", children: "Until stream end" }) }), [5, 10, 15, 30, 60].map((minutes) => ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { onPress: () => {
                                                    if (!streamerDID)
                                                        return;
                                                    const expiresAt = new Date(Date.now() + minutes * 60 * 1000);
                                                    pinChatMessage(message.uri, streamerDID, expiresAt.toISOString())
                                                        .then(() => {
                                                        toast.show("Comment pinned", "", { duration: 3 });
                                                        onOpenChange?.(false);
                                                    })
                                                        .catch((e) => {
                                                        toast.show("Error pinning comment", e instanceof Error
                                                            ? e.message
                                                            : "Failed to pin", { duration: 5 });
                                                    });
                                                }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "primary", children: minutes < 60 ? `${minutes} min` : "1 hour" }) }, minutes)))] }) })] }) }, "pin-actions")), modPermissions.canBan &&
                        agent?.did &&
                        message.author.did !== agent.did &&
                        message.author.did !== streamerDID && ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { disabled: isBlockLoading, onPress: () => {
                            if (isBlockLoading)
                                return;
                            createBlock(message.author.did, streamerDID ?? undefined)
                                .then((r) => {
                                toast.show("User blocked", `${(0, format_handle_1.formatHandleWithAt)(message.author)} has been blocked from this channel.`, { duration: 3 });
                                onOpenChange?.(false);
                            })
                                .catch((e) => {
                                console.error(e);
                                toast.show("Error blocking user", e instanceof Error ? e.message : "Failed to block user", { duration: 5 });
                            });
                        }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "destructive", children: isBlockLoading
                                ? "Blocking..."
                                : `Block user ${(0, format_handle_1.formatHandleWithAt)(message.author)} from this channel` }) }))] }, "moderation-actions")), (0, jsx_runtime_1.jsxs)(ui_1.DropdownMenuGroup, { title: `User actions`, children: [(0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { onPress: () => {
                            react_native_1.Linking.openURL(`https://${BSKY_FRONTEND_DOMAIN}/profile/${(0, format_handle_1.formatHandle)(message.author)}`);
                        }, children: (0, jsx_runtime_1.jsxs)(ui_1.Text, { color: "primary", children: ["View user on ", BSKY_FRONTEND_DOMAIN] }) }), agent?.did && message.author.did === agent.did && ((0, jsx_runtime_1.jsx)(DeleteButton, { message: message, deleteChatMessage: deleteChatMessage, onOpenChange: onOpenChange })), (!agent?.did || message.author.did !== agent.did) && ((0, jsx_runtime_1.jsx)(ReportButton, { message: message, setReportModalOpen: setReportModalOpen, setReportSubject: setReportSubject, onOpenChange: onOpenChange }))] }, "user-actions")] }));
}
var DeleteState;
(function (DeleteState) {
    DeleteState[DeleteState["None"] = 0] = "None";
    DeleteState[DeleteState["Confirmed"] = 1] = "Confirmed";
    DeleteState[DeleteState["Deleting"] = 2] = "Deleting";
})(DeleteState || (DeleteState = {}));
function DeleteButton({ message, deleteChatMessage, onOpenChange, }) {
    const [confirming, setConfirming] = (0, react_1.useState)(DeleteState.None);
    const toast = (0, ui_1.useToast)();
    return ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { closeOnPress: false, onPress: () => {
            if (!message)
                return;
            if (!confirming) {
                setConfirming(DeleteState.Confirmed);
                return;
            }
            if (confirming === DeleteState.Confirmed) {
                setConfirming(DeleteState.Deleting);
            }
            deleteChatMessage(message.uri)
                .then(() => {
                // wait ~a second before resetting state to allow deletion to take effect
                setTimeout(() => setConfirming(DeleteState.None), 1000);
                onOpenChange?.(false);
            })
                .catch((e) => {
                toast.show("Couldn't delete the message", e);
                setConfirming(DeleteState.None);
            });
        }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "destructive", children: confirming === DeleteState.Confirmed
                ? "Are you sure? Click again to confirm."
                : confirming === DeleteState.Deleting
                    ? "Deleting..."
                    : "Delete message" }) }));
}
function ReportButton({ message, setReportModalOpen, setReportSubject, onOpenChange, }) {
    return ((0, jsx_runtime_1.jsx)(ui_1.DropdownMenuItem, { onPress: () => {
            if (!message)
                return;
            onOpenChange?.(false);
            setReportModalOpen(true);
            setReportSubject({
                $type: "com.atproto.repo.strongRef",
                uri: message.uri,
                cid: message.cid,
                context: message,
            });
        }, children: (0, jsx_runtime_1.jsx)(ui_1.Text, { color: "warning", children: "Report chat..." }) }));
}
//# sourceMappingURL=mod-view.js.map