const SELFBOOK_BASE_URL="https://sdk.selfbook.com",SELFBOOK_BACKEND_URL="https://api.selfbook.com/api/v2",SELFBOOK_SCRIPT_ID="selfbook_jssdk",SELFBOOK_HOTEL_ID_PROP="hotelId",SELFBOOK_API_KEY_PROP="apiKey",SELFBOOK_WIDGET_ELEMENT_ID="selfbook_sdkwidget",SELFBOOK_WIDGET_WRAPPER_ELEMENT_ID="selfbook_sdkwidget_wrapper",SELFBOOK_WIDGET_LOADING_ELEMENT="selfbook-loading",SELFBOOK_WIDGET_RESUME="selfbook-sdkwidget-resume",SELFBOOK_WIDGET_RESUME_TEXT="selfbook-sdkwidget-resume-text",BOOTSTRAP_ACTION="WIDGET/BOOTSTRAP",SELFBOOK_HOTEL_GROUP_INFO="selfbook_hotel_group_info",BLACK_SQUARE_THEME_HOTELS=["6739"],THE_LINE_HOTELS=["68711","71661","2427"],COMPLETE_BOOKING_BTN_CLICK="Complete your reservation button click",ROUTE_PATHS={app:{confirmation:"/confirmation",wallet:"/wallet",account:"/account",settings:"/settings",reservations:"/reservations",reservationDetail:"/reservation-detail",editBooking:"/edit-booking",bookingConfirmed:"/booking-confirmed"}},INITIAL_PERSISTED_DATA={isExpired:!0,all:null,booking:null,core:null,router:null},GUEST_TYPE={ADULT:"adult",CHILD:"child",INFANT:"infants"};function checkStatus(t){if(t.status>=200&&t.status<300)return t;const e=new Error(t.statusText);throw e.response=t,e}async function parseJSON(t){try{const e=await t.text();if(!e)return;return JSON.parse(e)}catch(t){console.error("parseJSON: err: ",t)}}function intervalWrapper(t,e){const n=setInterval(t,e);return function(){clearInterval(n)}}function getHotelBasicData(t,e){try{const n=getFromLocalStorage(t,SELFBOOK_HOTEL_GROUP_INFO).hotels?.filter((t=>t.id==e));return n?.[0]||{}}catch(t){return console.error("getHotelBasicData: err: ",t),{}}}function getFromLocalStorage(t,e){try{return JSON.parse(t.getItem(e))}catch(t){return console.error("getFromLocalStorage: err: ",{e:t}),{}}}function getPersistedData(t){try{const e=JSON.parse(t.getItem("persist:root"));if(!e)return INITIAL_PERSISTED_DATA;const n=JSON.parse(e.booking||"{}"),o=JSON.parse(e.core||"{}"),r=JSON.parse(e?.router||"{}"),{expireTime:a}=o,s=(Date.now()-new Date(o.interactionTime))/1e3;return{isExpired:s>a,all:e,booking:n,core:o,router:r}}catch(t){return console.error("getPersistedData: err: ",t),INITIAL_PERSISTED_DATA}}function fillGuestsFields(t=[],e){const n=e.default_adult_occupancy?e.default_adult_occupancy:2;return t.map((t=>t.type===GUEST_TYPE.ADULT?{type:GUEST_TYPE.ADULT,count:parseInt(t.count)||n}:t.type===GUEST_TYPE.CHILD&&parseInt(t.count)>0?{type:GUEST_TYPE.CHILD,count:parseInt(t.count),age:parseInt(t.age)||1,special_request:t.special_request||""}:t.type===GUEST_TYPE.INFANT&&parseInt(t.count)>0?{type:GUEST_TYPE.INFANT,count:parseInt(t.count)||1,age:parseInt(t.age)||1,special_request:t.special_request||""}:void 0)).filter(Boolean)}function buildRedirectSynxisLink(t,e){let n=`https://be.synxis.com/?hotel=${e.id}&theme=${e.synxis_theme}&config=${e.synxis_config}`;try{if(t){const{startDate:e,endDate:o,promoCode:r,groupCode:a,guests:s,iataNumber:i,couponCode:l,destinationId:d,nights:c,rate:p,hotelId:u,roomCategory:m}=t;c&&(n+=`&nights=${c}`),e&&(n+=`&arrive=${e}`),o&&(n+=`&depart=${o}`),r&&(n+=`&promo=${r}`),a&&(n+=`&group=${a}`),i&&(n+=`&iataNumber=${i}`),l&&(n+=`&couponCode=${l}`),p&&(n+=`&rate=${p}`),d&&(n+=`&destinationId=${d}`),Array.isArray(m)?n+=`&roomCategory=${m.map((t=>t)).join(",")}`:m&&(n+=`&roomCategory=${m}`),s&&s.length>0?("adult"===s[0].type&&(n+=`&adult=${s[0].count}`),s[1]&&"child"===s[1].type&&(n+=`&child=${s[1].count}`)):n+="&adult=1"}}catch(t){console.error("buildRedirectSynxisLink: err: ",t)}return n}function selectShowWidgetButtonCopies(t){return t.core.showWidgetButtonCopies||{}}function selectRoute(t){return t?.router?.location?t.router.location.pathname:ROUTE_PATHS.app.editBooking}function isObjectEqual(t,e){return JSON.stringify(t)===JSON.stringify(e)}function isTemplateDomainMatch(t,e){return t?.booking_template_domain&&e?.target?.href?.includes(t.booking_template_domain)}function getElementById(t){return document?.getElementById(t)}function runDirectApplication(){console.info("(!) selfbook: widget initialization started");let t,e,n,o,r,a=!1,s=!1,i=!1,l=!1;async function d({url:t,method:e,data:n,headers:o}){try{const r=await fetch(t,{method:e,body:n,headers:o});checkStatus(r);return await parseJSON(r)}catch(t){console.debug("requestWrapper: Request failed",t)}}function c(){try{const t=n||{},e=o||ROUTE_PATHS.app.editBooking;n=selectShowWidgetButtonCopies(window.selfbookWidgetStore.getState()),o=selectRoute(window.selfbookWidgetStore.getState());const r=getElementById(SELFBOOK_WIDGET_RESUME_TEXT);let a=t.COMPLETE_BOOKING;isObjectEqual(t,n)&&o===e||(a=o===ROUTE_PATHS.app.reservations?n.VIEW_RESERVATIONS:o===ROUTE_PATHS.app.confirmation||o===ROUTE_PATHS.app.reservationDetail?n.VIEW_RESERVATION:o===ROUTE_PATHS.app.account?n.VIEW_ACCOUNT:o===ROUTE_PATHS.app.wallet?n.VIEW_WALLET:o===ROUTE_PATHS.app.bookingConfirmed?n.RETURN_BOOKING:n.COMPLETE_BOOKING,r&&(r.innerHTML=a))}catch(t){console.error("handleStoreChange: err: ",t)}}function p(){return THE_LINE_HOTELS.includes(t)?"Lydian BT":"Main"}function u(e){const n=e?.colors||{},o=`\n      position: fixed;\n      overflow: hidden;\n      cursor: pointer;\n      display: flex;\n      justify-content: space-evenly;\n      align-items: center;\n      width: 217px;\n      height: 46px;\n      box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.25), 0px 4px 4px rgba(0, 0, 0, 0.1);\n      right: 30px;\n      z-index: 100000000000;\n      bottom: 40px;\n      font-family: ${p()}!important;\n      font-size: 14px;\n      line-height: 142%;\n      letter-spacing: 0.02em;\n      text-transform: capitalize!important;\n      border: none;\n      transform: translateX(300px);\n    `,r="\n      background: #343A40;\n      color: #FFFFFF;\n    ",a=`\n      ${r}\n      border-radius: 23px;\n    `,s=`\n      background: ${n.primary_color||n.primary};\n      color: ${n.secondary_color||n.secondary}!important;\n    `;return i=e?.id||t,BLACK_SQUARE_THEME_HOTELS.includes(i)?`${o}${r}`:n.primary_color&&n.secondary_color||n.primary&&n.secondary?`${o}${s}`:`${o}${a}`;var i}function m(t){const e=document.createElement("style");e.textContent=t,document.head.append(e)}function y(n,o){if(!r)return;m(`#${SELFBOOK_WIDGET_RESUME} {\n      ${u(o)}\n    }`),document.body.style.overflow="hidden";const a=getElementById("selfbook_sdkwidget"),s=getElementById("selfbook_sdkwidget_wrapper"),l=getElementById(SELFBOOK_WIDGET_RESUME),d=l?l.getAttribute("class"):null;d&&d.includes("dismiss-btn")&&(l.removeAttribute("class"),l.setAttribute("class","dismiss-btn-slide-out")),window.selfbookWidgetStore||(s.appendChild(function(){const t=document.createElement("div");return t.id="selfbook-loading",t.style.color="white",t.style.marginRight="-50%",t.style.position="absolute",t.style.top="50%",t.style.left="50%",t.style.fontFamily="sans-serif",t.style.transform="translate(-50%, -50%)",t.innerHTML='<img src="https://sdk.selfbook.com/assets/selfbook_loading_logo.svg" height="20" width="100%">',t}()),s.style.zIndex=1e11,s.style.height="100%",s.style.background="rgba(0, 0, 0, .74)",document.body.style.overflow="hidden"),function(){if(!0===i)return;r&&r.length>0&&r.forEach((t=>{if(t.includes(".js")){const e=document.createElement("script");e.type="text/javascript",e.src=`${SELFBOOK_BASE_URL}/${t}`,document.body.appendChild(e)}}));(function(){try{const t=document.createElement("script");t.innerHTML='\n        !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","identify","reset","group","track","ready","alias","debug","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="https://cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};analytics._writeKey="c77UfR3BzZDUXmAth2DaHEA8kkKhDIU2";;analytics.SNIPPET_VERSION="4.15.3";\n        analytics.load("c77UfR3BzZDUXmAth2DaHEA8kkKhDIU2");\n        }}();\n      ',document.head.appendChild(t);const e=document.createElement("script");e.type="application/ld+json",e.innerHTML='{"@context": "http://schema.org/","@type": "SoftwareApplication","name": "SelfBook"}',document.head.appendChild(e);const n=document.createElement("script");n.src="https://onboard.triptease.io/bootstrap.js",n.async=!0,n.crossOrigin="anonymous",n.type="text/javascript",document.head.appendChild(n)}catch(t){console.error("inject3rdPartyScripts: err: ",t)}})(),i=!0}();const p=setInterval((()=>{if(window.selfbookWidgetStore){window.selfbookWidgetStore.subscribe(c);!function(){const t=document.getElementById("selfbook-loading");t&&getElementById("selfbook_sdkwidget_wrapper").removeChild(t)}(),clearInterval(p),window.selfbookWidgetStore.dispatch({type:BOOTSTRAP_ACTION,payload:{hotelInfo:{apiKey:n.apiKey||e,hotelId:n.hotelId||t,hotelIdAsArg:!!n.hotelId},bookingData:n,hotelGroupInfo:getFromLocalStorage(localStorage,SELFBOOK_HOTEL_GROUP_INFO)}}),"none"===a.style.display&&(s.style.zIndex=1e11,s.style.height="100%",s.style.background="rgba(0, 0, 0, .4)",document.body.style.overflow="hidden"),setTimeout((()=>{a.style.display="block",a.setAttribute("class","slide-in")}),20),setTimeout((()=>{const t=s.querySelector('[aria-modal="true"]');t&&t.focus()}),250),function(){const t=getElementById("selfbook_sdkwidget"),e=getElementById("selfbook_sdkwidget_wrapper"),n=getElementById(SELFBOOK_WIDGET_RESUME);n.addEventListener("click",(o=>{try{if(n){const o=n?n.getAttribute("class"):null;o&&o.includes("dismiss-btn")&&(n.removeAttribute("class"),n.setAttribute("class","dismiss-btn-slide-out")),document.body.style.overflow="hidden",e.style.zIndex=1e11,e.style.height="100%",e.style.background="rgba(0, 0, 0, .5)",t.style.display="block",t.setAttribute("class","slide-in"),window.selfbookWidgetStore.dispatch({type:"ANALYTICS/TRACK_EVENT",payload:{eventType:COMPLETE_BOOKING_BTN_CLICK,eventPayload:null}}),setTimeout((()=>{const t=e.querySelector('[aria-modal="true"]');t&&t.focus()}),500)}}catch(t){console.error("handleWidgetCloseListeneres: err: ",t)}}))}()}}),100)}function f(){try{const{isExpired:t,core:e,booking:n}=getPersistedData(localStorage),o=!!e?.hotel?.data?.feature_flags?.persist_state;if(t||!e?.hotel?.data?.id||!o)return void function(){try{localStorage.removeItem("persist:root")}catch(t){console.error("removePersistedData: err",t)}}();const r=e.bootstrapArgs;E({...r,startDate:n.bookingForm.start_date.slice(0,10),endDate:n.bookingForm.end_date?.slice(0,10)||null,guests:n.bookingForm.guests,propertyId:n.bookingForm.property_id,persistActive:!0,hotelId:e.hotel.data.id})}catch(t){console.error("openPersistWidget: err",t)}}const g=async()=>await fetch(`${SELFBOOK_BASE_URL}/asset-manifest.json`,{headers:{"content-type":"application/json"}}).then((t=>t.json())).then((t=>function(t){r=t.entrypoints}(t)));async function E(e={}){try{e.apiKey&&await k(e.apiKey,e.hotelId);const n=getHotelBasicData(localStorage,e.hotelId||t);if(e.guests?e.guests=fillGuestsFields(e.guests,n):e.guests=[{type:GUEST_TYPE.ADULT,count:n.default_adult_occupancy?n.default_adult_occupancy:2}],console.log(e),n.redirect_to_synxis){const t=buildRedirectSynxisLink(e,n);return void window.open(t,"_blank").focus()}y(e,n),document.getElementsByTagName("html")[0].setAttribute("translate","no")}catch(t){console.error("bookNow: err: ",t)}}function h(t){const e={startdate:"startDate",enddate:"endDate",rateplancode:"ratePlanCode",rate:"rate",roomid:"roomId",propertyid:"propertyId",destinationid:"destinationId",room:"room",adult:"adult",child:"child",infants:"infants",currency:"currency",group:"group",locale:"locale",hotel:"hotel",promo:"promo",promocode:"promocode",selfbook:"selfbook",iatanumber:"iataNumber",couponcode:"couponCode",nights:"nights",reservationid:"reservationId",lastname:"lastName",search:"search",sbsearch:"sbsearch",threeDsContinueId:"three_ds_continue_id",status:"status",roomcategory:"roomCategory",properties:"properties",source:"source"};return Array.from(t.entries()).reduce(((t,[n,o])=>({...t,[e[n.toLowerCase()]]:o})),{})}function _(){setTimeout((()=>{const e=setInterval((()=>{if(a)return;clearInterval(e);const n=h(new URLSearchParams(window.location.search));"true"===n.selfbook&&b(n,getHotelBasicData(localStorage,n.hotel||t))}),100)}),500)}function b(t,e={}){const n=parseInt(e?.default_adult_occupancy)||2,o=[{type:"adult",count:t.adult||n},{type:"child",count:t.child||0},{type:"infants",count:t.infants||0}];E({...t,guests:o,groupCode:t.group,promoCode:t.promo||t.promocode,hotelId:t.hotel||void 0,roomCategory:"string"==typeof t.roomCategory?t.roomCategory.split(",").map((t=>t.trim())):void 0})}async function w(){!function(){const t=document.createElement("div"),e=document.createElement("div"),n=document.createElement("button"),o=document.createElement("span"),r=document.createElement("img");n.id=SELFBOOK_WIDGET_RESUME,n.style.cursor="pointer",r.src="https://sdk.selfbook.com/assets/resume-icon-black.png",r.alt="Resume booking",r.width="16",r.height="16",o.innerHTML="Complete your booking",o.id=SELFBOOK_WIDGET_RESUME_TEXT,n.appendChild(o),n.appendChild(r),t.setAttribute("id","selfbook_sdkwidget"),t.style.display="none",e.setAttribute("id","selfbook_sdkwidget_wrapper"),e.style.background="rgba(0, 0, 0, 0)",e.style.position="fixed",e.style.top="0",e.style.right="0",e.style.width="100%",e.style.transition="background .5s ease-out",e.appendChild(t),document.body.appendChild(e),document.body.appendChild(n)}(),await g(),function(){if(!0!==l){if(r&&r.length>0){const t=document.getElementsByTagName("head")[0];r.forEach((e=>{if(e.includes(".css")){const n=document.createElement("link");n.rel="stylesheet",n.type="text/css",n.media="all",n.href=`${SELFBOOK_BASE_URL}/${e}`,t.appendChild(n)}}))}l=!0}}(),f(),document?.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(e=>{try{"A"!==e.target.tagName&&"A"===e.target.parentNode?.tagName&&(e.target.href=e.target.parentNode.href);const n=e.target.href||"";if(-1===n.indexOf("?"))return;const o=h(new URLSearchParams(n.substring(n.indexOf("?")))),r=getHotelBasicData(localStorage,o.hotel||t);if(r?.mobile_display_only&&window.innerWidth>=768)return;(isTemplateDomainMatch(r,e)||"true"===o.selfbook)&&(e.preventDefault(),b(o,r))}catch(t){console.error("a-element: err: ",t)}}))})),"complete"===document?.readyState?_():window?.addEventListener("load",_)}async function k(t,e){a=!0;const n=e?`?id=${e}`:"",o=await d({url:`${SELFBOOK_BACKEND_URL}/hotels/info${n}`,headers:{"content-type":"application/json","API-Key":t}});localStorage.setItem(SELFBOOK_HOTEL_GROUP_INFO,JSON.stringify(o)),s||w(),s=!0,a=!1}const S=document?.getElementById("selfbook_jssdk");if(S){const n=new URL(S.getAttribute("src"));if(t=n.searchParams.get("hotelId"),e=n.searchParams.get("apiKey"),!e||!t)throw new Error("(!) selfbook: ApiKey and HotelId are required.");window.isSelfbookSDKActive=!0,k(e,t),intervalWrapper((()=>{k(e,t)}),3e5),function(){const t=`\n      #selfbook_sdkwidget {\n        position: absolute;\n        width: 100%;\n        height: 100%;\n        top: 0px;\n        right: 0px;\n      }\n\n      #${SELFBOOK_WIDGET_RESUME} {\n        ${u()}\n      }\n\n      #${SELFBOOK_WIDGET_RESUME_TEXT} {\n        display: block!important;\n        font-family: ${p()}!important;\n        font-size: 14px!important;\n        font-weight: 400!important;\n        color: #ffffff!important;\n      }\n\n      .dismiss-btn-slide-in {\n        -webkit-transition: 500ms;\n        -moz-transition: 500ms;\n        transition: 500ms;\n        transform: translateX(0)!important\n      }\n\n      .dismiss-btn-slide-out {\n        -webkit-transition: 500ms;\n        -moz-transition: 500ms;\n        transition: 500ms;\n        transform: translateX(300px)!important\n      }\n\n      .dismiss-btn-slide-out span {\n        display: none;\n      }\n\n      .payment-summary-wrapper {\n        overflow: scroll!important;\n        -ms-overflow-style: none!important;\n        scrollbar-width: none!important;\n      }\n      .payment-summary-wrapper::-webkit-scrollbar {\n        display: none!important;\n      }\n\n      .dismiss-btn-resize-in {\n        width: 46px!important;\n        height: 46px!important;\n        transition: 500ms;\n        right: 30px!important;\n      }\n\n      .dismiss-btn-resize-in span {\n        display: none;\n      }\n\n      .dismiss-btn-resize-in:hover {\n        width: 217px!important;\n        height: 46px!important;\n        transition: all 300ms linear;\n        cursor: pointer;\n      }\n\n      .dismiss-btn-resize-in:hover span {\n        display: inline;\n        height: 20px!important;\n        overflow: hidden;\n      }\n\n      .dismiss-btn-resize-out {\n        width: 46px!important;\n        height: 46px!important;\n        transition: 500ms;\n        right: -100px!important;\n      }\n\n      .slide-in {\n        transform: translateX(100%);\n        -webkit-transform: translateX(100%);\n        animation: slide-in 0.8s forwards !important;\n        -webkit-animation: slide-in 0.8s forwards !important;\n        z-index: 1000000000000;\n      }\n\n      .slide-out {\n        transform: translateX(100%);\n        -webkit-transform: translateX(100%);\n        animation: slide-out 1s forwards !important;\n        -webkit-animation: slide-out 1s forwards !important;\n        z-index: -1000000000000;\n      }\n\n      @media screen and (max-width:495px) {\n        .slide-in {\n          transform: translateY(100%);\n          -webkit-transform: translateY(100%);\n          animation: slide-up 0.8s forwards !important;\n          -webkit-animation: slide-up 0.8s forwards !important;\n          z-index: 1000000000000;\n        }\n        .slide-out {\n          transform: translateY(100%);\n          -webkit-transform: translateY(100%);\n          animation: slide-down 0.5s forwards !important;\n          -webkit-animation: slide-down 1s forwards !important;\n          z-index: -1000000000000;\n        }\n      }\n\n      @keyframes slide-in {\n        100% {\n          transform: translateX(0%);\n        }\n      }\n\n      @-webkit-keyframes slide-in {\n        100% {\n          -webkit-transform: translateX(0%);\n        }\n      }\n\n      @keyframes slide-up {\n        100% {\n          transform: translateY(0%);\n        }\n      }\n\n      @-webkit-keyframes slide-up {\n        100% {\n          -webkit-transform: translateY(0%);\n        }\n      }\n\n      @keyframes slide-out {\n        0% {\n          transform: translateX(0%);\n        }\n        100% {\n          transform: translateX(100%);\n        }\n      }\n\n      @-webkit-keyframes slide-out {\n        0% {\n          -webkit-transform: translateX(0%);\n        }\n        100% {\n          -webkit-transform: translateX(100%);\n        }\n      }\n\n      @keyframes slide-down {\n        0% {\n          transform: translateY(0%);\n        }\n        100% {\n          transform: translateY(100%);\n        }\n      }\n\n      @-webkit-keyframes slide-down {\n        0% {\n          -webkit-transform: translateY(0%);\n        }\n        100% {\n          -webkit-transform: translateY(100%);\n        }\n      }\n    `,e=document.createElement("style");e.textContent=t,document.head.append(e),m(t)}()}window&&(window.sbApiLogger=function(n){try{d({url:`${SELFBOOK_BACKEND_URL}/hotels/${t}/events`,method:"POST",headers:{"content-type":"application/json","API-Key":e},data:JSON.stringify({generated_at:(new Date).toISOString(),event_source:"SDK",body:n})})}catch(t){console.log(t)}},window.book=function(t,e,n,o,r,a,s,i,l,d,c="fr",p,u,m){E({startDate:t,endDate:e,guests:n,propertyId:o,currency:r,roomId:a,ratePlanCode:s,rate:i,promoCode:l,groupCode:d,locale:c,destinationId:u,hotelId:p,roomCategory:m})},window.bookNow=E,window.closeSelfbookWidget=function(){const t=getElementById("selfbook_sdkwidget"),e=getElementById("selfbook_sdkwidget_wrapper"),n=getElementById(SELFBOOK_WIDGET_RESUME);document.body.style.overflow="initial",t.setAttribute("class","slide-out"),e.style.background="rgba(0, 0, 0, 0)",window.selfbookWidgetStore.dispatch({type:"WIDGET/SELFBOOK_WIDGET_CLOSED"}),window.selfbookWidgetStore.dispatch({type:"ANALYTICS/TRACK_EVENT",payload:{eventType:"widget closed"}}),setTimeout((()=>{t.style.display="none",e.style.zIndex=-1e11;const o=getFromLocalStorage(localStorage,SELFBOOK_HOTEL_GROUP_INFO);o&&(o.maintenance_mode||(n.setAttribute("class","dismiss-btn-slide-in"),n.focus()))}),800)})}runDirectApplication();

