// ============================================================
// MediaCardContextMenu — 画布媒体卡片右键菜单
//
// 菜单项定义见 menus/media-card-menu.ts
// 组件职责：读取 Store 状态 + 绑定 IPC 操作 → 生成菜单项
// ============================================================

import { message } from 'antd';
import { useCallback } from 'react';
import { useCanvasStore } from '../../stores/useCanvasStore';
import { useSidecarSync } from '../../hooks/useSidecarSync';
import { getMediaCardMenuItems } from '../../controllers/menus';
import { ContextMenu } from '@/shared/components/ContextMenu';
import { safeIpcInvoke } from '@/shared/utils/bus';
import { BIDIRECTIONAL } from '@shared/constants/ipc-channels';
import { ITEM_W, ITEM_H } from '../../utils/constants';
import type { AuditStatus } from '../../stores/useCanvasStore';

interface MediaCardContextMenuProps {
    itemId: number;
    children: React.ReactNode;
    /** 画布中的绝对定位 */
    x: number;
    y: number;
}

export function MediaCardContextMenu({ itemId, children, x, y }: MediaCardContextMenuProps) {
    const item = useCanvasStore((s) => s.items.find((i) => i.id === itemId));
    const { commitMetadata } = useSidecarSync();

    // ── 回调：复制文件路径 ──
    const handleCopyPath = useCallback(async () => {
        if (!item) return;
        try {
            await navigator.clipboard.writeText(item.path);
            void message.success('已复制文件路径');
        } catch {
            void message.error('复制失败');
        }
    }, [item]);

    // ── 回调：在文件夹中打开 ──
    const handleOpenFolder = useCallback(async () => {
        if (!item) return;
        await safeIpcInvoke(BIDIRECTIONAL.SHOW_ITEM_IN_FOLDER, {
            filePath: item.path,
        });
    }, [item]);

    // ── 回调：设置审核状态 ──
    const handleSetAudit = useCallback(
        (status: AuditStatus) => {
            if (!item) return;
            commitMetadata(itemId, item.path, { audit_status: status });
            void message.success(`审核状态已更新为：${status}`);
        },
        [item, itemId, commitMetadata],
    );

    if (!item) return <>{children}</>;

    const isAuditable = ['Storyboard', 'Keyframe', 'Video', 'Audio', 'LipSync'].includes(item.stage);

    // ── 通过菜单定义函数生成 ContextMenuItems ──
    const menuItems = getMediaCardMenuItems({
        isAuditable,
        onSetAudit: handleSetAudit,
        onCopyPath: handleCopyPath,
        onOpenFolder: handleOpenFolder,
    });

    return (
        <div
            style={{
                position: 'absolute',
                left: x,
                top: y,
                width: ITEM_W,
                height: ITEM_H,
            }}
        >
            <ContextMenu items={menuItems}>
                {children}
            </ContextMenu>
        </div>
    );
}
