<!-- ==========================================
     HURME QASSIM - WORDPRESS CHECKOUT WIDGET
     Apple-style 2026 Jednoklikna kupovina za BiH
     ========================================== -->

<style>
  /* 1. Reset i bazične varijable za WordPress okruženje */
  :root {
    --hq-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    --hq-gold: #b08d57;
    --hq-gold-hover: #9c7b48;
    --hq-dark: #1d1d1f;
    --hq-border: #e8e8ed;
    --hq-bg-light: #f5f5f7;
    --hq-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
    --hq-transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  }

  /* 2. Apple-Style dugme (možete klasi dodati stil na bilo koje dugme u WP) */
  .hq-wp-order-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background-color: var(--hq-dark) !important;
    color: #ffffff !important;
    font-family: var(--hq-font) !important;
    font-size: 14px !important;
    font-weight: 700 !important;
    padding: 14px 28px !important;
    border-radius: 30px !important;
    border: none !important;
    outline: none !important;
    cursor: pointer !important;
    transition: var(--hq-transition) !important;
    text-decoration: none !important;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05) !important;
  }

  .hq-wp-order-btn:hover {
    background-color: var(--hq-gold) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 8px 24px rgba(176, 141, 87, 0.3) !important;
    color: white !important;
  }

  .hq-wp-order-btn:active {
    transform: translateY(0) !important;
  }

  /* Plutajuća ikonica korpe u uglu ekrana */
  .hq-floating-cart-trigger {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 60px;
    height: 60px;
    background-color: var(--hq-dark);
    color: #ffffff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    cursor: pointer;
    z-index: 99998;
    transition: var(--hq-transition);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  .hq-floating-cart-trigger:hover {
    background-color: var(--hq-gold);
    transform: scale(1.08);
  }

  .hq-floating-cart-badge {
    position: absolute;
    top: -5px;
    right: -2px;
    background-color: var(--hq-gold);
    color: white;
    font-size: 11px;
    font-weight: 800;
    min-width: 22px;
    height: 22px;
    border-radius: 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
    border: 2px solid var(--hq-dark);
    animation: hqPulse 2s infinite;
  }

  @keyframes hqPulse {
    0% { box-shadow: 0 0 0 0 rgba(176,141,87, 0.5); }
    70% { box-shadow: 0 0 0 8px rgba(176,141,87, 0); }
    100% { box-shadow: 0 0 0 0 rgba(176,141,87, 0); }
  }

  /* 3. Slide-Out Panel Korpe */
  #hq-wp-cart-overlay {
    position: fixed;
    inset: 0;
    background-color: rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    z-index: 999990;
    opacity: 0;
    visibility: hidden;
    transition: var(--hq-transition);
  }

  #hq-wp-cart-overlay.active {
    opacity: 1;
    visibility: visible;
  }

  #hq-wp-cart-drawer {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    max-width: 440px;
    background-color: #ffffff;
    box-shadow: -10px 0 50px rgba(0, 0, 0, 0.1);
    z-index: 999995;
    transform: translateX(100%);
    transition: transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-family: var(--hq-font);
    box-sizing: border-box;
  }

  #hq-wp-cart-drawer.active {
    transform: translateX(0);
  }

  #hq-wp-cart-drawer *, #hq-wp-cart-drawer *::before, #hq-wp-cart-drawer *::after {
    box-sizing: border-box;
  }

  /* Header korpe */
  .hq-cart-hdr {
    padding: 24px;
    border-bottom: 1px solid var(--hq-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fafafa;
  }

  .hq-cart-hdr h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 800;
    color: var(--hq-dark);
  }

  .hq-cart-close {
    background: none;
    border: none;
    font-size: 28px;
    line-height: 1;
    cursor: pointer;
    color: #999;
    transition: var(--hq-transition);
  }

  .hq-cart-close:hover {
    color: var(--hq-dark);
  }

  /* Skrolujući sadržaj */
  .hq-cart-content {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
  }

  /* Individualni artikal */
  .hq-cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #f5f5f7;
  }

  .hq-cart-item-info {
    flex: 1;
  }

  .hq-cart-item-title {
    font-size: 15px;
    font-weight: 700;
    color: var(--hq-dark);
    margin-bottom: 4px;
  }

  .hq-cart-item-price {
    font-size: 13px;
    color: var(--hq-gold);
    font-weight: 600;
  }

  .hq-cart-item-ctrls {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .hq-qty-grp {
    display: flex;
    align-items: center;
    border: 1px solid var(--hq-border);
    border-radius: 8px;
    overflow: hidden;
  }

  .hq-qty-btn {
    background: none;
    border: none;
    width: 28px;
    height: 28px;
    font-size: 15px;
    font-weight: bold;
    cursor: pointer;
    transition: var(--hq-transition);
  }

  .hq-qty-btn:hover {
    background-color: #f5f5f7;
  }

  .hq-qty-val {
    font-size: 13px;
    font-weight: 700;
    min-width: 20px;
    text-align: center;
  }

  .hq-item-del {
    background: none;
    border: none;
    color: #ef4444;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: var(--hq-transition);
  }

  .hq-item-del:hover {
    text-decoration: underline;
  }

  .hq-empty-state {
    text-align: center;
    padding: 40px 0;
    color: #888;
  }

  .hq-empty-state svg {
    margin-bottom: 16px;
    opacity: 0.5;
  }

  /* 4. Minimalistička forma za dostavu unutar korpe */
  .hq-delivery-form {
    border-top: 1px solid var(--hq-border);
    padding-top: 24px;
    margin-top: 24px;
  }

  .hq-form-title {
    font-size: 16px;
    font-weight: 800;
    color: var(--hq-dark);
    margin-bottom: 15px;
  }

  .hq-form-group {
    margin-bottom: 14px;
  }

  .hq-form-group label {
    display: block;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    color: #555;
    margin-bottom: 6px;
  }

  .hq-form-group input, .hq-form-group textarea {
    width: 100%;
    border: 1px solid var(--hq-border);
    background-color: #fafafa;
    border-radius: 10px;
    padding: 12px;
    font-size: 13px;
    font-family: inherit;
    outline: none;
    transition: var(--hq-transition);
  }

  .hq-form-group input:focus, .hq-form-group textarea:focus {
    border-color: var(--hq-gold);
    background-color: #ffffff;
  }

  .hq-form-error {
    color: #ef4444;
    font-size: 11px;
    font-weight: 600;
    margin-top: 5px;
    display: none;
  }

  /* Footer proračuni i narudžba */
  .hq-cart-ftr {
    border-top: 1px solid var(--hq-border);
    padding: 24px;
    background-color: #fafafa;
  }

  .hq-calc-row {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    margin-bottom: 8px;
    color: #555;
  }

  .hq-calc-row.grand-total {
    font-size: 18px;
    font-weight: 900;
    color: var(--hq-dark);
    margin-top: 14px;
    border-top: 1px dashed var(--hq-border);
    padding-top: 14px;
  }

  .hq-checkout-btn {
    width: 100%;
    background-color: var(--hq-dark);
    color: #ffffff;
    font-weight: 700;
    font-size: 15px;
    padding: 16px;
    border: none;
    border-radius: 12px;
    cursor: pointer;
    transition: var(--hq-transition);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-top: 6px;
  }

  .hq-checkout-btn:hover {
    background-color: var(--hq-gold);
  }

  /* WordPress Admin Bar Popravka */
  body.admin-bar #hq-wp-cart-drawer {
    top: 32px;
  }