// /*
//     [iHotelier] Miiro Hotels - group site
//     https://www.miirohotels.com/
//     Borneta - 98767
//     Le Grand Hotel Cayre - 116367
// */

// Hotel's agency performed integration.
console.log(
    '%cCustom script has been initialized',
    'background: green; color: white;',
);


const customStyles = document.createElement('style');
customStyles.innerText = `
    /* hide beds icons */
    #selfbook_sdkwidget svg[title="bed"],
    #selfbook_sdkwidget svg[title="bed"] + div,
    #selfbook_sdkwidget [aria-label="Room details"] div.css-e4ugwc:first-child {
        display: none !important;
    }

    /* fix room title wrapping */
    li.sb-room-item h3 {
        width: 275px !important;
    }
    li.sb-room-item div.css-1y8jd5f {
        align-items: start !important;
    }
    [data-testid="sb-edit-booking-guest-count"] #sb-modalcontent [data-testid="sb-input-container"] span {
        display: none;
    }
    /* Style links in room description */
    #sb-screen-content #room-detail-description a {
        color: rgb(0, 123, 255) !important;
        cursor: pointer;
    }
    /* Style unsubscribe link */
    #selfbook_sdkwidget .payment-summary-wrapper form + div + button + div p a {
        color: #007BFF !important;
        text-decoration: underline;
        cursor: pointer;
    }
    `;
