<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Chatbot By Dailybranding.Tech</title>
    <meta property="og:title" content="Ganesh Saw Mill" />
    <meta property="og:description" content="Premium Laminated Mica, Doors, and UPVC solutions." />
    <meta property="og:image" content="https://dailybranding.tech/GSM/2.jpg" />
    <meta property="og:type" content="website" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    
 <link rel="manifest" href="manifest.json">
  <style>
    #install-btn {
    padding: 10px 20px;
    background-color: transparent;
    color: white;
    border: none;
    cursor: pointer;
    display: none; /* Hidden by default, shown with JavaScript */
    background-image: url('playstore.webp');
    background-repeat: no-repeat;
    background-position: 10px center; /* Position image 10px from left and vertically centered */
    background-size: 40px auto; /* Increased size to 40px width (adjust as needed) */
    font-size: 16px;
    border-radius: 5px;
    position: fixed;
    top: 10px;
    right: 50px;
    z-index: 90;
    padding-left: 40px; 
    height: 40px;
    }
    iframe {width: 100%; }
  </style>
  <button id="install-btn"></button>
  <script>
    let deferredPrompt;
    const installButton = document.getElementById('install-btn');
    window.addEventListener('beforeinstallprompt', (e) => {
      e.preventDefault();
      deferredPrompt = e;
      installButton.style.display = 'block';
      installButton.addEventListener('click', () => {
        deferredPrompt.prompt();
        deferredPrompt.userChoice.then((choiceResult) => {
          console.log(choiceResult.outcome);  // 'accepted' or 'dismissed'
          deferredPrompt = null;
          installButton.style.display = 'none';
        });
      });
    });
  </script>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('./service-worker.js')
          .then((registration) => {
            console.log('Service Worker registered with scope:', registration.scope);
          })
          .catch((error) => {
            console.log('Service Worker registration failed:', error);
          });
      });
    }
  </script>
 <style>
      /* Button Style */
#qr-button {
padding: 10px 20px;
    background-color: transparent;
    color: white;
    border: none;
    cursor: pointer;
    position: fixed;
    top: 10px;
    right: 10px;
    z-index: 500;
    margin-left:200px;
    height: 40px;
}
/* Modal Styles */
.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 10px;
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: auto; /* Let content determine width, respecting max-width */
    aspect-ratio: 1 / 1;
    max-width: 300px;
    position: relative;
    border-radius: 20px;
    display: flex; /* Enable flexbox for centering */
    justify-content: center; /* Center content horizontally */
    align-items: center; /* Center content vertically */
    flex-direction: column; /* Optional: Stack items vertically if needed */
}
.close {
    color: #aaa;
   
    top: 0;
    font-size: 28px;
    font-weight: bold;
}
#qrcode {
    display: flex;
    justify-content: center;
}

  </style>
  <button id="qr-button">
        <img src="qr.png" alt="QR Code Icon" width="20px" style="vertical-align: middle;">
    </button>

    <div id="qr-modal" class="modal">
        <div class="modal-content">
            
            <div id="qrcode"></div>
        </div>
        <span class="close">×</span>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="script.js"></script>
    <style>
        table {
            display: none !important;
        }
        video{ 
            width: 100%;
        }
        img {
            width: 100%;
        }
    </style>
    <link rel="stylesheet" href="style.css">
</head>
<body >
<div class="chat-container">
    <div class="chat-header">
        <img src="2.png" alt="Bot Avatar">
        <div>
            <div class="name">GANESH SAW MILL </div>
            <div class="status"><a class="status" href="https://wa.me/+919307137189?text=Hi%2C%20I'm%20interested%20in%20learning%20more%20about%20your%20chatbot." target="_blank">
        Powred By Daily Branding
    </a></div>
        </div>
        
    </div>
    <div class="chat-messages" id="chat-messages"></div>
    
    <div class="chat-input" id="chat-input" style="display:none;">
        <input type="text" id="user-input" placeholder="Type your message...">
        <button id="send-button"><i class="fas fa-paper-plane"></i></button>
    </div>
</div>
<div id="sidebar">
    <iframe id="sidebarIframe" src="" frameborder="0"></iframe>