</style>

<!-- Elementi koji se automatski brizgaju u vašu WP stranicu -->
<div id="hq-wp-cart-overlay" onclick="window.hqToggleCart(false)"></div>
<div id="hq-wp-cart-drawer">
  <div class="hq-cart-hdr">
    <h3>Vaša Korpa</h3>
    <button class="hq-cart-close" onclick="window.hqToggleCart(false)">&times;</button>
  </div>

  <div class="hq-cart-content">
    <div id="hq-wp-cart-items-list">
      <!-- Generiše JavaScript -->
    </div>

    <!-- Forma unutar istog panela korpe -->
    <div class="hq-delivery-form" id="hq-delivery-section" style="display: none;">
      <h4 class="hq-form-title">Podaci za brzu isporuku (BiH)</h4>
      
      <div class="hq-form-group">
        <label for="hq-input-name">Ime i Prezime *</label>
        <input type="text" id="hq-input-name" placeholder="E.g. Amina Hodžić" />
        <div class="hq-form-error" id="hq-err-name">Unesite vaše ime i prezime.</div>
      </div>

      <div class="hq-form-group">
        <label for="hq-input-address">Adresa, Grad i Poštanski broj *</label>
        <input type="text" id="hq-input-address" placeholder="E.g. Titova 44, Sarajevo 71000" />
        <div class="hq-form-error" id="hq-err-address">Unesite tačnu adresu i grad za dostavu.</div>
      </div>

      <div class="hq-form-group">
        <label for="hq-input-phone">Broj telefona (WhatsApp / Viber) *</label>
        <input type="tel" id="hq-input-phone" placeholder="E.g. +387 61 123 456" />
        <div class="hq-form-error" id="hq-err-phone">Unesite tačan telefon za brzu potvrdu.</div>
      </div>

      <div class="hq-form-group">
        <label for="hq-input-notes">Napomena (Opcionalno)</label>
        <textarea id="hq-input-notes" rows="2" placeholder="Npr. dostaviti poslije 16h, ostaviti kod čuvara..."></textarea>
      </div>
    </div>
  </div>

  <div class="hq-cart-ftr">
    <div class="hq-calc-row">
      <span>Artikli:</span>
      <span id="hq-wp-subtotal">0.00 KM</span>
    </div>
    <div class="hq-calc-row">
      <span>Poštarina (BiH):</span>
      <span id="hq-wp-shipping">BESPLATNA (iznad 60 KM)</span>
    </div>
    <div class="hq-calc-row grand-total">
      <span>UKUPNO:</span>
      <span id="hq-wp-grandtotal">0.00 KM</span>
    </div>

    <button class="hq-checkout-btn" onclick="window.hqSubmitWordPressOrder()">
      <span>POTVRDI NARUDŽBU</span>
      <svg style="width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2.5;" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
      </svg>
    </button>
  </div>
