import{M as q,T as ae}from"./bootstrap.esm-Bb7dPm-H.js";import{s as Y}from"./store-api-Cl_W-5C2.js";import{a as Z}from"./api-client-QIUkDUfA.js";import{m as Q,o as re,i as se}from"./tld-extra-fields-DqBnP-rv.js";function $(e){return e==null?"":String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function S(e,o){const i=(typeof e=="number"?e:parseFloat(e||0)).toFixed(2);if(o&&typeof o=="object")return o.prefix?`${o.prefix}${i}`:o.suffix?`${i} ${o.suffix}`:`${o.code} ${i}`;const a=o||"TRY";switch(a){case"USD":return`$${i}`;case"EUR":return`€${i}`;case"GBP":return`£${i}`;case"TRY":return`${i} ₺`;default:return`${a} ${i}`}}function ce(e){if(!e||e.length===0)return"";let o="";const i={};return e.forEach(a=>{if(!a||!a.option_id){console.warn("Invalid config option:",a);return}const c=a.option_id;i[c]||(i[c]=[]),i[c].push(a)}),Object.keys(i).forEach(a=>{const c=i[a],m=c[0],u=m.name&&m.name.includes("(x")&&m.quantity>1,g=c.length>1;if(u){const b=J(m.name);o+=`<span class="badge bg-info text-white me-2 mb-1">
                <strong>${b}</strong>: ${m.quantity}
            </span>`}else if(g){const b=c.map(w=>w&&w.name?X(w.name):null).filter(w=>w);if(b.length>0){const w=J(m.name);o+=`<span class="badge bg-success text-white me-2 mb-1">
                    <strong>${w}</strong>: ${b.join(", ")}
                </span>`}}else{const b=X(m.name),w=J(m.name);b&&(o+=`<span class="badge bg-primary text-white me-2 mb-1">
                    <strong>${w}</strong>: ${b}
                </span>`)}}),o}function J(e){return!e||typeof e!="string"?"Option":e.includes(" (x")?e.split(" (x")[0]:e.includes(" - ")?e.split(" - ")[0]:e}function X(e){return!e||typeof e!="string"||e.includes(" (x")?null:e.includes(" - ")?e.split(" - ")[1]:e}async function M(){const e=document.getElementById("basketSummaryLoading"),o=document.getElementById("basketSummaryContent"),i=document.getElementById("basketEmpty");e.style.display="block",o.style.display="none",i.style.display="none";try{const a=await Y.getBasketSummary(),c=(a==null?void 0:a.summary)||null;return window.__basketCurrentSummary=c,c}catch(a){return console.error("[Basket] Summary fetch failed:",a),null}}function A(e){var C,B,I,T,x;const o=document.getElementById("basketSummaryLoading"),i=document.getElementById("basketSummaryContent"),a=document.getElementById("basketEmpty");if(!e||(e.totalItems??0)===0||(e.items??[]).length===0){o.style.display="none",i.style.display="none",a.style.display="block",document.getElementById("basketItemsContainer").innerHTML="";return}o.style.display="none",a.style.display="none",i.style.display="block",document.getElementById("basketSubtotal").textContent=S(e.subtotal,e.currency);const c=document.getElementById("basketSetupFeeRow");(e.setup_fee||0)>0?(c.classList.add("d-flex"),c.style.display="",document.getElementById("basketSetupFeeAmount").textContent=S(e.setup_fee,e.currency)):(c.classList.remove("d-flex"),c.style.display="none");const m=document.getElementById("basketTaxRow");(e.tax_amount||0)>0?(m.classList.add("d-flex"),m.style.display="",document.getElementById("basketTaxName").textContent=e.tax_name||((C=window.translations)==null?void 0:C.store_products_tax)||"Tax",document.getElementById("basketTaxAmount").textContent=S(e.tax_amount,e.currency)):(m.classList.remove("d-flex"),m.style.display="none");const u=document.getElementById("basketPromoDiscountRow");if((e.discount_amount||0)>0){u.classList.add("d-flex"),u.style.display="",document.getElementById("basketPromoDiscountAmount").textContent=`-${S(e.discount_amount,e.currency)}`;const _=document.getElementById("basketDiscountLabel");_&&((B=e.discount)!=null&&B.discount_text)?_.textContent=e.discount.discount_text:_.textContent=((I=window.translations)==null?void 0:I.store_basket_discount)||"İndirim";const v=((T=e.discount)==null?void 0:T.type)==="coupon"&&((x=e.discount)==null?void 0:x.coupon_code)||null;v?j!==v&&(j=v,G(v)):j&&(j=null,G(null))}else u.classList.remove("d-flex"),u.style.display="none",j&&(j=null,G(null));const g=document.getElementById("basketPaidTrialDiscountRow");if(g){const _=Number(e.paid_trial_total_savings||0);_>0?(g.classList.add("d-flex"),g.style.display="",document.getElementById("basketPaidTrialDiscountAmount").textContent=`-${S(_,e.currency)}`):(g.classList.remove("d-flex"),g.style.display="none")}document.getElementById("basketTotal").textContent=S(e.total,e.currency);const b=(e.items||[]).map((_,v)=>de(_,v)).join("");document.getElementById("basketItemsContainer").innerHTML=b;const w=(e.items||[]).some(_=>_.type==="domain"),E=document.getElementById("domainConfigBanner");E&&(E.style.display=w?"block":"none"),[...document.querySelectorAll('[data-bs-toggle="tooltip"]')].map(_=>new ae(_,{boundary:document.body})),ue(e).catch(_=>console.warn("[Basket] extra-fields decorate failed",_))}function de(e,o){var C,B,I,T,x,_;const i=e.type==="domain",a=i&&e.domain_action==="transfer",c=i,m=e.type==="product",u=e.currency||"TRY";let g="";if(m){const v=e.period||1,H=e.available_periods&&e.available_periods.length>0?e.available_periods:[1,3,6,12,24,36];g=`
            <div class="d-flex align-items-center gap-2">
                <select class="form-select form-select-sm" style="width: 100px;" data-action="changePeriod" data-index="${o}">
                    ${H.map(t=>{var d;return`<option value="${t}" ${t===v?"selected":""}>${t} ${((d=window.translations)==null?void 0:d.store_products_period_month)||"Ay"}</option>`}).join("")}
                </select>
            </div>`}else if(c&&(e.domain_action==="register"||e.domain_action==="transfer")){const v=e.period||1,H=e.available_periods&&e.available_periods.length>0?e.available_periods:[1,2,3,4,5,6,7,8,9,10];g=`
            <div class="d-flex align-items-center gap-2">
                <select class="form-select form-select-sm" style="width: 100px;" data-action="changeDomainPeriod" data-index="${o}">
                    ${H.map(t=>{var d;return`<option value="${t}" ${t===v?"selected":""}>${t} ${((d=window.translations)==null?void 0:d.store_basket_period_year)||"Yıl"}</option>`}).join("")}
                </select>
            </div>`}let b="";a&&(b+=`<button class="btn btn-sm btn-outline-secondary me-2" data-action="openEpp" data-index="${o}" data-bs-toggle="tooltip" title="${((C=window.translations)==null?void 0:C.store_domain_transfer_code)||"Transfer Code"}"><i class="fas fa-key"></i></button>`),c&&(b+=`<button class="btn btn-sm btn-outline-secondary me-2" data-action="openExtraFields" data-index="${o}" data-bs-toggle="tooltip" title="${((B=window.translations)==null?void 0:B.store_basket_extra_fields_title)||"Additional Info"}"><i class="fas fa-id-card"></i></button>`);let w="";m&&e.configurableOptions&&e.configurableOptions.length>0&&(w=`
            <div class="mt-2">
                <small class="text-muted d-block mb-1">${((I=window.translations)==null?void 0:I.store_products_configurable_options)||"Konfigürasyon Seçenekleri"}:</small>
                <div class="config-options-list">
                    ${ce(e.configurableOptions)}
                </div>
            </div>`);let E="";m&&(E=`
            <button class="btn btn-sm btn-outline-primary me-2" data-action="editProduct" data-index="${o}" data-bs-toggle="tooltip" title="${((T=window.translations)==null?void 0:T.store_basket_edit_product)||"Ürünü Düzenle"}">
                <i class="fas fa-edit"></i>
            </button>`);const O=i?`<span class="extra-fields-status" data-extra-fields-status="${o}"></span>`:"";return`
    <div class="card mb-3" data-item-index="${o}">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col">
                    <h6 class="mb-1">${$(e.name||"-")}${O}</h6>
                    ${e.subtitle?`<small class="text-muted">${$(e.subtitle)}</small>`:""}
                    ${e.connectedDomain?`<div class="small text-success"><i class="fas fa-link me-1"></i>Domain: ${$(e.connectedDomain)}</div>`:""}
                    ${w}
                </div>
                <div class="col-auto d-flex align-items-center gap-3">
                    ${g}
                    <div class="fw-semibold text-primary text-end">
                        ${e._paid_trial_preview_applied?`
                            <div>
                                <small class="text-muted text-decoration-line-through me-2">${S(e._paid_trial_original_price||0,u)}</small>
                                <span class="text-success fw-bold">${S(e._paid_trial_discounted_price||0,u)}</span>
                                <div class="small text-muted fst-italic mt-1" style="font-size: 0.75rem;">
                                    <i class="fas fa-info-circle me-1 opacity-75"></i>${(((x=window.translations)==null?void 0:x.store_paid_trial_next_period_hint)||"Sonraki dönemler: :amount").replace(":amount",S(e._paid_trial_recurring_amount||0,u))}
                                </div>
                            </div>
                        `:e.has_discount?`
                            <div>
                                <small class="text-muted text-decoration-line-through me-2">${S(e.original_price||0,u)}</small>
                                <span class="text-success fw-bold">${S(e.discounted_price||0,u)}</span>
                            </div>
                        `:S(e.price||0,u)}
                    </div>
                    <div class="d-flex">
                        ${E}
                        ${b}
                        <button class="btn btn-sm btn-outline-danger" data-action="removeItem" data-index="${o}" data-bs-toggle="tooltip" title="${((_=window.translations)==null?void 0:_.store_basket_delete)||"Sil"}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>`}const z=new Map;async function W(e){if(!e)return{};if(z.has(e))return z.get(e);const o=window.storeConfig&&window.storeConfig.routes&&window.storeConfig.routes.domainExtraFields||"/storeapi/store/domain-extra-fields",i=o.includes("?")?"&":"?",a=o+i+"tld_id="+encodeURIComponent(e);try{const c=await fetch(a,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!c.ok)return z.set(e,{}),{};const m=await c.json(),u=m&&m.fields||{};return z.set(e,u),u}catch{return z.set(e,{}),{}}}function P(e){return String(e??"").replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function le(e,o){if(!e||Object.keys(e).length===0)return"";const i=window.translations||{},a=re(e),c=o||{};let m='<hr class="my-4"><h6 class="mb-3">'+$(i.store_basket_extra_fields_title||"Additional Info")+'</h6><div id="extraFieldsSection" class="row g-3">';for(const[u,g]of a){const b=se(g,c),w=g.required?' <span class="text-danger">*</span>':"",E=c[u]!=null?c[u]:g.default!=null?g.default:"",O=b?"":' style="display:none"';let C="";if(g.type==="select"){const I=Object.entries(g.options||{}).map(([T,x])=>{const _=String(T)===String(E)?" selected":"";return'<option value="'+P(T)+'"'+_+">"+$(x)+"</option>"}).join("");C='<select class="form-select" data-extra-field="'+P(u)+'" name="extra_fields['+P(u)+']"><option value="">--</option>'+I+"</select>"}else if(g.type==="textarea")C='<textarea class="form-control" data-extra-field="'+P(u)+'" name="extra_fields['+P(u)+']">'+$(E)+"</textarea>";else if(g.type==="checkbox"){const I=E?" checked":"";C='<div class="form-check"><input type="checkbox" class="form-check-input" data-extra-field="'+P(u)+'" name="extra_fields['+P(u)+']" value="1"'+I+'><label class="form-check-label">'+$(g.label||u)+"</label></div>"}else C='<input type="'+(g.type==="password"?"password":"text")+'" class="form-control" data-extra-field="'+P(u)+'" name="extra_fields['+P(u)+']" value="'+P(E)+'" placeholder="'+P(g.placeholder||"")+'">';const B=g.type==="checkbox"?"":'<label class="form-label">'+$(g.label||u)+w+"</label>";m+='<div class="col-12 extra-field-row" data-field-key="'+P(u)+'"'+O+">"+B+C+(g.description?'<div class="form-text small">'+$(g.description)+"</div>":"")+"</div>"}return m+="</div>",m}function ie(){const e={};return document.querySelectorAll("#extraFieldsSection [data-extra-field]").forEach(o=>{const i=o.getAttribute("data-extra-field");o.type==="checkbox"?e[i]=o.checked?"1":"":e[i]=(o.value||"").trim()}),e}function ee(e){const o=ie();document.querySelectorAll("#extraFieldsSection .extra-field-row").forEach(i=>{const a=i.getAttribute("data-field-key"),c=e[a];c&&(i.style.display=se(c,o)?"":"none")})}async function ue(e){const o=e&&e.items||[],i=window.translations||{};for(const[m,u]of o.entries()){const g=document.querySelector('[data-extra-fields-status="'+m+'"]');if(!g)continue;if(u.type!=="domain"||!u.tld_id){g.innerHTML="";continue}const b=await W(u.tld_id);if(Object.keys(b).length===0){g.innerHTML="";continue}const w=Q(b,u.additional_fields||{});g.innerHTML=w.length?'<span class="badge bg-warning text-dark ms-2"><i class="fas fa-exclamation-triangle me-1"></i>'+$(i.store_basket_extra_fields_missing||"Additional info required")+"</span>":""}const a=document.getElementById("confirmOrderBtn")||document.querySelector('[data-action="checkout"]');if(!a)return;let c=!1;for(const m of o){if(m.type!=="domain"||!m.tld_id)continue;const u=await W(m.tld_id);if(Object.keys(u).length===0)continue;if(Q(u,m.additional_fields||{}).length>0){c=!0;break}}c?(a.setAttribute("disabled","disabled"),a.setAttribute("aria-disabled","true"),a.setAttribute("title",i.store_basket_extra_fields_complete_first||"")):(a.removeAttribute("disabled"),a.removeAttribute("aria-disabled"),a.removeAttribute("title"))}async function V(e,o){try{await Y.updateBasketItem(e,o)}catch(i){console.error("[Basket] Update error:",i)}}async function me(e){try{await Y.removeBasketItem(e)}catch(o){console.error("[Basket] Remove error:",o)}}function pe(){var _,v,H;document.addEventListener("change",async t=>{const d=t.target.closest('[data-action="changePeriod"]');if(!d)return;const p=parseInt(d.getAttribute("data-index")),s=parseInt(d.value);await V(p,{period:s});const n=await M();A(n),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"changePeriod"}}))}),document.addEventListener("change",async t=>{const d=t.target.closest('[data-action="changeDomainPeriod"]');if(!d)return;const p=parseInt(d.getAttribute("data-index")),s=parseInt(d.value);await V(p,{domain_period:s});const n=await M();A(n),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"changeDomainPeriod"}}))}),document.addEventListener("click",async t=>{var f,y;const d=t.target.closest('[data-action="removeItem"]');if(!d)return;const p=parseInt(d.getAttribute("data-index")),s=(y=(f=window.__basketCurrentSummary)==null?void 0:f.items)==null?void 0:y[p];await me(p);try{window.procpFireCustomEvent&&window.procpFireCustomEvent("BasketItemRemoved",{product_id:(s==null?void 0:s.product_id)??null})}catch(r){console.warn("[tracking] BasketItemRemoved emit failed",r)}const n=await M();A(n),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"removeItem"}}))});let e=null;document.addEventListener("click",t=>{var f,y;const d=t.target.closest('[data-action="openEpp"]');if(!d)return;e=parseInt(d.getAttribute("data-index"));const p=document.getElementById("transferCodeModal"),s=(y=(f=window.__basketCurrentSummary)==null?void 0:f.items)==null?void 0:y[e];if(s&&s.epp_code){const r=document.getElementById("transferCodeInput");r&&(r.value=s.epp_code)}new q(p).show()}),(_=document.getElementById("saveTransferCodeBtn"))==null||_.addEventListener("click",async()=>{var d;const t=document.getElementById("transferCodeInput").value;if(e!==null){await V(e,{epp_code:t});const p=await M();A(p),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"saveEpp"}}))}(d=q.getInstance(document.getElementById("transferCodeModal")))==null||d.hide()});let o=null,i={},a=0;document.addEventListener("click",async t=>{var l,h,F;const d=t.target.closest('[data-action="openExtraFields"]');if(!d)return;const p=++a,s=parseInt(d.getAttribute("data-index")),n=(h=(l=window.__basketCurrentSummary)==null?void 0:l.items)==null?void 0:h[s],f=await W(n==null?void 0:n.tld_id);if(p!==a)return;o=s,i=f;const y=document.getElementById("extraFieldsModal"),r=y.querySelector("#extraFieldsModalBody");Object.keys(f).length===0?r.innerHTML=`<div class="text-muted">${((F=window.translations)==null?void 0:F.store_basket_extra_fields_none)||"Bu TLD için ek kayıt bilgisi gerekmiyor."}</div>`:(r.innerHTML=le(f,(n==null?void 0:n.additional_fields)||{}),r.querySelectorAll("[data-extra-field]").forEach(k=>{k.addEventListener("change",()=>ee(f)),k.addEventListener("input",()=>ee(f))})),new q(y).show()}),(v=document.getElementById("saveExtraFieldsBtn"))==null||v.addEventListener("click",async()=>{var t;if(o!==null&&i&&Object.keys(i).length>0){await V(o,{additional_fields:ie()});const d=await M();A(d),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"saveExtraFields"}}))}(t=q.getInstance(document.getElementById("extraFieldsModal")))==null||t.hide()}),document.addEventListener("click",async t=>{var d,p,s,n;if(t.target.closest("#confirmOrderBtn")){const f=t.target.closest("#confirmOrderBtn"),y=await M();if(!y||!y.items||y.items.length===0){window.showWarning(((d=window.translations)==null?void 0:d.store_basket_empty)||"Sepetiniz boş. Lütfen ürün ekleyiniz.");return}try{for(const l of y.items){if(l.type!=="domain"||!l.tld_id)continue;const h=await W(l.tld_id);if(Object.keys(h).length===0)continue;if(Q(h,l.additional_fields||{}).length>0){const k=((p=window.translations)==null?void 0:p.store_basket_extra_fields_complete_first)||"Please complete the missing registration info before checkout.";(window.showWarning||window.showError||window.alert)(k);return}}}catch(l){console.warn("[Basket] extra-fields guard error",l)}f.disabled=!0;const r=f.innerHTML;f.innerHTML='<i class="fas fa-spinner fa-spin me-2"></i>'+(((s=window.translations)==null?void 0:s.store_checkout_processing)||"İşleniyor...");try{const l=window.checkoutUrl||"/checkout";window.location.href=l}catch(l){console.error("Checkout redirect error:",l),f.disabled=!1,f.innerHTML=r,window.showError(((n=window.translations)==null?void 0:n.store_checkout_error)||"Checkout sayfasına yönlendirilirken hata oluştu.")}}});let c=null,m=null;document.addEventListener("click",async t=>{var s,n;const d=t.target.closest('[data-action="editProduct"]');if(!d)return;c=parseInt(d.getAttribute("data-index"));const p=(n=(s=window.__basketCurrentSummary)==null?void 0:s.items)==null?void 0:n[c];!p||!p.product_id||(window.__currentEditItem=p,await u(p))});async function u(t){var s,n,f,y;const d=document.getElementById("productEditModal"),p=new q(d);document.getElementById("productEditLoading").style.display="block",document.getElementById("productEditContent").style.display="none",p.show();try{const r=(n=(s=window.__basketCurrentSummary)==null?void 0:s.currency)==null?void 0:n.id,l=t.period||1;if(!r||!l)throw new Error("Currency ve period bilgileri eksik");const h=((y=(f=window.routes)==null?void 0:f.productConfigOptions)==null?void 0:y.replace(":id",t.product_id))||`/storeapi/store/products/${t.product_id}/config-options`,k=await(await fetch(`${h}?currency=${r}&period=${l}`)).json();if(k.success&&k.data)m=k.data,g(t,k.data);else throw new Error("Config options yüklenemedi")}catch(r){console.error("Product edit modal error:",r),window.showError("Ürün bilgileri yüklenirken hata oluştu."),p.hide()}}function g(t,d){var f,y;document.getElementById("productEditLoading").style.display="none",document.getElementById("productEditContent").style.display="block",document.getElementById("productEditName").textContent=t.name||"",document.getElementById("productEditSubtitle").textContent=t.subtitle||"";const p=t.available_periods||[1,3,6,12,24,36],s=t.period||1,n=p.map(r=>{var l;return`
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="edit_period" id="edit_period_${r}"
                       value="${r}" ${r===s?"checked":""}>
                <label class="form-check-label" for="edit_period_${r}">
                    ${r} ${((l=window.translations)==null?void 0:l.store_products_period_month)||"Ay"}
                </label>
            </div>
        `}).join("");if(document.getElementById("productEditPeriods").innerHTML=n,d.config_option_groups&&d.config_option_groups.length>0){let r='<div class="mb-4">';r+=`<h6 class="mb-3">${((f=window.translations)==null?void 0:f.store_products_configurable_options)||"Konfigürasyon Seçenekleri"}</h6>`,d.config_option_groups.forEach(l=>{r+=b(l,d.currencies,t)}),r+="</div>",document.getElementById("productEditConfigOptions").innerHTML=r,I()}else document.getElementById("productEditConfigOptions").innerHTML="";if(d.custom_fields&&d.custom_fields.length>0){let r='<div class="mb-4">';r+=`<h6 class="mb-3">${((y=window.translations)==null?void 0:y.store_products_custom_fields)||"Ek Bilgiler"}</h6>`,r+='<div class="row g-3">',d.custom_fields.forEach(l=>{var F;const h=((F=t.customFields)==null?void 0:F[l.id])||"";r+='<div class="col-12">',l.type==="select"||l.type==="dropdown"?(r+=`<label class="form-label">${l.label} ${l.required?'<span class="text-danger">*</span>':""}</label>`,r+=`<select class="form-select" name="custom_fields[${l.id}]" ${l.required?"required":""}>`,r+='<option value="">--</option>',l.options&&l.options.forEach(k=>{const N=typeof k=="object"?k.value||k.label||"":k,K=typeof k=="object"?k.label||k.value||"":k;r+=`<option value="${N}" ${String(N)===String(h)?"selected":""}>${K}</option>`}),r+="</select>"):l.type==="textarea"?(r+=`<label class="form-label">${l.label} ${l.required?'<span class="text-danger">*</span>':""}</label>`,r+=`<textarea class="form-control" name="custom_fields[${l.id}]" placeholder="${l.placeholder||""}" ${l.required?"required":""}>${h}</textarea>`):l.type==="checkbox"?(r+='<div class="form-check">',r+=`<input type="checkbox" class="form-check-input" id="cf_edit_${l.id}" name="custom_fields[${l.id}]" value="1" ${String(h)==="1"?"checked":""}>`,r+=`<label class="form-check-label" for="cf_edit_${l.id}">${l.label} ${l.required?'<span class="text-danger">*</span>':""}</label>`,r+="</div>"):(r+=`<label class="form-label">${l.label} ${l.required?'<span class="text-danger">*</span>':""}</label>`,r+=`<input type="text" class="form-control" name="custom_fields[${l.id}]" value="${h}" placeholder="${l.placeholder||""}" ${l.required?"required":""}>`),r+="</div>"}),r+="</div></div>",document.getElementById("productEditCustomFields").innerHTML=r}else document.getElementById("productEditCustomFields").innerHTML="";document.querySelectorAll('#productEditModal input[name="edit_period"]').forEach(r=>{r.removeEventListener("change",x),r.addEventListener("change",function(){console.log("Period changed from modal to:",this.value),x()})}),setTimeout(()=>{x()},100)}(H=document.getElementById("saveProductEditBtn"))==null||H.addEventListener("click",async()=>{var y;if(c===null)return;const t=document.querySelector('input[name="edit_period"]:checked');if(!t)return;const d=parseInt(t.value);console.log("Saving product edit with period:",d);const p={};document.querySelectorAll('.cfg-select, .cfg-checkbox:checked, .cfg-number, input[type="range"]').forEach(r=>{if(r.value){const l=r.name.match(/config_options\[(\d+)\]/);if(l){const h=l[1];r.type==="checkbox"&&r.name.includes("[]")?(p[h]||(p[h]=[]),p[h].push(r.value)):p[h]=r.value}}});const s={};document.querySelectorAll('select[name^="custom_fields"], input[name^="custom_fields"], textarea[name^="custom_fields"]').forEach(r=>{const l=r.name.match(/custom_fields\[(\d+)\]/);if(!l)return;const h=l[1];r.type==="checkbox"?s[h]=r.checked?"1":"0":r.value.trim()&&(s[h]=r.value.trim())});const n={period:d,config_options:p,custom_fields:s};console.log("Sending update data:",n),await V(c,n);const f=await M();A(f),(y=q.getInstance(document.getElementById("productEditModal")))==null||y.hide(),window.dispatchEvent(new CustomEvent("basketUpdated",{detail:{source:"editProduct"}}))});function b(t,d,p){let s='<div class="card mb-3">';return s+=`<div class="card-header"><h6 class="mb-0">${$(t.name)}</h6></div>`,s+='<div class="card-body">',t.options.forEach(n=>{s+=w(n,d,p)}),s+="</div></div>",s}function w(t,d,p){var y,r;let s=`<div class="mb-3" data-option-id="${t.id}">`;s+=`<label class="form-label">${$(t.name)}`,t.is_required&&(s+=` <span class="text-danger">*</span> <small class="text-muted">(${((y=window.translations)==null?void 0:y.store_products_config_option_required)||"Zorunlu"})</small>`),s+="</label>";const n=((r=p.configurableOptions)==null?void 0:r.filter(l=>l.option_id==t.id))||[],f=n.map(l=>l.value_id||l.value);switch(t.type){case"select":s+=E(t,d,f);break;case"checkboxgroup":s+=O(t,d,f);break;case"checkbox":s+=C(t,d,f);break;case"number":s+=B(t,d,n);break}return s+="</div>",s}function E(t,d,p){var n;let s=`<select class="form-select cfg-select" name="config_options[${t.id}]" data-option-id="${t.id}">`;return s+=`<option value="">${((n=window.translations)==null?void 0:n.store_products_select_option)||"Seçiniz"}</option>`,t.config_values&&t.config_values.length>0&&t.config_values.forEach(f=>{const y=p.includes(f.id.toString())||p.includes(f.id);if(s+=`<option value="${f.id}" data-value-id="${f.id}" ${y?"selected":""}>`,s+=$(f.value),f.pricing&&f.pricing.price){const r=f.pricing.prefix||f.pricing.suffix||f.pricing.code;s+=` - ${r}${parseFloat(f.pricing.price).toFixed(2)}`}s+="</option>"}),s+="</select>",s}function O(t,d,p){let s="";return t.config_values&&t.config_values.length>0&&t.config_values.forEach(n=>{const f=p.includes(n.id.toString())||p.includes(n.id);if(s+='<div class="form-check">',s+='<input class="form-check-input cfg-checkbox" type="checkbox" ',s+=`id="cfg_${t.id}_${n.id}" `,s+=`data-option-id="${t.id}" `,s+=`data-value-id="${n.id}" `,s+=`name="config_options[${t.id}][]" `,s+=`value="${n.id}" ${f?"checked":""}>`,s+=`<label class="form-check-label" for="cfg_${t.id}_${n.id}">`,s+=$(n.value),n.pricing&&n.pricing.price){const y=n.pricing.prefix||n.pricing.suffix||n.pricing.code;s+=` - ${y}${parseFloat(n.pricing.price).toFixed(2)}`}s+="</label></div>"}),s}function C(t,d,p){const s=p.length>0;let n='<div class="form-check">';if(n+='<input class="form-check-input cfg-checkbox" type="checkbox" ',n+=`id="cfg_${t.id}" `,n+=`data-option-id="${t.id}" `,n+=`name="config_options[${t.id}]" `,n+=`value="1" ${s?"checked":""}>`,n+=`<label class="form-check-label" for="cfg_${t.id}">`,n+=$(t.name),t.pricing&&t.pricing.price){const f=t.pricing.prefix||t.pricing.suffix||t.pricing.code;n+=` - ${f}${parseFloat(t.pricing.price).toFixed(2)}`}return n+="</label></div>",n}function B(t,d,p){const s=p.length>0&&p[0].quantity?p[0].quantity:t.minimum||0;let n="",f="";return t.pricing&&t.pricing.price&&(f=` [${t.pricing.prefix||t.pricing.suffix||t.pricing.code}${parseFloat(t.pricing.price).toFixed(2)}]`),t.minimum!==null&&t.maximum!==null&&t.maximum-t.minimum<100?(n+='<div class="range-slider-container">',n+='<div class="d-flex align-items-center gap-3">',n+='<div class="range-slider-wrapper flex-grow-1">',n+='<input type="range" class="form-range" ',n+=`min="${t.minimum}" max="${t.maximum}" `,n+=`step="1" value="${s}" `,n+=`name="config_options[${t.id}]" `,n+=`data-option-id="${t.id}" `,n+=`id="range_${t.id}">`,n+="</div>",n+=`<div class="price-display"><span class="badge bg-primary range-value">${s}</span> x ${f}</div>`,n+="</div>",n+="</div>"):(n+='<input type="number" class="form-control cfg-number" ',n+=`name="config_options[${t.id}]" `,n+=`data-option-id="${t.id}" `,n+=`value="${s}" `,n+=`min="${t.minimum||0}" `,t.maximum!==null&&(n+=`max="${t.maximum}" `),n+=`placeholder="${t.minimum||0} - ${t.maximum||"∞"}">`,n+=`<small class="text-muted">${f} per unit</small>`),n}function I(){console.log("Adding config options event listeners..."),document.querySelectorAll('input[type="range"]').forEach(t=>{t.addEventListener("input",function(){this.dataset.optionId;const d=this.value,p=this.closest(".range-slider-container").querySelector(".range-value");p&&(p.textContent=d),x()})}),document.querySelectorAll("#productEditModal .cfg-select, #productEditModal .cfg-checkbox, #productEditModal .cfg-number").forEach(t=>{t.removeEventListener("change",x),t.addEventListener("change",function(){console.log("Config option changed:",this.name,this.value),x()})}),document.querySelectorAll('#productEditModal select[name^="custom_fields"], #productEditModal input[name^="custom_fields"], #productEditModal textarea[name^="custom_fields"]').forEach(t=>{t.removeEventListener("change",x),t.addEventListener("change",function(){console.log("Custom field changed:",this.name,this.value),x()})})}let T;async function x(){console.log("calculateModalPrice called"),clearTimeout(T),T=setTimeout(async()=>{var t,d,p,s,n,f;try{console.log("Starting price calculation...");const y=document.getElementById("productEditPrice");y&&(y.innerHTML='<span class="spinner-border spinner-border-sm" role="status"></span>');const r=document.querySelector('input[name="edit_period"]:checked');if(!r){console.log("No period selected");return}const l=parseInt(r.value),h=(d=(t=window.__basketCurrentSummary)==null?void 0:t.currency)==null?void 0:d.id,F=(p=window.__currentEditItem)==null?void 0:p.product_id;if(console.log("Price calculation data:",{period:l,currency:h,productId:F}),!h||!F)return;const k={};document.querySelectorAll('.cfg-select, .cfg-checkbox:checked, .cfg-number, input[type="range"]').forEach(L=>{if(L.value){const U=L.name.match(/config_options\[(\d+)\]/);if(U){const D=U[1];L.type==="checkbox"&&L.name.includes("[]")?(k[D]||(k[D]=[]),k[D].push(L.value)):k[D]=L.value}}});const N={};document.querySelectorAll('select[name^="custom_fields"], input[name^="custom_fields"], textarea[name^="custom_fields"]').forEach(L=>{if(L.value.trim()){const U=L.name.match(/custom_fields\[(\d+)\]/);if(U){const D=U[1];N[D]=L.value.trim()}}});const K=await Y.calculateProductPrice(F,{period:l,currency:h,config_options:k,domain_action:((s=window.__currentEditItem)==null?void 0:s.domain_action)||null,domain_name:((n=window.__currentEditItem)==null?void 0:n.domain_name)||null,custom_fields:N});if(K.success){const L=document.getElementById("productEditPrice");L&&(L.textContent=S(K.data.total,(f=window.__basketCurrentSummary)==null?void 0:f.currency))}}catch(y){console.error("Modal fiyat hesaplama hatası:",y)}},300)}}let j=null;function fe(){const e=document.getElementById("applyPromoCodeBtn"),o=document.getElementById("promoCodeInput"),i=document.getElementById("removePromoCodeBtn");!e||!o||(e.addEventListener("click",async()=>{var c;const a=o.value.trim();if(!a){R("error",((c=window.translations)==null?void 0:c.store_basket_empty_coupon)||"Lütfen promosyon kodunu girin");return}await te(a)}),o.addEventListener("keypress",async a=>{var c;if(a.key==="Enter"){const m=o.value.trim();if(!m){R("error",((c=window.translations)==null?void 0:c.store_basket_empty_coupon)||"Lütfen promosyon kodunu girin");return}await te(m)}}),i&&i.addEventListener("click",async()=>{await ge()}))}async function te(e){var a,c,m,u;const o=document.getElementById("applyPromoCodeBtn");document.getElementById("promoCodeFeedback");const i=o.textContent;o.disabled=!0,o.innerHTML='<i class="fas fa-spinner fa-spin"></i>';try{const g=(a=window.routes)==null?void 0:a.basketApplyCoupon,b=await Z.post(g,{coupon_code:e});if(b.success){j=e,R("success",((c=window.translations)==null?void 0:c.store_basket_promo_code_applied)||"Promosyon kodu uygulandı"),G(e);try{window.procpFireCustomEvent&&window.procpFireCustomEvent("CouponApplied",{code:e,discount_amount:Number(b.discount_amount||0)})}catch(E){console.warn("[tracking] CouponApplied emit failed",E)}const w=await M();A(w)}else{try{window.procpFireCustomEvent&&window.procpFireCustomEvent("CouponRejected",{code:e,error:b.message||"unknown"})}catch(w){console.warn("[tracking] CouponRejected emit failed",w)}R("error",b.message||((m=window.translations)==null?void 0:m.store_basket_invalid_promo_code)||"Geçersiz promosyon kodu")}}catch(g){console.error("Promo code apply error:",g);try{window.procpFireCustomEvent&&window.procpFireCustomEvent("CouponRejected",{code:e,error:"network"})}catch(b){console.warn("[tracking] CouponRejected emit failed",b)}R("error",((u=window.translations)==null?void 0:u.store_basket_invalid_promo_code)||"Geçersiz promosyon kodu")}finally{o.disabled=!1,o.textContent=i}}async function ge(){var o,i;const e=document.getElementById("removePromoCodeBtn");e&&(e.disabled=!0,e.innerHTML='<i class="fas fa-spinner fa-spin"></i>');try{const a=(o=window.routes)==null?void 0:o.basketRemoveCoupon;await Z.delete(a),j=null,R("info",((i=window.translations)==null?void 0:i.store_basket_promo_code_removed)||"Promosyon kodu kaldırıldı"),G(null);const c=await M();A(c)}catch(a){console.error("Promo code remove error:",a),R("error","Promosyon kodu kaldırılırken hata oluştu")}finally{e&&(e.disabled=!1,e.innerHTML='<i class="fas fa-times"></i>')}}function G(e){const o=document.getElementById("appliedPromoCodeSection"),i=document.getElementById("promoCodeInputSection"),a=document.getElementById("appliedPromoCodeText"),c=document.getElementById("promoCodeInput");e?(o&&(o.style.display="block"),i&&(i.style.display="none"),a&&(a.textContent=e),c&&(c.value="")):(o&&(o.style.display="none"),i&&(i.style.display="block"),c&&(c.value=""))}function R(e,o){const i=document.getElementById("promoCodeFeedback");i&&(i.style.display="block",i.className=`small ${e==="success"?"text-success":e==="error"?"text-danger":"text-info"}`,i.textContent=o,(e==="success"||e==="info")&&setTimeout(()=>{i.style.display="none"},3e3))}async function ye(){const e=document.getElementById("configureNameserversBtn"),o=document.getElementById("configureContactsBtn"),i=document.getElementById("saveBulkNameserversBtn"),a=document.getElementById("saveBulkContactsBtn");e&&e.addEventListener("click",async()=>{await ne("nameservers"),new q(document.getElementById("bulkNameserversModal")).show()}),o&&o.addEventListener("click",async()=>{await ne("contacts"),new q(document.getElementById("bulkContactsModal")).show()}),i&&i.addEventListener("click",async()=>{await be()}),a&&a.addEventListener("click",async()=>{await we()})}function ne(e){var o,i;if(e==="nameservers"){const a=((o=window.storeConfig)==null?void 0:o.defaultNameservers)||[];for(let c=0;c<4;c++){const m=document.getElementById(`bulkNs${c+1}`);m&&!m.value&&(m.value=a[c]||"")}}else if(e==="contacts"){const a=((i=window.storeConfig)==null?void 0:i.defaultContacts)||{},c={first_name:"bulkContactFirstName",last_name:"bulkContactLastName",company:"bulkContactCompanyName",email:"bulkContactEmail",phone:"bulkContactPhone",address1:"bulkContactAddress1",address2:"bulkContactAddress2",city:"bulkContactCity",state:"bulkContactState",postcode:"bulkContactPostcode",country:"bulkContactCountry"};Object.keys(a).forEach(m=>{const u=document.getElementById(c[m]||"");u&&!u.value&&(u.value=a[m]||"")})}}async function be(){var i;const e=document.getElementById("saveBulkNameserversBtn"),o=e.innerHTML;try{e.disabled=!0,e.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>Kaydediliyor...';const a=[];for(let u=1;u<=4;u++){const g=(i=document.getElementById(`bulkNs${u}`))==null?void 0:i.value.trim();g&&a.push(g)}if(a.length<2){window.showWarning("En az 2 nameserver girmelisiniz");return}const m=await Z.post("/storeapi/store/basket/bulk-nameservers",{nameservers:a});if(m.success){const u=q.getInstance(document.getElementById("bulkNameserversModal"));u==null||u.hide(),window.showSuccess(m.message||"Nameserver bilgileri kaydedildi");const g=await M();A(g)}else window.showError(m.message||"Hata oluştu")}catch(a){console.error("Error saving bulk nameservers:",a),window.showError("Nameserver bilgileri kaydedilirken hata oluştu")}finally{e.disabled=!1,e.innerHTML=o}}async function we(){var i,a,c,m,u,g,b,w,E,O,C;const e=document.getElementById("saveBulkContactsBtn"),o=e.innerHTML;try{e.disabled=!0,e.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>Kaydediliyor...';const B={first_name:(i=document.getElementById("bulkContactFirstName"))==null?void 0:i.value.trim(),last_name:(a=document.getElementById("bulkContactLastName"))==null?void 0:a.value.trim(),company:(c=document.getElementById("bulkContactCompanyName"))==null?void 0:c.value.trim(),email:(m=document.getElementById("bulkContactEmail"))==null?void 0:m.value.trim(),phone:(u=document.getElementById("bulkContactPhone"))==null?void 0:u.value.trim(),address1:(g=document.getElementById("bulkContactAddress1"))==null?void 0:g.value.trim(),address2:(b=document.getElementById("bulkContactAddress2"))==null?void 0:b.value.trim(),city:(w=document.getElementById("bulkContactCity"))==null?void 0:w.value.trim(),state:(E=document.getElementById("bulkContactState"))==null?void 0:E.value.trim(),postcode:(O=document.getElementById("bulkContactPostcode"))==null?void 0:O.value.trim(),country:(C=document.getElementById("bulkContactCountry"))==null?void 0:C.value.trim()};if(["first_name","last_name","email","phone","address1","city","postcode","country"].filter(v=>!B[v]).length>0){window.showWarning("Lütfen tüm zorunlu alanları doldurun");return}const _=await Z.post("/storeapi/store/basket/bulk-contacts",B);if(_.success){const v=q.getInstance(document.getElementById("bulkContactsModal"));v==null||v.hide(),window.showSuccess(_.message||"İletişim bilgileri kaydedildi");const H=await M();A(H)}else window.showError(_.message||"Hata oluştu")}catch(B){console.error("Error saving bulk contacts:",B),window.showError("İletişim bilgileri kaydedilirken hata oluştu")}finally{e.disabled=!1,e.innerHTML=o}}async function oe(){pe(),fe(),ye();const e=await M();A(e)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",oe):oe();
