const i=window.storeUpgradeConfig||{},d={productId:null,productName:null,period:null,selections:{options:[],custom_fields:[],drops_acknowledged:!1,edit_optional_unlocked:!1},pendingCompatibility:null};function p(t){return String(t).replace(/[&<>"']/g,l=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[l])}function B(t,l,r){const e=p(t.label||`Field #${t.field_id}`),a=r?' <span class="text-danger">*</span>':"",_=r?" required":"",v=`${l}="${t.field_id}"`;let b;switch(t.type){case"checkbox":b=`<div class="form-check"><input type="checkbox" class="form-check-input" value="1" ${v}></div>`;break;case"dropdown":{const h=(t.options||[]).map(m=>{const y=m&&typeof m=="object"?m.value??"":m,g=m&&typeof m=="object"?m.label??m.value??"":m;return`<option value="${p(y)}">${p(g)}</option>`}).join("");b=`<select class="form-select" ${v}${_}><option value="">—</option>${h}</select>`;break}case"textarea":b=`<textarea class="form-control" ${v}${_}></textarea>`;break;default:b=`<input type="text" class="form-control" ${v}${_}>`}return`<div class="mb-2"><label class="form-label">${e}${a}</label>${b}</div>`}function E(){const t=document.getElementById("continue-btn");t&&(t.disabled=!(d.productId&&d.period))}function T(t){document.querySelectorAll(".product-card").forEach(l=>l.classList.remove("selected")),t.classList.add("selected"),d.productId=parseInt(t.dataset.productId,10),d.productName=t.dataset.productName||"",d.period=null,d.selections={options:[],custom_fields:[],drops_acknowledged:!1,edit_optional_unlocked:!1},d.pendingCompatibility=null,M(),E()}function M(){const t=document.getElementById("period-section"),l=document.getElementById("period-buttons"),r=document.getElementById("selected-product-name");if(!t||!l)return;const e=(i.targetsByProduct||[]).find(a=>a.product_id===d.productId);if(!e){t.classList.add("d-none");return}r.textContent=e.product_name,t.classList.remove("d-none"),l.innerHTML=e.periods.map(a=>{const _=i.periodLabels[a.period]||`${a.period} mo`,v=Number(a.amount).toFixed(2);return`
            <div class="col-md-4 col-sm-6">
                <label class="period-btn d-block">
                    <input type="radio" name="selected_period" value="${a.period}">
                    <div class="period-label">
                        <div class="fw-semibold">${p(_)}</div>
                        <div class="small mt-1">${v}</div>
                    </div>
                </label>
            </div>
        `}).join(""),l.querySelectorAll('input[name="selected_period"]').forEach(a=>{a.addEventListener("change",()=>{d.period=parseInt(a.value,10),E()})}),t.scrollIntoView({behavior:"smooth",block:"nearest"})}function H(t){var m,y,g,k;document.getElementById("step-select").classList.add("d-none"),document.getElementById("step-preview").classList.add("d-none"),document.getElementById("step-options").classList.remove("d-none");const l=document.getElementById("options-drops-block"),r=document.getElementById("options-drops-list");(m=t.drops)!=null&&m.length?(l.classList.remove("d-none"),r.innerHTML=t.drops.map(s=>{var f;const u=((f=s.option)==null?void 0:f.name)||s.label||`#${s.field_id||""}`;return`<li>• ${p(u)}</li>`}).join("")):l.classList.add("d-none");const e=document.getElementById("options-required-block"),a=document.getElementById("options-required-fields");(y=t.required_selections)!=null&&y.length?(e.classList.remove("d-none"),a.innerHTML=t.required_selections.map(s=>{var u;if(s.kind==="option"){const f=i.translations.options_select_placeholder||"Seç",$=(s.available_values||[]).map(n=>`<option value="${n.id}">${p(n.value)}</option>`).join("");return`<div class="mb-2">
                    <label class="form-label">${p(((u=s.option)==null?void 0:u.name)||"")} <span class="text-danger">*</span></label>
                    <select class="form-select" data-required-option="${s.option.id}" required>
                        <option value="">— ${p(f)} —</option>
                        ${$}
                    </select>
                </div>`}return B(s,"data-required-field",!0)}).join("")):(e.classList.add("d-none"),a.innerHTML="");const _=document.getElementById("options-auto-carry-block"),v=document.getElementById("options-auto-carry-fields");(g=t.auto_carry)!=null&&g.length&&v?(_.classList.remove("d-none"),v.innerHTML=t.auto_carry.map(s=>{var n,o;if(s.kind!=="option")return"";const u=((n=s.option)==null?void 0:n.name)||"",f=(o=s.value)==null?void 0:o.id,$=(s.available_values||[]).map(I=>`<option value="${I.id}" ${I.id===f?"selected":""}>${p(I.value)}</option>`).join("");return`<div class="mb-2">
                <label class="form-label">${p(u)}</label>
                <select class="form-select"
                        data-edit-option="${s.option.id}"
                        data-edit-current-value-id="${f}">
                    ${$}
                </select>
            </div>`}).join("")):_&&_.classList.add("d-none");const b=document.getElementById("options-optional-block"),h=document.getElementById("options-optional-fields");if((k=t.optional_editables)!=null&&k.length&&h){b.classList.remove("d-none");const s=i.translations.options_select_placeholder||"Seç";h.innerHTML=t.optional_editables.map(u=>{var f;if(u.kind==="option"){const $=(u.available_values||[]).map(n=>`<option value="${n.id}">${p(n.value)}</option>`).join("");return`<div class="mb-2">
                    <label class="form-label">${p(((f=u.option)==null?void 0:f.name)||"")}</label>
                    <select class="form-select" data-optional-option="${u.option.id}">
                        <option value="">— ${p(s)} —</option>
                        ${$}
                    </select>
                </div>`}return B(u,"data-optional-field",!1)}).join("")}else b&&b.classList.add("d-none");x()}function x(){var e;const t=d.pendingCompatibility;if(!t)return;let l=!0;if((e=t.drops)!=null&&e.length){const a=document.getElementById("opt-drops-ack");(!a||!a.checked)&&(l=!1)}document.querySelectorAll("[data-required-option]").forEach(a=>{a.value||(l=!1)}),document.querySelectorAll("[data-required-field]").forEach(a=>{a.type==="checkbox"?a.checked||(l=!1):(!a.value||a.value.trim()==="")&&(l=!1)});const r=document.getElementById("opt-continue-btn");r&&(r.disabled=!l)}async function S(t,l){const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","X-CSRF-TOKEN":i.csrfToken,"X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(l),credentials:"same-origin"}),e=await r.json();if(!r.ok){const a=(e==null?void 0:e.error)||(e==null?void 0:e.message)||i.translations.error_generic;throw new Error(a)}return e}async function q(){var l;if(!d.productId||!d.period)return;const t=document.getElementById("continue-btn");t&&(t.disabled=!0);try{const e=(await S(i.routes.preview,{target_product_id:d.productId,period:d.period,selections:d.selections})).data,a=(d.selections.options||[]).length>0||(d.selections.custom_fields||[]).length>0||d.selections.drops_acknowledged===!0||d.selections.edit_optional_unlocked===!0;if((l=e.compatibility)!=null&&l.needs_user_input&&!a){d.pendingCompatibility=e.compatibility,H(e.compatibility);return}const _=Number(e.tax_rate||0),v=Number(e.tax_amount||0),b=Number(e.total??e.diff),h=e.diff>0,m=e.diff<0,y=e.currency||{},g=y.prefix||"",k=y.suffix||(y.code?" "+y.code:""),s=c=>`${g}${Number(c??0).toFixed(2)}${k}`,u=c=>`${g}${Number(c??0).toFixed(4)}${k}`;let f=`
            <tr>
                <td class="text-muted">${i.translations.subtotal}</td>
                <td class="text-end">${s(e.diff)}</td>
            </tr>
        `;h&&_>0&&(f+=`
                <tr>
                    <td class="text-muted">${i.translations.tax_label} (${_}%)</td>
                    <td class="text-end">${s(v)}</td>
                </tr>
            `),f+=`
            <tr class="border-top">
                <td class="fw-semibold pt-2">${i.translations.total_label}</td>
                <td class="text-end fw-bold pt-2">${s(b)}</td>
            </tr>
        `;let $;h?$=`<div class="alert alert-warning mb-0"><strong>${i.translations.diff_pay}: ${s(b)}</strong></div>`:m?$=`<div class="alert alert-success mb-0"><strong>${i.translations.diff_refund}: ${s(Math.abs(e.diff))}</strong></div>`:$=`<div class="alert alert-secondary mb-0"><strong>${i.translations.diff_zero}</strong></div>`;const n=i.translations,o=c=>Number(c??0).toFixed(2),I=c=>Number(c??0).toFixed(4),N=e.current_daily_rate!==void 0&&e.target_daily_rate!==void 0?`
            <div class="accordion accordion-flush mb-3" id="planChangeBreakdownAccordion">
                <div class="accordion-item border rounded">
                    <h2 class="accordion-header">
                        <button class="accordion-button collapsed py-2 px-3" type="button"
                                data-bs-toggle="collapse"
                                data-bs-target="#planChangeBreakdownBody"
                                aria-expanded="false"
                                aria-controls="planChangeBreakdownBody">
                            <i class="fas fa-calculator me-2"></i>
                            <span class="fw-semibold">${n.calc_title||"Hesaplama detayı"}</span>
                            <small class="text-muted ms-2">
                                ${e.remaining_days} ${n.calc_per_day||"gün"}
                                · ${u(e.current_daily_rate)} → ${u(e.target_daily_rate)}
                            </small>
                        </button>
                    </h2>
                    <div id="planChangeBreakdownBody"
                         class="accordion-collapse collapse"
                         data-bs-parent="#planChangeBreakdownAccordion">
                        <div class="accordion-body py-3 px-3">
                            <div class="row g-3 mb-3">
                                <div class="col-md-4">
                                    <small class="text-muted">${n.remaining_days}</small>
                                    <div class="fs-5">${e.remaining_days}</div>
                                </div>
                                <div class="col-md-4">
                                    <small class="text-muted">${n.current_value}</small>
                                    <div class="fs-5">${s(e.current_value)}</div>
                                    <div class="text-muted small">
                                        ${u(e.current_daily_rate??0)} × ${e.remaining_days}
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <small class="text-muted">${n.target_value}</small>
                                    <div class="fs-5">${s(e.target_value)}</div>
                                    <div class="text-muted small">
                                        ${u(e.target_daily_rate??0)} × ${e.remaining_days}
                                    </div>
                                </div>
                            </div>
                            <table class="table table-sm mb-0 align-middle">
                                <thead class="text-muted small">
                                    <tr>
                                        <th>${n.calc_line_label||"Satır"}</th>
                                        <th class="text-end">${n.calc_current||"Mevcut"} /${n.calc_per_day||"gün"}</th>
                                        <th class="text-end">${n.calc_new||"Yeni"} /${n.calc_per_day||"gün"}</th>
                                        <th class="text-end">${n.calc_line_diff||"Etki"}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${(e.lines||[]).map(c=>{const A=c.line_diff<0?"−":c.line_diff>0?"+":"",C=c.line_diff<0?"text-success":c.line_diff>0?"text-warning":"text-muted";let w="";return c.kind==="option_carry"&&(w=`<small class="text-muted ms-1">(${p(n.line_kind_option_carry||"carry-over")})</small>`),c.kind==="option_drop"&&(w=`<small class="text-warning ms-1">(${p(c.refunded?n.line_kind_option_drop||"kaldırıldı":n.line_dropped_no_refund||"iade yok")})</small>`),c.kind==="option_add"&&(w=`<small class="text-success ms-1">(${p(n.line_kind_option_add||"yeni")})</small>`),c.kind==="option_change"&&(w=`<small class="text-info ms-1">(${p(c.from_value_label||"?")} → ${p(c.to_value_label||"?")})</small>`),`<tr>
                                            <td>
                                                <strong>${p(c.label||"-")}</strong>
                                                ${w}
                                            </td>
                                            <td class="text-end">${c.current_daily!==void 0?u(c.current_daily):"—"}</td>
                                            <td class="text-end">${c.target_daily!==void 0?u(c.target_daily):"—"}</td>
                                            <td class="text-end ${C}">${A}${s(Math.abs(c.line_diff||0))}</td>
                                        </tr>`}).join("")}
                                </tbody>
                            </table>
                            <hr class="my-2">
                            <div class="small text-muted">
                                ${n.calc_formula_label||"Formül"}:
                                <code>(${n.calc_new_daily||"yeni günlük"} − ${n.calc_current_daily||"mevcut günlük"}) × ${n.remaining_days}</code>
                            </div>
                            <div class="small mt-1">
                                = ( ${u(e.target_daily_rate)} − ${u(e.current_daily_rate)} )
                                × ${e.remaining_days}
                                = <strong>${s(e.diff)}</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `:"",j=e.current_product_id&&e.target_product_id&&e.current_product_id!==e.target_product_id,L=c=>i.periodLabels&&{monthly:i.periodLabels[1],quarterly:i.periodLabels[3],semiannually:i.periodLabels[6],semi_annually:i.periodLabels[6],"semi-annually":i.periodLabels[6],annually:i.periodLabels[12],biennially:i.periodLabels[24],triennially:i.periodLabels[36]}[c]||c,F=e.current_product_name&&e.target_product_name?`
            <div class="row g-2 align-items-stretch mb-3">
                <div class="col-md-5">
                    <div class="card border h-100">
                        <div class="card-body py-2 px-3">
                            <small class="text-muted d-block mb-1">
                                <i class="fas fa-arrow-circle-left me-1"></i>${n.from_label||"Mevcut"}
                            </small>
                            <div class="fw-semibold">${p(e.current_product_name)}</div>
                            <div class="small text-muted">
                                ${p(L(e.current_billing_cycle))}
                                · ${s(e.current_period_total)}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-center justify-content-center">
                    <i class="fas fa-arrow-right fs-3 text-primary"></i>
                </div>
                <div class="col-md-5">
                    <div class="card border-${j?"primary":"success"} h-100" style="border-width: 2px;">
                        <div class="card-body py-2 px-3">
                            <small class="text-muted d-block mb-1">
                                <i class="fas fa-arrow-circle-right me-1"></i>${n.to_label||"Yeni"}
                            </small>
                            <div class="fw-semibold">${p(e.target_product_name)}</div>
                            <div class="small text-muted">
                                ${p(L(e.target_billing_cycle))}
                                · ${s(e.target_period_total)}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `:"";document.getElementById("preview-content").innerHTML=`
            ${F}
            ${N}
            <div class="card border-0 bg-body-tertiary mb-3">
                <div class="card-body py-2">
                    <table class="table table-sm mb-0 align-middle">
                        <tbody>
                            ${f}
                        </tbody>
                    </table>
                </div>
            </div>
            ${$}
        `,document.getElementById("step-select").classList.add("d-none"),document.getElementById("step-preview").classList.remove("d-none"),window.scrollTo({top:0,behavior:"smooth"})}catch(r){t&&(t.disabled=!1),alert(r.message||i.translations.error_generic)}}function O(){d.selections={options:[],custom_fields:[],drops_acknowledged:!1,edit_optional_unlocked:!1},d.pendingCompatibility=null,document.getElementById("step-preview").classList.add("d-none"),document.getElementById("step-select").classList.remove("d-none"),document.getElementById("continue-btn")&&E()}async function P(){if(!d.productId||!d.period)return;const t=document.getElementById("confirm-btn");t&&(t.disabled=!0);try{const r=(await S(i.routes.execute,{target_product_id:d.productId,period:d.period,selections:d.selections})).data||{};if(r.outcome==="aborted_paid_in_progress"){alert(i.translations.aborted_paid_in_progress||"There is already a paid upgrade in progress for this service. Please wait until it completes."),t&&(t.disabled=!1),window.location=r.redirect;return}if(r.outcome==="no_change"){alert(i.translations.no_change_notice||"Hiçbir değişiklik yapılmadı."),t&&(t.disabled=!1);return}if(r.cancelled_invoice_id&&alert(i.translations.cancelled_notice),r.outcome==="applied"){const a=r.direction==="downgrade"?i.translations.applied_downgrade||"Plan change applied (downgrade).":i.translations.applied_same||"Plan change applied.";alert(a)}window.location=r.redirect}catch(l){t&&(t.disabled=!1),alert(l.message||i.translations.error_generic)}}document.addEventListener("DOMContentLoaded",()=>{var t,l,r,e,a,_,v,b,h,m,y;document.querySelectorAll(".product-card").forEach(g=>{g.addEventListener("click",()=>T(g))}),(t=document.getElementById("continue-btn"))==null||t.addEventListener("click",q),(l=document.getElementById("back-btn"))==null||l.addEventListener("click",O),(r=document.getElementById("confirm-btn"))==null||r.addEventListener("click",P),(e=document.getElementById("opt-back-btn"))==null||e.addEventListener("click",()=>{d.selections={options:[],custom_fields:[],drops_acknowledged:!1,edit_optional_unlocked:!1},document.getElementById("step-options").classList.add("d-none"),document.getElementById("step-select").classList.remove("d-none")}),(a=document.getElementById("options-drops-block"))==null||a.addEventListener("change",x),(_=document.getElementById("options-required-block"))==null||_.addEventListener("change",x),(v=document.getElementById("options-required-block"))==null||v.addEventListener("input",x),(b=document.getElementById("options-auto-carry-block"))==null||b.addEventListener("change",x),(h=document.getElementById("options-optional-block"))==null||h.addEventListener("change",x),(m=document.getElementById("options-optional-block"))==null||m.addEventListener("input",x),(y=document.getElementById("opt-continue-btn"))==null||y.addEventListener("click",()=>{const g=document.getElementById("opt-drops-ack");d.selections.drops_acknowledged=(g==null?void 0:g.checked)||!1;const k=Array.from(document.querySelectorAll("[data-required-option]")).map(o=>({option_id:parseInt(o.dataset.requiredOption,10),value_id:parseInt(o.value,10)})).filter(o=>Number.isFinite(o.option_id)&&Number.isFinite(o.value_id)),s=Array.from(document.querySelectorAll("[data-optional-option]")).map(o=>({option_id:parseInt(o.dataset.optionalOption,10),value_id:parseInt(o.value,10)})).filter(o=>Number.isFinite(o.option_id)&&Number.isFinite(o.value_id)),u=Array.from(document.querySelectorAll("[data-edit-option]")).map(o=>({option_id:parseInt(o.dataset.editOption,10),value_id:parseInt(o.value,10),_orig:parseInt(o.dataset.editCurrentValueId,10)})).filter(o=>Number.isFinite(o.option_id)&&Number.isFinite(o.value_id)&&o.value_id!==o._orig).map(({option_id:o,value_id:I})=>({option_id:o,value_id:I}));d.selections.options=[...k,...s,...u];const f=o=>o.type==="checkbox"?o.checked?"1":"0":o.value,$=Array.from(document.querySelectorAll("[data-required-field]")).map(o=>({field_id:parseInt(o.dataset.requiredField,10),value:f(o)})).filter(o=>Number.isFinite(o.field_id)),n=Array.from(document.querySelectorAll("[data-optional-field]")).map(o=>({field_id:parseInt(o.dataset.optionalField,10),value:f(o)})).filter(o=>Number.isFinite(o.field_id)&&o.value!=="");d.selections.custom_fields=[...$,...n],d.selections.edit_optional_unlocked=!0,document.getElementById("step-options").classList.add("d-none"),q()})});
