import { expect, test } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';

const __dirname = dirname(fileURLToPath(import.meta.url));

// Run `pnpm build --qwik --dev` to update
test('qwikloader script', () => {
  let qwikLoader: string = '';
  try {
    qwikLoader = readFileSync(resolve(__dirname, '../dist/qwikloader.js'), 'utf-8');
  } catch {
    // ignore, we didn't build yet
  }
  expect(qwikLoader).toMatchInlineSnapshot(
    `"const e=document,t=window,n="w",r="wp",o="d",s="dp",i="e",a="ep",c="capture:",l="readystatechange",p=0,u=new Set,d=new Set([e]),f=new Map,h={};let q,b,g;const m=(e,t)=>Array.from(e.querySelectorAll(t)),v=e=>{const t=[];return d.forEach(n=>t.push(...m(n,e))),t},w=(e,t,n,r=!1,o=!1)=>e.addEventListener(t,n,{capture:r,passive:o}),y=e=>{H(e);const t=m(e,"[q\\\\:shadowroot]");for(let e=0;e<t.length;e++){const n=t[e].shadowRoot;n&&y(n)}},A=e=>e&&"function"==typeof e.then,E=async e=>{for(let t=0;t<e.length;t++)await e[t]()},C=e=>{if(e.length){const t=()=>E(e);g=g?g.then(t,t):t()}},S=t=>{if(void 0===t._qwikjson_){let n=(t===e.documentElement?e.body:t).lastElementChild;for(;n;){if("SCRIPT"===n.tagName&&"qwik/json"===n.getAttribute("type")){t._qwikjson_=JSON.parse(n.textContent.replace(/\\\\x3C(\\/?script)/gi,"<$1"));break}n=n.previousElementSibling}}},_=e=>{h[e]=1,I(l)},k=t=>{const n=t.getAttribute("q:instance");return"paused"===t.getAttribute("q:container")&&"loading"===e.readyState&&!h[n]&&new Promise(t=>{w(e,l,()=>{("loading"!==e.readyState||h[n])&&t()})})},$=(e,t)=>new CustomEvent(e,{detail:t}),I=(t,n)=>{e.dispatchEvent($(t,n))},N=e=>e.replace(/([A-Z-])/g,e=>"-"+e.toLowerCase()),R=e=>e.replace(/-./g,e=>e[1].toUpperCase()),T=e=>{const t=e.indexOf(":");return{scope:e.slice(0,t),eventName:R(e.slice(t+1))}},x=e=>2===e.length,B=e=>e.charAt(0),L=e=>!!e&&1===e.nodeType,U=(e,t,n)=>e.hasAttribute(n)&&(!!e._qDispatch?.[t]||e.hasAttribute("q-"+t)),j=(t,n,r,o,s,i,a,c=!0)=>{const l={qBase:r,symbol:i,element:n,reqTime:a};if(!s){const n=(e["qFuncs_"+t.getAttribute("q:instance")]||[])[+i];if(!n&&c){const e=Error("sym:"+i);I("qerror",{importError:"sync",error:e,...l}),console.error(e)}return n}const p=\`\${i}|\${r}|\${s}\`,u=f.get(p);if(u)return u;const d=new URL(s,o).href,h=import(d);return S(t),h.then(e=>{const t=e[i];if(t)f.set(p,t),I("qsymbol",l);else{const e=Error(\`\${i} not in \${d}\`);I("qerror",{importError:"no-symbol",error:e,...l}),console.error(e)}return t},e=>{I("qerror",{importError:"async",error:e,...l}),console.error(e)})},D=(t,n,r,o,s,i=!0)=>{let a=!1;s&&(i&&t.hasAttribute("preventdefault:"+s)&&n.preventDefault(),t.hasAttribute("stoppropagation:"+s)&&n.stopPropagation());const c=t._qDispatch?.[r];if(c){if("function"==typeof c){const e=()=>c(n,t);if(a)o.push(async()=>{const t=e();A(t)&&await t});else{const t=e();A(t)&&(a=!0,o.push(()=>t))}}else if(c.length)for(let e=0;e<c.length;e++){const r=c[e];if(r){const e=()=>r(n,t);if(a)o.push(async()=>{const t=e();A(t)&&await t});else{const t=e();A(t)&&(a=!0,o.push(()=>t))}}}return}const l=t.getAttribute("q-"+r);if(l){const r=t.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])"),s=r.getAttribute("q:base"),i=new URL(s,e.baseURI),c=l.split("|"),p=k(r);for(let e=0;e<c.length;e++){const l=c[e],u=performance.now(),[d,f,h]=l.split("#"),q=e=>{if(e&&t.isConnected){const r=e=>{I("qerror",{error:e,qBase:s,symbol:f,element:t,reqTime:u})};try{const o=e.call(h,n,t);if(A(o))return o.catch(r)}catch(e){return r(e)}}},b=(e=!0)=>j(r,t,s,i,d,f,u,e),g=p?void 0:b();if(p)a=!0,o.push(async()=>{await p,await q(await b(!1)||await b())});else if(A(g))a=!0,o.push(()=>g.then(q));else if(a)a=!0,o.push(async()=>{await q(g||await b())});else{const e=q(g);A(e)&&(a=!0,o.push(()=>e))}}}},O=(e,t=i,n=!0)=>{const r=N(e.type),o=t+":"+r,s=c+r,a=[],l=[],p=[];let u=e.target;for(;u;)L(u)?(a.push(u),l.push(U(u,o,s)),u=u.parentElement):u=u.parentElement;for(let t=a.length-1;t>=0;t--)if(l[t]&&(D(a[t],e,o,p,r,n),e.cancelBubble))return void C(p);for(let t=0;t<a.length;t++)if(!l[t]&&(D(a[t],e,o,p,r,n),!e.bubbles||e.cancelBubble))return void C(p);C(p)},P=e=>O(e,a,!1),F=(e,t,n=!0)=>{const r=N(t.type),o=e+":"+r,s=v("[q-"+e+"\\\\:"+r+"]"),i=[];for(let e=0;e<s.length;e++){const a=s[e];D(a,t,o,i,r,n)}C(i)},J=e=>{F(o,e)},M=e=>{F(s,e,!1)},Z=e=>{F(n,e)},z=e=>{F(r,e,!1)},G=()=>{const n=e.readyState;if("interactive"==n||"complete"==n){if(b=1,d.forEach(y),u.has("d:qinit")){u.delete("d:qinit");const e=$("qinit"),t=v("[q-d\\\\:qinit]"),n=[];for(let r=0;r<t.length;r++){const o=t[r];D(o,e,"d:qinit",n),o.removeAttribute("q-d:qinit")}C(n)}if(u.has("d:qidle")&&(u.delete("d:qidle"),(t.requestIdleCallback??t.setTimeout).bind(t)(()=>{const e=$("qidle"),t=v("[q-d\\\\:qidle]"),n=[];for(let r=0;r<t.length;r++){const o=t[r];D(o,e,"d:qidle",n),o.removeAttribute("q-d:qidle")}C(n)})),u.has("e:qvisible")){q||(q=new IntersectionObserver(e=>{const t=[];for(let n=0;n<e.length;n++){const r=e[n];r.isIntersecting&&(q.unobserve(r.target),D(r.target,$("qvisible",r),"e:qvisible",t))}C(t)}));const e=v("[q-e\\\\:qvisible]:not([q\\\\:observed])");for(let t=0;t<e.length;t++){const n=e[t];q.observe(n),n.setAttribute("q:observed","true")}}}},H=(...e)=>{for(let r=0;r<e.length;r++){const s=e[r];if(0===s)_(e[++r]);else if("string"==typeof s){if(!u.has(s)){u.add(s);const{scope:e,eventName:r}=T(s),i=x(e),a=B(e);a===n?w(t,r,i?z:Z,!0,i):d.forEach(e=>w(e,r,a===o?i?M:J:i?P:O,!0,i)),1!==b||"e:qvisible"!==s&&"d:qinit"!==s&&"d:qidle"!==s||G()}}else d.has(s)||(u.forEach(e=>{const{scope:t,eventName:r}=T(e),i=x(t),a=B(t);a!==n&&w(s,r,a===o?i?M:J:i?P:O,!0,i)}),d.add(s))}},K=t._qwikEv;K?.roots||(Array.isArray(K)?H(...K):H("e:click","e:input"),t._qwikEv={events:u,roots:d,push:H},w(e,l,G),G());"`
  );
});

// Keep this the same as in qwikloader.ts
const kebabToCamel = (eventName: string) => eventName.replace(/-./g, (a) => a[1].toUpperCase());
test('kebab-to-camel event names', () => {
  expect(kebabToCamel('-custom-event')).toBe('CustomEvent');
  expect(kebabToCamel('--custom---event')).toBe('-custom-Event');
});
