import { describe, it, expect, beforeEach } from 'vitest';
import { countDemoTryOns, recordDemoTryOn, remainingDemoTryOns } from './demoCounter';

beforeEach( () => localStorage.clear() );

describe( 'demo try-on counter', () => {
	it( 'starts at zero', () => {
		expect( countDemoTryOns() ).toBe( 0 );
	} );

	it( 'counts each recorded try-on', () => {
		recordDemoTryOn();
		recordDemoTryOn();
		expect( countDemoTryOns() ).toBe( 2 );
	} );

	it( 'reports the new total as it records', () => {
		expect( recordDemoTryOn() ).toBe( 1 );
		expect( recordDemoTryOn() ).toBe( 2 );
	} );

	it( 'survives a reload, because the count outlives the page', () => {
		recordDemoTryOn();
		expect( localStorage.getItem( 'aisthetix-demo-tryons' ) ).toBe( '1' );
	} );

	it( 'shrugs off a corrupt stored value instead of counting NaN', () => {
		localStorage.setItem( 'aisthetix-demo-tryons', 'not a number' );
		expect( countDemoTryOns() ).toBe( 0 );
	} );

	it( 'shrugs off a negative stored value', () => {
		localStorage.setItem( 'aisthetix-demo-tryons', '-4' );
		expect( countDemoTryOns() ).toBe( 0 );
	} );
} );

describe( 'remainingDemoTryOns', () => {
	it( 'reports what is left against the demo limit', () => {
		recordDemoTryOn();
		expect( remainingDemoTryOns( 5 ) ).toBe( 4 );
	} );

	it( 'is the whole limit before anything is spent', () => {
		expect( remainingDemoTryOns( 5 ) ).toBe( 5 );
	} );

	it( 'never reports a negative remainder, even past the cap', () => {
		for ( let i = 0; i < 9; i += 1 ) {
			recordDemoTryOn();
		}
		expect( remainingDemoTryOns( 5 ) ).toBe( 0 );
	} );
} );
