import { afterEach, it, expect, vi } from 'vitest';
import { withShareLandingParam, stripShareLandingParam } from './shareLanding';
afterEach(()=>vi.restoreAllMocks());
it('keeps variants, drops tracking/hash/duplicate atx, appends atx last',()=>{
 expect(withShareLandingParam('https://shop.test/p?ATX=0&variant=7&utm_source=x&fbclid=x&gclid=y&atx=1&AtX=2#x')).toBe('https://shop.test/p?variant=7&atx=1');
 expect(withShareLandingParam('https://shop.test/p?variation_id=2&attribute_pa_size=m&msclkid=x&mc_cid=x&dclid=x&mc_eid=x')).toBe('https://shop.test/p?variation_id=2&attribute_pa_size=m&atx=1');
 for (const value of [null,'','http://shop.test/p','bad url']) expect(withShareLandingParam(value)).toBeNull();
});
it.each([null,'','invalid','https://shop.test/p?x=a%20b'])('leaves unchanged non-landing telemetry %s',value=>expect(stripShareLandingParam(value)).toBe(value));
it('strips telemetry marker without losing hash or variants',()=>expect(stripShareLandingParam('https://shop.test/p?atx=1&ATX=0&variant=7#x')).toBe('https://shop.test/p?variant=7#x'));
it.each([['?a=1&ATX=0&atx=1&b=2#hash',true,'/p?a=1&b=2#hash'],['?atx=0',false,'/p'],['?atx=',false,'/p'],['?atx=2',false,'/p'],['?a=1',false,null]])('consumes %s once',async(query,expected,path)=>{
 vi.resetModules();const {consumeShareLanding}=await import('./shareLanding');
 const replaceState=vi.fn(),state={kept:1};const win={location:{href:'https://shop.test/p'+query},history:{state,replaceState}} as any;
 expect(consumeShareLanding(win)).toBe(expected);expect(consumeShareLanding(win)).toBe(false);
 if(path)expect(replaceState).toHaveBeenCalledWith(state,'',path);else expect(replaceState).not.toHaveBeenCalled();
});
it('survives history rejection and invalid location',async()=>{
 vi.resetModules();let {consumeShareLanding}=await import('./shareLanding');
 expect(consumeShareLanding({location:{href:'https://shop.test/?atx=1'},history:{replaceState:()=>{throw Error();}}} as any)).toBe(true);
 vi.resetModules();({consumeShareLanding}=await import('./shareLanding'));expect(consumeShareLanding({location:{href:'bad'}} as any)).toBe(false);
});