document.head.appendChild(customStyles);

setInterval(() => {
  // scrolling issue when mobile/responsive menu is open
  if (document.querySelector('nav[aria-label="Main"] ul li')) {
    document.querySelectorAll('nav[aria-label="Main"] ul li').forEach((li, index) => {
      const ctaText = li.innerText.toLowerCase();
      if (ctaText.includes('borneta') || ctaText.includes('cayr') || ctaText.includes('book now')) {
        if (!li.hasAttribute('data-sb-updated')) {
          li.setAttribute('data-sb-updated', 'true');
          li.addEventListener('click', (e) => {
            document.querySelector('button[aria-label="Open Menu"]').click();
          }
          );
        }
      }
    }
    );
  }
  if (document.querySelector('#sb-screen-content #room-detail-description a') && !document.querySelector('#sb-screen-content #room-detail-description a[target="_blank"]')) {
    document.querySelector('#sb-screen-content #room-detail-description a').setAttribute("target", "_blank");
  }
}, 1000);

// Save a reference to the original bookNow() function
const originalBookNow = bookNow;

// Custom function that tracks bookNow()
function sbBookNowTracker() {
  if (arguments.length && arguments[0] !== undefined) {
    let myArgs = arguments[0];
    // console.log("arguments hotelId:", myArgs.hotelId);
  } else {
    addSBcustomColor();
    // console.log("no arguments");
  }
}