</div>

<!-- Plutajući okidač u dnu ekrana -->
<div class="hq-floating-cart-trigger" onclick="window.hqToggleCart(true)">
  <svg style="width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 2;" viewBox="0 0 24 24">
    <path stroke-linecap="round" stroke-linejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
  </svg>
  <div class="hq-floating-cart-badge" id="hq-wp-floating-badge">0</div>
</div>

<!-- ==========================================
     Samo-izvršavajuća JavaScript logika vidgeta
     ========================================== -->
<script>
  (function () {
    // 1. Unutrašnje stanje korpe
    let hqCart = [];

    // 2. Inicijalno sakrivanje overlay-a i fioke
    window.hqToggleCart = function (open) {
      const overlay = document.getElementById('hq-wp-cart-overlay');
      const drawer = document.getElementById('hq-wp-cart-drawer');
      if (open) {
        overlay.classList.add('active');
        drawer.classList.add('active');
      } else {
        overlay.classList.remove('active');
        drawer.classList.remove('active');
      }
    };

    // 3. GLOBALNA FUNKCIJA ZA UBACIVANJE ARTIKLA SA BILO KOJE WP STRANICE
    window.dodajUKorpu = function (naziv, cijena) {
      const numericPrice = parseFloat(cijena);
      if (isNaN(numericPrice)) return;

      const existingItem = hqCart.find(item => item.productName === naziv);
      if (existingItem) {
        existingItem.quantity += 1;
      } else {
        hqCart.push({
          productName: naziv,
          price: numericPrice,
          quantity: 1
        });
      }

      window.hqUpdateWidgetUI();
      
      // Otvori korpu automatski nakon kratke animacije
      setTimeout(() => {
        window.hqToggleCart(true);
      }, 350);
    };

    // 4. Izmjena količina (+ / -) i brisanje
    window.hqChangeQty = function (naziv, delta) {
      const item = hqCart.find(i => i.productName === naziv);
      if (!item) return;

      item.quantity += delta;
      if (item.quantity <= 0) {
        hqCart = hqCart.filter(i => i.productName !== naziv);
      }
      window.hqUpdateWidgetUI();
    };

    window.hqRemoveItem = function (naziv) {
      hqCart = hqCart.filter(i => i.productName !== naziv);
      window.hqUpdateWidgetUI();
    };

    // 5. Sinhronizacija i prerendering UI elemenata
    window.hqUpdateWidgetUI = function () {
      const totalQuantity = hqCart.reduce((sum, item) => sum + item.quantity, 0);
      document.getElementById('hq-wp-floating-badge').innerText = totalQuantity;

      const itemsListContainer = document.getElementById('hq-wp-cart-items-list');
      const deliverySection = document.getElementById('hq-delivery-section');

      if (hqCart.length === 0) {
        itemsListContainer.innerHTML = `
          <div class="hq-empty-state">
            <svg style="width: 48px; height: 48px; fill: none; stroke: #ccc; stroke-width: 1.5; margin: 0 auto 12px auto; display: block;" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
            </svg>
            <p style="margin: 0; font-size: 14px; font-weight: 500;">Vaša korpa je prazna</p>
            <p style="margin: 4px 0 0 0; font-size: 11px;">Dodajte proizvode klikom na dugmad iz ponude.</p>
          </div>
        `;
        deliverySection.style.display = 'none';
      } else {
        deliverySection.style.display = 'block';
        let listHtml = '';

        hqCart.forEach(item => {
          listHtml += `
            <div class="hq-cart-item">
              <div class="hq-cart-item-info">
                <div class="hq-cart-item-title">${item.productName}</div>
                <div class="hq-cart-item-price">${(item.price * item.quantity).toFixed(2)} KM</div>
              </div>
              <div class="hq-cart-item-ctrls">
                <div class="hq-qty-grp">
                  <button class="hq-qty-btn" onclick="window.hqChangeQty('${item.productName}', -1)">-</button>
                  <span class="hq-qty-val">${item.quantity}</span>
                  <button class="hq-qty-btn" onclick="window.hqChangeQty('${item.productName}', 1)">+</button>
                </div>
                <button class="hq-item-del" onclick="window.hqRemoveItem('${item.productName}')">Ukloni</button>
              </div>
            </div>
          `;
        });
        itemsListContainer.innerHTML = listHtml;
      }

      // Proračun poštarine na osnovu limita od 60 KM unutar Bosne i Hercegovine
      const subtotalTotal = hqCart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      const deliveryShippingLimit = 60.00;
      const deliveryCost = (subtotalTotal >= deliveryShippingLimit || subtotalTotal === 0) ? 0.00 : 8.00;
      const finalGrandAmount = subtotalTotal + deliveryCost;

      document.getElementById('hq-wp-subtotal').innerText = `${subtotalTotal.toFixed(2)} KM`;
      document.getElementById('hq-wp-shipping').innerText = deliveryCost === 0 
        ? 'BESPLATNA DOSTAVA' 
        : '8.00 KM';
      document.getElementById('hq-wp-grandtotal').innerText = `${finalGrandAmount.toFixed(2)} KM`;
    };

    // 6. Validacija polja i prosleđivanje WhatsApp naloga
    window.hqSubmitWordPressOrder = function () {
      if (hqCart.length === 0) {
        alert("Vaša korpa je prazna. Dodajte barem jedan proizvod.");
        return;
      }

      // Inputi
      const name = document.getElementById('hq-input-name').value.trim();
      const address = document.getElementById('hq-input-address').value.trim();
      const phone = document.getElementById('hq-input-phone').value.trim();
      const notes = document.getElementById('hq-input-notes').value.trim();

      // Čišćenje grešaka
      document.getElementById('hq-err-name').style.display = 'none';
      document.getElementById('hq-err-address').style.display = 'none';
      document.getElementById('hq-err-phone').style.display = 'none';

      let valid = true;
      if (!name) {
        document.getElementById('hq-err-name').style.display = 'block';
        valid = false;
      }
      if (!address) {
        document.getElementById('hq-err-address').style.display = 'block';
        valid = false;
      }
      if (!phone) {
        document.getElementById('hq-err-phone').style.display = 'block';
        valid = false;
      }

      if (!valid) return;

      // Izračun krajnje cijene
      const subtotalTotal = hqCart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
      const deliveryCost = subtotalTotal >= 60.00 ? 0.00 : 8.00;
      const finalGrandAmount = subtotalTotal + deliveryCost;

      // Konstrukcija WhatsApp poruke
      let message = `*NARUDŽBA S WP SAJTA - HURME QASSIM*\n`;
      message += `----------------------------\n`;
      hqCart.forEach(item => {
        message += `• *${item.productName}* x ${item.quantity} = ${(item.price * item.quantity).toFixed(2)} KM\n`;
      });
      message += `----------------------------\n`;
      message += `*Poštarina:* & ${deliveryCost === 0 ? 'BESPLATNA' : '8.00 KM'}\n`;
      message += `*UKUPNO ZA PLAĆANJE:* *${finalGrandAmount.toFixed(2)} KM*\n\n`;

      message += `*PODACI KORISNIKA:*
`;
      message += `👤 Ime i prezime: ${name}\n`;
      message += `📍 Adresa i grad: ${address}\n`;
      message += `📞 Telefon: ${phone}\n`;
      if (notes) {
        message += `📝 Napomena: ${notes}\n`;
      }

      /* 
       * ====================================================================
       * AUTOMATIZACIJA PREKO WEBHOOK-A (n8n, Google Sheets, Zapier)
       * ====================================================================
       * Ako želite automatski slati podatke o narudžbi u vaš Google Sheets ili n8n,
       * otkomentarišite kod ispod i postavite vašu Webhook adresu:
       * 
       * const webHookUrl = 'https://tvoj-n8n-ili-zapier-webhook-url.com';
       * fetch(webHookUrl, {
       *   method: 'POST',
       *   headers: { 'Content-Type': 'application/json' },
       *   body: JSON.stringify({
       *     vrijeme: new Date().toISOString(),
       *     kupac: { ime_i_prezime: name, adresa: address, telefon: phone, napomena: notes },
       *     stavke: hqCart.map(i => ({ artikal: i.productName, kolicina: i.quantity, cijena: i.price })),
       *     ukupno: finalGrandAmount
       *   })
       * })
       * .then(res => console.log('Uspješno poslano na Webhook!'))
       * .catch(err => console.error('Webhook Greška:', err));
       */

      // Slanje i preusmjeravanje na službeni WhatsApp
      const redirectUrl = `https://wa.me/387603151593?text=${encodeURIComponent(message)}`;
      window.open(redirectUrl, '_blank');

      // Reset skripte
      hqCart = [];
      window.hqUpdateWidgetUI();
      window.hqToggleCart(false);
      
      // Reset formi
      document.getElementById('hq-input-name').value = '';
      document.getElementById('hq-input-address').value = '';
      document.getElementById('hq-input-phone').value = '';
      document.getElementById('hq-input-notes').value = '';

      alert("Vaša narudžba je pripremljena i proslijeđena na WhatsApp! Hvala Vam na povjerenju.");
    };

    // Pokretanje inicijalnog UI-ja
    window.hqUpdateWidgetUI();
  })();
</script>