import{Component}from"@theme/component";const ENDPOINT_BASE="https://apimanagement.gco.com.co:8444/customer/api/tracking/selfservice/",BRAND_CODE="34",FETCH_TIMEOUT_MS=1e4,ORDER_PATTERN=/^\d{1,20}$/,RECAPTCHA_SRC="https://www.google.com/recaptcha/api.js?render=explicit",CHALLENGE_SELECTOR='iframe[src*="/recaptcha/"][src*="bframe"]',CLOSE_DELAY_MS=250,DELIVERY_ORDER=["ready-for-handling","handling","invoiced","transit","in-distribution","delivered"],PICKUP_ORDER=["ready-for-handling","handling","invoiced","pickup","pickup-invoiced","delivered"],DATE_FIELDS=new Set(["lastUpdate","expectedDate"]),CARD_TONES={canceled:"danger",unknown:"neutral"},FOCUSABLE='a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])';export class OrderTrackingComponent extends Component{requiredRefs=["panel","field","orderInput","submit","captcha","validation","results","card"];connectedCallback(){if(this.parentElement!==document.body){this.portal();return}super.connectedCallback(),this.siteKey=this.getAttribute("data-recaptcha-site-key")??"",this.orderPrefix=this.getAttribute("data-order-prefix")??"",this.orderValue=this.refs.card.querySelector('[data-value="order"]'),this.detailRows=this.refs.card.querySelectorAll("[data-field]"),this.timelines=this.refs.results.querySelectorAll("[data-flow]"),this.knownStatuses=new Set(Array.from(this.refs.card.querySelectorAll(".tracking-link-block__status-title [data-status]")).flatMap(node=>node.dataset.status.split(" "))),this.isOpen=!1,this.closeTimer=null,this.previousFocus=null,this.scrollY=0,this.abortController=null,this.timeoutId=null,this.widgetId=null,this.token="",this.captchaFailed=!1,this.trigger=document.querySelector(`[data-tracking-trigger="${this.dataset.trackingModal}"]`),this.trigger?.addEventListener("click",this.open),this.ready=!0}disconnectedCallback(){this.ready&&(super.disconnectedCallback(),this.abortLookup(),clearTimeout(this.timeoutId),clearTimeout(this.closeTimer),document.removeEventListener("keydown",this.handleKeydown),this.trigger?.removeEventListener("click",this.open),this.releaseScrollLock())}portal(){const id=this.dataset.trackingModal;for(const stale of document.querySelectorAll(`body > [data-tracking-modal="${id}"]`))stale!==this&&stale.remove();document.body.appendChild(this)}open=()=>{this.isOpen||(this.isOpen=!0,clearTimeout(this.closeTimer),this.previousFocus=document.activeElement,this.lockScroll(),this.hidden=!1,this.trigger?.setAttribute("aria-expanded","true"),document.addEventListener("keydown",this.handleKeydown),requestAnimationFrame(()=>this.classList.add("is-open")),this.refs.panel.focus({preventScroll:!0}),this.setupCaptcha())};close=()=>{this.isOpen&&(this.isOpen=!1,document.removeEventListener("keydown",this.handleKeydown),this.classList.remove("is-open"),this.trigger?.setAttribute("aria-expanded","false"),this.abortLookup(),this.resetCaptcha(),this.updateSubmitGate(),this.closeTimer=setTimeout(()=>{this.hidden=!0},CLOSE_DELAY_MS),this.releaseScrollLock(),this.previousFocus instanceof HTMLElement&&this.previousFocus.focus())};lockScroll(){this.scrollY=window.scrollY,document.body.style.width="100%",document.body.style.position="fixed",document.body.style.top=`-${this.scrollY}px`}releaseScrollLock(){document.body.style.position==="fixed"&&(document.body.style.width="",document.body.style.position="",document.body.style.top="",window.scrollTo({top:this.scrollY,behavior:"instant"}))}handleKeydown=event=>{if(event.key==="Escape"){event.preventDefault(),this.close();return}if(event.key!=="Tab"||isChallengeOpen())return;const focusable=Array.from(this.refs.panel.querySelectorAll(FOCUSABLE)).filter(node=>node.offsetParent!==null);if(focusable.length===0)return;const first=focusable[0],last=focusable[focusable.length-1];event.shiftKey&&document.activeElement===first?(event.preventDefault(),last.focus()):!event.shiftKey&&document.activeElement===last&&(event.preventDefault(),first.focus())};setView(view){this.dataset.view=view;for(const node of this.querySelectorAll("[data-view]"))node.hidden=!node.dataset.view.split(" ").includes(view)}setStatus(status){for(const node of this.refs.card.querySelectorAll("[data-status]"))node.hidden=!node.dataset.status.split(" ").includes(status)}async setupCaptcha(){if(!(this.widgetId!==null||this.captchaFailed)){if(!this.siteKey){this.renderCaptchaError();return}try{const grecaptcha=await loadRecaptchaScript();this.renderWidget(grecaptcha)}catch{this.renderCaptchaError()}}}renderWidget(grecaptcha){if(!(this.widgetId!==null||this.captchaFailed))try{this.widgetId=grecaptcha.render(this.refs.captcha,{sitekey:this.siteKey,callback:()=>{this.token=grecaptcha.getResponse(this.widgetId)||"",this.clearValidation(),this.updateSubmitGate()},"expired-callback":()=>{this.token="",this.showValidation("El reCAPTCHA expir\xF3. Verif\xEDcalo nuevamente."),this.updateSubmitGate()},"error-callback":()=>{this.token="",this.showValidation("No se pudo verificar el reCAPTCHA. Intenta nuevamente."),this.updateSubmitGate()}}),this.updateSubmitGate()}catch{this.renderCaptchaError()}}renderCaptchaError(){this.captchaFailed=!0;const message=document.createElement("p");message.className="tracking-link-block__captcha-error",message.textContent="No se pudo cargar el reCAPTCHA. Verifica tu conexi\xF3n e intenta nuevamente.",this.refs.captcha.replaceChildren(message),this.refs.submit.disabled=!0}resetCaptcha(){try{this.widgetId!==null&&typeof window.grecaptcha?.reset=="function"&&window.grecaptcha.reset(this.widgetId)}catch{}this.token=""}updateSubmitGate=()=>{if(this.captchaFailed){this.refs.submit.disabled=!0;return}const hasOrder=this.refs.orderInput.value.trim().length>0;this.refs.submit.disabled=!(hasOrder&&this.token)};handleInput=()=>{this.clearValidation(),this.refs.field.classList.remove("is-invalid"),this.refs.orderInput.removeAttribute("aria-invalid"),this.dataset.view!=="idle"&&this.setView("idle"),this.updateSubmitGate()};readOrderNumber(){let value=this.refs.orderInput.value.trim().replace(/\s+/g,"");const prefix=this.orderPrefix.replace(/[^a-z0-9]/gi,"");return prefix&&value.toUpperCase().startsWith(prefix.toUpperCase())&&(value=value.slice(prefix.length)),value.replace(/^[-\s]+/,"")}handleSubmit=event=>{if(event.preventDefault(),this.captchaFailed)return;const number=this.readOrderNumber();if(!ORDER_PATTERN.test(number)){this.showValidation("Ingresa solo el n\xFAmero del pedido, sin letras ni guiones."),this.refs.orderInput.focus();return}if(!this.token){this.showValidation("Completa el reCAPTCHA para continuar.");return}this.refs.orderInput.value=number,this.clearValidation(),this.lookup(this.orderPrefix+number)};reset=()=>{this.abortLookup(),this.refs.orderInput.value="",this.token="",this.refs.field.classList.remove("is-invalid"),this.refs.orderInput.removeAttribute("aria-invalid"),this.clearValidation(),this.setView("idle"),this.resetCaptcha(),this.updateSubmitGate(),this.refs.orderInput.focus()};abortLookup(){this.abortController?.abort(),this.abortController=null,clearTimeout(this.timeoutId),this.timeoutId=null}async lookup(order){this.abortLookup(),this.setView("loading"),this.refs.results.setAttribute("aria-busy","true"),this.refs.submit.disabled=!0;const controller=new AbortController;this.abortController=controller;const timeoutId=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS);this.timeoutId=timeoutId;const url=`${ENDPOINT_BASE}${BRAND_CODE}/${encodeURIComponent(order)}`;let result=null,outcome=null;try{const response=await fetch(url,{signal:controller.signal,headers:{Accept:"application/json"}});if(response.status===404)outcome="not-found";else if(!response.ok)outcome="error";else{let data;try{data=await response.json()}catch{outcome="error"}outcome===null&&(result=this.normalize(data),result?result.type==="empty"?outcome="not-found":outcome="found":outcome="error")}}catch{if(this.abortController!==controller)return;outcome="error"}this.abortController===controller&&(clearTimeout(timeoutId),this.abortController=null,this.resetCaptcha(),this.refs.results.setAttribute("aria-busy","false"),outcome==="found"?this.renderFound(order,result):this.renderFailure(outcome),this.updateSubmitGate())}normalize(data){if(!Array.isArray(data))return null;const entries=data.filter(item=>item&&typeof item=="object").map(toEntry);if(entries.length===0)return{type:"empty"};const tracked=entries.filter(entry=>entry.status);if(tracked.length===0)return{type:"status",status:"unknown",entry:entries[entries.length-1]};const statuses=tracked.map(entry=>entry.status),current=statuses[statuses.length-1],currentEntry=tracked[tracked.length-1];if(statuses.includes("canceled"))return{type:"status",status:"canceled",entry:tracked.find(entry=>entry.status==="canceled")??currentEntry};if(!this.knownStatuses.has(current))return null;const isPickup=current==="pickup"||current==="pickup-invoiced";return(isPickup?PICKUP_ORDER:DELIVERY_ORDER).includes(current)?{type:"timeline",status:current,isPickup,entry:currentEntry}:{type:"status",status:current,entry:currentEntry}}renderFound(order,result){this.refs.card.dataset.tone=CARD_TONES[result.status]??"success",this.orderValue&&(this.orderValue.textContent=order),this.setStatus(result.status),this.fillDetails(result.entry),this.markTimeline(result),this.setView("found")}fillDetails(entry){for(const row of this.detailRows){const field=row.dataset.field,raw=entry[field]??"",value=DATE_FIELDS.has(field)?formatDate(raw):raw,slot=row.querySelector("[data-value]");slot&&(slot.textContent=value),row.hidden=!value}}markTimeline(result){const flow=result.isPickup?"pickup":"delivery";for(const list of this.timelines){const active=result.type==="timeline"&&list.dataset.flow===flow;if(list.hidden=!active,!active)continue;const steps=Array.from(list.children),currentIndex=steps.findIndex(step=>step.dataset.match.split(" ").includes(result.status));steps.forEach((step,index)=>{step.classList.toggle("is-done",index div");if(container&&container.style.visibility!=="hidden")return!0}return!1}function toEntry(item){const text=value=>typeof value=="string"?value:"";return{orderId:text(item.orderId),status:text(item.status),lastUpdate:text(item.lastUpdate),expectedDate:text(item.expectedDate),trackingNumber:text(item.trackingNumber),courierName:text(item.courierName)}}function formatDate(value){if(!value)return"";const normalized=/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00`:value.replace(" ","T"),date=new Date(normalized);return Number.isNaN(date.getTime())?value:new Intl.DateTimeFormat("es-CO",{day:"numeric",month:"long",year:"numeric"}).format(date)}function loadRecaptchaScript(){return typeof window.grecaptcha?.render=="function"?Promise.resolve(window.grecaptcha):(loadRecaptchaScript.promise||(loadRecaptchaScript.promise=new Promise((resolve,reject)=>{const existing=document.querySelector(`script[src="${RECAPTCHA_SRC}"]`),script=existing??document.createElement("script"),cleanup=()=>{script.removeEventListener("load",onLoad),script.removeEventListener("error",onError)},onLoad=()=>{const grecaptcha=window.grecaptcha;typeof grecaptcha?.render=="function"?(cleanup(),resolve(grecaptcha)):typeof grecaptcha?.ready=="function"?grecaptcha.ready(()=>{cleanup(),resolve(grecaptcha)}):(cleanup(),reject(new Error("reCAPTCHA unavailable")))},onError=()=>{cleanup(),reject(new Error("reCAPTCHA script failed to load"))};script.addEventListener("load",onLoad),script.addEventListener("error",onError),existing||(script.src=RECAPTCHA_SRC,script.async=!0,script.defer=!0,document.head.appendChild(script))})),loadRecaptchaScript.promise)} //# sourceMappingURL=/cdn/shop/t/35/assets/gco-order-tracking.js.map?v=6493793286179149771792161660