{% comment %}
================================================================================
MIRROR VIRTUAL TRY-ON & SIZE RECOMMENDATION - SHOPIFY INTEGRATION
================================================================================

Installation instructions:
1. Copy this code into a new snippet: snippets/mirror-reco.liquid
2. Include the snippet in your theme.liquid before </body>:
   {% render 'mirror-reco' %}

================================================================================
{% endcomment %}


{% comment %} CONFIGURATION {% endcomment %}


{% assign mirror_iframe_url = "https://digitalmirror.younzee.com" %}

{% assign mirror_collection_handle = 'mirror-compatible' %}
{% assign mirror_enabled_on_product_page = false %}
{% assign mirror_compatible_collection = collections[mirror_collection_handle] %}

{% if template contains 'product' and product %}

  {% if mirror_compatible_collection.handle == mirror_collection_handle %}

    {% for collection in product.collections %}
      {% if collection.handle == mirror_collection_handle %}
        {% assign mirror_enabled_on_product_page = true %}
        {% break %}
      {% endif %}
    {% endfor %}

  {% else %}

    {% assign mirror_enabled_on_product_page = true %}

  {% endif %}

{% endif %}

{% if mirror_enabled_on_product_page %}


<!-- Button and iframe styles -->
<style>
  /* Custom styles for specific adjustments only */
   .mirror-cta-wrapper {
    width: 100%;
    margin: 12px 0;
  }

  .mirror-cta-button {
    appearance: none !important;
    -webkit-appearance: none !important;

    display: flex !important;
    align-items: center !important;
    justify-content: center !important;

    max-width: 100%;
    min-height: 48px;
    padding: 12px 20px !important;
    box-sizing: border-box !important;

    background: #ffffff !important;
    color: #000000 !important;
    border: 1px solid #000000 !important;
    border-radius: 0 !important;

    font: inherit;
    line-height: inherit;
    text-align: center !important;
    text-decoration: none !important;
    cursor: pointer !important;

    box-shadow: none !important;
  }

  .mirror-cta-button:hover,
  .mirror-cta-button:focus {
    background: #000000 !important;
    color: #ffffff !important;
    border-color: #000000 !important;
    box-shadow: none !important;
  }

  .mirror-cta-button:focus-visible {
    outline: 2px solid #000000 !important;
    outline-offset: 2px !important;
  }

  .mirror-cta-button::before,
  .mirror-cta-button::after {
    display: none !important;
    content: none !important;
    box-shadow: none !important;
  }

  /* Iframe container - covers the full page */
  .mirror-iframe-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    pointer-events: none;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease;
  }

  .mirror-iframe-container.active {
    pointer-events: auto;
    opacity: 1;
    visibility: visible;
  }

  .mirror-iframe-container iframe {
    width: 100%;
    height: 100%;
    border: none;
  }

  /* "Powered by Mirror" badge (optional) */
  .mirror-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #666;
    margin-top: 8px;
  }

  .mirror-badge strong {
    color: #000;
  }
</style>


<!-- CTA button on the product page -->
<div class="mirror-cta-wrapper">
  <button
    id="mirror-open-button"
    class="mirror-cta-button"
    type="button"
    aria-label="Try virtually with Mirror"
  >
    <span id="mirror-button-label"></span>
  </button>
</div>


<!-- Iframe container (hidden by default) -->
<div id="mirror-iframe-container" class="mirror-iframe-container">
  <iframe
    id="mirror-iframe"
    src="{{ mirror_iframe_url }}"
    allow="camera"
    title="Mirror Virtual Try-On"
    loading="eager"
  ></iframe>
</div>

