Home

<div id="pawscheck-chat-container" style="width:100%; max-width:800px; margin:0 auto; border:1px solid #ddd; border-radius:8px; font-family:Arial,sans-serif; box-shadow:0 2px 10px rgba(0,0,0,0.1);">
  <div style="background:#4CAF50; color:white; padding:15px; border-radius:8px 8px 0 0;">
    <h3 style="margin:0; font-size:18px;">PawsCheck Veterinary Assistant</h3>
  </div>
  <div id="pc-messages" style="height:400px; overflow-y:auto; padding:15px; background:#f9f9f9;"></div>
  <div style="display:flex; padding:12px; background:white; border-top:1px solid #eee;">
    <input id="pc-input" type="text" placeholder="Type your question here..." style="flex-grow:1; padding:12px 15px; border:1px solid #ddd; border-radius:20px; outline:none; font-size:14px;">
    <button id="pc-btn" style="background:#4CAF50; color:white; border:none; padding:12px 18px; margin-left:10px; border-radius:20px; cursor:pointer; font-weight:bold;">Send</button>
  </div>
</div>

<script>
window.addEventListener('load', function() {
  setTimeout(function() {
    // Initialize chat
    var messagesDiv = document.getElementById('pc-messages');
    var inputField = document.getElementById('pc-input');
    var sendButton = document.getElementById('pc-btn');
    var sessionId = 'session-' + Math.random().toString(36).substring(2, 15);
    
    // If elements not found, try again (sometimes needed in WordPress)
    if (!messagesDiv || !inputField || !sendButton) {
      console.error("PawsCheck: Elements not found on first try. Will retry.");
      setTimeout(arguments.callee, 500);
      return;
    }
    
    // Add welcome message
    messagesDiv.innerHTML = '<div style="background:#F1F1F1; padding:15px; border-radius:18px; margin-bottom:15px; max-width:85%; text-align:left;"><p>Hello! I\'m PawsCheck, your veterinary assistant. How can I help with your pet today?</p></div>';
    
    // Enhanced conversation tracking
    var conversationContext = {
      petType: null,
      petAge: null,
      petBreed: null,
      symptoms: [],
      symptomDuration: null,
      previousTreatments: [],
      medicationHistory: [],
      vaccineStatus: null,
      dietInfo: null,
      ownerConcerns: [],
      lastFollowUp: null,
      answeredQuestions: [],
      lastUserResponse: ""
    };
    
    // Common symptoms with their proper forms
    var commonSymptoms = [
      {text: "vomit", form: "vomiting"},
      {text: "diarrhea", form: "having diarrhea"},
      {text: "cough", form: "coughing"},
      {text: "sneez", form: "sneezing"},
      {text: "limp", form: "limping"},
      {text: "lame", form: "lame"},
      {text: "not eating", form: "not eating"},
      {text: "lethargy", form: "lethargic"},
      {text: "tired", form: "showing lethargy"},
      {text: "itch", form: "itching"},
      {text: "scratch", form: "scratching"},
      {text: "breath", form: "having breathing issues"},
      {text: "snor", form: "snoring"},
      {text: "eye", form: "having eye issues"},
      {text: "ear", form: "having ear issues"},
      {text: "drink", form: "drinking excessively"},
      {text: "urinat", form: "having urination issues"}
    ];
    
    // Function to extract information from user message
    function extractInformation(message) {
      try {
        var lowerMsg = message.toLowerCase();
        
        // Extract pet type
        if (!conversationContext.petType) {
          if (lowerMsg.includes("dog") || lowerMsg.includes("puppy")) {
            conversationContext.petType = "dog";
          } else if (lowerMsg.includes("cat") || lowerMsg.includes("kitten")) {
            conversationContext.petType = "cat";
          } else if (lowerMsg.includes("rabbit")) {
            conversationContext.petType = "rabbit";
          } else if (lowerMsg.includes("hamster")) {
            conversationContext.petType = "hamster";
          } else if (lowerMsg.includes("guinea pig")) {
            conversationContext.petType = "guinea pig";
          } else if (lowerMsg.includes("bird") || lowerMsg.includes("parrot")) {
            conversationContext.petType = "bird";
          }
        }
        
        // Extract pet age
        if (!conversationContext.petAge) {
          var ageRegex = /(\d+)\s*(year|month|week|day)s?\s*(old)?/i;
          var ageMatch = lowerMsg.match(ageRegex);
          if (ageMatch) {
            conversationContext.petAge = ageMatch[0];
          }
        }
        
        // Extract breed
        if (!conversationContext.petBreed && conversationContext.petType) {
          var dogBreeds = ["labrador", "retriever", "german shepherd", "bulldog", "poodle", "beagle", "rottweiler", "dachshund", "corgi"];
          var catBreeds = ["siamese", "persian", "maine coon", "bengal", "ragdoll", "british shorthair", "abyssinian"];
          
          var breeds = conversationContext.petType === "dog" ? dogBreeds : 
                      conversationContext.petType === "cat" ? catBreeds : [];
          
          for (var i = 0; i < breeds.length; i++) {
            if (lowerMsg.includes(breeds[i])) {
              conversationContext.petBreed = breeds[i];
              break;
            }
          }
        }
        
        // Extract symptoms
        for (var j = 0; j < commonSymptoms.length; j++) {
          var symptom = commonSymptoms[j];
          if (lowerMsg.includes(symptom.text) && !conversationContext.symptoms.includes(symptom.form)) {
            conversationContext.symptoms.push(symptom.form);
          }
        }
        
        // Extract symptom duration
        if (!conversationContext.symptomDuration) {
          var durationRegex = /(\d+)\s*(day|week|month|hour|minute)s?/i;
          var durationMatch = lowerMsg.match(durationRegex);
          if (durationMatch) {
            conversationContext.symptomDuration = durationMatch[0];
          } else if (lowerMsg.includes("yesterday")) {
            conversationContext.symptomDuration = "since yesterday";
          } else if (lowerMsg.includes("today")) {
            conversationContext.symptomDuration = "since today";
          } else if (lowerMsg.includes("since")) {
            var sinceIndex = lowerMsg.indexOf("since");
            if (sinceIndex !== -1) {
              var nextSpaceIndex = lowerMsg.indexOf(" ", sinceIndex + 6);
              var endIndex = nextSpaceIndex !== -1 ? nextSpaceIndex : lowerMsg.length;
              var sincePhrase = lowerMsg.substring(sinceIndex, endIndex);
              conversationContext.symptomDuration = sincePhrase;
            }
          }
        }
        
        // Extract medication history
        var medications = ["antibiotic", "steroid", "insulin", "thyroid", "pain", "nsaid", "anti-inflammatory", "allergy", "heartworm"];
        for (var k = 0; k < medications.length; k++) {
          if (lowerMsg.includes(medications[k]) && !conversationContext.medicationHistory.includes(medications[k])) {
            conversationContext.medicationHistory.push(medications[k]);
          }
        }
        
        // Extract vaccination status
        if (conversationContext.vaccineStatus === null) {
          if (lowerMsg.includes("vaccin")) {
            if (lowerMsg.includes("up to date") || lowerMsg.includes("current") || lowerMsg.includes("recent")) {
              conversationContext.vaccineStatus = true;
            } else if (lowerMsg.includes("not vaccin") || lowerMsg.includes("no vaccin") || lowerMsg.includes("behind")) {
              conversationContext.vaccineStatus = false;
            }
          }
        }
        
        // Save the last user response
        conversationContext.lastUserResponse = message;
      } catch (error) {
        console.error("Error in extractInformation:", error);
      }
    }
    
    // Function to format responses better
    function formatResponse(text) {
      try {
        // Clean up any XML/HTML tags from the response
        text = text.replace(/<\/?[^>]+(>|$)/g, "");
        
        // Fix spacing issues by joining broken lines
        text = text.replace(/([a-z,.!?:;])\n([a-z])/g, '$1 $2');
        
        // Fix numbered list items that might be broken
        text = text.replace(/(\d+\.\s+)([A-Z][^:]+):\s*\n/g, '$1<strong>$2</strong>: ');
        
        // Bold
        text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        
        // Italic
        text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
        
        // Paragraphs
        text = text.replace(/\n\n+/g, '</p><p>');
        text = '<p>' + text + '</p>';
        
        return text;
      } catch (error) {
        console.error("Error in formatResponse:", error);
        // Fallback to simpler formatting
        return '<p>' + text.replace(/\n\n/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';
      }
    }
    
    // Send message function
    function sendMessage() {
      try {
        var message = inputField.value.trim();
        if (!message) return;
        
        // Clear input
        inputField.value = '';
        
        // Extract information
        extractInformation(message);
        
        // Add user message
        messagesDiv.innerHTML += '<div style="background:#E3F2FD; padding:15px; border-radius:18px; margin-bottom:15px; max-width:85%; margin-left:auto; text-align:left;"><p>' + message + '</p></div>';
        
        // Scroll to bottom
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
        
        // Call API
        fetch('https://pawscheck-389381042163.us-central1.run.app/api/vet_consult', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            query: message,
            session_id: sessionId
          })
        })
        .then(function(response) {
          return response.json();
        })
        .then(function(data) {
          // Add bot response with better formatting
          if (data && data.response) {
            var formattedResponse = formatResponse(data.response);
            messagesDiv.innerHTML += '<div style="background:#F1F1F1; padding:15px; border-radius:18px; margin-bottom:15px; max-width:85%; text-align:left;">' + formattedResponse + '</div>';
          } else {
            throw new Error("Invalid response format");
          }
          
          // Scroll to bottom
          messagesDiv.scrollTop = messagesDiv.scrollHeight;
        })
        .catch(function(error) {
          console.error("API error:", error);
          // Add error message
          messagesDiv.innerHTML += '<div style="background:#F1F1F1; padding:15px; border-radius:18px; margin-bottom:15px; max-width:85%; text-align:left;"><p>Sorry, I encountered an error. Please try again later.</p></div>';
          
          // Scroll to bottom
          messagesDiv.scrollTop = messagesDiv.scrollHeight;
        });
      } catch (error) {
        console.error("Error in sendMessage:", error);
        // Add error message
        messagesDiv.innerHTML += '<div style="background:#F1F1F1; padding:15px; border-radius:18px; margin-bottom:15px; max-width:85%; text-align:left;"><p>Sorry, something went wrong. Please try again.</p></div>';
        
        // Scroll to bottom
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
      }
    }
    
    // Event listeners
    sendButton.addEventListener('click', sendMessage);
    
    inputField.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        sendMessage();
      }
    });
  }, 500); // 500ms delay to ensure DOM is ready
});
</script>