<%# Ahoy.js - Built-in visitor analytics (async loading for page speed) %>
<script>
  // Load Ahoy.js asynchronously after page load for better page speed
  document.addEventListener('DOMContentLoaded', function() {
    var ahoyScript = document.createElement('script');
    ahoyScript.src = 'https://cdn.jsdelivr.net/npm/ahoy.js@0.4.2/dist/ahoy.min.js';
    ahoyScript.async = true;
    ahoyScript.onload = function() {
      // Configure Ahoy for this website
      ahoy.configure({
        urlPrefix: "",
        visitsUrl: "/ahoy/visits",
        eventsUrl: "/ahoy/events",
        page: null,
        platform: "Web",
        useBeacon: true,
        startOnReady: true,
        trackVisits: true,
        cookies: true,
        cookieDomain: null,
        headers: {},
        visitParams: {},
        withCredentials: false
      });

      // Track property gallery clicks
      document.querySelectorAll('[data-property-gallery]').forEach(function(el) {
        el.addEventListener('click', function() {
          ahoy.track('gallery_viewed', { property_id: this.dataset.propertyId });
        });
      });

      // Track contact form opens
      document.querySelectorAll('[data-contact-trigger]').forEach(function(el) {
        el.addEventListener('click', function() {
          ahoy.track('contact_form_opened', {
            property_id: this.dataset.propertyId,
            source: this.dataset.source || 'button'
          });
        });
      });

      // Track property shares
      document.querySelectorAll('[data-share-property]').forEach(function(el) {
        el.addEventListener('click', function() {
          ahoy.track('property_shared', {
            property_id: this.dataset.propertyId,
            platform: this.dataset.platform
          });
        });
      });

      // Track favorite/save clicks
      document.querySelectorAll('[data-favorite-property]').forEach(function(el) {
        el.addEventListener('click', function() {
          ahoy.track('property_favorited', {
            property_id: this.dataset.propertyId
          });
        });
      });
    };
    document.head.appendChild(ahoyScript);
  });
</script>

<%# Google Analytics (Legacy) - already loads asynchronously %>
<% if @current_website.render_google_analytics %>
<script>
  // GA loads after page content, wrapped in DOMContentLoaded for page speed
  document.addEventListener('DOMContentLoaded', function() {
    var _gaq = window._gaq || [];
    _gaq.push(['_setAccount', '<%= @current_website.analytics_id %>']);
    _gaq.push(['_trackPageview']);

    var ga = document.createElement('script');
    ga.async = true;
    ga.src = 'https://ssl.google-analytics.com/ga.js';
    document.head.appendChild(ga);
    window._gaq = _gaq;
  });
</script>
<% end %>
