(function(){"use strict";const $="kginicis_pay_form_",D="__sirsoftKginicisReloadStandardPaySdk",b="__sirsoftKginicisMobilePaymentReturnPending";function he(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${$}"]`);return e.forEach(t=>t.remove()),e.length}function gt(){typeof window>"u"||(window[D]=!0)}function _t(){if(typeof window>"u")return!1;const e=window,t=e[D]===!0;return delete e[D],t}function wt(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function bt(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(b,String(e))}catch{window[b]=e}}function B(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(b)}catch{}delete window[b]}}function ge(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(b);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[b];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(B(),!1):!0}const j="sirsoft-pay_kginicis",kt=j,Pt="payment-window-closed",_e="__sirsoftKginicisPaymentCloseListenerInstalled",Y="__sirsoftKginicisActiveStandardPaymentCloseContext",we=20,xt=100,U={info:(...e)=>console.info(`[${j}]`,...e),warn:(...e)=>console.warn(`[${j}]`,...e)};function Ct(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===kt&&t.type===Pt}function H(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function A(){return window}function Et(){const e=A()[Y];return!e||typeof e!="object"?null:e}function vt(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function St(e){e.closeReportUrl&&(A()[Y]={...e,reported:!1})}function be(){delete A()[Y]}function ke(){be()}async function It(e="payment-window-closed"){const t=Et();if(!t||t.reported||!H())return;t.reported=!0;const n={oid:t.oid,price:t.price,buyer_email:t.buyer_email??"",buyer_phone:t.buyer_phone??"",payment_method:t.payment_method??"",reason:e};try{const r=window.G7Core?.api;typeof r?.post=="function"?await r.post(t.closeReportUrl,n):await fetch(vt(t.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(r){U.warn("failed to report KG payment window close",{reason:e,error:r})}finally{be()}}function Pe(e="payment-window-closed",t=!0){if(!H())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&U.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(he(),gt(),r({isSubmittingOrder:!1}),U.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function At(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!ge())){if(Pe(e,n>=we)){t&&B();return}!H()||n>=we||window.setTimeout(r,xt)}};r()}function T(e){ge()&&At(e,!0)}function Tt(){if(typeof window>"u")return;const e=A();e[_e]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&Ct(t.data)&&(It(t.data.reason),Pe(t.data.reason))}),window.addEventListener("pagehide",()=>{ke()}),window.addEventListener("beforeunload",()=>{ke()}),window.addEventListener("pageshow",t=>{T(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{T("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&T("mobile-payment-visibility-return")}),e[_e]=!0,T("mobile-payment-listener-installed"))}function xe(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function Rt(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function Ce(e,t){if(!t.startsWith("kginicis_"))return e;const n=new URL(e,window.location.origin);return n.searchParams.set("selectedPaymentMethod",t),n.toString()}function Nt(e){const t=(e??"").trim().toUpperCase();return t===""||t==="WON"?"KRW":t}function Ee(e,t,n="utf-8",r){const i=document.createElement("form");r&&(i.id=r),i.method="POST",i.action=e,i.acceptCharset=n,i.style.display="none";for(const[o,a]of Object.entries(t)){const s=document.createElement("input");s.type="hidden",s.name=o,s.value=a,i.appendChild(s)}document.body.appendChild(i),i.submit()}const Mt={card:"Card",vbank:"VBank",bank:"DirectBank",phone:"HPP",kginicis_samsung_pay:"onlyssp",kginicis_naverpay:"onlynaverpay",kginicis_lpay:"onlylpay",kginicis_kakaopay:"onlykakaopay"},Lt={card:"CARD",vbank:"VBANK",bank:"BANK",phone:"MOBILE"},Kt={kginicis_samsung_pay:"d_samsungpay=Y",kginicis_naverpay:"d_npay=Y",kginicis_lpay:"d_lpay=Y",kginicis_kakaopay:"d_kakaopay=Y"},Ot=["CARD","CVS","PAYpay"],ve={card:["CARD"],kginicis_japan_paypay:["PAYpay"],kginicis_japan_cvs:["CVS"]},Gt=new Set(Object.keys(ve)),$t=new Set(["kginicis_samsung_pay","kginicis_naverpay","kginicis_lpay","kginicis_kakaopay"]);async function Dt(e,t,n,r){const i=String(Math.floor(Date.now())),o=await e.api.post(t.callback_urls.mobile_signature,{oid:n.order_number,price:n.amount,timestamp:i,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),{chkfake:a,mobile_payment_url:s}=o.data,c=Ce(window.location.origin+t.callback_urls.mobile_callback+"?orderId="+encodeURIComponent(n.order_number),r),l=Kt[r],d=l!==void 0,u=d?s.replace(/\/smart\/[^/]+\/?$/,"/smart/wcard/"):s,f=Lt[r]??"CARD",p=t.use_escrow?"below1000=Y&vbank_receipt=Y&useescrow=Y¢erCd=Y&amt_hash=Y":"below1000=Y&vbank_receipt=Y¢erCd=Y&amt_hash=Y",m=d?p.replace("&useescrow=Y","")+"&"+l:p,y={P_MID:t.mid,P_OID:n.order_number,P_AMT:String(n.amount),P_GOODS:n.order_name,P_UNAME:n.customer_name??"",P_MOBILE:n.customer_phone??"",P_EMAIL:n.customer_email??"",P_NEXT_URL:c,P_CHARSET:"utf8",P_TIMESTAMP:i,P_CHKFAKE:a,P_RESERVED:m};d?y.P_SKIP_TERMS="Y":y.P_INI_PAYMENT=f,f==="MOBILE"&&!d&&(y.P_HPP_METHOD="2"),f==="VBANK"&&!d&&(y.P_NOTI_URL=window.location.origin+t.callback_urls.mobile_vbank_notify),bt(),Ee(u,y,"euc-kr",$+"mobile_"+Date.now())}async function Bt(e,t,n,r){const i=String(Math.floor(Date.now())),o=await e.api.post(t.callback_urls.signature,{oid:n.order_number,price:n.amount,timestamp:i,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),{signature:a,verification:s,mKey:c}=o.data;if(_t()&&wt(t.sdk_url),window.INIStdPay||await Rt(t.sdk_url),window.INIStdPay||await new Promise(m=>setTimeout(m,100)),!window.INIStdPay)throw new Error("INIStdPay SDK not available");const l=Ce(window.location.origin+t.callback_urls.callback,r),d=window.location.origin+t.callback_urls.close;he();const u=$+Date.now(),f=document.createElement("form");f.id=u,f.method="POST",f.acceptCharset="euc-kr";const p={version:"1.0",mid:t.mid,oid:n.order_number,goodname:n.order_name,price:String(n.amount),currency:"WON",buyername:n.customer_name??"",buyeremail:n.customer_email??"",buyertel:n.customer_phone??"",timestamp:i,signature:a,verification:s,mKey:c,returnUrl:l,closeUrl:d,gopaymethod:Mt[r]??"Card",acceptmethod:(()=>{const m=t.use_escrow?"useescrow:":"",y=t.use_credit_point?"CREDITCARD(Y):":"",h=r==="phone"?`HPP(1):${m}${y}centerCd(Y)`:`${m}${y}centerCd(Y)`;return r==="kginicis_samsung_pay"||r==="kginicis_naverpay"||r==="kginicis_lpay"||r==="kginicis_kakaopay"?h?`${h}:cardonly`:"cardonly":h})(),payViewType:"overlay",use_chkfake:"Y",charset:"UTF-8"};for(const[m,y]of Object.entries(p)){const h=document.createElement("input");h.type="hidden",h.name=m,h.value=y,f.appendChild(h)}document.body.appendChild(f),t.callback_urls.close_report&&St({closeReportUrl:t.callback_urls.close_report,oid:n.order_number,price:Number(n.amount),buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??"",payment_method:r}),window.INIStdPay.pay(u)}function jt(e=new Date){const t=n=>String(n).padStart(2,"0");return e.getFullYear().toString()+t(e.getMonth()+1)+t(e.getDate())+t(e.getHours())+t(e.getMinutes())+t(e.getSeconds())}function Yt(e,t){const n=e.cbt_extra_data??{},i=(t?ve[t]:void 0)??n.payment?.paymethod??Ot,o=window.location.origin+e.callback_urls.cbt_cvs_notify;return{...n,paymentUI:{language:"JP",...n.paymentUI??{}},payment:{...n.payment??{},paymethod:i,isMobile:xe()?"true":"false",cvs:{...n.payment?.cvs??{},notiUrl:o}}}}async function Ut(e,t,n,r){const i=t.japan_mid,o=jt(),a=n.customer_email??"",s=n.customer_phone??"",c=await e.api.post(t.callback_urls.cbt_checkout_token,{oid:n.order_number,price:n.amount,buyer_email:a,buyer_phone:s}),{checkout_token:l}=c.data,d=await e.api.post(t.callback_urls.cbt_hash_data,{oid:n.order_number,price:n.amount,timestamp:o,buyer_email:a,buyer_phone:s,checkout_token:l}),{hash_data:u}=d.data,f=window.location.origin+t.callback_urls.cbt_callback+`?oid=${encodeURIComponent(n.order_number)}&selectedPaymentMethod=${encodeURIComponent(r??"card")}`;Ee(t.callback_urls.cbt_auth_url,{cbtType:"JPPG",mid:i,timestamp:o,returnUrl:f,buyerName:n.customer_name??"",buyerTel:n.customer_phone??"",buyerEmail:n.customer_email??"",goodName:n.order_name,amount:String(n.amount),orderId:n.order_number,hashData:u,extraData:JSON.stringify(Yt(t,r))})}async function Se(e,t){const{pgPaymentData:n,paymentMethod:r}=e.params||{};if(!n)return;const i=window.__templateApp?.globalState?._local,o=r??i?.paymentMethod??"card",a=window.G7Core;try{const s=await a.api.get("/modules/sirsoft-ecommerce/payments/client-config/kginicis");if(!s.data)throw new Error("Failed to fetch KG Inicis client config");const c=s.data,l=Nt(n.currency),d=l==="JPY",u=l==="KRW",f=o.startsWith("kginicis_japan_"),p=$t.has(o),m=c.japan_enabled&&!!c.japan_mid&&c.japan_configured!==!1,y=c.japan_restrict_jpy_payment_methods===!0;if(f&&!d)throw new Error("KG Inicis Japan payment methods require a JPY order.");if(p&&Array.isArray(c.easy_pay_enabled_methods)&&!c.easy_pay_enabled_methods.includes(o))throw new Error("Selected KG Inicis easy pay method is disabled.");if(!d&&!u)throw new Error("KG Inicis supports only KRW standard payments or JPY Japan CBT payments.");if(d&&!m)throw new Error("KG Inicis Japan CBT payment is not configured.");if(d&&y&&!Gt.has(o))throw new Error("JPY orders can only use KG Inicis Japan CBT payment methods.");const h=xe();if(u&&c.standard_configured===!1)throw new Error("KG Inicis live standard payment is not configured.");if(u&&h&&c.mobile_configured===!1)throw new Error("KG Inicis live mobile payment is not configured.");d?await Ut(a,c,n,o):h?await Dt(a,c,n,o):await Bt(a,c,n,o)}catch(s){const c=s instanceof Error?s.message:"Unknown error";a?.state?.setLocal?.({paymentErrorMessage:c,isSubmittingOrder:!1,paymentMethod:o}),a?.modal?.open?.("kginicis_payment_error_modal")}}const Ie={requestPayment:Se},Ae="/api/modules/sirsoft-ecommerce/user/orders",Ht="sirsoft-kginicis",J="sirsoft-pay_kginicis",R="__sirsoftKginicisNavigateSuppressor",k={info:(...e)=>console.info(`[${J}]`,...e),warn:(...e)=>console.warn(`[${J}]`,...e),error:(...e)=>console.error(`[${J}]`,...e)};function Jt(e){try{const t=JSON.parse(e),n=t.payment_method;if(typeof n=="string"&&n.startsWith("kginicis_")){const r=n;return t.payment_method="card",{rewritten:JSON.stringify(t),originalMethod:r}}return{rewritten:e,originalMethod:typeof n=="string"?n:void 0}}catch{return{rewritten:e,originalMethod:void 0}}}function Ft(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function Wt(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function qt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===Ae||n.endsWith(Ae)}function zt(){return window.location.pathname+window.location.search+window.location.hash}function Te(e){try{const t=new URL(e,window.location.origin);return t.pathname+t.search+t.hash}catch{return e}}function Vt(e){const t=window,r=t.__templateApp?.getRouter?.();if(!r||typeof r.navigate!="function")return;t[R]?.restore();const o=r.navigate.bind(r),a=Te(e);let s=!1,c=!1,l=0;const d=()=>{if(s)return;s=!0,r.navigate===u&&(r.navigate=o),window.clearTimeout(l),t[R]?.restore===d&&delete t[R]},u=(f,p)=>{const m=Te(f);if(!c&&m===a){c=!0,k.info("suppressed checkout self-navigation after PG popup",{path:m}),d();return}return d(),o(f,p)};l=window.setTimeout(d,3e3),r.navigate=u,t[R]={restore:d,timer:l}}function Xt(e,t){const n=JSON.stringify(t);return new Response(n,{status:e.status,statusText:e.statusText,headers:e.headers})}function Zt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftKginicisInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n="__sirsoftPgOriginalFetch";t[n]||(t[n]=window.fetch.bind(window));const r=window.fetch.bind(window);window.fetch=async function(o,a){const s=Ft(o),c=Wt(o,a);if(!qt(s,c))return r(o,a);let l,d=a;if(a?.body&&typeof a.body=="string"){const{rewritten:g,originalMethod:E}=Jt(a.body);l=E,g!==a.body&&(k.info("rewrote request payment_method",{from:E,to:"card"}),d={...a,body:g})}if(!l)try{l=window.G7Core?.state?.getLocal?.()?.paymentMethod}catch{}const u=await r(o,d);let f;try{f=u.clone()}catch{return u}let p=null;try{p=await f.json()}catch{return u}const m=p?.data;if(!m)return u;const y=typeof l=="string"&&l.startsWith("kginicis_"),h=m.requires_pg_payment===!0,Jr=m.pg_provider===Ht;if(!y&&(!h||!Jr))return u;let C=m.pg_payment_data;if(!C&&y){const g=m.order;if(g){const E=g.options,ht=E?.[0]?.product_name??String(g.order_number??""),Wr=(E?.length??0)>1?`${ht} 외 ${(E?.length??0)-1}건`:ht;C={order_number:g.order_number,order_name:Wr,amount:Math.floor(Number(g.total_amount??0)),currency:String(g.currency??g.currency_code??(l?.startsWith("kginicis_japan_")?"JPY":"KRW")),customer_name:g.orderer_name??null,customer_email:g.orderer_email??null,customer_phone:String(g.orderer_phone??"").replace(/[^0-9]/g,"")},k.info("pg_payment_data constructed from order (기본 PG 미설정 또는 다른 PG)",{order_number:C.order_number,amount:C.amount})}}if(!C)return k.warn("kginicis order detected but pg_payment_data missing"),u;k.info("intercepted order create response — opening PG popup"),Se({params:{pgPaymentData:C,paymentMethod:l}});const yt=zt();Vt(yt);const Fr={...p,data:{...m,requires_pg_payment:!1,redirect_url:yt}};return Xt(u,Fr)},k.info("order response interceptor installed")}const Qt="sirsoft-pay_kginicis";function en(){return localStorage.getItem("auth_token")}function tn(){try{const t=sessionStorage.getItem("g7_guest_order_token");if(t)return t}catch{}const e=window.G7Core?.state?.get?.("_global")?.guestOrderToken;return typeof e=="string"&&e!==""?e:null}async function Re(e,t){try{const n=await fetch(`/api/plugins/${Qt}/user/orders/${e}/receipt`,{headers:t,credentials:"same-origin"});return n.ok?{status:n.status,data:await n.json()}:{status:n.status,data:null}}catch{return{status:0,data:null}}}async function Ne(e){const t=en(),n=tn(),r={Accept:"application/json"};t?r.Authorization=`Bearer ${t}`:n&&(r["X-Guest-Order-Token"]=n);const i=await Re(e,r);if(i.data||i.status!==401||!t)return{status:i.status,info:i.data};const o={Accept:"application/json"};n&&(o["X-Guest-Order-Token"]=n);const a=await Re(e,o);return{status:a.status,info:a.data}}async function N(e){return(await Ne(e)).info}function v(e){return e?e.receipt_url?!0:e.receipt_type==="cbt_confirmation"&&Array.isArray(e.receipt_fields)&&e.receipt_fields.length>0:!1}function M(e){return e?.receipt_view_label||"영수증 조회"}function nn(e){return e?.receipt_label||"영수증"}function Me(e){if(e.receipt_url){window.open(e.receipt_url,"kginicis_receipt","width=800,height=600,scrollbars=yes,resizable=yes");return}e.receipt_type==="cbt_confirmation"&&rn(e)}function rn(e){const t=window.open("","kginicis_receipt","width=800,height=700,scrollbars=yes,resizable=yes");if(!t)return;const n=e.receipt_title||"KG 이니시스 CBT 결제확인서",r=e.receipt_notice||"",i=(e.receipt_fields??[]).map(o=>`
${S(o.label)}
${S(o.value)}
`).join("");t.document.open(),t.document.write(` ${S(n)}

${S(n)}

${r?`

${S(r)}

`:""}
${i}
`),t.document.close()}function S(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const F="sirsoft-pay_kginicis",Le="__kginicisOrderShowInjectorInstalled",W="kginicis-mp-receipt-row",Ke=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,q=new Map;function on(e){try{const n=window.G7Core?.getState,o=n?.()?.currentDataContext?.order?.data;return o&&(o.order_number===e||o.id!==void 0&&String(o.id)===e)?o:null}catch{return null}}function an(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const i=r.textContent?.trim()??"";return i.includes("결제 정보")||/^Payment Information$/i.test(i)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function sn(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const i=Array.from(r.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(i.length<2)continue;const o=i[0].textContent?.trim();if(o!=="결제 방법"&&o!=="결제수단"&&o!=="Payment Method")continue;const a=i[i.length-1];return a.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(a.textContent=t,a.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function cn(e,t){const n=document.createElement("div");n.id=W,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=nn(t);const i=document.createElement("button");return i.type="button",i.dataset.kginicisReceiptButton="mypage-order",i.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",i.textContent=M(t),i.addEventListener("click",async()=>{i.disabled=!0,i.textContent="로딩 중...";const o=await N(e);i.disabled=!1,i.textContent=M(o??t),v(o)&&Me(o)}),n.appendChild(r),n.appendChild(i),n}async function dn(e,t){const n=on(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const i=n?.order_number??(t?e:null);if(!i)return!1;if(!t&&n&&!r)return!0;const o=an();if(!o)return!1;const{status:a,info:s}=await Ne(i);if(!t&&a===404)return!0;const c=r?.payment_status==="paid",l=s?.receipt_type==="cbt_confirmation";if(r&&!c&&!l)return!0;if(!r&&!v(s))return!1;const d=sn(o,s?.payment_method_display_label);return!document.getElementById(W)&&v(s)&&(o.appendChild(cn(i,s)),console.info(`[${F}] receipt button injected on mypage order show`)),d&&console.info(`[${F}] payment method display patched on mypage order show`),!!(document.getElementById(W)||d)}function ln(e,t){if(q.has(e))return;let n=0;const r=window.setInterval(()=>{n++,dn(e,t).then(i=>{(i||n>=30)&&(window.clearInterval(r),q.delete(e))})},400);q.set(e,r)}function un(){const e=location.pathname.match(Ke);if(e){const t=e[1],n=e[2],r=t??n;r&&ln(r,n!==void 0)}}function fn(){if(typeof window>"u")return;const e=window;if(e[Le])return;e[Le]=!0,console.info(`[${F}] mypage order show injector installed`);let t=null;const n=(s=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,un()},s)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...s)=>{r(...s),n(600)};const i=history.replaceState.bind(history);history.replaceState=(...s)=>{i(...s),n(600)},window.addEventListener("popstate",()=>n(500));const o=document.getElementById("app")??document.body;new MutationObserver(()=>{Ke.test(location.pathname)&&n(250)}).observe(o,{childList:!0,subtree:!0})}const z="sirsoft-pay_kginicis",Oe="__kginicisAdminPaymentDisplayInjectorInstalled",mn=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function pn(){return localStorage.getItem("auth_token")}async function yn(e){const t=pn();if(!t)return null;try{const n=await fetch(`/api/plugins/${z}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function hn(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function gn(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const i of r){const o=hn(i),a=o.findIndex(u=>u.textContent?.trim()==="결제수단");if(a<0)continue;const s=o.slice(a+1).find(u=>u.textContent?.trim()&&u.textContent.trim()!=="결제수단");if(!s)continue;const c=o.slice(a+2).find(u=>/^\(.+\)$/.test(u.textContent?.trim()??"")),l=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=l&&t.endsWith(")")?t.replace(/\)$/,`, ${l})`):t;s.textContent?.trim()!==d&&(s.textContent=d,s.dataset.kginicisPaymentMethodPatched="true"),i.dataset.kginicisPaymentMethodRow="admin-order",c&&l&&(c.textContent="",c.style.display="none",c.dataset.kginicisPaymentInstallmentHidden="true"),n=!0}return n}function _n(e,t,n){const i=Array.from(e.querySelectorAll("span")).filter(o=>o.textContent?.trim()===t).find(o=>{const a=typeof o.className=="string"?o.className:"";return a.includes("rounded-full")||a.includes("font-medium")});return i?(i.textContent=n,i.dataset.kginicisPaymentMethodPatched="true",i.dataset.kginicisPaymentMethodBadge="admin-order",!0):!1}function wn(e,t){const n=t?._pay_method_label,r=t?._embedded_pg_provider_label,i=t?._base_pay_method_label;if(!n||!r)return!1;const o=gn(e,n),a=i?_n(e,i,r):!1;return o||a}async function bn(e){const t=document.getElementById("section_payment_info")??document.getElementById("payment_info_card");if(!t)return!1;const n=await yn(e);return n&&wn(t,n)&&console.info(`[${z}] payment method display patched on admin order detail`),!0}function kn(e){let t=0;const n=setInterval(()=>{t++,bn(e).then(r=>{(r||t>=30)&&clearInterval(n)})},400)}function Pn(){const e=location.pathname.match(mn);e&&kn(e[1])}function xn(){if(typeof window>"u")return;const e=window;if(e[Oe])return;e[Oe]=!0,console.info(`[${z}] admin order payment display injector installed`);const t=(r=1500)=>setTimeout(Pn,r);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...r)=>{n(...r),t(600)},window.addEventListener("popstate",()=>t(500))}const Ge="sirsoft-pay_kginicis",$e="__kginicisOcReceiptInjectorInstalled",De="kginicis-oc-receipt-btn",Cn=/^\/shop\/orders\/([^/]+)\/complete$/;function En(){return localStorage.getItem("auth_token")}function vn(){try{const t=sessionStorage.getItem("g7_guest_order_token");if(t)return t}catch{}const e=window.G7Core?.state?.get?.("_global")?.guestOrderToken;return typeof e=="string"&&e!==""?e:null}async function Sn(e){const t=En(),n=vn();if(!t&&!n)return null;const r={Accept:"application/json"};t?r.Authorization=`Bearer ${t}`:n&&(r["X-Guest-Order-Token"]=n);try{const i=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:r});return i.ok?(await i.json())?.data?.payment??null:null}catch{return null}}function In(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const r=Array.from(n.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(r.length<2)continue;const i=r[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="결제 방식")continue;const o=r[r.length-1];return o.textContent?.trim()===e?(n.dataset.kginicisPaymentMethodRow="true",!0):(o.textContent=e,o.dataset.kginicisPaymentMethodPatched="true",n.dataset.kginicisPaymentMethodRow="true",!0)}return!1}async function An(e){if(document.getElementById(De))return;const t=await N(e);if(!v(t))return;const n=await Sn(e);if(n){if(n.pg_provider!=="kginicis"||!n.transaction_id)return;const s=n.payment_status==="paid",c=t.receipt_type==="cbt_confirmation";if(!s&&!c)return}In(t.payment_method_display_label);const r=Array.from(document.querySelectorAll('button[type="button"]')).find(s=>s.className.includes("bg-blue-600"));if(!r?.parentElement)return;const i=r.parentElement;i.dataset.kginicisReceiptContainer="order-complete";const o=document.createElement("button");o.id=De,o.type="button",o.dataset.kginicisReceiptButton="order-complete",o.className=r.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),o.textContent=M(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const s=await N(e);o.disabled=!1,o.textContent=M(s??t),v(s)&&Me(s)});const a=i.lastElementChild;i.insertBefore(o,a),console.info(`[${Ge}] receipt button injected on order complete page`)}function Tn(){const e=location.pathname.match(Cn);e&&An(e[1])}function Rn(){if(typeof window>"u")return;const e=window;if(e[$e])return;e[$e]=!0,console.info(`[${Ge}] order complete receipt injector installed`);const t=(r=1200)=>setTimeout(Tn,r);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...r)=>{n(...r),t()},window.addEventListener("popstate",()=>t(500))}const Be="sirsoft-pay_kginicis",je="__kginicisVbankInfoInjectorInstalled",V="kginicis-mp-vbank-info",Nn=/^\/shop\/orders\/([^/]+)\/complete$/,Mn=/^\/mypage\/orders\/([^/]+)$/,Ln=/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+\-]\d{2}:\d{2}/,Kn={"03":"기업은행","04":"국민은행","05":"외환은행","07":"수협중앙회",11:"농협중앙회",20:"우리은행",23:"SC 제일은행",31:"대구은행",32:"부산은행",34:"광주은행",37:"전북은행",39:"경남은행",53:"한국씨티은행",71:"우체국",81:"하나은행",88:"신한은행",89:"케이뱅크",90:"카카오뱅크",92:"토스뱅크",D1:"동양종합금융증권",D2:"현대증권",D3:"미래에셋증권",D4:"한국투자증권",D5:"우리투자증권",D6:"하이투자증권",D7:"HMC 투자증권",D8:"SK 증권",D9:"대신증권",DA:"하나대투증권",DB:"굿모닝신한증권",DC:"동부증권",DD:"유진투자증권",DE:"메리츠증권",DF:"신영증권"};function On(e){if(e.vbank_code)return String(e.vbank_code);const t=(e.vbank_name??"").trim();if(!t)return null;for(const[n,r]of Object.entries(Kn))if(r===t)return n;return null}function Gn(){try{const t=window.G7Core?.getState;return t?.()?.currentDataContext?._global?.currentUser?.is_admin===!0}catch{return!1}}function Ye(e){try{return new Date(e).toLocaleString("ko-KR",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"Asia/Seoul"})}catch{return e}}function $n(){const e=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),t=[];let n=e.nextNode();for(;n;){const r=n.textContent??"",i=r.match(Ln);i&&t.push({node:n,formatted:r.replace(i[0],Ye(i[0]))}),n=e.nextNode()}for(const{node:r,formatted:i}of t)r.textContent=i}function Dn(e){try{const n=window.G7Core?.getState,o=n?.()?.currentDataContext?.order?.data;return!o||o.order_number!==e?null:o}catch{return null}}function Bn(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>r.textContent?.includes("결제 정보"));if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function _(e,t,n=!1){const r=document.createElement("div");r.className="flex items-center justify-between";const i=document.createElement("span");i.className="text-gray-500 dark:text-gray-400 text-sm",i.textContent=e;const o=document.createElement("span");return o.className=n?"text-sm font-medium text-blue-600 dark:text-blue-400":"text-sm text-gray-900 dark:text-gray-100",o.textContent=t,r.appendChild(i),r.appendChild(o),r}function jn(e,t){const n=document.createElement("div");n.id=V,n.className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 space-y-2";const r=document.createElement("p");if(r.className="text-sm font-semibold text-gray-700 dark:text-gray-300",r.textContent="가상계좌 입금 안내",n.appendChild(r),e.vbank_name&&n.appendChild(_("은행",e.vbank_name)),Gn()){const i=On(e);i&&n.appendChild(_("은행코드",i))}return e.vbank_number&&n.appendChild(_("계좌번호",e.vbank_number)),e.vbank_holder&&n.appendChild(_("예금주",e.vbank_holder)),t&&n.appendChild(_("입금 기한",t,!0)),n}function w(e,t){return e?.receipt_fields?.find(n=>n.label===t)?.value??""}function Yn(e,t){if(t?.receipt_type!=="cbt_confirmation")return!1;if(w(t,"결제수단").includes("편의점"))return!0;const r=String(e.transaction_id??"");return String(e.currency??"").toUpperCase()==="JPY"&&(String(e.vbank_name??"").toUpperCase()==="CVS"||r.startsWith("INIJPGCVS"))}function Un(e,t,n){const r=document.createElement("div");r.id=V,r.className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 space-y-2";const i=document.createElement("p");i.className="text-sm font-semibold text-gray-700 dark:text-gray-300",i.textContent="일본 편의점 입금 안내",r.appendChild(i);const o=w(t,"입금 상태"),a=w(t,"입금예정금액")||w(t,"결제금액"),s=w(t,"편의점 코드"),c=w(t,"편의점 확인번호")||String(e.vbank_number??""),l=w(t,"편의점 접수번호"),d=w(t,"입금 마감일시")||n;return o&&r.appendChild(_("상태",o)),a&&r.appendChild(_("입금예정금액",a,!0)),s&&r.appendChild(_("편의점 코드",s)),c&&r.appendChild(_("편의점 확인번호",c)),l&&r.appendChild(_("편의점 접수번호",l)),d&&r.appendChild(_("입금 마감일시",d,!0)),r}async function Hn(e){const t=Dn(e);if(!t)return!1;const{payment:n}=t;if(!n||n.pg_provider!=="kginicis"||n.payment_status!=="waiting_deposit"||!n.vbank_number||document.getElementById(V))return!0;const r=Bn();if(!r)return!1;const i=await N(e),o=n.vbank_due_at?Ye(n.vbank_due_at):"";return r.appendChild(Yn(n,i)?Un(n,i,o):jn(n,o)),console.info(`[${Be}] vbank info injected on mypage`),!0}function Jn(e){let t=0;const n=setInterval(()=>{t++,Hn(e).then(r=>{(r||t>=30)&&clearInterval(n)})},400)}function Fn(){if(location.pathname.match(Nn)){setTimeout($n,500);return}const t=location.pathname.match(Mn);t&&Jn(t[1])}function Wn(){if(typeof window>"u")return;const e=window;if(e[je])return;e[je]=!0,console.info(`[${Be}] vbank info injector installed`);const t=(r=800)=>setTimeout(Fn,r);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...r)=>{n(...r),t(600)},window.addEventListener("popstate",()=>t(500))}const Ue="sirsoft-pay_kginicis",He="__sirsoftKginicisCheckoutJpyPaymentMethodRestrictorInstalled",X=/^\/shop\/checkout\/?$/,qn="/api/modules/sirsoft-ecommerce/checkout",zn="/api/modules/sirsoft-ecommerce/settings/payment",Vn="/api/modules/sirsoft-ecommerce/payments/client-config/kginicis",Je="__sirsoftKginicisCheckoutCurrency",Z=new Set(["card","kginicis_japan_paypay","kginicis_japan_cvs"]),Q=new Set(["kginicis_japan_paypay","kginicis_japan_cvs"]),Fe=new Set(["card","vbank","dbank","bank","phone","kginicis_samsung_pay","kginicis_naverpay","kginicis_lpay","kginicis_kakaopay","kginicis_japan_paypay","kginicis_japan_cvs"]),Xn=[{id:"card",labels:["신용카드","Credit Card","クレジットカード"]},{id:"vbank",labels:["가상계좌","Virtual Account","バーチャル口座"]},{id:"dbank",labels:["무통장입금","Bank Transfer","銀行振込"]},{id:"bank",labels:["계좌이체","Account Transfer","口座振替"]},{id:"phone",labels:["휴대폰결제","Mobile Payment","携帯電話決済"]},{id:"kginicis_naverpay",labels:["네이버페이 (KG이니시스)","Naver Pay (KG Inicis)"]},{id:"kginicis_samsung_pay",labels:["삼성페이 (KG이니시스)","Samsung Pay (KG Inicis)"]},{id:"kginicis_lpay",labels:["L.pay (KG이니시스)","L.pay (KG Inicis)"]},{id:"kginicis_kakaopay",labels:["카카오페이 (KG이니시스)","Kakao Pay (KG Inicis)"]},{id:"kginicis_japan_paypay",labels:["PayPay (일본 KG이니시스)","PayPay (KG Inicis Japan)"]},{id:"kginicis_japan_cvs",labels:["일본 편의점결제 (KG이니시스)","Japan Convenience Store (KG Inicis)"]}],ee={info:(...e)=>console.info(`[${Ue}]`,...e),warn:(...e)=>console.warn(`[${Ue}]`,...e)};let I=null,te=null,P=null;function ne(){return window}function Zn(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function Qn(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function er(e){try{return new URL(e,window.location.origin).pathname}catch{return e.split("?")[0].split("#")[0]}}function We(e){if(typeof e!="string")return null;const t=e.trim().toUpperCase();return/^[A-Z]{3}$/.test(t)?t:null}function re(e,t){return t.split(".").reduce((n,r)=>{if(!(n===null||typeof n!="object"))return n[r]},e)}function tr(e,t){for(const n of t){const r=We(re(e,n));if(r)return r}return null}function nr(e){return tr(e,["data.calculation.summary.selected_payment_currency","data.calculation.metadata.payment_currency","data.calculation.metadata.currency","data.currency","data.currency_code"])}function rr(e){const t=nr(e);t&&(ne()[Je]=t)}function qe(){const e=ne(),n=e.__templateApp?.globalState,r=[e[Je],n?.preferredCurrency];try{r.push(window.localStorage?.getItem("g7_preferred_currency"))}catch{}r.push(re(n,"modules.sirsoft-ecommerce.language_currency.default_currency"),re(n,"modules.sirsoft-ecommerce.language_currency.currencies.0.code"));for(const i of r){const o=We(i);if(o)return o}return null}function ie(){return X.test(window.location.pathname)&&qe()==="JPY"}function oe(){if(!X.test(window.location.pathname))return!1;const e=qe();return e!==null&&e!=="JPY"}async function ze(e){return I!==null||(I=(async()=>{try{const t=await e(Vn,{headers:{Accept:"application/json"}});return t.ok?(await t.json()).data?.japan_restrict_jpy_payment_methods===!0:!1}catch{return!1}})()),I}function ir(e){const t=e.data?.order_settings?.payment_methods;return Array.isArray(t)?{...e,data:{...e.data,order_settings:{...e.data?.order_settings,payment_methods:t.map(n=>{const r=typeof n.id=="string"?n.id:"";return!Fe.has(r)||Z.has(r)?n:{...n,is_active:!1,_kginicis_restricted_for_jpy:!0}})}}}:e}function or(e){const t=e.data?.order_settings?.payment_methods;return Array.isArray(t)?{...e,data:{...e.data,order_settings:{...e.data?.order_settings,payment_methods:t.map(n=>{const r=typeof n.id=="string"?n.id:"";return Q.has(r)?{...n,is_active:!1,_kginicis_restricted_for_non_jpy:!0}:n})}}}:e}function ar(e,t){const n=new Headers(e.headers);return n.set("Content-Type","application/json"),new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:n})}function sr(){const e=Array.from(document.querySelectorAll("h2")).find(n=>{const r=n.textContent??"";return r.includes("결제 수단")||r.includes("결제 방법")||r.includes("Payment Method")});if(!e)return null;let t=e.parentElement;for(;t&&t!==document.body;){if(t.tagName==="DIV"&&String(t.className).includes("rounded-lg"))return t;t=t.parentElement}return null}function cr(e){const t=e.querySelector("p")?.textContent?.trim()??e.textContent?.trim()??"";for(const n of Xn)if(n.labels.some(r=>t.includes(r)))return n.id;return null}function ae(){const e=ie(),t=oe();if(!e&&!t)return!1;const n=sr();if(!n)return!1;let r=!1;if(n.querySelectorAll('button[type="button"]').forEach(i=>{const o=cr(i);if(!o||!Fe.has(o))return;if(e?Z.has(o):!Q.has(o)){i.style.removeProperty("display"),i.disabled=!1,i.removeAttribute("aria-hidden");return}i.style.display="none",i.disabled=!0,i.setAttribute("aria-hidden","true"),e?i.dataset.kginicisRestrictedForJpy="true":i.dataset.kginicisRestrictedForNonJpy="true",r=!0}),r)try{const o=window.G7Core?.state?.getLocal?.()?.paymentMethod;typeof o=="string"&&(e&&!Z.has(o)||t&&Q.has(o))&&window.G7Core?.state?.setLocal?.({paymentMethod:"card"})}catch{}return r}async function Ve(e){if(!X.test(window.location.pathname))return;const t=ie(),n=oe();if(!t&&!n||t&&!await ze(e))return;ae(),te===null&&(te=new MutationObserver(()=>{ae()}),te.observe(document.body,{childList:!0,subtree:!0})),P!==null&&clearInterval(P);let r=0;P=setInterval(()=>{r++,ae(),r>=50&&P!==null&&(clearInterval(P),P=null)},200)}function Xe(e){I=null,Ve(e)}function dr(){if(typeof window>"u"||typeof window.fetch!="function")return;const e=ne();if(e[He])return;e[He]=!0;const t=window.fetch.bind(window);window.fetch=async function(o,a){const s=Zn(o),c=Qn(o,a),l=er(s),d=await t(o,a);if(c==="GET"&&l.endsWith(qn)){try{const p=await d.clone().json();rr(p)}catch{}return d}if(c!=="GET"||!l.endsWith(zn))return d;const u=ie(),f=oe();if(!u&&!f||u&&!await ze(t))return d;try{const p=await d.clone().json(),m=u?ir(p):or(p);return ee.info(u?"restricted checkout payment methods for JPY order":"hid Japan-only payment methods for non-JPY order"),ar(d,m)}catch(p){return ee.warn("failed to restrict checkout payment methods",p),d}},ee.info("checkout JPY payment method restrictor installed");const n=()=>{Ve(t)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n):n();const r=history.pushState.bind(history);history.pushState=(...i)=>{r(...i),setTimeout(()=>Xe(t),200)},window.addEventListener("popstate",()=>setTimeout(()=>Xe(t),200))}const lr="sirsoft-pay_kginicis",Ze="__sirsoftKginicisCheckoutBrandPaymentButtonsInstalled",ur=/^\/shop\/checkout\/?$/,fr="/api/modules/sirsoft-ecommerce/payments/client-config/kginicis",mr=220,pr=12,Qe=10;let se=null,L=null,K=null;const ce=[{id:"kginicis_naverpay",labels:["네이버페이 (KG이니시스)","Naver Pay (KG Inicis)"],ko:{heading:"네이버페이",description:"네이버페이로 결제 (kg이니시스)",title:"네이버페이로 결제 (kg이니시스)"},en:{heading:"Naver Pay",description:"Pay with Naver Pay (KG Inicis)",title:"Pay with Naver Pay (KG Inicis)"},markSvg:['','','N','Pay',""].join("")},{id:"kginicis_samsung_pay",labels:["삼성페이 (KG이니시스)","Samsung Pay (KG Inicis)"],ko:{heading:"삼성페이",description:"삼성페이로 결제 (kg이니시스)",title:"삼성페이로 결제 (kg이니시스)"},en:{heading:"Samsung Pay",description:"Pay with Samsung Pay (KG Inicis)",title:"Pay with Samsung Pay (KG Inicis)"},markSvg:['','','S','Pay',""].join("")},{id:"kginicis_lpay",labels:["L.pay (KG이니시스)","L.pay (KG Inicis)"],ko:{heading:"L.pay",description:"L.pay로 결제 (kg이니시스)",title:"L.pay로 결제 (kg이니시스)"},en:{heading:"L.pay",description:"Pay with L.pay (KG Inicis)",title:"Pay with L.pay (KG Inicis)"},markSvg:['','','L','pay',""].join("")},{id:"kginicis_kakaopay",labels:["카카오페이 (KG이니시스)","Kakao Pay (KG Inicis)"],ko:{heading:"카카오페이",description:"카카오페이로 결제 (kg이니시스)",title:"카카오페이로 결제 (kg이니시스)"},en:{heading:"Kakao Pay",description:"Pay with Kakao Pay (KG Inicis)",title:"Pay with Kakao Pay (KG Inicis)"},markSvg:['','','Kakao','Pay',""].join("")},{id:"kginicis_japan_paypay",labels:["PayPay (일본 KG이니시스)","PayPay (KG Inicis Japan)"],ko:{heading:"PayPay",description:"PayPay로 결제 (일본 KG)",title:"PayPay로 결제 (일본 KG이니시스)"},en:{heading:"PayPay",description:"Pay with PayPay (KG Japan)",title:"Pay with PayPay (KG Inicis Japan)"},markSvg:['','','Pay','Pay',""].join("")},{id:"kginicis_japan_cvs",labels:["일본 편의점결제 (KG이니시스)","Japan Convenience Store (KG Inicis)"],ko:{heading:"일본 편의점결제",description:"편의점 결제 (일본 KG)",title:"일본 편의점결제 (KG이니시스)"},en:{heading:"Convenience Store",description:"Pay at store (KG Japan)",title:"Japan Convenience Store (KG Inicis)"},markSvg:['','','CVS','JP',""].join("")}],yr={info:(...e)=>console.info(`[${lr}]`,...e)};function et(){return window}function hr(){return ur.test(window.location.pathname)}function gr(){return(document.documentElement.lang||navigator.language||"").toLowerCase().startsWith("ko")}function O(e){return gr()?e.ko:e.en}function tt(e){return(e??"").replace(/\s+/g," ").trim()}function nt(e){const t=e.getBoundingClientRect().width;return t>0?t:e.clientWidth}function _r(e){const t=nt(e);return t>0&&t0&&t<144?"9.5px":t>0&&t<160?"10px":t>0&&t<176?"11px":"12px"}async function br(e){return L!==null||(L=(async()=>{try{const t=await e(fr,{headers:{Accept:"application/json"}});return t.ok?(await t.json()).data?.easy_pay_show_brand_button===!0:!1}catch{return!1}})()),L}function kr(e){const t=e.dataset.kginicisBrandPaymentMethod,n=ce.find(i=>i.id===t);if(n)return n;if(e.dataset.kginicisNaverpayBrandButton==="true")return ce.find(i=>i.id==="kginicis_naverpay")??null;const r=tt(e.textContent);return ce.find(i=>{const o=O(i);return i.labels.some(a=>r.includes(a))||r.includes(i.ko.heading)||r.includes(i.en.heading)||r.includes(o.heading)})??null}function rt(e,t){const n=O(t);return e.find(r=>{const i=tt(r.textContent);return r.dataset.kginicisBrandPaymentHeading===t.id||t.labels.some(o=>i.includes(o))||i.includes(t.ko.heading)||i.includes(t.en.heading)||i.includes(n.heading)})??null}function Pr(e,t){const n=Array.from(e.querySelectorAll("p")),r=rt(n,t);if(!r)return;const i=O(t);r.textContent!==i.heading&&(r.textContent=i.heading),r.dataset.kginicisBrandPaymentHeading=t.id,t.id==="kginicis_naverpay"&&(r.dataset.kginicisNaverpayHeading=i.heading),r.getAttribute("aria-label")!==i.heading&&r.setAttribute("aria-label",i.heading);const o=n[n.indexOf(r)+1]??n.find(a=>a!==r);o&&(o.textContent!==i.description&&(o.textContent=i.description),o.dataset.kginicisBrandPaymentDescription=t.id,t.id==="kginicis_naverpay"&&(o.dataset.kginicisNaverpayDescription=i.description))}function xr(e,t){const n=_r(e),r=n?Qe:pr;e.style.paddingLeft=`${r}px`,e.style.paddingRight=`${r}px`,e.style.boxSizing="border-box",e.style.minWidth="0";const i=e.querySelector(".flex.items-center.gap-2, .flex.items-center.gap-3")??e.querySelector(".flex.items-center");i&&(i.style.gap=n?"6px":"8px",i.style.width="100%",i.style.minWidth="0",i.style.maxWidth="100%",i.style.boxSizing="border-box",i.style.flexWrap=n?"wrap":"nowrap");const o=rt(Array.from(e.querySelectorAll("p")),t);if(!o)return;o.style.whiteSpace="normal",o.style.wordBreak="keep-all",o.style.overflowWrap="anywhere",o.style.removeProperty("font-size"),o.style.removeProperty("line-height"),o.style.maxWidth="100%";const a=o.parentElement;if(a instanceof HTMLElement){a.style.display=n?"contents":"",a.style.flex=n?"":"1 1 0px",a.style.minWidth="0",a.style.maxWidth="100%",Array.from(a.querySelectorAll("p")).forEach(c=>{c.style.minWidth="0",c.style.maxWidth="100%",c.style.whiteSpace="normal",c.style.wordBreak="keep-all",c.style.overflowWrap="anywhere",c.style.removeProperty("order"),c.style.removeProperty("flex")});const s=Array.from(a.querySelectorAll("p")).find(c=>c.dataset.kginicisBrandPaymentDescription===t.id||c!==o);s&&(n&&(o.style.order="2",o.style.flex="1 1 0px",s.style.order="3",s.style.flex="0 0 100%",s.style.whiteSpace="nowrap",s.style.wordBreak="normal",s.style.overflowWrap="normal"),s.style.fontSize=n?wr(e):"12px",s.style.lineHeight="1rem")}}function Cr(e){const t=document.createElement("span");return t.dataset.kginicisBrandPaymentMark="true",t.dataset.kginicisBrandPaymentMethod=e.id,e.id==="kginicis_naverpay"&&(t.dataset.kginicisNaverpayMark="true"),t.setAttribute("aria-hidden","true"),t.style.display="inline-flex",t.style.width="32px",t.style.height="32px",t.style.flex="0 0 32px",t.style.alignItems="center",t.style.justifyContent="center",t.innerHTML=e.markSvg,t}function Er(e){return e.querySelector("svg")??e.querySelector('i[class*="fa-"], i[role="img"], i')}function vr(e){return e.querySelector(".flex.items-center.gap-2, .flex.items-center.gap-3")??e.querySelector(".flex.items-center")}function de(e=document){let t=!1;return e.querySelectorAll("button").forEach(n=>{const r=kr(n);if(!r)return;const i=O(r);if(n.title=i.title,n.dataset.kginicisBrandPaymentButton="true",n.dataset.kginicisBrandPaymentMethod=r.id,r.id==="kginicis_naverpay"&&(n.dataset.kginicisNaverpayBrandButton="true"),Pr(n,r),xr(n,r),n.querySelector('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"]'))return;const o=Cr(r),a=Er(n);if(a&&a.parentElement){a.replaceWith(o),t=!0;return}const s=vr(n);s&&(s.prepend(o),t=!0)}),t}function it(){K!==null&&(window.clearInterval(K),K=null)}function Sr(){it();let e=0;K=window.setInterval(()=>{e+=1,de(),e>=50&&it()},200)}async function Ir(e){hr()&&await br(e)&&(de(),Sr(),se===null&&(se=new MutationObserver(()=>{de()}),se.observe(document.body,{childList:!0,subtree:!0,characterData:!0})))}function Ar(e=fetch){typeof window>"u"||typeof document>"u"||et()[Ze]!==!0&&(et()[Ze]=!0,Ir(e).then(()=>{yr.info("checkout KG Inicis brand payment button patcher installed")}))}const Tr="sirsoft-pay_kginicis",ot="__kginicisAdminPaymentMethodBrandInjectorInstalled",at="__kginicisAdminPaymentMethodBrandSyncListenerAttached",Rr=/^\/admin\/ecommerce\/settings\/?$/,st='[data-kginicis-admin-payment-brand-mark="true"]',Nr=200,Mr=120,Lr=[{id:"kginicis_naverpay",labels:["네이버페이 (KG이니시스)","Naver Pay (KG Inicis)"],shortLabels:[],markLines:["N","Pay"],markClassName:"bg-green-500 text-white"},{id:"kginicis_samsung_pay",labels:["삼성페이 (KG이니시스)","Samsung Pay (KG Inicis)"],shortLabels:[],markLines:["S","Pay"],markClassName:"bg-blue-700 text-white"},{id:"kginicis_lpay",labels:["L.pay (KG이니시스)","L.pay (KG Inicis)"],shortLabels:[],markLines:["L","pay"],markClassName:"bg-red-600 text-white"},{id:"kginicis_kakaopay",labels:["카카오페이 (KG이니시스)","Kakao Pay (KG Inicis)"],shortLabels:[],markLines:["Kakao","Pay"],markClassName:"bg-yellow-400 text-gray-950"},{id:"kginicis_japan_paypay",labels:["PayPay (일본 KG이니시스)","PayPay (KG Inicis Japan)"],shortLabels:[],markLines:["Pay","Pay"],markClassName:"bg-red-600 text-white"},{id:"kginicis_japan_cvs",labels:["일본 편의점결제 (KG이니시스)","Japan Convenience Store (KG Inicis)"],shortLabels:[],markLines:["CVS","JP"],markClassName:"bg-blue-600 text-white"}];let ct=null,G=null,le=!1;function Kr(){return window}function ue(){if(!Rr.test(window.location.pathname))return!1;const e=new URLSearchParams(window.location.search).get("tab");return e===null||e===""||e==="order_settings"}function Or(e){return e instanceof HTMLElement?e.className:""}function dt(e){return(e??"").replace(/\u200B/g,"").replace(/\s+/g," ").trim()}function Gr(e){const t=Or(e);return t.includes("excel-card")||t.includes("flex-center")&&t.includes("border")&&t.includes("gap-4")}function lt(e){return e.querySelector(".font-medium")}function $r(e){const t=dt(lt(e)?.textContent),n=dt(e.textContent);return Lr.find(r=>r.shortLabels.some(i=>t===i)||r.labels.some(i=>n.includes(i)))??null}function Dr(e){return Array.from(e.querySelectorAll("div")).filter(Gr)}function Br(e){return Array.from(e.querySelectorAll("svg, [data-icon], i")).find(n=>!n.closest("[data-drag-handle]")&&!n.closest(st)&&!n.closest('.row-stack, .excel-card-body, button, select, [role="switch"]'))??null}function ut(e,t){e.dataset.kginicisAdminPaymentBrandMark="true",e.dataset.kginicisAdminPaymentMethod=t.id,e.setAttribute("aria-hidden","true"),e.className=`inline-flex items-center justify-center rounded-lg font-bold ${t.markClassName}`,e.style.width="32px",e.style.height="32px",e.style.flex="0 0 32px",e.style.flexDirection="column",e.style.lineHeight="1",e.style.fontSize="9px";const n=t.markLines.join("");e.textContent!==n&&(e.replaceChildren(),t.markLines.forEach(r=>{const i=document.createElement("span");i.style.lineHeight="1",i.textContent=r,e.appendChild(i)}))}function jr(e){const t=document.createElement("span");return ut(t,e),t}function Yr(e,t){const n=e.querySelector(st);if(n instanceof HTMLSpanElement)return e.dataset.kginicisAdminPaymentMethod=t.id,ut(n,t),!0;const r=jr(t),i=Br(e);if(i&&i.parentElement)return e.dataset.kginicisAdminPaymentMethod=t.id,i.replaceWith(r),!0;const o=lt(e);return o&&o.parentElement?(e.dataset.kginicisAdminPaymentMethod=t.id,o.parentElement.insertBefore(r,o),!0):!1}function fe(e=document){if(typeof window>"u"||typeof document>"u"||!ue())return!1;let t=!1;return Dr(e).forEach(n=>{const r=$r(n);r&&Yr(n,r)&&(t=!0)}),t}function Ur(){le||(le=!0,window.setTimeout(()=>{le=!1,fe()},0))}function me(){G!==null&&(window.clearInterval(G),G=null)}function pe(){if(!ue())return;me(),fe();let e=0;G=window.setInterval(()=>{e+=1,fe(),e>=Mr&&me()},Nr);const t=document.body;t[at]||(t[at]=!0,ct=new MutationObserver(()=>Ur()),ct.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function ft(){if(ue()){pe();return}me()}function Hr(){if(typeof window>"u"||typeof document>"u")return;const e=Kr();if(e[ot])return;e[ot]=!0,console.info(`[${Tr}] admin payment method brand sync installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>pe()):pe();const t=history.pushState.bind(history);history.pushState=(...n)=>{t(...n),window.setTimeout(()=>ft(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>ft(),200))}const x="sirsoft-pay_kginicis",ye={info:(...e)=>console.info(`[${x}]`,...e),warn:(...e)=>console.warn(`[${x}]`,...e),error:(...e)=>console.error(`[${x}]`,...e)};function mt(){const e=window.G7Core;if(!e)return 0;const t=e.getActionDispatcher;if(typeof t!="function")return 0;const n=t();if(!n||typeof n.registerHandler!="function")return 0;let r=0;for(const[i,o]of Object.entries(Ie)){const a=`${x}.${i}`;n.registerHandler(a,o,{category:"plugin",source:x}),r++}return r}function pt(){const e=()=>{const t=mt();if(t>0){ye.info(`${t} handler(s) registered`);return}let n=0;const r=50,i=setInterval(()=>{n++;const o=mt();if(o>0){clearInterval(i),ye.info(`${o} handler(s) registered (after ${n} retries)`);return}n>=r&&(clearInterval(i),ye.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}Zt(),dr(),Ar(),fn(),xn(),Hr(),Rn(),Wn(),Tt(),pt(),window.__SirsoftKginicis={identifier:x,handlers:Object.keys(Ie),initPlugin:pt}})();