import type { DevicePresetDto } from '@/types/layout';

export type BezelGeometry = {
    chassisRadius: number;
    inset: number;
    island?: { width: number; height: number; y: number };
};

export function bezelGeometry(
    width: number,
    height: number,
    preset: DevicePresetDto | undefined,
): BezelGeometry {
    const min = Math.min(width, height);
    const isTablet = preset?.category === 'tablet';
    const isAndroid = !!preset && preset.key.startsWith('android-');
    // Android phones carry thinner, more uniformly-rounded bezels than iPhones;
    // Android tablets skew slightly squarer than iPads.
    let chassisRadius: number;
    let inset: number;
    if (isAndroid) {
        chassisRadius = isTablet ? min * 0.04 : min * 0.08;
        inset = isTablet ? min * 0.01 : min * 0.014;
    } else {
        chassisRadius = min * (isTablet ? 0.06 : 0.11);
        inset = min * (isTablet ? 0.012 : 0.018);
    }
    // Dynamic island: iPhone 15/16 series only.
    const hasDynamicIsland = !!preset && /^iphone-1[56]/.test(preset.key);
    if (hasDynamicIsland) {
        return {
            chassisRadius,
            inset,
            island: {
                width: width * 0.28,
                height: Math.max(height * 0.018, 8),
                y: inset + height * 0.012,
            },
        };
    }
    // Android phone punch-hole: emit as a square pill (width == height) so the
    // existing consumer path — which draws `Rect` with `cornerRadius = height/2`
    // — renders a circle without needing a new discriminator.
    if (isAndroid && !isTablet) {
        const diameter = Math.max(min * 0.022, 10);
        return {
            chassisRadius,
            inset,
            island: {
                width: diameter,
                height: diameter,
                y: inset + height * 0.014,
            },
        };
    }
    return { chassisRadius, inset };
}

export type FrameInnerRect = {
    x: number;
    y: number;
    width: number;
    height: number;
    cornerRadius: number;
};

/** Inner screen rect of a frame (the area a bound screenshot fills). */
export function frameInnerRect(
    outer: { x: number; y: number; width: number; height: number },
    preset: DevicePresetDto | undefined,
): FrameInnerRect {
    const bezel = bezelGeometry(outer.width, outer.height, preset);
    return {
        x: outer.x + bezel.inset,
        y: outer.y + bezel.inset,
        width: outer.width - bezel.inset * 2,
        height: outer.height - bezel.inset * 2,
        cornerRadius: Math.max(0, bezel.chassisRadius - bezel.inset),
    };
}
