// ============================================================
// LODImage — 多级清晰度图片组件
//
// 优先级：
//   1. 已缓存的 Blob URL（Store 中 item.blobUrl）
//   2. dataSource.generateThumbnail() → base64 data URL
//   3. 棋盘格背景占位（加载前）
//
// 图片加载完成后通过 CanvasStore.loadThumbnail 缓存 URL。
// ============================================================

import { useState, useEffect, useRef } from 'react';
import { logger } from '@/shared/utils/bus';
import { useCanvasStore } from '../../stores/useCanvasStore';
import { LOD_LEVELS } from '../../utils/constants';
import type { LODLevel } from '../../utils/constants';

interface LODImageProps {
    itemId: number;
    filePath: string;
    /** 当前需要的 LOD 级别（基于 zoom 计算） */
    targetLevel: number; // 0-3 index into LOD_LEVELS
}

/**
 * 根据 zoom 倍率确定 LOD 级别索引。
 * zoom < 0.5 → 512px, < 1.0 → 1024px, < 2.0 → 2048px, >= 2.0 → 4096px
 */
export function zoomToLODIndex(zoom: number): number {
    if (zoom < 0.5) return 0;
    if (zoom < 1.0) return 1;
    if (zoom < 2.0) return 2;
    return 3;
}

export function LODImage({ itemId, filePath, targetLevel }: LODImageProps) {
    const blobUrl = useCanvasStore((s) => {
        const item = s.items.find((i) => i.id === itemId);
        return item?.blobUrl;
    });
    const loadedLevel = useCanvasStore((s) => {
        const item = s.items.find((i) => i.id === itemId);
        return item?.loadedLevel;
    });
    const loadThumbnail = useCanvasStore((s) => s.loadThumbnail);
    const getDataSource = useCanvasStore((s) => s.getDataSource);

    const [src, setSrc] = useState<string | null>(blobUrl || null);
    const [loading, setLoading] = useState(!blobUrl);
    const [error, setError] = useState(false);
    const loadingRef = useRef(false);

    // 当 Store 中的 blobUrl 更新时同步
    useEffect(() => {
        if (blobUrl) {
            setSrc(blobUrl);
            setLoading(false);
        }
    }, [blobUrl]);

    // 按需加载更高清晰度的缩略图
    useEffect(() => {
        // 已有足够清晰的版本
        if (loadedLevel !== undefined && loadedLevel >= targetLevel) return;
        // 正在加载中
        if (loadingRef.current) return;

        const requiredSize = LOD_LEVELS[Math.min(targetLevel, LOD_LEVELS.length - 1)] as LODLevel;

        loadingRef.current = true;

        const dataSource = getDataSource();
        dataSource
            .generateThumbnail({ filePath, size: requiredSize })
            .then((thumb) => {
                const url = `data:${thumb.mimeType};base64,${thumb.data}`;
                setSrc(url);
                setLoading(false);
                setError(false);
                loadThumbnail(itemId, url, targetLevel);
                loadingRef.current = false;
            })
            .catch((err) => {
                logger.warn('canvas', 'LOD 图片加载失败', err instanceof Error ? err : undefined);
                setLoading(false);
                setError(true);
                loadingRef.current = false;
            });
    }, [itemId, filePath, targetLevel, loadedLevel, loadThumbnail, getDataSource]);

    if (error) {
        return (
            <div
                style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 24,
                    background: '#f5f5f5',
                }}
            >
                🖼️
            </div>
        );
    }

    return (
        <div
            style={{
                width: '100%',
                height: '100%',
                position: 'relative',
                overflow: 'hidden',
                // 棋盘格背景
                backgroundImage: `
                    linear-gradient(45deg, #e0e0e0 25%, transparent 25%),
                    linear-gradient(-45deg, #e0e0e0 25%, transparent 25%),
                    linear-gradient(45deg, transparent 75%, #e0e0e0 75%),
                    linear-gradient(-45deg, transparent 75%, #e0e0e0 75%)
                `,
                backgroundSize: '16px 16px',
                backgroundPosition: '0 0, 0 8px, 8px -8px, -8px 0px',
            }}
        >
            {src && (
                <img
                    src={src}
                    alt=""
                    style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'contain',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        opacity: loading ? 0.3 : 1,
                        transition: 'opacity 0.2s',
                    }}
                    onLoad={() => setLoading(false)}
                />
            )}
        </div>
    );
}