<!-- Communication script with the iframe -->
<script>
(function() {
  'use strict';


  // ============================================================
  // CUSTOMIZATION — change the button label here
  // ============================================================
  const BUTTON_LABEL = 'Find my size & Try-on';
  // ============================================================


  // Configuration
  const MIRROR_IFRAME_ORIGIN = '{{ mirror_iframe_url }}';
  const iframeContainer = document.getElementById('mirror-iframe-container');
  const iframe = document.getElementById('mirror-iframe');
  const openButton = document.getElementById('mirror-open-button');

  // Inject button label
  document.getElementById('mirror-button-label').textContent = BUTTON_LABEL;

  // Current Shopify product data
  function getCurrentProductData() {
    {% if product %}
    return {
      id: '{{ product.id }}',
      customerDomain: '{{ shop.domain }}',
      handle: '{{ product.handle }}',
      title: '{{ product.title | escape }}',

      // Main product image (displayed inside the iframe)
      imageUrl: '{{ product.featured_image | img_url: "1024x1024" }}',
    };
    {% else %}
    return null;
    {% endif %}
  }

  // Open the iframe
  function openMirror() {
    iframeContainer.classList.add('active');
    document.body.style.overflow = 'hidden'; // Prevent page scroll

    // Send message to open the popup inside the iframe
    iframe.contentWindow.postMessage({
      type: 'OPEN_MIRROR'
    }, MIRROR_IFRAME_ORIGIN);
  }

  // Close the iframe
  function closeMirror() {
    iframeContainer.classList.remove('active');
    document.body.style.overflow = ''; // Re-enable page scroll
  }

  // Listen for clicks on the button
  if (openButton) {
    openButton.addEventListener('click', function() {
      console.log('🎯 Opening Mirror VTO');
      openMirror();
    });
  }

  // Listen for messages from the iframe
  window.addEventListener('message', function(event) {
    // Verify origin in production
    if (event.origin !== MIRROR_IFRAME_ORIGIN) {
      return;
    }

    console.log('📩 Message received from Mirror:', event.data.type);

    // The iframe is requesting product information
    if (event.data.type === 'REQUEST_CLOTHING_ITEM') {
      const productData = getCurrentProductData();

      if (productData) {
        iframe.contentWindow.postMessage({
          type: 'CLOTHING_ITEM_DATA',
          item: productData
        }, MIRROR_IFRAME_ORIGIN);

        console.log('✅ Product data sent to Mirror');
      }
    }

    // The user wants to add to cart with the recommended size
    if (event.data.type === 'ADD_TO_CART') {
      const { size, fitType } = event.data;

      console.log('🛒 Adding to cart:', { size, fitType });

      // Add to Shopify cart
      addToShopifyCart(size, fitType);
    }

    // The iframe has been closed
    if (event.data.type === 'MIRROR_CLOSED') {
      console.log('❌ Mirror closed');
      closeMirror();
    }

    // Close the iframe and redirect to cart
    if (event.data.type === 'CLOSE_AND_GO_TO_CART') {
      console.log('🛒 Redirecting to cart');
      closeMirror();
      window.location.href = '/cart';
    }
  });

  // Add to Shopify cart
  function addToShopifyCart(size, fitType) {
    {% if product %}

    // Find the variant matching the recommended size
    const variants = {{ product.variants | json }};

    // Look for the variant with the matching size
    let variantToAdd = variants.find(v => {
      const title = v.title.toLowerCase();
      return title.includes(size.toLowerCase());
    });

    // If no variant found, fall back to the currently selected variant
    if (!variantToAdd) {
      variantToAdd = variants.find(v => v.id === {{ product.selected_or_first_available_variant.id }});
    }

    if (!variantToAdd || !variantToAdd.available) {
      iframe.contentWindow.postMessage({
        type: 'CART_ADD_ERROR',
        message: 'Size not available'
      }, MIRROR_IFRAME_ORIGIN);
      return;
    }

    // Add to cart via the Shopify API
    fetch('/cart/add.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        id: variantToAdd.id,
        quantity: 1,
        properties: {
          'Recommended size': size,
          'Fit type': fitType === 'fit' ? 'Slim' :
                      fitType === 'ideal' ? 'Regular' : 'Oversized',
          '_Mirror VTO': 'Yes'
        }
      })
    })
    .then(response => response.json())
    .then(data => {
      console.log('✅ Product added to cart:', data);

      // Notify the iframe of success
      iframe.contentWindow.postMessage({
        type: 'CART_ADD_SUCCESS'
      }, MIRROR_IFRAME_ORIGIN);

      // Trigger the Shopify event to update the cart counter
      document.dispatchEvent(new CustomEvent('cart:updated'));
    })
    .catch(error => {
      console.error('❌ Error adding to cart:', error);

      // Notify the iframe of the error
      iframe.contentWindow.postMessage({
        type: 'CART_ADD_ERROR',
        message: 'An error occurred. Please try again.'
      }, MIRROR_IFRAME_ORIGIN);
    });

    {% endif %}
  }

  // Preload the iframe on button hover (optional, improves performance)
  if (openButton) {
    openButton.addEventListener('mouseenter', function() {
      if (!iframe.src) {
        iframe.src = MIRROR_IFRAME_ORIGIN;
      }
    }, { once: true });
  }
})();
// Move the button right before the "Add to cart" button
function insertMirrorButton() {
  var mirrorCta = document.querySelector('.mirror-cta-wrapper');
  if (!mirrorCta) return false;

  // button[name="add"] is the standard Shopify ATC button attribute present in all themes
  var addToCartBtn = document.querySelector('button[name="add"], input[name="add"]');
  

  if (addToCartBtn) {
  var mirrorButton = document.getElementById('mirror-open-button');
  var addToCartStyles = window.getComputedStyle(addToCartBtn);

  if (mirrorButton) {
    Object.assign(mirrorButton.style, {
      font: addToCartStyles.font,
      letterSpacing: addToCartStyles.letterSpacing,
      textTransform: addToCartStyles.textTransform,
      width: addToCartBtn.getBoundingClientRect().width + 'px',
      minHeight: addToCartBtn.getBoundingClientRect().height + 'px'
    });
  }

  addToCartBtn.parentNode.insertBefore(mirrorCta, addToCartBtn);
  return true;
}



  // Fallback: insert at the end of the cart form if the ATC button is not found
  var cartForm = document.querySelector('form[action*="/cart/add"]');
  if (cartForm) {
    cartForm.appendChild(mirrorCta);
    return true;
  }

  return false;
}

// Immediate attempt (if the DOM is already ready)
if (!insertMirrorButton()) {
  document.addEventListener('DOMContentLoaded', function() {
    if (insertMirrorButton()) return;

    // Fallback: the theme loads the form asynchronously (e.g. sections API)
    var observer = new MutationObserver(function() {
      if (insertMirrorButton()) observer.disconnect();
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // Safety: stop observing after 5 seconds
    setTimeout(function() { observer.disconnect(); }, 5000);
  });
}

</script>

{% endif %}
