{% comment %}
  Shopify Staff Member Draft Order Creator
  Place this snippet in your theme's snippets folder and render it on cart.liquid
{% endcomment %}

{% if customer and customer.tags contains 'staff-member' %}
<style>
  .staff-draft-order-btn {
    width: 100%;
    padding: 15px 20px;
    font-size: 16px;
    font-weight: bold;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 15px;
    transition: all 0.3s ease;
  }
  
  .staff-draft-order-btn.initial {
    background-color: #dc3545;
    color: white;
  }
  
  .staff-draft-order-btn.initial:hover {
    background-color: #c82333;
  }
  
  .staff-draft-order-btn.sending {
    background-color: #6c757d;
    color: white;
    cursor: not-allowed;
  }
  
  .staff-draft-order-btn.success {
    background-color: #28a745;
    color: white;
    cursor: not-allowed;
  }
  
  .clear-cart-link {
    display: block;
    text-align: center;
    margin-bottom: 10px;
    text-decoration: underline;
    color: #333;
    font-size: 14px;
  }
  
  .clear-cart-link:hover {
    color: #000;
  }
</style>

<script>
(function() {
  // Wait for DOM to be ready
  function initDraftOrderButton() {
    const cartFooter = document.querySelector('.cart__footer .cart__ctas');
    
    if (!cartFooter) {
      console.error('Cart footer element not found');
      return;
    }
    
    // Create button container
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'staff-draft-order-container';
    
    // Create the draft order button
    const draftOrderBtn = document.createElement('button');
    draftOrderBtn.className = 'staff-draft-order-btn initial';
    draftOrderBtn.textContent = 'Create Draft Order';
    draftOrderBtn.type = 'button';
    
    // Add button to container
    buttonContainer.appendChild(draftOrderBtn);
    
    // Insert before the checkout button area
    cartFooter.parentNode.insertBefore(buttonContainer, cartFooter);
    
    // Button click handler
    draftOrderBtn.addEventListener('click', async function() {
      if (draftOrderBtn.disabled) return;
      
      try {
        // Disable button and update state
        draftOrderBtn.disabled = true;
        draftOrderBtn.className = 'staff-draft-order-btn sending';
        draftOrderBtn.textContent = 'Sending...please wait';
        
        // Get cart data from Shopify Cart API
        const cartResponse = await fetch('/cart.js', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        if (!cartResponse.ok) {
          throw new Error('Failed to fetch cart data');
        }
        
        const cartData = await cartResponse.json();
        
        // Send cart data to Make.com webhook
        const webhookResponse = await fetch('https://hook.us2.make.com/8ylyxvx2kwq7dw25nmirb7a2tmfq78rb', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(cartData)
        });
        
        if (!webhookResponse.ok) {
          throw new Error('Failed to send data to webhook');
        }
        
        const result = await webhookResponse.json();
        
        // Check for success response
        if (result.status === 'Success') {
          // Update button to success state
          draftOrderBtn.className = 'staff-draft-order-btn success';
          draftOrderBtn.textContent = 'Success!';
          
          // Create clear cart link
          const clearCartLink = document.createElement('a');
          clearCartLink.href = '/cart/clear';
          clearCartLink.className = 'clear-cart-link';
          clearCartLink.textContent = 'Clear Cart';
          
          // Insert clear cart link above button
          buttonContainer.insertBefore(clearCartLink, draftOrderBtn);
        } else {
          throw new Error('Unexpected response from webhook');
        }
        
      } catch (error) {
        console.error('Error creating draft order:', error);
        
        // Reset button on error
        draftOrderBtn.disabled = false;
        draftOrderBtn.className = 'staff-draft-order-btn initial';
        draftOrderBtn.textContent = 'Create Draft Order';
        
        alert('There was an error creating the draft order. Please try again.');
      }
    });
  }
  
  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDraftOrderButton);
  } else {
    initDraftOrderButton();
  }
})();
</script>
{% endif %}