</div>
<!-- Overlay to close sidebar when clicked outside -->
<div id="overlay"></div>
</div>
<script>
    const chatMessages = document.getElementById('chat-messages');
    const optionsContainer = document.getElementById('options-container');
    const chatInput = document.getElementById('chat-input');
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-button');
    // setting
    fetch('./data/BPW.json') // Adjust the path if needed
        .then(response => response.json())
        .then(data => {
            //const chatbotData = data;
            const chatbotData = data.botdata;
            let currentStep = 'step1';
            ////setting
            const MAX_INITIAL_BUTTONS = 8;
            function displayMessage(message, sender = 'bot', options = null) {
                const messageDiv = document.createElement('div');
                messageDiv.classList.add('message', sender);
            
                const textDiv = document.createElement('div');
                textDiv.classList.add('text');
                messageDiv.appendChild(textDiv);
            
                if (sender === 'bot') {
                    // Typing indicator for bot messages
                    messageDiv.classList.add('typing');
                    const typingIndicator = document.createElement('div');
                    typingIndicator.classList.add('typing-dots');
                    typingIndicator.innerHTML = `
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                    `;
                    messageDiv.appendChild(typingIndicator);
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                        
                    // Simulate typing
                    setTimeout(() => {
                        messageDiv.classList.remove('typing');
                        messageDiv.classList.add('show-text');
                        textDiv.innerHTML = message; // Set message text
            
                        // Display options if provided
                        if (options) {
                            const optionsContainer = document.createElement('div');
                            optionsContainer.classList.add('options-container');
            
                            const initialButtons = options.slice(0, MAX_INITIAL_BUTTONS);
                            const additionalButtons = options.slice(MAX_INITIAL_BUTTONS);
            
                            initialButtons.forEach(option => {
                                const button = document.createElement('button');
                                button.innerHTML = option.text;
                                button.classList.add('option-button');
                                // Add url attribute if option.button exists
                                if (option.button) {
                                    button.setAttribute('url', option.button);
                                    button.classList.add('openSidebarBtn'); // Add the class for sidebar buttons
                                }
                                button.addEventListener('click', () => handleOptionClick(option));
                                optionsContainer.appendChild(button);
                            });
            
                            if (additionalButtons.length > 0) {
                                const moreButton = document.createElement('button');
                                moreButton.innerHTML = 'More Options';
                                moreButton.classList.add('option-button', 'more-options-btn');
                                moreButton.addEventListener('click', () => openMoreOptionsModal(additionalButtons));
                                optionsContainer.appendChild(moreButton);
                            }
            
                            textDiv.appendChild(optionsContainer);
            
                            // *** Call attachSidebarButtonListeners after initial buttons are added ***
                            attachSidebarButtonListeners();
                        }
            
                        // Show message after a delay
                        setTimeout(() => {
                            messageDiv.classList.add('show', 'show-text');
                            chatMessages.scrollTop = chatMessages.scrollHeight;
                        }, 300);
                        //setting
                    }, 1200); // Typing duration
                } else {
                    // User messages - show immediately
                    textDiv.innerHTML = message;
                    messageDiv.classList.add('show-text', 'show'); // Show immediately
                }
            
                chatMessages.appendChild(messageDiv);
            
                // Scroll to the bottom after adding the message
                chatMessages.scrollTop = chatMessages.scrollHeight;
            
                // Add a slight delay to ensure proper scrolling on some mobile devices
         
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                
            }

            function openMoreOptionsModal(additionalButtons) {
                // Create or get existing sidebar
                let sidebar = document.getElementById('more-options-sidebar');
                let overlay = document.getElementById('more-options-overlay');

                if (!sidebar) {
                    // Create sidebar
                    sidebar = document.createElement('div');
                    sidebar.id = 'more-options-sidebar';
                    sidebar.classList.add('more-options-sidebar');

                    // Create overlay
                    overlay = document.createElement('div');
                    overlay.id = 'more-options-overlay';
                    overlay.classList.add('more-options-overlay');

                    // Append to body
                    document.body.appendChild(sidebar);
                    document.body.appendChild(overlay);

                    // Add click outside listener to close sidebar
                    overlay.addEventListener('click', closeMoreOptionsModal);
                }

                // Clear previous buttons
                sidebar.innerHTML = '';

                // Add title
                const title = document.createElement('div');
                title.classList.add('sidebar-title');
                title.textContent = 'More Options';
                sidebar.appendChild(title);

                // Render additional buttons
                additionalButtons.forEach(option => {
                    const button = document.createElement('button');
                    button.innerHTML = option.text;
                    button.classList.add('sidebar-option-button');
                    button.addEventListener('click', () => {
                        handleOptionClick(option);
                        closeMoreOptionsModal();
                    });
                    sidebar.appendChild(button);
                });

                // Show sidebar and overlay
                sidebar.classList.add('open');
                overlay.classList.add('active');
            }

            function closeMoreOptionsModal() {
                const sidebar = document.getElementById('more-options-sidebar');
                const overlay = document.getElementById('more-options-overlay');

                if (sidebar) sidebar.classList.remove('open');
                if (overlay) overlay.classList.remove('active');
            }

// Add CSS for the sidebar and overlay
            const style = document.createElement('style');
            style.textContent = `
  .more-options-sidebar {
    position: fixed;
    bottom: -100%;
    left: 0;
    width: 100%;
    background: white;
    z-index: 1000;
    transition: bottom 0.5s ease;
    max-height: 70vh;
    overflow-y: auto;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    box-shadow: 0 -5px 15px rgba(0,0,0,0.1);
  }

  .more-options-sidebar.open {
    bottom: 0;
  }

  .more-options-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 999;
    display: none;
  }

  .more-options-overlay.active {
    display: block;
  }

  .sidebar-title {
    text-align: center;
    padding: 15px;
    font-weight: bold;
    border-bottom: 1px solid #eee;
  }

  .sidebar-option-button {
    width: 100%;
    padding: 15px;
    text-align: left;
    border: none;
    border-bottom: 1px solid #eee;
    background: white;
  }

  .sidebar-option-button:hover {
    background: #f5f5f5;
  }

  .more-options-btn {
    background-color: #95ffb7;
    color: #333;
  }
`;
            document.head.appendChild(style);

            const notificationSound = new Audio('https://asset.mindvyuh.com/pop.mp3');

            function handleOptionClick(option) {
                if (option.link) {
                    window.open(option.link, '_blank');
                } else if (option.next && chatbotData[option.next]) {
                    const clickedOptionText = event.target.innerHTML;
                    displayMessage(clickedOptionText, 'user');
                    notificationSound.play();
                    currentStep = option.next;
                    showNextStep();
                } else if (option.button) {
                    openSidebar(option.button);
                } else {
                    displayMessage(chatbotData.invalid.message, 'error');
                }
            }

            function showNextStep() {
                const stepData = chatbotData[currentStep];
                if (stepData) {
                    let message = stepData.message || "";
                    let options = stepData.options || null;
                    displayMessage(message, 'bot', options);
                    if (!options) {
                        chatInput.style.display = 'flex';
                    }
                    // After rendering the message with buttons, reattach event listeners
                    attachSidebarButtonListeners();
                } else {
                    displayMessage("An error occurred. Check your JSON data.", "error");
                }
            }

// Function to attach event listeners to all dynamically added buttons
            function attachSidebarButtonListeners() {
                const buttons = document.querySelectorAll('.openSidebarBtn');
                buttons.forEach(button => {
                    button.addEventListener('click', function () {
                        const url = button.getAttribute('url');
                        openSidebar(url);
                    });
                });
            }

            showNextStep();  // Initial call to start the conversation
        })
        .catch(error => {
            console.error("Error loading chatbot data:", error);
        });
        
        
        
        
        
       class InteractionTracker {
            constructor(botId, serverUrl = 'https://analytics.dailybranding.tech') {
              this.botId = botId;
              this.serverUrl = serverUrl;
              this.sessionId = this.getSessionId();
              this.initializeTracking();
            }
          
            // Get session ID from localStorage or generate a new one
            getSessionId() {
              try {
                let sessionId = localStorage.getItem('sessionId');
                if (!sessionId) {
                  sessionId = this.generateUniqueId(); // Use a custom function for ID generation
                  localStorage.setItem('sessionId', sessionId);
                }
                return sessionId;
              } catch (error) {
                console.error('Error accessing localStorage:', error);
                // Fallback: Generate a session ID without local storage (less ideal)
                return this.generateUniqueId();
              }
            }
              // Function to generate a UUID-like string
              generateUniqueId() {
                  return 'xxx-xxxx-4xx-yxxx-x'.replace(/[xy]/g, function(c) {
                      var r = Math.random() * 16 | 0,
                          v = c == 'x' ? r : (r & 0x3 | 0x8);
                      return v.toString(16);
                  });
              }
          
            async initializeTracking() {
              try {
                console.log('Session initialized with ID:', this.sessionId);
                this.trackView(); // Track the initial page view
                this.attachInitialTracking();
                this.setupMutationObserver();
              } catch (error) {
                console.error('Failed to initialize tracking:', error);
              }
            }
          
            async trackView() {
              this.trackInteraction('view', null); // Send a "view" event
            }
          
            async trackButtonClick(buttonText) {
              this.trackInteraction('button_click', buttonText);
            }
          
            async trackInteraction(type, buttonText) {
              try {
                const response = await fetch(`${this.serverUrl}/track_interaction`, {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify({
                    sessionId: this.sessionId,
                    botId: this.botId,
                    type: type, // 'view' or 'button_click'
                    buttonText: buttonText, // Optional for button clicks
                  }),
                });
          
                if (!response.ok) {
                  throw new Error('Tracking request failed with status: ' + response.status);
                }
              } catch (error) {
                console.error('Interaction tracking error:', error);
              }
            }
            attachInitialTracking() {
                // Delay to ensure initial buttons are rendered
                setTimeout(() => {
                    const initialButtons = document.querySelectorAll(
                        '.options-container .option-button, ' + 
                        '.options-container .more-options-btn, ' + 
                        '.sidebar-option-button'
                    );
                    
                    initialButtons.forEach(button => {
                        // Remove any existing listeners to prevent duplicates
                        button.removeEventListener('click', this.handleButtonClick);
                        
                        // Add click listener
                        const boundClickHandler = this.handleButtonClick.bind(this, button);
                        button.addEventListener('click', boundClickHandler);
                    });
                }, 100);
            }
          
            setupMutationObserver() {
                // Create a MutationObserver to watch for new buttons
                const observer = new MutationObserver((mutations) => {
                    mutations.forEach((mutation) => {
                        if (mutation.type === 'childList') {
                            mutation.addedNodes.forEach((node) => {
                                if (node.nodeType === Node.ELEMENT_NODE) {
                                    // Find buttons within the added node
                                    const buttons = node.querySelectorAll(
                                        '.option-button, ' + 
                                        '.sidebar-option-button, ' + 
                                        '.more-options-btn'
                                    );
                                    
                                    buttons.forEach(button => {
                                        // Remove any existing listeners to prevent duplicates
                                        button.removeEventListener('click', this.handleButtonClick);
                                        
                                        // Bind the click handler with the correct context
                                        const boundClickHandler = this.handleButtonClick.bind(this, button);
                                        button.addEventListener('click', boundClickHandler);
                                    });
                                }
                            });
                        }
                    });
                });
          
                // Configure the observer
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
          
            handleButtonClick = (button) => {
                // Track the button click
                this.trackButtonClick(button.textContent);
            }
          }
          // Initialize tracker when DOM is ready
          document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => {
                const deploymentId = getDeploymentIdentifier();
                const cartKey = `cart_${deploymentId}`; // Example: 'cart_gsm', 'cart_TDS'
                console.log('Cart Key:', cartKey);
                window.interactionTracker = new InteractionTracker(cartKey);
              //window.interactionTracker = new InteractionTracker('GSM');
            }, 500);
          });       
          function getDeploymentIdentifier() {
            const path = window.location.pathname;
            const segments = path.replace(/^\/+|\/+$/g, '').split('/');
            return segments[0] || 'default';
        }

