import { getThemeTileDisplayEntry, getThemeTileSize, getThemeTileFitMul } from './TileDisplayMeta';
import { SpriteFrame } from 'cc';

/** 与 Unity / Cocos sprite-frame 原始尺寸一致（无主题数据时的回退） */
export interface TileSize {
    width: number;
    height: number;
}

const DEFAULT_SIZES: Record<string, TileSize> = {
    Baseblock: { width: 101, height: 80 },
    JumpBlock: { width: 101, height: 99 },
    WallBlock: { width: 101, height: 115 },
    kuai11: { width: 101, height: 74 },
};

/** 等距菱形格宽度（与 grid-math CELL_PIXEL 一致） */
const CELL_W = 100;

export function getTileSize(tileName: string, theme?: string): TileSize {
    const fallback = DEFAULT_SIZES[tileName] ?? { width: 101, height: 80 };
    return getThemeTileSize(theme, tileName, fallback);
}

/** 优先主题 meta（裁剪后尺寸），避免 sprite originalSize 含透明边导致缩放偏小 */
export function resolveTilePixelSize(
    tileName: string,
    sf?: SpriteFrame | null,
    theme?: string,
): TileSize {
    if (theme && getThemeTileDisplayEntry(theme, tileName)) {
        return getTileSize(tileName, theme);
    }
    if (sf) {
        const rect = sf.rect;
        if (rect.width > 0 && rect.height > 0) {
            return { width: rect.width, height: rect.height };
        }
        const os = sf.originalSize;
        if (os.width > 0 && os.height > 0) {
            return { width: os.width, height: os.height };
        }
    }
    return getTileSize(tileName, theme);
}

/** 等比缩放：宽度贴满格子（100px），可叠加主题 fitMul */
export function getTileFitScale(tileName: string, width?: number, _height?: number, theme?: string): number {
    const size = theme && getThemeTileDisplayEntry(theme, tileName)
        ? getTileSize(tileName, theme)
        : { width: width ?? getTileSize(tileName, theme).width, height: _height ?? getTileSize(tileName, theme).height };
    return (CELL_W / size.width) * getThemeTileFitMul(theme, tileName);
}

export function getTileDrawSize(tileName: string, width?: number, height?: number, theme?: string): TileSize {
    const source = theme && getThemeTileDisplayEntry(theme, tileName)
        ? getTileSize(tileName, theme)
        : {
            width: width ?? getTileSize(tileName, theme).width,
            height: height ?? getTileSize(tileName, theme).height,
        };
    const s = (CELL_W / source.width) * getThemeTileFitMul(theme, tileName);
    return { width: source.width * s, height: source.height * s };
}
