import { describe, it, expect } from 'vitest';
import { applyFrame, frameStyleVars, stringifyFrame } from '../../../../assets/admin/media/imageFrame';

// Same cases as tests/Unit/Twig/ImageFrameExtensionTest.php: the editor preview must match the server render.
describe('imageFrame', () => {
    it('renders nothing without a setting', () => {
        expect(frameStyleVars(null, null, true, false, null)).toEqual([]);
        expect(frameStyleVars({ x: 50, y: 50, zoom: 1 }, null, true, false, null)).toEqual([]);
    });

    it('gives each theme its own frame', () => {
        expect(frameStyleVars({ x: 30, zoom: 1.5 }, { y: 80 }, true, true, null)).toEqual([
            ['--img-x', '30%'], ['--img-zoom', '1.5'], ['--img-dy', '80%'],
        ]);
    });

    it('applies the fallback: the frame follows the displayed image', () => {
        // Hiver without its own image shows the Été image with the Été frame
        expect(frameStyleVars({ x: 30 }, { x: 90 }, true, false, null)).toEqual([['--img-x', '30%'], ['--img-dx', '30%']]);
        // Hiver with its own image but no frame stays at the default
        expect(frameStyleVars({ x: 30 }, null, true, true, null)).toEqual([['--img-x', '30%']]);
        // Été without its own image shows the Hiver image with the Hiver frame
        expect(frameStyleVars({ x: 10 }, { x: 70 }, false, true, null)).toEqual([['--img-x', '70%'], ['--img-dx', '70%']]);
    });

    it('clamps values and ignores unknown ratios', () => {
        expect(frameStyleVars({ x: 150, y: -3, zoom: 9 }, null, true, false, '5/1')).toEqual([
            ['--img-x', '100%'], ['--img-y', '0%'], ['--img-zoom', '3'],
            ['--img-dx', '100%'], ['--img-dy', '0%'], ['--img-dzoom', '3'],
        ]);
    });

    it('stringifies the default frame as empty', () => {
        expect(stringifyFrame({ x: 50, zoom: 1 })).toBe('');
        expect(stringifyFrame({ x: 20 })).toBe('{"x":20}');
    });

    it('applies vars and the ratio marker on the slot, and clears them again', () => {
        const field = document.createElement('div');
        field.dataset.mediaId = 'u';
        field.dataset.imageFrame = '{"x":20}';
        field.dataset.imageRatio = '4/5';

        applyFrame(field);
        expect(field.style.getPropertyValue('--img-x')).toBe('20%');
        expect(field.style.getPropertyValue('--img-ratio')).toBe('4/5');
        expect(field.hasAttribute('data-img-ratio')).toBe(true);

        field.dataset.imageFrame = '';
        field.dataset.frameRatio = 'false';
        applyFrame(field);
        expect(field.getAttribute('style')).toBe('');
        expect(field.hasAttribute('data-img-ratio')).toBe(false);
    });
});
