"use strict";(()=>{var O=document.querySelector("#cart-button"),oe=document.querySelector("#added-to-cart"),A={};async function k(){try{let n=await(await fetch("https://koszyk.vsprint.pl/api/cart",{credentials:"include"})).json();if(!Array.isArray(n))throw new Error("Received data is not an array");return n}catch(e){return console.error("Failed to fetch cart items:",e),[]}}async function N(){O?.classList.remove("hide");let e=document.querySelector(".state-default"),n=document.querySelector(".state-empty"),o=document.querySelector(".state-error");try{let a=await k(),s=a.reduce((t,c)=>t+c.price*c.quantity,0),r=document.getElementById("cart-total");r&&(r.style.display="block",r.textContent=`${s.toFixed(2)} z\u0142 + VAT`);let i=document.getElementById("cart-quantity");if(i){let t=a.reduce((c,l)=>c+l.quantity,0);i.textContent=t.toString()}e&&n&&o&&(a.length>0?(n.style.display="none",o.style.display="none",e.style.display="block"):(e.style.display="none",o.style.display="none",n.style.display="flex")),await V(a)}catch(a){console.error("Failed to update cart UI:",a),e&&n&&o&&(n.style.display="none",e.style.display="none",o.style.display="flex")}}async function D(e,n=null){try{let o=n==="null"?null:n,a=await fetch(`https://koszyk.vsprint.pl/api/cart/${e}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({variant:o})});if(!a.ok)throw new Error(`Failed to remove item: ${a.statusText}`);window.dataLayer.push({ecommerce:null}),window.dataLayer.push({event:"remove_from_cart",ecommerce:{items:[{item_id:e,item_name:e,affiliation:"Konferencja App"}]}}),await N()}catch(o){console.error("Failed to remove item from cart:",o)}}async function q(e,n,o=null){try{let a=await fetch(`https://koszyk.vsprint.pl/api/cart/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({variant:o==="null"?null:o,quantity:n,attendeeName:A[e]||[]})});if(!a.ok)throw new Error(`Failed to update item quantity: ${a.statusText}`);window.location.href.includes("koszyk")||await N()}catch(a){console.error("Failed to update item quantity:",a)}}function B(){document.addEventListener("change",async e=>{let n=e.target;if(!n.classList.contains("is-quantity"))return;let o=parseInt(n.value,10),a=n.closest(".cart-item"),s=a?.querySelector(".deletebutton")?.getAttribute("data-item-id"),r=a?.querySelector(".deletebutton")?.getAttribute("data-variant")||null;s&&o>0&&await q(s,o,r)})}async function V(e){let n=document.querySelector(".cart-list");if(!n)return;n.innerHTML="",e.forEach((a,s)=>{let r=document.createElement("div");r.className="cart-item",r.innerHTML=`
${a.ticketType.toUpperCase()}
Wariant:
 ${a.variant}
Cena:
 ${a.price} z\u0142 + VAT
Ilo\u015B\u0107:
 ${a.quantity}
`,n.appendChild(r)}),B(),document.querySelectorAll(".deletebutton").forEach(a=>{a.addEventListener("click",async s=>{let r=s.currentTarget,i=r.getAttribute("data-item-id"),t=r.getAttribute("data-variant")||null;i?await D(i,t):console.error("Failed to remove item from cart: missing item ID")})})}function H(e,n){let o=document.createElement("select");o.classList.add("form_input"),o.dataset.input="variant",o.setAttribute("validate","true");let a=document.createElement("option");return a.value="",a.disabled=!0,a.selected=!0,a.textContent=e,o.appendChild(a),n.forEach(({value:s,label:r})=>{let i=document.createElement("option");i.value=s,i.textContent=r,o.appendChild(i)}),R(o),o}function R(e){e.style.appearance="none",e.style.setProperty("-webkit-appearance","none"),e.style.setProperty("-moz-appearance","none"),e.style.paddingRight="2.5rem",e.style.boxSizing="border-box";let n=``;e.style.backgroundImage=`url("data:image/svg+xml;charset=UTF-8,${encodeURIComponent(n)}")`,e.style.backgroundRepeat="no-repeat",e.style.backgroundPosition="right 1rem center"}function M(e,n){let o=[{value:"Rynek polski",label:"Rynek polski"},{value:"Rynek zagraniczny",label:"Rynek zagraniczny"},{value:"Automatyzacja",label:"Automatyzacja"}],a=[{value:"Szczecin",label:"Szczecin"},{value:"Gda\u0144sk",label:"Gda\u0144sk"},{value:"Bydgoszcz",label:"Bydgoszcz"},{value:"Pozna\u0144",label:"Pozna\u0144"}];document.querySelectorAll(".order-item-list").forEach((r,i)=>{r&&(r.innerHTML="",e.forEach(t=>{let c=document.createElement("div");if(c.className="order-item",c.innerHTML=` ${t.ticketType.toUpperCase()} `,n===1&&i===0){let l=t.ticketType;if(l==="VIP"||l==="Premium"||l==="Standard"||l==="Objazd\xF3wka Standard"||l==="Objazd\xF3wka Premium"){let p=document.createElement("div");if(p.className="cart-product-parameter",t.variant!==null)p.innerHTML=`
Wariant:
 ${t.variant}
`;else{p.style.marginBottom="0.5rem";let u=null;l==="VIP"?u=H("Wybierz rodzaj warsztat\xF3w",o):(l==="Objazd\xF3wka Standard"||l==="Objazd\xF3wka Premium")&&(u=H("Wybierz miasto",a)),u&&(u.value=t.variant||"",p.innerHTML='
Wariant:
',p.appendChild(u),u.addEventListener("change",async()=>{t.variant=u.value,await q(t.id,t.quantity,t.variant),u.disabled=!0,u.style.cursor="not-allowed"}))}c.appendChild(p)}let m=document.createElement("div");m.className="cart-product-parameter",Array.isArray(t.attendeeName)||(t.attendeeName=[]);let d=()=>{m.innerHTML="";for(let p=0;p{t.attendeeName||(t.attendeeName=[]),t.attendeeName[p]=u.value,A[t.id]=[...t.attendeeName]}),m.appendChild(u)}};d(),c.appendChild(m);let y=document.createElement("div");y.className="cart-product-parameter",y.innerHTML=`
Ilo\u015B\u0107:
`;let v=document.createElement("div");v.className="cart-product-parameter",v.innerHTML=`
Cena:
${(t.price*t.quantity).toFixed(2)} z\u0142 + VAT
`;let f=y.querySelector('input[data-input="quantity"]');f?.addEventListener("input",async()=>{let p=parseInt(f.value,10);if(p>0){if(t.quantity=p,!t.attendeeName||t.attendeeName.length>p)t.attendeeName&&(t.attendeeName=t.attendeeName.slice(0,p));else for(;t.attendeeName.length{c.innerHTML+=`
Imi\u0119 i nazwisko #${d+1}:
 ${m}
`}),t.variant!==null&&(c.innerHTML+=`
Wariant:
 ${t.variant}
`),c.innerHTML+=`
Cena:
 ${t.price} z\u0142 + VAT
Ilo\u015B\u0107:
 ${t.quantity}
`);r.appendChild(c)}))})}function W(e,n,o){let a=e.querySelector(".text-weight-semibold.text-color-brand");a&&(a.textContent=`${(n*o).toFixed(2)} z\u0142 + VAT`)}async function P(){try{return(await(await fetch("https://koszyk.vsprint.pl/api/session-id",{method:"GET",headers:{"Content-Type":"application/json"},credentials:"include"})).json()).sessionID}catch(e){return console.error("B\u0142\u0105d podczas pobierania ID sesji:",e),null}}function U(){let e=document.querySelectorAll('select[data-input="variant"][validate="true"]'),n=!0;return e.forEach(o=>{o.value===""&&(alert("Prosz\u0119 wybra\u0107 wariant warsztat\xF3w przed przej\u015Bciem dalej."),n=!1)}),n}var K=()=>{let e=document.querySelector("#Email")?.value||"",n=document.querySelector("#wf-ecom-shipping-name")?.value||"",o=document.querySelector("#nip")?.value||"",a=document.querySelector("#Telefon")?.value||"",s=document.querySelector("#DodatkoweInformacje")?.value||"",r=document.querySelector("#nazwa-firmy")?.value||"",i=document.querySelector("#Kod-pocztowy")?.value||"",t=document.querySelector("#Miasto")?.value||"",c=document.querySelector("#Adres-Firmy")?.value||"",l=document.querySelector("#address-line1")?.value||"",m=document.querySelector("#address-line2")?.value||"",d=document.querySelector("#city")?.value||"",y=document.querySelector("#state")?.value||"",v=document.querySelector("#postal-code")?.value||"",f=document.querySelector("#country")?.value||"PL";return{email:e,name:n,nip:o,phone:a,additionalInfo:s,companyName:r,companyZip:i,companyCity:t,companyAddress:c,addressLine1:l,addressLine2:m,city:d,state:y,postalCode:v,country:f}},Z=e=>/^\d{10}$/.test(e),L=(e,n)=>!e||e.value.trim()===""?(alert(`Prosz\u0119 uzupe\u0142ni\u0107 pole: ${n}.`),!1):!0,J=()=>{let e=document.querySelector("#Company"),n=document.querySelector("#nip"),o=document.querySelector("#nazwa-firmy"),a=document.querySelector("#Kod-pocztowy"),s=document.querySelector("#Miasto"),r=document.querySelector("#Adres-Firmy");return e?.checked?(n?.value?Z(n.value.trim()):!0)?L(n,"NIP")&&L(o,"Nazwa firmy")&&L(a,"Kod pocztowy")&&L(s,"Miasto")&&L(r,"Adres firmy"):(alert("Podany NIP jest niepoprawny."),!1):!0},Q=()=>{if(!J())return!1;let o=document.querySelector('div[data-step="1"]')?.querySelectorAll("input[required], select[required]");if(!Array.from(o||[]).every(i=>i.value.trim()!==""))return alert("Prosz\u0119 uzupe\u0142ni\u0107 wszystkie wymagane pola."),!1;if(document.querySelector("#is-items")?.value!=="true")return alert("Koszyk musi zawiera\u0107 przedmioty."),!1;let r=document.querySelectorAll("input.attendee-name");for(let i of r)if(!i.value.trim())return alert("Prosz\u0119 wpisa\u0107 imi\u0119 i nazwisko dla ka\u017Cdego biletu."),!1;return!0},G=()=>{let e=document.querySelector('div[data-step="1"]'),n=document.querySelector("#is-items");if(n&&(n.value=String(!0)),!e)return;e.querySelectorAll("input[required], select[required]").forEach(s=>{s.addEventListener("input",g)}),e.querySelectorAll("input.attendee-name").forEach(s=>{s.addEventListener("input",g)}),n?.addEventListener("input",g),g()},Y=(e,n,o,a)=>{let s=document.querySelector(".products-cost");s&&(s.textContent=`${e.toFixed(2)} z\u0142 + VAT`);let r=document.querySelector(".coupon-amount");r&&r.parentElement&&(a>0?(r.parentElement.style.display="block",r.textContent=`${a.toFixed(2)} z\u0142`):r.parentElement.style.display="none");let i=document.querySelector(".tax");i&&(i.textContent=`${n.toFixed(2)} z\u0142`);let t=document.querySelector(".total-cost");t&&(t.textContent=`${o.toFixed(2)} z\u0142`)},C=(e,n)=>(e.reduce((a,s)=>a+s.price*s.quantity,0)-n).toFixed(2),X=document.querySelector('a[data-form="next-btn"]'),$=document.querySelector('div[data-step="1"]'),j=document.querySelector('div[data-step="2"]'),x=document.querySelector("#Company"),T=document.querySelector(".company-info");T&&(T.style.display="none");var F=T?.querySelectorAll("input"),z=document.querySelector("#nip");z?.removeAttribute("required");x&&T&&F&&x.addEventListener("change",()=>{x.checked?(T.style.display="flex",z?.setAttribute("required","true")):(T.style.display="none",F.forEach(e=>e.value=""),z?.removeAttribute("required"))});var g=()=>{let e=document.querySelector('a[data-form="next-btn"]'),n=document.querySelector('div[data-step="1"]'),o=document.querySelector("#is-items");if(!n||!e||!o)return;let a=n.querySelectorAll("input[required], select[required]"),s=n.querySelectorAll("input.attendee-name"),r=[],i=[];a.forEach(d=>{if(d.value.trim()===""){let y=d.closest(".form-group")?.querySelector("label")?.textContent?.trim()||d.name||d.id;r.push(y)}}),s.forEach((d,y)=>{d.value.trim()===""&&i.push(`Bilet #${y+1}`)});let t=o.value==="true",c=r.length===0,l=i.length===0,m=c&&l&&t;console.clear(),m?console.log("\u2705 Wszystkie dane s\u0105 poprawne. Przycisk \u201EDalej\u201D dost\u0119pny."):(console.group("\u{1F512} Przycisk \u201EDalej\u201D zablokowany \u2013 brakuje:"),t||console.warn('\u{1F6D2} Koszyk jest pusty (isItemsInput !== "true")'),r.length>0&&console.warn("\u{1F4C4} Pola wymagane:",r),i.length>0&&console.warn("\u{1F465} Imiona i nazwiska brakuj\u0105ce:",i),console.groupEnd()),e.disabled=!m,e.style.cursor=m?"pointer":"not-allowed",e.style.opacity=m?"1":"0.5",e.style.display="block"},ee=async()=>{$&&j?($.style.display="none",j.style.display="flex",window.scrollTo({top:0,behavior:"smooth"})):console.error("One of the step wrappers is not found.")},te=async(e,n,o,a,s,r,i,t)=>{try{return console.log("Sending to backend:",s),await(await fetch("https://koszyk.vsprint.pl/api/create-payment-intent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({products_cost:Math.round(e*100),tax_cost:Math.round(n*100),total_amount:Math.round(o*100),coupon_amount:Math.round(a*100),coupon_code:t.code,coupon_type:t.type,currency:"PLN",items:s.flatMap(l=>Array.from({length:l.quantity},(m,d)=>({id:l.id,ticketType:l.ticketType,quantity:1,price:l.price,variant:l.variant||null,attendeeName:l.attendeeName?.[d]||""}))),customer_email:r.email,customer_name:r.name,nip:r.nip,phone:r.phone,additional_info:r.additionalInfo,company_name:r.companyName,company_zip:r.companyZip,company_city:r.companyCity,company_address:r.companyAddress,sessionID:i})})).json()}catch(c){return console.error("Error creating payment intent:",c),null}};async function ne(e){let n=document.querySelector('div[data-output="nip"]'),o=document.querySelector('div[data-output="company-name"]'),a=document.querySelector('div[data-output="company-zip"]'),s=document.querySelector('div[data-output="company-city"]'),r=document.querySelector('div[data-output="company-address"]');e.nip!==""&&n&&o&&r&&a&&s?(n.textContent=e.nip,o.textContent=e.companyName,r.textContent=e.companyAddress,a.textContent=e.companyZip,s.textContent=e.companyCity):e.nip===""&&n&&n.parentElement&&(n.parentElement.style.display="none")}var ae=async()=>{let e=window.Stripe?.("pk_live_51QebhPBRhKsel0GPxR0Z3cpb7mXwBvS7pm2HiDTkCyWCJ59IzEcFarfmXsqgnR0RpMuFtF01Ew1CvHN1oJ8mbAGV00eCKC7aDn",{stripeAccount:"acct_1QebhPBRhKsel0GP"});if(!e){console.error("Stripe nie zosta\u0142o zainicjalizowane.");return}let n=document.querySelector('[data-element="payment_form"]');if(n)n.addEventListener("keydown",i=>{i.key==="Enter"&&i.preventDefault()});else{console.error("Payment form element could not be found. Ensure that the form has the correct data-element attribute.");return}let o=await k();if(o.length===0&&window.location.pathname.includes("/koszyk")){alert("Tw\xF3j koszyk jest pusty. Dodaj przedmioty do koszyka."),window.location.href="/";return}G();let a=async(i,t)=>{try{return await(await fetch("https://koszyk.vsprint.pl/api/validate-coupon",{credentials:"include",method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({couponCode:i,cartItems:t})})).json()}catch(c){return console.error("Error checking coupon:",c),{isValid:!1,discountType:null,amount:0}}},s={code:"",type:"",amount:0};document.getElementById("apply-coupon")?.addEventListener("click",async()=>{let i=document.getElementById("coupon-code"),t=document.getElementById("coupon-feedback");if(!i||!t){console.error("Nie znaleziono elementu formularza kuponu.");return}let c=i.value.trim(),{isValid:l,discountType:m,amount:d,couponCode:y}=await a(c,o);if(!l){t.textContent="Nieprawid\u0142owy kupon.",t.style.display="block",t.style.color="#b42318",t.classList.remove("hide");return}s={code:y,type:m,amount:d/100};let v=m==="fixed"?`Zni\u017Cka: ${(d/100).toFixed(2)} z\u0142`:`Zni\u017Cka: ${d}%`;t.innerHTML=`Kupon zosta\u0142 dodany. ${v}
Cena zostanie zrabatowana w kolejnym kroku.`,t.style.display="block",t.style.color="#027a48",t.classList.remove("hide");let f=C(o,0);s.amount=m==="percentage"?Number(f)*(d/100):d/100}),M(o,1),(()=>{document.querySelectorAll("input.attendee-name").forEach(t=>{t.removeEventListener("input",g),t.addEventListener("input",g)})})(),X?.addEventListener("click",async()=>{if(!Q()||!U())return;let i=K();await ne(i);let t=await k();document.querySelectorAll("input.attendee-name").forEach(b=>{let S=b.dataset.ticketId,E=parseInt(b.dataset.attendeeIndex||"0"),w=b.value,h=t.find(_=>_.id===S);h&&(h.attendeeName||(h.attendeeName=[]),h.attendeeName[E]=w)}),M(t,2);let c=C(t,0),l=C(t,s.amount),m=(Number(l)*.23).toFixed(2);if(l=(Number(l)*1.23).toFixed(2),Number(l)<=2){alert("Suma produkt\xF3w w koszyku musi wynosi\u0107 wi\u0119cej ni\u017C 2.00 z\u0142, aby kontynuowa\u0107.");return}Y(Number(c),Number(m),Number(l),Number(s.amount)),await ee();let d=await P(),y=await te(Number(c),Number(m),Number(l),Number(s.amount),t,{...i,address_line1:i.addressLine1,address_line2:i.addressLine2,city:i.city,state:i.state,postal_code:i.postalCode,country:i.country},d,s);if(!y){console.error("Payment intent is missing.");return}let v=document.querySelector('[data-element="stripe"]');if(!v){console.error("Stripe element could not be found. Ensure that the element has the correct data-element attribute.");return}let f=e.elements({clientSecret:y.client_secret});f.create("payment").mount(v);let u=window.location.origin,I="";u.includes("konferencja.vsprint.pl")?I="https://konferencja.vsprint.pl/potwierdzenie-zamowienia":u.includes("landing.vsprint.pl")?I="https://landing.vsprint.pl/podsumowanie":(console.warn("\u26A0\uFE0F Nieznany origin, ustawiam fallback na konferencja.vsprint.pl"),I="https://konferencja.vsprint.pl/potwierdzenie-zamowienia"),n.addEventListener("submit",async b=>{b.preventDefault(),b.stopPropagation(),await f.submit();let S=await e.confirmPayment({elements:f,clientSecret:y.client_secret,redirect:"always",confirmParams:{return_url:I}}),E=document.querySelector(".w-form-done"),w=document.querySelector(".w-form-fail"),h=document.querySelector(".container-medium");S.error?(w&&(w.textContent=`P\u0142atno\u015B\u0107 nieudana: ${S.error.message}`,w.style.display="block"),E&&(E.style.display="none")):(E&&(E.textContent="P\u0142atno\u015B\u0107 zako\u0144czona sukcesem!",E.style.display="block"),w&&(w.style.display="none"),h&&(h.style.display="none"))},!0)})};document.addEventListener("DOMContentLoaded",ae);})();