// Override Selfbook's bookNow() function with new custom function
function newCustomBookNow(args) {
  sbBookNowTracker(args); // Pass the arguments to tracker function
  originalBookNow.apply(this, arguments); // Call the original function with the original arguments
}

// Assign override function to bookNow();
bookNow = newCustomBookNow;

function addSBcustomColor() {
  const customStyles = document.createElement("style");
  customStyles.innerText = `
        /* Style property selection screen only */
        /* English */
        [aria-label="BOOKING"] [data-testid="sb-screen-header"], 
        [aria-label="BOOKING"] [data-testid="sb-screen-body"], 
        [aria-label="BOOKING"] [data-testid="sb-screen-body"] [data-testid="sb-screen-footer"] button {
            background-color: #051E2B !important;
        }
        /* French */
        [aria-label="RÉSERVATION"] [data-testid="sb-screen-header"], 
        [aria-label="RÉSERVATION"] [data-testid="sb-screen-body"], 
        [aria-label="RÉSERVATION"] [data-testid="sb-screen-body"] [data-testid="sb-screen-footer"] button {
            background-color: #051E2B !important;
        }
        /* Spanish */
        [aria-label="RESERVANDO"] [data-testid="sb-screen-header"], 
        [aria-label="RESERVANDO"] [data-testid="sb-screen-body"], 
        [aria-label="RESERVANDO"] [data-testid="sb-screen-body"] [data-testid="sb-screen-footer"] button {
            background-color: #051E2B !important;
        }
    `;
  document.head.appendChild(customStyles);
}
if (window.location.href.includes("selfbook=true") && !window.location.href.includes("hotel=")) {
  addSBcustomColor()
}



