// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterEach, beforeEach, it, expect, vi } from 'vitest';
const source=readFileSync(resolve(__dirname,'../../assets/bootstrap.js'),'utf8');
beforeEach(()=>{
 vi.useFakeTimers();document.body.innerHTML='';document.head.innerHTML='';
 Object.defineProperty(document,'readyState',{configurable:true,value:'complete'});
 Object.defineProperty(document,'referrer',{configurable:true,value:'https://ref.test/p?ATX=1&x=2'});
 (window as any).AISTHETIX_CONFIG={eventsUrl:'https://events.test/api/events',analyticsEnabled:true,publishableKey:'pk_fixture',visitorKey:'visitor',productId:'42'};
 (window as any).AISTHETIX_WIDGET_URL='/widget.js';
 delete window.AISTHETIX_SHARE_LANDING;
 vi.stubGlobal('fetch',vi.fn().mockResolvedValue({ok:true}));
});
afterEach(()=>{vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();history.replaceState(null,'','/');delete window.AISTHETIX_SHARE_LANDING;});
it.each([['?variant=7&ATX=0&atx=1#keep',true,true],['?atx=2',true,false],['',true,false],['?atx=1',false,false]])('bootstrap %s / trigger %s', (query,trigger,eager)=>{
 history.replaceState({kept:true},'','/p'+query);
 if(trigger)document.body.innerHTML='<button id="aisthetix-tryon-trigger"></button>';
 const replace=vi.spyOn(history,'replaceState');
 new Function(source)();
 expect(location.search.toLowerCase()).not.toContain('atx');
 expect(window.AISTHETIX_SHARE_LANDING===true).toBe(eager);
 expect(document.querySelectorAll('script[src="/widget.js"]').length).toBe(eager?1:0);
 const payloads=vi.mocked(fetch).mock.calls.map(c=>JSON.parse(c[1]?.body as string));
 const viewed=payloads.find(p=>p.event==='product_viewed'||p.eventName==='product_viewed'||p.event_name==='product_viewed');
 expect(viewed).toBeDefined();expect(viewed.url).not.toMatch(/atx/i);expect(viewed.referrer).toBe('https://ref.test/p?x=2');
 if(query.includes('variant')){expect(location.search).toBe('?variant=7');expect(location.hash).toBe('#keep');expect(replace).toHaveBeenCalledWith({kept:true},'','/p?variant=7#keep');}
 if(!query)expect(replace).not.toHaveBeenCalled();
});
it('strips attribution even if replaceState is denied',()=>{
 history.replaceState(null,'','/p?atx=1');vi.spyOn(history,'replaceState').mockImplementation(()=>{throw Error('denied');});
 new Function(source)();expect(vi.mocked(fetch).mock.calls.map(c=>JSON.parse(c[1]?.body as string)).every(p=>!p.url?.includes('atx'))).toBe(true);
});
