// ============================================================
// MediaCard — 缩略图卡片（画布核心渲染单元）
//
// 功能：
//   - LOD 多级缩略图加载（LODImage 组件）
//   - 棋盘格背景（图片加载前由 LODImage 内部提供）
//   - 审核角标（pending/approved/rework/deprecated）
//   - 文件名标签
//   - 选中高亮（SELECT 模式）
//   - 视频/音频的首帧/图标
// ============================================================

import { useCallback, memo } from 'react';
import { LODImage, zoomToLODIndex } from './LODImage';
import { useCanvasStore, type InteractionMode } from '../../stores/useCanvasStore';
import { AUDIT_STATUS_COLORS, ITEM_W, ITEM_H } from '../../utils/constants';

export interface MediaCardProps {
    itemId: number;
    /** 在画布中的绝对像素坐标 */
    x: number;
    y: number;
    /** 当前视图缩放倍率 */
    zoom: number;
    /** 当前交互模式 */
    mode: InteractionMode;
    /** 双击回调 → 打开全屏预览 */
    onDoubleClick?: (itemId: number) => void;
}

/**
 * MediaCard 使用 React.memo 优化：仅在以下属性变化时重渲染：
 *   - itemId / x / y（位置变化）
 *   - zoom（影响 LOD 级别）
 *   - mode（影响选中行为和 UI）
 *   - blobUrl / auditStatus（从 Store 选择器获取）
 */
export const MediaCard = memo(function MediaCard({ itemId, x, y, zoom, mode, onDoubleClick }: MediaCardProps) {
    const item = useCanvasStore((s) => s.items.find((i) => i.id === itemId));
    const selectedIds = useCanvasStore((s) => s.selectedIds);
    const toggleSelection = useCanvasStore((s) => s.toggleSelection);

    const isVideo = ['mp4', 'webm', 'mov', 'avi', 'mkv'].includes(item?.ext || '');
    const isAudio = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'].includes(item?.ext || '');
    const isSelected = selectedIds.has(itemId);

    const handleClick = useCallback(() => {
        if (mode === 'SELECT') {
            toggleSelection(itemId);
        }
    }, [mode, itemId, toggleSelection]);

    const handleDoubleClick = useCallback(() => {
        onDoubleClick?.(itemId);
    }, [itemId, onDoubleClick]);

    // 启动原生文件拖拽（拖放缩略图到 Photoshop/Explorer 等外部应用）
    const handleDragStart = useCallback((e: React.DragEvent) => {
        if (mode !== 'BROWSE' || !item) return;
        if (typeof window.canvas?.startDrag === 'function') {
            e.preventDefault();
            e.stopPropagation();
            window.canvas.startDrag({
                filePath: item.path,
                fileName: item.fileName,
            }).catch(() => {
                // 静默忽略拖拽失败（文件可能已被移动或删除）
            });
        }
    }, [mode, item]);

    if (!item) return null;

    const lodIndex = zoomToLODIndex(zoom);
    const auditStatus = item.metadata?.audit_status;
    const auditColor = auditStatus ? AUDIT_STATUS_COLORS[auditStatus] : undefined;

    return (
        <div
            style={{
                position: 'absolute',
                left: x,
                top: y,
                width: ITEM_W,
                height: ITEM_H,
                borderRadius: 4,
                overflow: 'hidden',
                cursor: mode === 'SELECT' ? 'pointer' : 'default',
                border: isSelected
                    ? '2px solid #6366F1'
                    : '1px solid rgba(0,0,0,0.08)',
                boxShadow: isSelected
                    ? '0 0 8px rgba(99, 102, 241, 0.4)'
                    : '0 1px 3px rgba(0,0,0,0.08)',
                transition: 'border 0.1s, box-shadow 0.1s',
                background: '#fff',
            }}
            draggable={mode === 'BROWSE'}
            onDragStart={handleDragStart}
            onClick={handleClick}
            onDoubleClick={handleDoubleClick}
        >
            {/* 缩略图区域 */}
            <div style={{ width: ITEM_W, height: ITEM_H - 22, position: 'relative' }}>
                {isVideo || isAudio ? (
                    /* 视频/音频：显示图标 */
                    <div
                        style={{
                            width: '100%',
                            height: '100%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            fontSize: 32,
                            background: '#f0f0f0',
                        }}
                    >
                        {isVideo ? '🎥' : '🎵'}
                    </div>
                ) : (
                    <LODImage itemId={itemId} filePath={item.path} targetLevel={lodIndex} />
                )}

                {/* 审核角标 */}
                {auditStatus && auditColor && (
                    <div
                        style={{
                            position: 'absolute',
                            top: 4,
                            right: 4,
                            width: 10,
                            height: 10,
                            borderRadius: '50%',
                            background: auditColor,
                            border: '1px solid rgba(255,255,255,0.8)',
                            boxShadow: '0 1px 2px rgba(0,0,0,0.2)',
                        }}
                        title={auditStatus}
                    />
                )}

                {/* 选中勾选（SELECT 模式） */}
                {mode === 'SELECT' && (
                    <div
                        style={{
                            position: 'absolute',
                            top: 4,
                            left: 4,
                            width: 18,
                            height: 18,
                            borderRadius: 3,
                            background: isSelected ? '#6366F1' : 'rgba(255,255,255,0.8)',
                            border: `2px solid ${isSelected ? '#6366F1' : '#d1d5db'}`,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            fontSize: 10,
                            color: '#fff',
                        }}
                    >
                        {isSelected ? '✓' : ''}
                    </div>
                )}
            </div>

            {/* 文件名标签 */}
            <div
                style={{
                    height: 22,
                    padding: '0 4px',
                    display: 'flex',
                    alignItems: 'center',
                    fontSize: 10,
                    color: '#6B7280',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    background: '#FAFAFA',
                    borderTop: '1px solid #F0F0F0',
                }}
                title={item.fileName}
            >
                {item.fileName}
            </div>
        </div>
    );
});