let defaultTerms = {
  english: {
    box1: `I have read and accept the 
                <a href="https://www.miirohotels.com/terms-and-conditions" target="_blank" rel="noreferrer">Terms and Conditions</a>, 
                <a href="https://www.miirohotels.com/privacy-policy" target="_blank" rel="noreferrer">Privacy Policy</a> and 
                <a href="https://www.miirohotels.com/terms-of-use" target="_blank" rel="noreferrer">Terms of Use</a> of the hotel and 
                <a href="https://selfbook.com/legal/terms-and-conditions" target="_blank" rel="noreferrer">Selfbook</a>`,
    box2: `I would like to receive news and offers from all hotels within the same group`,
  },
  french: {
    box1: `J'ai lu et j'accepte les 
                <a href="https://www.miirohotels.com/fr/conditions-generales-dutilisation" target="_blank" rel="noreferrer">Conditions Générales</a>, la 
                <a href="https://www.miirohotels.com/fr/politique-de-confidentialite" target="_blank" rel="noreferrer">Politique de Confidentialité</a> et les 
                <a href="https://www.miirohotels.com/fr/conditions-dutilisation" target="_blank" rel="noreferrer">Conditions d'Utilisation</a>  de l'hôtel et de 
                <a href="https://selfbook.com/legal/terms-and-conditions" target="_blank" rel="noreferrer">Selfbook</a>`,
    box2: `Je souhaite recevoir les nouveautés et les offres de tous les hôtels du même groupe`,
  },
  spanish: {
    box1: `He leído y acepto los  
                <a href="https://www.miirohotels.com/es/terminos-y-condiciones" target="_blank" rel="noreferrer">Términos y Condiciones</a>, la 
                <a href="https://www.miirohotels.com/es/politica-de-privacidad" target="_blank" rel="noreferrer">Política de Privacidad</a> y las  
                <a href="https://www.miirohotels.com/es/condiciones-de-uso" target="_blank" rel="noreferrer">Condiciones de Uso </a> del hotel y de  
                <a href="https://selfbook.com/legal/terms-and-conditions" target="_blank" rel="noreferrer">Selfbook</a>`,
    box2: `Me gustaría recibir noticias y ofertas de todos los hoteles del mismo grupo`,
  },
};

