/*
 * ------------------------------------------------------------
 * IMPORTANT: The contents of this file are auto-generated.
 *
 * This file may be updated by the Shopify admin theme editor
 * or related systems. Please exercise caution as any changes
 * made to this file may be overwritten.
 * ------------------------------------------------------------
 */
{
  "sections": {
    "main": {
      "type": "main-page",
      "custom_css": [
        ".page-width,.main-page-content {max-width: 1200px; margin: 2rem auto; padding: 2rem; border-radius: 8px;}"
      ],
      "settings": {
        "padding_top": 36,
        "padding_bottom": 0
      }
    },
    "custom_liquid_Kg6NpJ": {
      "type": "custom-liquid",
      "name": "t:sections.custom-liquid.presets.name",
      "settings": {
        "custom_liquid": "{% if customer and customer.tags contains 'Reseller' %}\n<div class=\"b2b-order-form\">\n  <style>\n    .b2b-order-form {\n      max-width: 1200px;\n      margin: 2rem auto;\n      padding: 2rem;\n      background: #f9f9f9;\n      border-radius: 8px;\n    }\n    .search-section {\n      margin-bottom: 2rem;\n    }\n    .search-input {\n      width: 100%;\n      max-width: 400px;\n      padding: 0.75rem;\n      font-size: 1rem;\n      border: 1px solid #ddd;\n      border-radius: 4px;\n    }\n    .loading-indicator {\n      padding: 1rem;\n      background: #e3f2fd;\n      border-radius: 4px;\n      margin-bottom: 1rem;\n    }\n    .order-table {\n      width: 100%;\n      border-collapse: collapse;\n      background: white;\n      margin-bottom: 2rem;\n    }\n    .order-table th,\n    .order-table td {\n      padding: 1rem;\n      text-align: left;\n      border-bottom: 1px solid #ddd;\n      vertical-align: middle;\n    }\n    .order-table th {\n      background: #f5f5f5;\n      font-weight: 600;\n    }\n    .product-image {\n      width: 60px;\n      height: 60px;\n      object-fit: cover;\n      border-radius: 4px;\n      border: 1px solid #ddd;\n    }\n    .qty-controls {\n      display: flex;\n      align-items: center;\n      gap: 0.5rem;\n    }\n    .qty-input {\n      width: 80px;\n      padding: 0.5rem;\n      border: 1px solid #ddd;\n      border-radius: 4px;\n      text-align: center;\n    }\n    .qty-btn {\n      background: #007bff;\n      color: white;\n      border: none;\n      width: 32px;\n      height: 32px;\n      border-radius: 4px;\n      cursor: pointer;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      font-size: 1rem;\n      transition: background 0.2s;\n    }\n    .qty-btn:hover {\n      background: #0056b3;\n    }\n    .qty-btn:disabled {\n      background: #ccc;\n      cursor: not-allowed;\n    }\n    .remove-btn {\n      background: #dc3545;\n      color: white;\n      border: none;\n      padding: 0.5rem 1rem;\n      border-radius: 4px;\n      cursor: pointer;\n    }\n    .add-to-cart-btn {\n      background: #28a745;\n      color: white;\n      border: none;\n      padding: 1rem 2rem;\n      font-size: 1.1rem;\n      border-radius: 4px;\n      cursor: pointer;\n      font-weight: 600;\n    }\n    .add-to-cart-btn:hover {\n      background: #218838;\n    }\n    .add-to-cart-btn:disabled {\n      background: #6c757d;\n      cursor: not-allowed;\n    }\n    .message {\n      padding: 1rem;\n      margin-bottom: 1rem;\n      border-radius: 4px;\n    }\n    .message.success {\n      background: #d4edda;\n      color: #155724;\n    }\n    .message.error {\n      background: #f8d7da;\n      color: #721c24;\n    }\n    .message.info {\n      background: #d1ecf1;\n      color: #0c5460;\n    }\n  </style>\n\n  <h2>{{ 'b2b_order.title' | t }}</h2>\n  \n  <div id=\"loading-message\" class=\"loading-indicator\" style=\"display: none;\">\n    {{ 'b2b_order.loading' | t }}\n  </div>\n\n  <div class=\"search-section\">\n    <input \n      type=\"text\" \n      id=\"sku-search\" \n      class=\"search-input\" \n      placeholder=\"{{ 'b2b_order.search_placeholder' | t }}\"\n      disabled\n    >\n    <div id=\"search-message\"></div>\n  </div>\n\n  <table class=\"order-table\" id=\"order-table\">\n    <thead>\n      <tr>\n        <th>{{ 'b2b_order.table.sku' | t }}</th>\n        <th>{{ 'b2b_order.table.image' | t }}</th>\n        <th>{{ 'b2b_order.table.product' | t }}</th>\n        <th>{{ 'b2b_order.table.quantity' | t }}</th>\n        <th>{{ 'b2b_order.table.action' | t }}</th>\n      </tr>\n    </thead>\n    <tbody id=\"order-items\">\n      <tr id=\"empty-row\">\n        <td colspan=\"5\" style=\"text-align: center; color: #999;\">\n          {{ 'b2b_order.empty_state' | t }}\n        </td>\n      </tr>\n    </tbody>\n  </table>\n\n  <button id=\"add-to-cart\" class=\"add-to-cart-btn\" disabled>\n    {{ 'b2b_order.add_to_cart' | t }}\n  </button>\n\n  <script>\n    const orderItems = [];\n    let productsDatabase = [];\n    let isLoading = true;\n\n    const translations = {\n      loading: {{ 'b2b_order.loading' | t | json }},\n      loadedSuccess: {{ 'b2b_order.loaded_success' | t | json }},\n      loadError: {{ 'b2b_order.load_error' | t | json }},\n      itemAdded: {{ 'b2b_order.item_added' | t | json }},\n      itemNotAvailable: {{ 'b2b_order.item_not_available' | t | json }},\n      skuNotFound: {{ 'b2b_order.sku_not_found' | t | json }},\n      emptyState: {{ 'b2b_order.empty_state' | t | json }},\n      addingToCart: {{ 'b2b_order.adding_to_cart' | t | json }},\n      addToCart: {{ 'b2b_order.add_to_cart' | t | json }},\n      minOneItem: {{ 'b2b_order.min_one_item' | t | json }},\n      addError: {{ 'b2b_order.add_error' | t | json }},\n      noImage: {{ 'b2b_order.no_image' | t | json }},\n      remove: {{ 'b2b_order.remove' | t | json }},\n      increaseQty: {{ 'b2b_order.increase_qty' | t | json }},\n      decreaseQty: {{ 'b2b_order.decrease_qty' | t | json }},\n      cartErrorDetail: {{ 'b2b_order.cart_error_detail' | t | json }}\n    };\n\n    function getPackagingUnit(tags) {\n      if (!tags || tags.length === 0) return 1;\n      for (let tag of tags) {\n        const match = tag.match(/^VE(\\d+)$/i);\n        if (match) {\n          const quantity = parseInt(match[1]);\n          return quantity > 0 ? quantity : 1;\n        }\n      }\n      return 1;\n    }\n\n    async function loadAllProducts() {\n      const loadingMsg = document.getElementById('loading-message');\n      const searchInput = document.getElementById('sku-search');\n      loadingMsg.style.display = 'block';\n\n      try {\n        let allProducts = [];\n        let page = 1;\n        let hasMore = true;\n\n        while (hasMore) {\n          const response = await fetch(`/products.json?limit=250&page=${page}`);\n          const data = await response.json();\n\n          if (data.products && data.products.length > 0) {\n            allProducts = allProducts.concat(data.products);\n            page++;\n            if (data.products.length < 250) hasMore = false;\n          } else {\n            hasMore = false;\n          }\n        }\n\n        productsDatabase = [];\n        allProducts.forEach(product => {\n          const packagingUnit = getPackagingUnit(product.tags);\n          product.variants.forEach(variant => {\n            if (variant.sku) {\n              productsDatabase.push({\n                variantId: variant.id,\n                sku: variant.sku.toUpperCase(),\n                productTitle: product.title,\n                variantTitle: variant.title,\n                image: variant.featured_image?.src ?? (product.images[0]?.src ?? null),\n                packagingUnit: packagingUnit\n                // ← 'available' wird nicht mehr gespeichert\n              });\n            }\n          });\n        });\n\n        loadingMsg.innerHTML = `✓ ${translations.loadedSuccess.replace('{count}', productsDatabase.length)}`;\n        setTimeout(() => { loadingMsg.style.display = 'none'; }, 2000);\n        searchInput.disabled = false;\n        searchInput.focus();\n        isLoading = false;\n\n      } catch (error) {\n        loadingMsg.innerHTML = `⚠ ${translations.loadError}`;\n        loadingMsg.className = 'message error';\n        console.error('Fehler beim Laden:', error);\n      }\n    }\n\n    document.getElementById('sku-search').addEventListener('keypress', function(e) {\n      if (e.key === 'Enter') {\n        const sku = this.value.trim().toUpperCase();\n        if (!sku) return;\n        searchProductBySKU(sku);\n        this.value = '';\n      }\n    });\n\n    function searchProductBySKU(sku) {\n      const messageDiv = document.getElementById('search-message');\n      const foundVariant = productsDatabase.find(v => v.sku === sku);\n      \n      if (foundVariant) {\n        // ← Keine available-Prüfung mehr – Preorder-App & Überverkauf werden respektiert\n        addItemToOrder(foundVariant);\n        messageDiv.innerHTML = `<p class=\"message success\">${translations.itemAdded}</p>`;\n        setTimeout(() => messageDiv.innerHTML = '', 2000);\n      } else {\n        messageDiv.innerHTML = `<p class=\"message error\">${translations.skuNotFound.replace('{sku}', sku)}</p>`;\n        setTimeout(() => messageDiv.innerHTML = '', 3000);\n      }\n    }\n\n    function addItemToOrder(variant) {\n      const existingIndex = orderItems.findIndex(item => item.id === variant.variantId);\n      if (existingIndex >= 0) {\n        orderItems[existingIndex].quantity += variant.packagingUnit;\n      } else {\n        const displayTitle = variant.productTitle + (variant.variantTitle !== 'Default Title' ? ' - ' + variant.variantTitle : '');\n        orderItems.push({\n          id: variant.variantId,\n          sku: variant.sku,\n          title: displayTitle,\n          image: variant.image,\n          quantity: variant.packagingUnit,\n          packagingUnit: variant.packagingUnit\n        });\n      }\n      renderOrderTable();\n    }\n\n    function renderOrderTable() {\n      const tbody = document.getElementById('order-items');\n      const addToCartBtn = document.getElementById('add-to-cart');\n      \n      if (orderItems.length === 0) {\n        tbody.innerHTML = `\n          <tr id=\"empty-row\">\n            <td colspan=\"5\" style=\"text-align: center; color: #999;\">\n              ${translations.emptyState}\n            </td>\n          </tr>\n        `;\n        addToCartBtn.disabled = true;\n        return;\n      }\n      \n      addToCartBtn.disabled = false;\n      tbody.innerHTML = orderItems.map((item, index) => {\n        const increaseTooltip = translations.increaseQty.replace('{quantity}', item.packagingUnit);\n        const decreaseTooltip = translations.decreaseQty.replace('{quantity}', item.packagingUnit);\n        return `\n        <tr>\n          <td>${item.sku}</td>\n          <td>\n            ${item.image \n              ? `<img src=\"${item.image}\" alt=\"${item.title}\" class=\"product-image\">` \n              : `<div style=\"width: 60px; height: 60px; background: #f0f0f0; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; color: #999;\">${translations.noImage}</div>`\n            }\n          </td>\n          <td>${item.title}</td>\n          <td>\n            <div class=\"qty-controls\">\n              <button \n                class=\"qty-btn\" \n                onclick=\"decreaseQuantity(${index})\"\n                ${item.quantity <= item.packagingUnit ? 'disabled' : ''}\n                title=\"${decreaseTooltip}\"\n              >▼</button>\n              <input \n                type=\"number\" \n                class=\"qty-input\" \n                value=\"${item.quantity}\" \n                min=\"${item.packagingUnit}\"\n                step=\"${item.packagingUnit}\"\n                data-index=\"${index}\"\n                onchange=\"updateQuantity(${index}, this.value)\"\n              >\n              <button \n                class=\"qty-btn\" \n                onclick=\"increaseQuantity(${index})\"\n                title=\"${increaseTooltip}\"\n              >▲</button>\n            </div>\n          </td>\n          <td>\n            <button class=\"remove-btn\" onclick=\"removeItem(${index})\">\n              ${translations.remove}\n            </button>\n          </td>\n        </tr>\n        `;\n      }).join('');\n    }\n\n    function increaseQuantity(index) {\n      orderItems[index].quantity += orderItems[index].packagingUnit;\n      renderOrderTable();\n    }\n\n    function decreaseQuantity(index) {\n      const item = orderItems[index];\n      const newQuantity = item.quantity - item.packagingUnit;\n      if (newQuantity >= item.packagingUnit) {\n        orderItems[index].quantity = newQuantity;\n        renderOrderTable();\n      }\n    }\n\n    function updateQuantity(index, quantity) {\n      const qty = parseInt(quantity);\n      const item = orderItems[index];\n      if (qty > 0) {\n        const roundedQty = Math.max(item.packagingUnit, Math.round(qty / item.packagingUnit) * item.packagingUnit);\n        orderItems[index].quantity = roundedQty;\n        if (roundedQty !== qty) renderOrderTable();\n      }\n    }\n\n    function removeItem(index) {\n      orderItems.splice(index, 1);\n      renderOrderTable();\n    }\n\n    document.getElementById('add-to-cart').addEventListener('click', async function() {\n      if (orderItems.length === 0) {\n        alert(translations.minOneItem);\n        return;\n      }\n\n      this.disabled = true;\n      this.textContent = translations.addingToCart;\n\n      try {\n        // ← Alle Items direkt senden, keine available-Filterung mehr\n        const formData = {\n          items: orderItems.map(item => ({\n            id: item.id,\n            quantity: item.quantity\n          }))\n        };\n\n        const response = await fetch('/cart/add.js', {\n          method: 'POST',\n          headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify(formData)\n        });\n\n        if (response.ok) {\n          await fetch('/cart/update.js', {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify({\n              attributes: { 'Bestellquelle': 'Schnellbestellformular' }\n            })\n          });\n\n          orderItems.length = 0;\n          renderOrderTable();\n          window.location.href = '/cart';\n        } else {\n          const errorData = await response.json();\n          console.error('Cart API Fehler:', JSON.stringify(errorData, null, 2));\n          const failedItem = orderItems.find(item => {\n            const dbEntry = productsDatabase.find(v => v.variantId === item.id);\n            return dbEntry && (errorData.description || '').includes(dbEntry.productTitle);\n          });\n          const skuInfo = failedItem ? `[${failedItem.sku}] ` : '';\n          alert(translations.cartErrorDetail.replace('{detail}', skuInfo + (errorData.description || errorData.message || JSON.stringify(errorData))));\n          throw new Error(errorData.description || 'Fehler beim Hinzufügen');\n        }\n      } catch (error) {\n        console.error(error);\n        this.disabled = false;\n        this.textContent = translations.addToCart;\n      }\n    });\n\n    loadAllProducts();\n  </script>\n</div>\n\n{% else %}\n  <div style=\"padding: 2rem; text-align: center;\">\n    <p>{{ 'b2b_order.access_restricted' | t }}</p>\n    {% if customer %}\n      <p>{{ 'b2b_order.contact_us' | t }}</p>\n    {% else %}\n      <p><a href=\"/account/login\">{{ 'b2b_order.please_login' | t }}</a></p>\n    {% endif %}\n  </div>\n{% endif %}",
        "color_scheme": "",
        "padding_top": 0,
        "padding_bottom": 52
      }
    }
  },
  "order": [
    "main",
    "custom_liquid_Kg6NpJ"
  ]
}
