{% extends 'base.html' %}
{% load static trade_offer_tags card_badge cache card_multiselect %}

{% block content %}
  <h1 class="text-center text-4xl font-bold mb-8 pt-4">Trade Offer Search</h1>
  
  <!-- Search Form Section -->
  <section id="trade-search" class="mb-8">
    <form method="post" action="{% url 'trade_offer_search' %}" class="space-y-4">
      {% csrf_token %}
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          {% card_multiselect "have_cards" "I Have:" "Select some cards..." cards have_cards %}
        </div>
        <div>
          {% card_multiselect "want_cards" "I Want:" "Select some cards..." cards want_cards %}
        </div>
      </div>
      <div class="flex flex-col md:flex-row gap-4">
        <button type="submit" class="btn btn-primary">Find a Trade Offer</button>
      </div>
    </form>
  </section>
  
  <!-- Search Results Section -->
  <section id="search-results" class="mb-8">
    {% include "trades/_search_results.html" with search_results=search_results %}
  </section>
{% endblock content %}

{% block javascript %}
<script defer>
document.addEventListener('DOMContentLoaded', function() {
  const tradeSearchForm = document.querySelector('#trade-search form');
  if (tradeSearchForm) {
    tradeSearchForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const formData = new FormData(tradeSearchForm);
      document.querySelector("#search-results").innerHTML = "<div class='text-center text-2xl font-bold'>Searching...</div>";
      fetch(tradeSearchForm.action, {
        method: "POST",
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: formData
      })
      .then(response => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.text();
      })
      .then(data => {
        document.querySelector("#search-results").innerHTML = data;
      })
      .catch(error => {
        alert("There was an error processing your search.");
        console.error("Error:", error);
      });
    });
    
    // AJAX pagination click handling
    document.addEventListener('click', function(e) {
      const target = e.target.closest('.ajax-page-link');
      if (target) {
        e.preventDefault();
        const page = target.getAttribute('data-page');
        let pageInput = document.getElementById('page');
        if (pageInput) {
          pageInput.value = page;
        } else {
          pageInput = document.createElement('input');
          pageInput.type = 'hidden';
          pageInput.id = 'page';
          pageInput.name = 'page';
          pageInput.value = page;
          tradeSearchForm.appendChild(pageInput);
        }
        tradeSearchForm.dispatchEvent(new Event('submit'));
      }
    });
  }
});
</script>
{% endblock %} 