function sbGetHotelInfo() {
  if (typeof selfbookWidgetStore !== 'undefined') {
    return selfbookWidgetStore?.getState()?.core?.hotel?.data?.id;
  }
  return "";
}

function setPolicies() {
  let hotelSpecificTerms = {
    /* Borneta */
    '98767': {
      box3_english: `By making the booking, you agree to receive news and offers from Borneta. In case you do not wish to receive such emails, please click <a href="mailto:marketing@hotelborneta.com" target="_blank">unsubscribe</a>.`,
      box3_spanish: `Al realizar la reserva, aceptas recibir noticias y ofertas de Borneta. En caso de que no desees recibir  correos electrónicos, haz clic <a href="mailto:marketing@hotelborneta.com" target="_blank">para darse de baja</a>.`,
      box3_french: `En effectuant la réservation, vous acceptez de recevoir des nouvelles et des offres du Borneta. Si vous ne souhaitez pas recevoir ces courriels, veuillez cliquer sur le bouton <a href="mailto:marketing@hotelborneta.com" target="_blank">se désabonner</a>.`,
    },
    /* Le Grand Hôtel Cayré */
    '116367': {
      box3_english: `By making the booking, you agree to receive news and offers from Le Grand Hôtel Cayré. In case you do not wish to receive such emails, please click <a href="mailto:marketing@legrandhotelcayre.com" target="_blank">unsubscribe</a>.`,
      box3_spanish: `Al realizar la reserva, aceptas recibir noticias y ofertas de Le Grand Hôtel Cayré. En caso de que no desees recibir  correos electrónicos, haz clic <a href="mailto:marketing@legrandhotelcayre.com" target="_blank">para darse de baja</a>.`,
      box3_french: `En effectuant la réservation, vous acceptez de recevoir des nouvelles et des offres du Le Grand Hôtel Cayré. Si vous ne souhaitez pas recevoir ces courriels, veuillez cliquer sur le bouton <a href="mailto:marketing@legrandhotelcayre.com" target="_blank">se désabonner</a>.`,
    },
    /* Templeton Garden */
    '9878941': {
      box3_english: `By making the booking, you agree to receive news and offers from Templeton Garden. In case you do not wish to receive such emails, please click <a href="mailto:marketing@templetongardens.com" target="_blank">unsubscribe</a>.`,
      box3_spanish: `Al realizar la reserva, aceptas recibir noticias y ofertas de Templeton Garden. En caso de que no desees recibir  correos electrónicos, haz clic <a href="mailto:marketing@templetongardens.com" target="_blank">para darse de baja</a>.`,
      box3_french: `En effectuant la réservation, vous acceptez de recevoir des nouvelles et des offres du Templeton Garden. Si vous ne souhaitez pas recevoir ces courriels, veuillez cliquer sur le bouton <a href="mailto:marketing@templetongardens.com" target="_blank">se désabonner</a>.`,
    }
  };
  let hotelId = sbGetHotelInfo();
  return hotelSpecificTerms[hotelId] || "Default";
};

