class ShopifyChatbot{constructor(a){this.webhookUrl=a.webhookUrl;this.metadata=a.metadata||{};this.config=a;this.sessionExpiryHours=24;this.isOpen=!1;this.whatsappSales=a.whatsappSales||"5511999999999";this.whatsappSupport=a.whatsappSupport||"5511999999999";this.bottomOffset=a.bottomOffset||20;this.buttonIcon=a.buttonIcon||"\ud83d\udcac";this.whatsappIcon=a.whatsappIcon||"\ud83d\udcf1";this.initializeSession();this.initializeElements();this.attachEventListeners();this.autoResize();this.startPulseAnimation();
this.createHoverMenu();this.restorePreviousConversation();this.applyCustomStyles();this.applyPositioning()}startPulseAnimation(){this.toggleBtn.addEventListener("click",()=>{this.toggleBtn.classList.remove("chat-pulse")},{once:!0})}createHoverMenu(){if(!(window.innerWidth<=768)){var a=document.createElement("div");a.id="chat-hover-menu";a.innerHTML=`
${this.whatsappIcon}
WhatsApp Suporte
${this.whatsappIcon}
WhatsApp Vendas
`;this.container.appendChild(a);var b,c=()=>{b=setTimeout(()=>{a.classList.remove("show")},200)};this.toggleBtn.addEventListener("mouseenter",()=>{this.isOpen||(clearTimeout(b),a.classList.add("show"))});this.toggleBtn.addEventListener("mouseleave",c);a.addEventListener("mouseenter",()=>{clearTimeout(b);a.classList.add("show")});a.addEventListener("mouseleave",c);a.addEventListener("click",d=>{if(d=d.target.closest(".hover-option")){switch(d.dataset.action){case "whatsapp-sales":this.openWhatsAppSales();
break;case "whatsapp-support":this.openWhatsAppSupport();break;case "chatbot":this.toggleChat()}a.classList.remove("show")}})}}openWhatsAppSales(){const a=encodeURIComponent("Ol\u00e1! Gostaria de saber mais sobre os produtos da Minimal Club.");window.open(`https://wa.me/${this.whatsappSales}?text=${a}`,"_blank")}openWhatsAppSupport(){const a=encodeURIComponent("Ol\u00e1! Preciso de suporte com meu pedido na Minimal Club.");window.open(`https://wa.me/${this.whatsappSupport}?text=${a}`,"_blank")}initializeSession(){const a=
this.getStoredSession();a&&!this.isSessionExpired(a.timestamp)?(this.sessionId=a.sessionId,console.log("Restored existing session:",this.sessionId)):(this.sessionId=this.generateSessionId(),this.saveSessionToStorage(),console.log("Created new session:",this.sessionId))}generateSessionId(){return"session_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}getStoredSession(){try{const a=localStorage.getItem("shopify_chatbot_session");return a?JSON.parse(a):null}catch(a){return console.error("Error reading session from localStorage:",
a),null}}saveSessionToStorage(){try{const a={sessionId:this.sessionId,timestamp:Date.now(),messages:[]};localStorage.setItem("shopify_chatbot_session",JSON.stringify(a))}catch(a){console.error("Error saving session to localStorage:",a)}}isSessionExpired(a){return Date.now()-a>this.sessionExpiryHours*60*60*1E3}saveMessageToStorage(a,b){try{const c=this.getStoredSession();c&&(c.messages.push({text:a,sender:b,timestamp:Date.now()}),c.messages.length>50&&(c.messages=c.messages.slice(-50)),localStorage.setItem("shopify_chatbot_session",
JSON.stringify(c)))}catch(c){console.error("Error saving message to localStorage:",c)}}restorePreviousConversation(){const a=this.getStoredSession();if(a&&a.messages&&a.messages.length>0){this.messagesContainer.innerHTML="";const b=document.createElement("div");b.className="welcome-message";b.textContent="Ol\u00e1, sou o Isra e estou aqui pra te ajudar no que for preciso?";this.messagesContainer.appendChild(b);a.messages.forEach(c=>{this.addMessageToDOM(c.text,c.sender,!1)});console.log(`Restored ${a.messages.length} previous messages`)}}clearSession(){try{localStorage.removeItem("shopify_chatbot_session");
this.sessionId=this.generateSessionId();this.saveSessionToStorage();this.messagesContainer.innerHTML="";const a=document.createElement("div");a.className="welcome-message";a.innerHTML="\n \ud83c\udfea Minimal Club
\n Ol\u00e1! Seja muito bem-vindo(a) \u00e0 Minimal Club.
\n Sou o Isra, seu especialista de produto e gerente de sucesso do cliente. Como posso te ajudar hoje a encontrar a pe\u00e7a perfeita que voc\u00ea procura? \ud83d\ude0a\n ";this.messagesContainer.appendChild(a);
const b=document.createElement("div");b.className="session-info";b.innerHTML=`
\ud83d\udcac Nova sess\u00e3o iniciada \u2022 ID: ${this.sessionId.substring(0,8)}...
`;this.messagesContainer.appendChild(b);this.scrollToBottom();console.log("Session cleared, new session created:",this.sessionId)}catch(a){console.error("Error clearing session:",a)}}applyCustomStyles(){this.config&&this.config.buttonColor&&(this.toggleBtn.style.background=this.config.buttonColor);this.config&&this.config.position==="bottom-left"&&(this.container.style.left="20px",this.container.style.right="auto")}applyPositioning(){this.container.style.bottom=`${this.bottomOffset}px`;(this.container.getAttribute("data-position")||
"bottom-right")==="bottom-left"?(this.container.style.left="20px",this.container.style.right="auto"):(this.container.style.right="20px",this.container.style.left="auto")}initializeElements(){this.container=document.getElementById("chatbot-container");this.toggleBtn=document.getElementById("chat-toggle");this.chatWindow=document.getElementById("chat-window");this.closeBtn=document.getElementById("chat-close");this.messagesContainer=document.getElementById("chat-messages");this.inputField=document.getElementById("chat-input");
this.sendBtn=document.getElementById("chat-send")}attachEventListeners(){this.toggleBtn.addEventListener("click",()=>this.toggleChat());this.closeBtn.addEventListener("click",()=>this.closeChat());this.sendBtn.addEventListener("click",()=>this.sendMessage());var a=document.getElementById("whatsapp-button");a&&a.addEventListener("click",()=>this.openWhatsApp());this.inputField.addEventListener("keypress",b=>{b.key!=="Enter"||b.shiftKey||(b.preventDefault(),this.sendMessage())});this.inputField.addEventListener("input",
()=>this.autoResize());(a=document.getElementById("chat-clear"))&&a.addEventListener("click",b=>{b.preventDefault();b.stopPropagation();confirm("Limpar hist\u00f3rico de conversa? Isso iniciar\u00e1 uma nova sess\u00e3o.")&&this.clearSession()});this.chatWindow.querySelector("#chat-header").addEventListener("contextmenu",b=>{b.preventDefault();confirm("Limpar hist\u00f3rico de conversa? Isso iniciar\u00e1 uma nova sess\u00e3o.")&&this.clearSession()});this.initSimpleMobileKeyboard()}initSimpleMobileKeyboard(){window.innerWidth<=
768&&(this.inputField.addEventListener("focus",()=>{setTimeout(()=>{document.body.classList.add("keyboard-active")},300)}),this.inputField.addEventListener("blur",()=>{setTimeout(()=>{document.body.classList.remove("keyboard-active")},300)}))}openWhatsApp(){const a=encodeURIComponent("Ol\u00e1! Estou com uma d\u00favida sobre a Minimal Club.");window.open(`https://wa.me/${this.whatsappSupport}?text=${a}`,"_blank")}autoResize(){this.inputField.style.height="auto";this.inputField.style.height=Math.min(this.inputField.scrollHeight,
100)+"px"}toggleChat(){this.isOpen?this.closeChat():this.openChat()}openChat(){this.chatWindow.style.display="flex";this.toggleBtn.innerHTML="\u00d7";this.isOpen=!0;setTimeout(()=>{this.inputField.focus()},100)}closeChat(){this.chatWindow.style.display="none";this.toggleBtn.innerHTML=this.buttonIcon;this.isOpen=!1;document.body.classList.remove("keyboard-active")}convertMarkdownToHtml(a){a=a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'");
a=a.replace(/\[([^\]]+)\]\((https?:\/\/[^\s\)]+)\)/g,'$1');a=a.replace(/\n/g,"
");a=a.replace(/\*\*([^*]+)\*\*/g,"$1");return a=a.replace(/\*([^*]+)\*/g,"$1")}addMessage(a,b,c=!0){this.addMessageToDOM(a,b,c)}addMessageToDOM(a,b,c=!0){const d=document.createElement("div");d.className=`message ${b}`;b==="bot"?d.innerHTML=this.convertMarkdownToHtml(a):d.textContent=a;this.messagesContainer.appendChild(d);this.scrollToBottom();
c&&this.saveMessageToStorage(a,b)}async sendMessage(){const a=this.inputField.value.trim();if(a){var b=this.getStoredSession();if(!b||this.isSessionExpired(b.timestamp))console.log("Session expired, creating new session"),this.clearSession();this.setInputState(!1);this.addMessage(a,"user");this.inputField.value="";this.autoResize();b=this.showTyping();try{const c=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chatInput:a,sessionId:this.sessionId,
metadata:{...this.metadata,timestamp:(new Date).toISOString(),user_agent:navigator.userAgent,current_page:window.location.href}})});if(!c.ok)throw Error(`HTTP error! status: ${c.status}`);const d=await c.json();this.removeTyping(b);this.addMessage(d.output||"Sorry, I encountered an error. Please try again.","bot")}catch(c){console.error("Chat error:",c),this.removeTyping(b),this.addMessage("Sorry, I'm having trouble connecting. Please try again later.","bot")}finally{this.setInputState(!0),this.inputField.focus()}}}showTyping(){const a=
"typing_"+Date.now(),b=document.createElement("div");b.className="message typing";b.id=a;b.innerHTML='\n Typing\n \n ';this.messagesContainer.appendChild(b);this.scrollToBottom();return a}removeTyping(a){(a=document.getElementById(a))&&a.remove()}setInputState(a){this.inputField.disabled=!a;this.sendBtn.disabled=!a}scrollToBottom(){this.messagesContainer.scrollTop=
this.messagesContainer.scrollHeight}getSessionInfo(){const a=this.getStoredSession();return{currentSessionId:this.sessionId,storedSession:a,isExpired:a?this.isSessionExpired(a.timestamp):null,messageCount:a?a.messages.length:0}}};