jQuery(function ($) {
  var $form = $('#wcmv-filter-form');
  if (!$form.length) {
    return;
  }

  var $paged = $('#wcmv-paged');
  var $view = $('#wcmv-view');
  var $mobileType = $('#wcmv-mobile-type');
  var $root = $('#wcmv-browse-root');
  var cfg = window.STAKMV_BROWSE || window.STAKMV_BROWSE || null;
  var $buyNowToggle = $form.find('input[name="type[]"][value="buy_now"]').first();
  var $auctionToggle = $form.find('input[name="type[]"][value="auction"]').first();

  function isMobileViewport() {
    return window.matchMedia('(max-width: 768px)').matches;
  }

  function syncMobileModeUI() {
    var mode = 'all';
    var hasBuy = !!$buyNowToggle.prop('checked');
    var hasAuction = !!$auctionToggle.prop('checked');

    if (hasBuy && !hasAuction) {
      mode = 'buy_now';
    } else if (hasAuction && !hasBuy) {
      mode = 'auction';
    }

    $form.find('.wcmv-mobile-type-tab').removeClass('is-active')
      .filter('[data-mobile-type="' + mode + '"]').addClass('is-active');

    if ($mobileType.length) {
      $mobileType.val(mode);
    }
  }

  function applyMobileMode(mode) {
    if (!$buyNowToggle.length || !$auctionToggle.length) {
      return;
    }

    if (mode === 'buy_now') {
      $buyNowToggle.prop('checked', true);
      $auctionToggle.prop('checked', false);
    } else if (mode === 'auction') {
      $buyNowToggle.prop('checked', false);
      $auctionToggle.prop('checked', true);
    } else {
      $buyNowToggle.prop('checked', false);
      $auctionToggle.prop('checked', false);
    }

    syncMobileModeUI();
  }

  function syncMobileFiltersVisibility() {
    var $toggle = $form.find('.wcmv-mobile-filter-toggle');
    if (!$toggle.length) {
      return;
    }

    if (isMobileViewport()) {
      if (!$root.hasClass('wcmv-mobile-filters-open') && !$root.hasClass('wcmv-mobile-filters-closed')) {
        $root.addClass('wcmv-mobile-filters-closed');
      }
      var expanded = $root.hasClass('wcmv-mobile-filters-open');
      $toggle.attr('aria-expanded', expanded ? 'true' : 'false');
      $toggle.text(expanded ? 'Hide filters' : 'Filter');
    } else {
      $root.removeClass('wcmv-mobile-filters-open wcmv-mobile-filters-closed');
      $toggle.attr('aria-expanded', 'false').text('Filter');
    }
  }

  function collectCurrentFilters() {
    var typeVals = [];
    $form.find('input[name="type[]"]:checked').each(function () {
      typeVals.push(String($(this).val() || ''));
    });

    return {
      search: String($form.find('input[name="search"]').val() || ''),
      cat: String($form.find('select[name="cat"]').val() || ''),
      type: typeVals,
      min_price: String($form.find('input[name="min_price"]').val() || ''),
      max_price: String($form.find('input[name="max_price"]').val() || '')
    };
  }

  function ensureSavedSearchContainer() {
    var $existing = $('#wcmv-saved-searches');
    if ($existing.length) {
      return $existing;
    }

    var html = [
      '<div class="wcmv-saved-searches" id="wcmv-saved-searches">',
      '<strong>Saved Searches</strong>',
      '<div class="wcmv-saved-searches-list"><span class="wcmv-saved-search-empty">No saved searches yet.</span></div>',
      '</div>'
    ].join('');
    $form.append(html);
    return $('#wcmv-saved-searches');
  }

  function renderSavedSearchChip(item, url) {
    if (!item || !item.id) {
      return;
    }

    var $container = ensureSavedSearchContainer();
    var $list = $container.find('.wcmv-saved-searches-list');
    $list.find('.wcmv-saved-search-empty').remove();

    var safeName = item.name || 'Saved Search';
    var safeUrl = url || '#';
    var $chip = $(
      '<span class="wcmv-saved-search-chip" data-search-id="' + item.id + '">' +
      '<a href="' + safeUrl + '"></a>' +
      '<button type="button" class="wcmv-delete-saved-search" aria-label="Delete saved search">&times;</button>' +
      '</span>'
    );

    $chip.find('a').text(safeName);
    $list.prepend($chip);
  }

  $(document).on('click', '.wcmv-view-toggle button[data-view]', function (e) {
    e.preventDefault();

    var view = $(this).data('view') === 'list' ? 'list' : 'grid';
    if ($view.length) {
      $view.val(view);
    }
    if ($paged.length) {
      $paged.val('1');
    }

    $form.trigger('submit');
  });

  $(document).on('click', '.wcmv-mobile-filter-toggle', function (e) {
    e.preventDefault();
    if (!isMobileViewport()) {
      return;
    }

    $root.toggleClass('wcmv-mobile-filters-open wcmv-mobile-filters-closed');
    syncMobileFiltersVisibility();
  });

  $(document).on('click', '.wcmv-mobile-type-tab', function (e) {
    e.preventDefault();
    var mode = String($(this).data('mobile-type') || 'all');
    applyMobileMode(mode);
    if ($paged.length) {
      $paged.val('1');
    }
    $form.trigger('submit');
  });

  $form.on('change', 'input[name="type[]"]', function () {
    syncMobileModeUI();
  });

  $(document).on('click', '.wcmv-save-search-btn', function (e) {
    e.preventDefault();

    if (!cfg || !cfg.ajax) {
      return;
    }

    var nonce = cfg.saved_search_nonce || $('#wcmv-saved-search-nonce').val() || '';
    if (!nonce) {
      return;
    }

    var $btn = $(this);
    if ($btn.prop('disabled')) {
      return;
    }
    $btn.prop('disabled', true).text('Saving...');

    $.post(cfg.ajax, {
      action: 'stakmv_saved_search_save',
      nonce: nonce,
      filters: collectCurrentFilters()
    }).done(function (res) {
      if (!res || !res.success) {
        var msg = (res && res.data && res.data.message) ? res.data.message : 'Could not save search.';
        alert(msg);
        return;
      }

      if (res.data && res.data.item) {
        renderSavedSearchChip(res.data.item, res.data.url || '#');
      }
    }).fail(function () {
      alert('Request failed.');
    }).always(function () {
      $btn.prop('disabled', false).text('Save Search');
    });
  });

  $(document).on('click', '.wcmv-delete-saved-search', function (e) {
    e.preventDefault();

    if (!cfg || !cfg.ajax) {
      return;
    }

    var nonce = cfg.saved_search_nonce || $('#wcmv-saved-search-nonce').val() || '';
    if (!nonce) {
      return;
    }

    var $chip = $(this).closest('.wcmv-saved-search-chip');
    var searchId = String($chip.data('search-id') || '');
    if (!searchId) {
      return;
    }

    $.post(cfg.ajax, {
      action: 'stakmv_saved_search_delete',
      nonce: nonce,
      search_id: searchId
    }).done(function (res) {
      if (!res || !res.success) {
        var msg = (res && res.data && res.data.message) ? res.data.message : 'Could not remove saved search.';
        alert(msg);
        return;
      }

      $chip.remove();
      var $list = $('#wcmv-saved-searches .wcmv-saved-searches-list');
      if ($list.length && !$list.find('.wcmv-saved-search-chip').length) {
        $list.append('<span class="wcmv-saved-search-empty">No saved searches yet.</span>');
      }
    }).fail(function () {
      alert('Request failed.');
    });
  });

  syncMobileModeUI();
  syncMobileFiltersVisibility();
  $(window).on('resize', syncMobileFiltersVisibility);
});