function loopThroughPolicies(policyData) {

  let selectorList = [{
    // English: Box 1 
    selector: '#selfbook_sdkwidget [lang="en"] .payment-summary-wrapper label[for="i-accept-hotel-terms-checkbox"]:nth-child(2)',
    replaceWith: defaultTerms.english.box1
  }, {
      // English: Box 2 
      selector: '#selfbook_sdkwidget [lang="en"] .payment-summary-wrapper label[for="email-me-special-offers"]:nth-child(2)',
      replaceWith: defaultTerms.english.box2
    }, {
    // English: Box 3A (below checkout button) 
    selector: '#selfbook_sdkwidget [lang="en"] .payment-summary-wrapper form + div + button + div p',
      replaceWith: policyData.box3_english
    }, {
      // English: Box 3B (below checkout button) 
      selector: '#selfbook_sdkwidget [lang="en"] .payment-summary-wrapper form + div + div + div p',
      replaceWith: policyData.box3_english
    }, {
      // French: Box 1 
      selector: '#selfbook_sdkwidget [lang="fr"] .payment-summary-wrapper label[for="i-accept-hotel-terms-checkbox"]:nth-child(2)',
      replaceWith: defaultTerms.french.box1
    }, {
      // French: Box 2 
      selector: '#selfbook_sdkwidget [lang="fr"] .payment-summary-wrapper label[for="email-me-special-offers"]:nth-child(2)',
      replaceWith: defaultTerms.french.box2
    }, {
      // French: Box 3 (below checkout button) 
    selector: '#selfbook_sdkwidget [lang="fr"] .payment-summary-wrapper form + div + button + div p',
      replaceWith: policyData.box3_french
    }, {
      // French: Box 3B (below checkout button) 
      selector: '#selfbook_sdkwidget [lang="fr"] .payment-summary-wrapper form + div + div + div p',
      replaceWith: policyData.box3_french
    }, {
      // Spanish: Box 1 
      selector: '#selfbook_sdkwidget [lang="es"] .payment-summary-wrapper label[for="i-accept-hotel-terms-checkbox"]:nth-child(2)',
      replaceWith: defaultTerms.spanish.box1
    }, {
      // Spanish: Box 2 
      selector: '#selfbook_sdkwidget [lang="es"] .payment-summary-wrapper label[for="email-me-special-offers"]:nth-child(2)',
      replaceWith: defaultTerms.spanish.box2
    }, {
      // Spanish: Box 3 (below checkout button) 
    selector: '#selfbook_sdkwidget [lang="es"] .payment-summary-wrapper form + div + button + div p',
      replaceWith: policyData.box3_spanish
    }, {
      // Spanish: Box 3B (below checkout button) 
      selector: '#selfbook_sdkwidget [lang="es"] .payment-summary-wrapper form + div + div + div p',
      replaceWith: policyData.box3_spanish
    }];
  selectorList.forEach(({ selector, replaceWith }) => updateText(selector, replaceWith));
}

