/** Shopify CDN: Minification failed

Line 20:16 Unexpected "="
Line 57:2 Comments in CSS use "/* ... */" instead of "//"
Line 133:2 Comments in CSS use "/* ... */" instead of "//"
Line 149:2 Comments in CSS use "/* ... */" instead of "//"
Line 155:4 Comments in CSS use "/* ... */" instead of "//"
Line 155:29 Unterminated string token
Line 162:4 Comments in CSS use "/* ... */" instead of "//"
Line 165:4 Comments in CSS use "/* ... */" instead of "//"
Line 169:4 Comments in CSS use "/* ... */" instead of "//"
Line 169:29 Unterminated string token
... and 37 more hidden warnings

**/
/**
 * TC Instant Search JS - v4
 * Shopify Predictive Search API
 */
window.TCSearch = (function () {
  'use strict';

  const DEBOUNCE_MS  = 250;
  const MIN_CHARS    = 2;
  const MAX_PRODUCTS = 10;
  const PAGE_SIZE    = 5;
  const SEARCH_URL   = window.routes?.predictive_search_url || '/search/suggest';

  const FEATURED_BRANDS = [
    { label: 'Skechers',      url: '/collections/skechers'      },
    { label: 'Salomon',       url: '/collections/salomon'       },
    { label: 'Merrell',       url: '/collections/merrell'       },
    { label: 'Jack Wolfskin', url: '/collections/jack-wolfskin' },
    { label: 'New Balance',   url: '/collections/new-balance'   },
  ];

  const QUICK_CATEGORIES = [
    { label: 'KADIN',           url: '/collections/kadin'              },
    { label: 'ERKEK',           url: '/collections/erkek'              },
    { label: 'Erkek Ayakkabı',  url: '/collections/erkek-ayakkabi'     },
    { label: 'Kadın Ayakkabı',  url: '/collections/kadin-ayakkabi'     },
    { label: 'Koşu Ayakkabısı', url: '/collections/kos-ayakkabilari'   },
    { label: 'Outdoor',         url: '/collections/outdoor'            },
    { label: 'İndirim',         url: '/collections/i̇ndirimli-urunler'  },
  ];

  let _debounceTimer   = null;
  let _currentQuery    = '';
  let _abortController = null;
  let _sliderPage      = 0;
  let _sliderProducts  = [];
  let _sliderQuery     = '';
  let _themePopupObserver = null;

  const _getEl = (id) => document.getElementById(id);

  // ─── PANEL HTML ──────────────────────────────────────────
  function _buildPanelHTML() {
    const brandsHTML = FEATURED_BRANDS.map(b =>
      `<a href="${b.url}" class="tc-search-brand-tag">${_escape(b.label)}</a>`
    ).join('');

    return `
      <div class="tc-search-panel-header">
        <div class="tc-search-panel-input-wrap">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
          </svg>
          <input type="search" class="tc-search-panel-input" id="tc-search-panel-input"
                 placeholder="Ürün, marka veya kategori ara..."
                 autocomplete="off" autocorrect="off" spellcheck="false">
        </div>
        <div class="tc-search-brands">
          <span class="tc-search-brands-label">Öne Çıkan Markalar</span>
          ${brandsHTML}
        </div>
        <button class="tc-search-panel-close" id="tc-panel-close-btn">✕ KAPAT</button>
      </div>
      <div class="tc-search-panel-body">
        <div class="tc-search-panel-left" id="tc-search-left">
          ${_buildLeftPanel('')}
        </div>
        <div class="tc-search-panel-right" id="tc-search-right">
          <div class="tc-search-loading" id="tc-search-loading" style="display:none">
            <div class="tc-search-spinner"></div>
            <span>Aranıyor...</span>
          </div>
          <div id="tc-search-results-inner" style="display:none"></div>
          <div class="tc-search-empty" id="tc-search-empty" style="display:none">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">
              <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
            </svg>
            <p>Sonuç bulunamadı.</p>
            <span class="tc-search-empty-tip">Farklı bir kelime deneyin</span>
          </div>
        </div>
      </div>`;
  }

  function _buildLeftPanel(query) {
    const catsHTML = QUICK_CATEGORIES.map(c =>
      `<a href="${c.url}" class="tc-search-category-link">${_escape(c.label)}</a>`
    ).join('');

    let suggestHTML = '';
    if (query.length >= MIN_CHARS) {
      const suggestions = [
        `${query} Erkek Ayakkabı`,
        `${query} Kadın Ayakkabı`,
        `${query} Unisex`,
      ];
      suggestHTML = `
        <div class="tc-search-left-section" style="border-top:1px solid #eee;padding-top:14px;margin-top:4px;">
          <div class="tc-search-left-title">Önerilen Aramalar</div>
          ${suggestions.map(s => `
            <a href="/search?q=${encodeURIComponent(s)}&type=product" class="tc-search-suggestion-link">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
              </svg>
              ${_escape(s)}
            </a>`).join('')}
        </div>`;
    }

    return `
      <div class="tc-search-left-section">
        <div class="tc-search-left-title">Kategoriler</div>
        ${catsHTML}
      </div>
      ${suggestHTML}`;
  }

  // ─── INIT ────────────────────────────────────────────────
  function init() {
    if (!_getEl('tc-search-overlay')) {
      const overlay = document.createElement('div');
      overlay.id = 'tc-search-overlay';
      overlay.className = 'tc-instant-search-overlay';
      document.body.appendChild(overlay);
    }
    if (!_getEl('tc-search-panel')) {
      const panel = document.createElement('div');
      panel.id = 'tc-search-panel';
      panel.className = 'tc-search-results-panel';
      document.body.appendChild(panel);
    }
  }

  // ─── OPEN ────────────────────────────────────────────────
  function onFocus() {
    const panel   = _getEl('tc-search-panel');
    const overlay = _getEl('tc-search-overlay');
    if (!panel || panel.classList.contains('active')) return;

    // Tema popup'ını kapat
    _suppressThemePopup();

    panel.innerHTML = _buildPanelHTML();
    panel.classList.add('active');
    if (overlay) overlay.classList.add('active');

    // Overlay tıklaması
    overlay.onclick = close;

    // Kapat butonu
    const closeBtn = _getEl('tc-panel-close-btn');
    if (closeBtn) closeBtn.addEventListener('click', close);

    // Panel input event'leri
    const panelInput = _getEl('tc-search-panel-input');
    if (panelInput) {
      panelInput.addEventListener('input', function() {
        _triggerSearch(this.value);
      });
      panelInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && _currentQuery.length >= MIN_CHARS) {
          window.location.href = `/search?q=${encodeURIComponent(_currentQuery)}&type=product`;
        }
        if (e.key === 'Escape') close();
      });

      // Focus ver
      setTimeout(function() {
        panelInput.focus();
      }, 60);
    }

    document.addEventListener('keydown', _onEsc);
  }

  function _onEsc(e) {
    if (e.key === 'Escape') close();
  }

  // ─── TEMA POPUP'INI ENGELLE ──────────────────────────────
  function _suppressThemePopup() {
    // Tema'nın predictive-search custom element'ini DOM'dan gizle
    function _hideThemeResults() {
      const themePopups = document.querySelectorAll(
        'predictive-search, .predictive-search, [id*="predictive-search"]'
      );
      themePopups.forEach(function(el) {
        // Sadece results container'ı gizle, input'u değil
        if (!el.matches('input')) {
          el.style.setProperty('display', 'none', 'important');
        }
      });
    }

    _hideThemeResults();

    // MutationObserver ile tema yeniden açarsa tekrar kapat
    if (!_themePopupObserver) {
      _themePopupObserver = new MutationObserver(function() {
        if (_getEl('tc-search-panel')?.classList.contains('active')) {
          _hideThemeResults();
        }
      });
      _themePopupObserver.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
    }
  }

  // ─── INPUT ───────────────────────────────────────────────
  function onInput(value) {
    // Bu fonksiyon artık tema'nın tetiklemesi için korunuyor
    // Eğer panel kapalıysa aç
    const panel = _getEl('tc-search-panel');
    if (!panel?.classList.contains('active')) {
      onFocus();
    }
  }

  function _triggerSearch(value) {
    clearTimeout(_debounceTimer);

    // Sol paneli güncelle
    const left = _getEl('tc-search-left');
    if (left) left.innerHTML = _buildLeftPanel(value);

    if (value.length < MIN_CHARS) {
      _showState('hide');
      return;
    }

    _currentQuery = value;
    _debounceTimer = setTimeout(() => _search(value), DEBOUNCE_MS);
  }

  // ─── SEARCH ──────────────────────────────────────────────
  async function _search(query) {
    if (_abortController) _abortController.abort();
    _abortController = new AbortController();

    _showState('loading');

    try {
      const url = `${SEARCH_URL}.json?q=${encodeURIComponent(query)}&resources[type]=product&resources[limit]=${MAX_PRODUCTS}`;
      const response = await fetch(url, {
        signal: _abortController.signal,
        headers: { 'Content-Type': 'application/json' }
      });
      if (!response.ok) throw new Error('Search failed');
      const data = await response.json();
      const products = data.resources?.results?.products || [];

      if (!products.length) {
        _showState('empty');
      } else {
        _sliderProducts = products;
        _sliderQuery    = query;
        _sliderPage     = 0;
        _renderSliderPage();
        _showState('results');
      }
    } catch (e) {
      if (e.name === 'AbortError') return;
      _showState('empty');
    }
  }

  // ─── RENDER ──────────────────────────────────────────────
  function _renderSliderPage() {
    const inner = _getEl('tc-search-results-inner');
    if (!inner) return;

    const products   = _sliderProducts;
    const query      = _sliderQuery;
    const totalPages = Math.ceil(products.length / PAGE_SIZE);
    const start      = _sliderPage * PAGE_SIZE;
    const pageItems  = products.slice(start, start + PAGE_SIZE);

    let html = `
      <div class="tc-search-right-title">
        Arama Sonuçları
        <a href="/search?q=${encodeURIComponent(query)}&type=product">Tümünü gör →</a>
      </div>
      <div class="tc-search-slider-wrap">
        <div class="tc-search-product-grid">`;

    pageItems.forEach(function(product) {
      const price        = product.price;
      const comparePrice = product.compare_at_price_max;
      const onSale       = comparePrice && comparePrice > price;
      const imgUrl       = product.featured_image?.url
        ? `${product.featured_image.url}&width=300` : null;
      const discount     = onSale
        ? Math.round((comparePrice - price) / comparePrice * 100) : 0;

      html += `<a href="${product.url}" class="tc-search-product-card">`;

      if (imgUrl) {
        html += `<img class="tc-search-product-card-img" src="${imgUrl}" alt="${_escape(product.title)}" loading="lazy">`;
      } else {
        html += `<div class="tc-search-product-card-img-placeholder">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1">
            <rect x="3" y="3" width="18" height="18" rx="2"/>
            <circle cx="8.5" cy="8.5" r="1.5"/>
            <polyline points="21 15 16 10 5 21"/>
          </svg>
        </div>`;
      }

      html += `<div class="tc-search-product-card-brand">${_escape(product.vendor || '')}</div>`;
      html += `<div class="tc-search-product-card-title">${_highlight(product.title, query)}</div>`;
      html += `<div class="tc-search-product-card-price">`;
      if (onSale) {
        html += `<span class="tc-search-card-price-sale">${_formatMoney(price)}</span>`;
        html += `<span class="tc-search-card-price-compare">${_formatMoney(comparePrice)}</span>`;
        html += `<span class="tc-search-card-badge-sale">%${discount}</span>`;
      } else {
        html += `<span class="tc-search-card-price-regular">${_formatMoney(price)}</span>`;
      }
      html += `</div></a>`;
    });

    html += `</div>`; // grid

    // Sonraki sayfa oku butonu
    if (_sliderPage < totalPages - 1) {
      html += `<button class="tc-search-slider-next" id="tc-slider-next" aria-label="Sonraki">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="9 18 15 12 9 6"/>
        </svg>
      </button>`;
    }

    html += `</div>`; // slider-wrap
    inner.innerHTML = html;

    // Slider next event listener — innerHTML sonrası ekle
    const nextBtn = _getEl('tc-slider-next');
    if (nextBtn) {
      nextBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const tp = Math.ceil(_sliderProducts.length / PAGE_SIZE);
        if (_sliderPage < tp - 1) {
          _sliderPage++;
          _renderSliderPage();
          _showState('results');
        }
      });
    }
  }

  // ─── STATE ───────────────────────────────────────────────
  function _showState(state) {
    const loading = _getEl('tc-search-loading');
    const inner   = _getEl('tc-search-results-inner');
    const empty   = _getEl('tc-search-empty');
    if (!loading || !inner || !empty) return;

    loading.style.display = state === 'loading' ? 'flex'  : 'none';
    inner.style.display   = state === 'results' ? 'block' : 'none';
    empty.style.display   = state === 'empty'   ? 'flex'  : 'none';
  }

  // ─── CLOSE ───────────────────────────────────────────────
  function close() {
    const panel   = _getEl('tc-search-panel');
    const overlay = _getEl('tc-search-overlay');
    if (panel)   panel.classList.remove('active');
    if (overlay) overlay.classList.remove('active');
    if (_themePopupObserver) {
      _themePopupObserver.disconnect();
      _themePopupObserver = null;
    }
    document.removeEventListener('keydown', _onEsc);
    if (_abortController) _abortController.abort();
    _currentQuery = '';
    // Tema input'u temizle
    const themeInput = document.querySelector('#search-template, .search__input[name="q"]');
    if (themeInput) themeInput.value = '';
  }

  function clear() {
    close();
  }

  // ─── HELPERS ─────────────────────────────────────────────
  function _formatMoney(cents) {
    if (!cents) return '';
    return (cents / 100).toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + '₺';
  }

  function _escape(str) {
    if (!str) return '';
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  function _highlight(text, query) {
    if (!query) return _escape(text);
    const escaped = _escape(text);
    const re = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')})`, 'gi');
    return escaped.replace(re, '<span class="tc-search-highlight">$1</span>');
  }

  // ─── HEADER HEIGHT ───────────────────────────────────────
  function _setHeaderHeight() {
    const header = document.querySelector('#header-sticky, header.header, header');
    if (header) {
      const h = header.getBoundingClientRect().bottom;
      document.documentElement.style.setProperty('--header-height', Math.round(h) + 'px');
    }
  }

  // ─── HOOK TEMA SEARCH ────────────────────────────────────
  function _hookThemeSearch() {
    init();

    // Tema'nın search input'una readonly + pointer-events:none ekle
    // Tamamen gizlemiyoruz — layout bozulmasın
    const themeInput = document.querySelector('#search-template, .search__input[name="q"]');
    if (themeInput) {
      themeInput.setAttribute('readonly', 'readonly');
      themeInput.setAttribute('tabindex', '-1');
      themeInput.style.cursor = 'pointer';
      // Input'a tıklanınca panel açsın
      themeInput.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        onFocus();
      }, true);
      themeInput.addEventListener('focus', function(e) {
        this.blur();
        onFocus();
      }, true);
    }

    // Tema search form submit'ini engelle
    document.querySelectorAll('#search_mini_form, form[action*="/search"]').forEach(function(form) {
      form.addEventListener('submit', function(e) { e.preventDefault(); }, true);
    });

    // Search ikon butonlarına tıklamayı yakala
    const triggers = document.querySelectorAll(
      '.top-search-toggle, .header_search button, .block-search button'
    );
    if (!triggers.length) {
      // Fallback: header içindeki tüm butonları tara
      const headerBtns = document.querySelectorAll('header button:not([type="submit"])');
      headerBtns.forEach(function(btn) {
        const svg = btn.querySelector('svg use[href*="search"], svg use[href*="icon-search"]');
        if (svg) {
          btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            onFocus();
          }, true);
        }
      });
      // Input'a tıklama yeterliyse devam et
      if (themeInput) {
        console.log('[TCSearch] v4 hazır, fallback modu.');
        return true;
      }
      return false;
    }

    triggers.forEach(function(btn) {
      btn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        onFocus();
      }, true);
    });

    console.log('[TCSearch] v4 hazır, ' + triggers.length + ' tetikleyici bağlandı.');
    return true;
  }

  document.addEventListener('DOMContentLoaded', function() {
    _setHeaderHeight();
    window.addEventListener('resize', _setHeaderHeight);
    window.addEventListener('scroll', _setHeaderHeight, { passive: true });

    if (!_hookThemeSearch()) {
      setTimeout(_hookThemeSearch, 600);
    }
  });

  return { onInput, onFocus, close, clear };
})();