</script>
<script>
    // JavaScript for Sidebar Toggle and Dynamic Button Handling
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('overlay');
    const sidebarIframe = document.getElementById('sidebarIframe');

    // Function to open the sidebar with a specific iframe URL
    function openSidebar(url) {
        // Set the iframe URL
        sidebarIframe.src = url;
        // Show the sidebar and overlay
        sidebar.style.bottom = "0";
        overlay.classList.add("active");
        // Push a new state to the history
        history.pushState({sidebarOpen: true}, "", window.location.href);

    }

    // Function to close the sidebar
    function closeSidebar() {
        // Hide the sidebar and overlay
        sidebar.style.bottom = "-100%";
        overlay.classList.remove("active");
        sidebarIframe.src = ""; // Clear iframe content
        // Push a new state to the history to reflect the sidebar closed state
        history.pushState({sidebarOpen: false}, "", window.location.href);
    }

    // Event listener to close the sidebar if clicking outside (on overlay)
    overlay.addEventListener('click', closeSidebar);
    // Select all buttons with class 'openSidebarBtn' and add click event listeners
    const buttons = document.querySelectorAll('.openSidebarBtn');
    buttons.forEach(button => {
        button.addEventListener('click', function () {
            const url = button.getAttribute('url');
            openSidebar(url);
        });
    });

    // Handle back button click (popstate event)
    window.onpopstate = function (event) {
        if (event.state && event.state.sidebarOpen) {
            // Do nothing if the sidebar was already open
        } else {
            // If the state indicates that the sidebar was not open, close it
            closeSidebar();
        }
    };
</script>
<script src="https://asset.mindvyuh.com/fullscreen.js"></script>
<script   disable-devtool-auto="" src="https://asset.mindvyuh.com/disable-devtool.min.js.download" url="https://www.instagram.com/mindvyuh_official/" disable-menu="true"></script>

</body>
</html>