function updateText(selector, replace) {
  if (document.querySelector(selector) && !document.querySelector(selector).hasAttribute('data-sb-updated')) {
    let orgEl = document.querySelector(selector);
    let clonedEl = orgEl.cloneNode(true);
    orgEl.parentNode.replaceChild(clonedEl, orgEl);
    clonedEl.setAttribute('data-sb-updated', 'true');
    clonedEl.innerHTML = replace;
  }
}
setInterval(() => {
  if (typeof selfbookWidgetStore !== 'undefined') {
    if (selfbookWidgetStore?.getState()?.core?.hotel?.data?.id) {
      loopThroughPolicies(setPolicies());
    }

  }
}
  , 1000)



const customDescStyles = document.createElement("style");
customDescStyles.innerText = `
        #selfbook_sdkwidget .payment-summary-wrapper label a, #selfbook_sdkwidget .payment-summary-wrapper form + div + div + div p a {
            color: rgb(0, 123, 255) !important;
            cursor: pointer !important;
            font-weight: 500 !important;
            text-decoration: underline !important;
        }
        #selfbook_sdkwidget .payment-summary-wrapper label svg {
            margin-top: -20px !important;
        }

        #selfbook_sdkwidget .payment-summary-wrapper form + div + div + div p {
          text-align: left !important;
          width: 100% !important;
        }
    `;
document.head.appendChild(customDescStyles);