{% extends "admin/base_site.html" %}
{% load humanize i18n palette palette_admin admin_urls %}

{% block topbar %}
{% comment %} {% block page_title %} {{ cl.opts.verbose_name_plural|title }} {% endblock page_title %} {% endcomment %}
{{ block.super }}

{% endblock topbar %}

{% block content %}

<style>
  /* Main Container */
  .change-list-container {
    background-color: var(--bs-bg-light);
    padding: 2rem 0;
    min-height: calc(100vh - 200px);
  }

  .change-list-wrapper {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 1.5rem;
  }

  /* Actions Section */
  .actions {
    background-color: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 0.5rem;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    color: var(--bs-body-color);
  }

  .actions form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 1rem;
  }

  .actions label {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-weight: 600;
    color: var(--bs-body-color);
    margin: 0;
    font-size: 0.95rem;
  }

  .actions select {
    padding: 0.5rem 2.5rem 0.5rem 0.75rem;
    border: 1px solid var(--input-border);
    border-radius: 0.375rem;
    background-color: var(--input-bg);
    color: var(--input-color);
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
    background-size: 16px 12px;
    padding-right: 2.5rem;
  }

  .actions select:hover {
    border-color: #adb5bd;
  }

  .actions select:focus {
    outline: none;
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
  }

  .actions button {
    padding: 0.5rem 1.5rem;
    background-color: #0d6efd;
    color: white;
    border: none;
    border-radius: 0.375rem;
    cursor: pointer;
    font-weight: 600;
    font-size: 0.875rem;
    transition: all 0.2s ease;
  }

  .actions button:hover {
    background-color: #0b5ed7;
    transform: translateY(-1px);
    box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
  }

  .actions button:active {
    transform: translateY(0);
  }

  .action-counter {
    font-size: 0.875rem;
    color: #6c757d;
    margin-left: auto;
    padding: 0.5rem 1rem;
    background-color: #e7f1ff;
    border-radius: 0.375rem;
    display: none;
  }

  .actions .hidden {
    display: none;
  }

  .actions .all,
  .actions .question,
  .actions .clear {
    font-size: 0.85rem;
    margin-left: 0.5rem;
  }

  .actions a {
    color: #0d6efd;
    text-decoration: none;
    cursor: pointer;
    font-weight: 500;
  }

  .actions a:hover {
    text-decoration: underline;
  }

  /* View Toggle */
  .view-toggle {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 2rem;
  }

  .view-toggle button {
    padding: 0.5rem 1rem;
    border: 2px solid var(--card-border);
    background-color: var(--card-bg);
    color: var(--bs-body-color);
    cursor: pointer;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 600;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .view-toggle button.active {
    background-color: #0d6efd;
    color: white;
    border-color: #0d6efd;
    box-shadow: 0 0.25rem 0.5rem rgba(13, 110, 253, 0.25);
  }

  .view-toggle button:hover:not(.active) {
    background-color: var(--bs-bg-light);
    border-color: var(--card-border);
  }

  /* Grid View Styles */
  .grid-view {
    display: none;
  }

  .grid-view.active{
    display: initial;
  }

  .grid-view > .card:hover {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    transform: translateY(-4px);
    border-color: #0d6efd;
  }

  .grid-view .result-item .item-actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
    margin-top: auto;
    padding-top: 1rem;
    border-top: 1px solid #e9ecef;
  }

  .grid-view .result-item .item-actions a {
    display: inline-block;
    padding: 0.4rem 0.75rem;
    background-color: #e7f1ff;
    color: #0d6efd;
    text-decoration: none;
    border-radius: 0.375rem;
    font-size: 0.8rem;
    font-weight: 600;
    transition: all 0.2s ease;
    border: 1px solid transparent;
  }

  .grid-view .result-item .item-actions a:hover {
    background-color: #0d6efd;
    color: white;
    transform: translateY(-1px);
  }

  .grid-view .result-item .item-actions a.deletelink {
    background-color: #f8d7da;
    color: #721c24;
  }

  .grid-view .result-item .item-actions a.deletelink:hover {
    background-color: #dc3545;
    color: white;
  }

  /* List View Styles */
  .list-view {
    display: none;
  }

  .list-view.active {
    display: block;
  }

  .list-view .table-responsive {
    background-color: var(--table-bg);
    border-radius: 0.5rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border: 1px solid var(--table-border);
  }

  .list-view table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 0;
    color: var(--bs-body-color);
  }

  .list-view table thead {
    background: var(--bs-bg-light);
    border-bottom: 2px solid var(--table-border);
  }

  .list-view table th {
    padding: 1rem;
    text-align: left;
    font-weight: 700;
    color: var(--bs-body-color);
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .list-view table td {
    padding: 1rem;
    border-bottom: 1px solid var(--table-border);
    color: var(--bs-body-color);
    vertical-align: middle;
  }

  .list-view table tbody tr {
    transition: all 0.2s ease;
    background-color: var(--table-bg);
  }

  .list-view table tbody tr:hover {
    background-color: var(--table-hover);
  }

  .list-view table tbody tr:last-child td {
    border-bottom: none;
  }

  .list-view .item-checkbox {
    width: 3rem;
    text-align: center;
  }

  .list-view .item-checkbox input[type="checkbox"] {
    width: 1.25rem;
    height: 1.25rem;
    cursor: pointer;
  }

  .list-view table td:first-child {
    font-weight: 600;
    color: #0d6efd;
  }

  .list-view .item-actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .list-view .item-actions a {
    display: inline-block;
    padding: 0.3rem 0.7rem;
    background-color: #e7f1ff;
    color: #0d6efd;
    text-decoration: none;
    border-radius: 0.375rem;
    font-size: 0.8rem;
    font-weight: 600;
    transition: all 0.2s ease;
    white-space: nowrap;
  }

  .list-view .item-actions a:hover {
    background-color: #0d6efd;
    color: white;
    transform: translateY(-1px);
  }

  .list-view .item-actions a.deletelink {
    background-color: #f8d7da;
    color: #721c24;
  }

  .list-view .item-actions a.deletelink:hover {
    background-color: #dc3545;
    color: white;
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 4rem 2rem;
    background-color: var(--card-bg);
    border: 2px dashed var(--card-border);
    border-radius: 0.5rem;
    color: var(--text-muted);
  }

  .empty-state p {
    font-size: 1.125rem;
    margin: 0;
    font-weight: 500;
  }

  /* Search and Actions Container */
  .search-actions-container {
    display: flex;
    gap: 1rem;
    align-items: flex-start;
    margin-bottom: 2rem;
    flex-wrap: wrap;
  }

  .search-box {
    flex: 1;
    min-width: 250px;
    background-color: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: 0.5rem;
    padding: 1.5rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  }

  .search-box form {
    margin: 0;
  }

  .search-box .input-group {
    display: flex;
    gap: 0;
  }

  .search-box .input-group-text {
    background-color: var(--bs-bg-light);
    border: 1px solid var(--input-border);
    border-right: none;
    border-radius: 0.375rem 0 0 0.375rem;
    padding: 0.5rem 0.75rem;
    color: var(--bs-body-color);
  }

  .search-box .form-control {
    border-radius: 0;
  }

  .search-box .btn {
    border-radius: 0;
    border-left: none;
    border-right: none;
  }

  .search-box .btn-secondary {
    border-radius: 0 0.375rem 0.375rem 0;
    border-left: none;
  }

  .actions-container {
    flex: 1;
    min-width: 250px;
  }

  /* Pagination Styling */
  .btn-outline-secondary {
    background-color: var(--input-bg);
    border-color: var(--input-border);
    color: var(--bs-body-color);
  }

  .btn-outline-secondary:hover:not(:disabled) {
    background-color: #0d6efd;
    border-color: #0d6efd;
    color: white;
  }

  .btn-outline-secondary:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  @media (max-width: 768px) {
    .search-actions-container {
      flex-direction: column;
    }

    .search-box,
    .actions-container {
      width: 100%;
      min-width: unset;
    }
  }
</style>

{% with results=cl %}
{% with result_list=cl.result_list %}


<div class="change-list-container">
  <div class="change-list-wrapper">

    <!-- Search and Actions Container -->
    <div class="row card-body p-1 mx-0 justify-content-between rounded shadow-sm mb-3">
      <!-- Search Section - Only show if search_fields are configured -->
      {% if cl.search_fields %}
        <div class="col-sm-6 col-lg-7 my-1">
          <form id="searchbar" method="get" class="w-100">
            <div class="input-group">
              <span class="input-group-text bg-light">
                <i class="bi bi-search text-dark"></i>
              </span>
              <input type="text" name="q" value="{{ cl.query }}" placeholder="{% trans 'Search' %}" class="form-control" aria-label="{% trans 'Search' %}">
              <button type="submit" class="btn btn-light">{% trans 'Search' %}</button>
              {% if cl.query %}
                <a href="{{ request.path }}" class="btn btn-light bi bi-x-circle"></a>
              {% endif %}
            </div>
          </form>
        </div>
      {% endif %}

      <!-- Actions Section -->
      <div class="{% if cl.search_fields %}col-sm-6 col-lg-5{% else %}col-12{% endif %} my-1">
        <div class="w-100">
          {% block actions %}
            <form method="post" id="changelist-form">
              {% csrf_token %}
              <input type="hidden" name="select_across" value="0" class="select-across">
              {% for field in action_form %}
                {% if field.label %}
                  <div class="d-flex gap-2 flex-1 w-100">
                    <select name="{{ field.html_name }}" class="select2 form-control flex-1">
                      <option disabled selected>{% trans 'Select an action' %}</option>
                      {% for option in field.field.choices %}
                        {% if "----" in option.1 %}
                        {% else %}
                          <option value="{{ option.0 }}">{{ option.1 }}</option>
                        {% endif %}
                      {% endfor %}
                    </select>
                    <button type="submit" class="btn btn-outline-secondary" title="{% trans "Run the selected action" %}" name="index" value="{{ action_index|default:0 }}">
                      {% trans "Submit" %}
                    </button>
                  </div>
                {% endif %}
              {% endfor %}
            </form>

            {% block actions-counter %}
            {{ block.super }}  
            {% endblock %}
          {% endblock %}
        </div>
      </div>
    </div>

    <!-- View Toggle -->
    <div class="d-flex justify-content-between align-items-center flex-wrap-reverse gap-2 mb-3">
      <div class="view-toggle m-0">
        <button class="view-btn" data-view="grid" title="Grid View">
          <i class="bi bi-grid-3x3-gap"></i> Grid View
        </button>
        <button class="view-btn active" data-view="list" title="List View">
          <i class="bi bi-list-ul"></i> List View
        </button>
      </div>

      <a href="{% url results.opts|admin_urlname:'add' %}" class="btn btn-primary shadow-sm" data-view="list" title="List View">
        <i class="bi bi-plus-circle"></i> Add {{ results.opts.verbose_name|capfirst }}
      </a>
    </div>

    {% if actions_selection_counter %}
      <span class="action-counter mb-4" data-actions-icnt="{{ cl.result_list|length }}">{{ selection_note }}</span>
    {% else %}
      <span class="action-counter mb-4"></span>
    {% endif %}

  

    <!-- Grid View -->
    <div class="grid-view">
      {% if cl.result_list %}
        <!-- Grid View Pagination Top -->
          <div class="d-flex align-items-center justify-content-between mb-4">
            {% if cl.paginator and cl.paginator.num_pages > 1 %}
            <nav aria-label="Grid view pagination" class="d-flex align-items-center gap-2">
              {% with current_page=cl.page_num %}
                {% if current_page > 1 %}
                  <a href="?p={{ current_page|add:'-1' }}" class="btn btn-sm btn-outline-secondary" title="{% trans 'Previous page' %}">
                    <i class="bi bi-chevron-left"></i>
                  </a>
                {% else %}
                  <button class="btn btn-sm btn-outline-secondary" disabled title="{% trans 'Previous page' %}">
                    <i class="bi bi-chevron-left"></i>
                  </button>
                {% endif %}
                
                <span class="px-3" style="min-width: 60px; text-align: center;">
                  <strong>{{ current_page }}</strong> / <strong>{{ cl.paginator.num_pages }}</strong>
                </span>
                
                {% if current_page < cl.paginator.num_pages %}
                  <a href="?p={{ current_page|add:'1' }}" class="btn btn-sm btn-outline-secondary" title="{% trans 'Next page' %}">
                    <i class="bi bi-chevron-right"></i>
                  </a>
                {% else %}
                  <button class="btn btn-sm btn-outline-secondary" disabled title="{% trans 'Next page' %}">
                    <i class="bi bi-chevron-right"></i>
                  </button>
                {% endif %}
              {% endwith %}
            </nav>
            {% endif %}
            
            <div class="form-check">
              <input type="checkbox" form="changelist-form" class="form-check-input grid-select-all" id="grid-select-all">
              <label class="form-check-label" for="grid-select-all">
                {% trans "Select all on this page" %}
              </label>
            </div>
          </div>

        <div class="row">
          {% for item in cl.result_list %}
            <div class="col-sm-6 col-lg-4 mb-2">
              {% palette_ui file="palette/components/card.html" component="card" %}
                {% palette_override card_header %}
                  <div class="d-flex align-items-center gap-2">
                    <input type="checkbox" name="_selected_action" value="{{ item.pk }}" class="action-select" form="changelist-form">

                    <h6> {{ results.opts.verbose_name|capfirst }} </h6>
                  </div>
                {% endpalette_override card_header %}

                {% palette_override card_body %}
                  {% if cl.grid_display %}
                    {% for field_name in cl.grid_display %}
                      {% if field_name == '__str__' %}
                        <p class="mb-1">
                          <strong>{{ results.opts.verbose_name|capfirst }}:</strong> {{ item|truncatewords:"7" }}
                        </p>
                      {% elif field_name == 'action_checkbox' %}
                      {% else %}
                        {% if field_name in cl.grid_display_links %}
                          <p class="mb-1">
                            <strong>{{ field_name|humanize_name }}:</strong> <a href="{{item}}"> {{ item|getattr:field_name|truncatewords:"7" }} </a>
                          </p>
                        {% else %}
                          <p class="mb-1">
                            <strong>{{ field_name|humanize_name }}:</strong> {{ item|getattr:field_name|format_field_value }}
                          </p>
                        {% endif %}
                      {% endif %}
                    {% endfor %}
                  {% else %}
                    {% for field_name in cl.list_display %}
                      {% if field_name == '__str__' %}
                        <p class="mb-1">
                          <strong>{{ results.opts.verbose_name|capfirst }}:</strong> {{ item|truncatewords:"7" }}
                        </p>
                      {% elif field_name == 'action_checkbox' %}
                      {% else %}
                        {% if field_name in cl.grid_display_links %}
                          <p class="mb-1">
                            <strong>{{ field_name|humanize_name }}:</strong> <a href="{{item}}"> {{ item|dir }} {{ item|getattr:field_name|truncatewords:"7" }} </a>
                          </p>
                        {% else %}
                          <p class="mb-1">
                            <strong>{{ field_name|humanize_name }}:</strong> {{ item|getattr:field_name|format_field_value }}
                          </p>
                        {% endif %}
                      {% endif %}
                    {% endfor %}
                  {% endif %}

                  {% if action_form %}
                  <hr />
                  {% endif %}

                  <div class="d-flex gap-2">
                    <a href="{{ item.pk }}/change/" class="btn btn-sm btn-primary"> Edit </a>
                  </div>
                {% endpalette_override card_body %}
              {% endpalette_ui %}
            </div>
          {% endfor %}
        </div>
      {% else %}
        <div class="empty-state">
          <p>{% trans "No items to display." %}</p>
        </div>
      {% endif %}
    </div>
    
    <!-- List View -->
    <div class="list-view active">
      {% if cl.result_list %}
        <div class="table-responsive">
          <table class="table table-hover text-nowrap">
            <thead>
              <tr>
                <th class="item-checkbox">
                  <input type="checkbox" name="select_across" id="action-toggle" class="action-toggle" form="changelist-form">
                </th>

                {% for field_name in cl.list_display %}
                  {% if field_name == '__str__' %}
                    <th>{% trans cl.opts.verbose_name|capfirst %}</th>
                  {% elif field_name == 'action_checkbox' %}
                  {% else %}
                    <th>{% trans field_name|humanize_name %}</th>
                  {% endif %}
                {% endfor %}
                <th class="position-sticky sticky-right">{% trans "Actions" %}</th>
              </tr>
            </thead>

            <tbody class="overflow-auto">
              {% for item in cl.result_list %}
                <tr>
                  <td class="item-checkbox">
                    <input type="checkbox" name="_selected_action" value="{{ item.pk }}" class="action-select" form="changelist-form">
                  </td>
                  {% for field_name in cl.list_display %}
                    {% if field_name == '__str__' %}
                      <td> <a href="{{ item.get_admin_url }}{{item.pk}}/change/"> <strong>{{ item|capfirst|truncatewords:"7" }}</strong></a></td>
                    {% elif field_name == 'action_checkbox' %}
                    {% else %}
                      <td>
                       {% if field_name in cl.list_display_links %}
                         <a class="link text-decoration-none text-primary font-weight-bold" href="{{ item.get_admin_url }}{{item.pk}}/change/"> {{ item|getattr:field_name|format_field_value|truncatewords:"7" }} </a>
                       {% else %}
                         {{ item|getattr:field_name|format_field_value }}
                       {% endif %}
                      </td>
                    {% endif %}
                  {% endfor %}
                  <td>
                    <div class="d-flex flex-nowrap gap-2">
                      <a class="btn btn-sm btn-info" href="{{ item.get_admin_url }}{{ item.pk }}/view/" title="{% trans "View" %}">{% trans "View" %}</a>
                      <a class="btn btn-sm btn-primary" href="{{ item.get_admin_url }}{{ item.pk }}/change/" title="{% trans "Edit" %}">{% trans "Edit" %}</a>
                      {% if 'delete_{{model.name}}' in user.perms %}
                        {{ user.perms }}
                        <a href="{{ item.get_admin_url }}delete/" title="{% trans "Delete" %}" class="deletelink">{% trans "Delete" %}</a>
                      {% endif %}
                    </div>
                  </td>
                </tr>
              {% endfor %}
            </tbody>
            
            <!-- List View Pagination Footer -->
          </table>
        </div>

        {% if cl.paginator and cl.paginator.num_pages > 1 %}
        <div class="mt-3 d-flex justify-content-end">
          <nav aria-label="List view pagination" class="d-flex align-items-center justify-content-center gap-3">
            {% with current_page=cl.page_num %}
              {% if current_page > 1 %}
                <a href="?p={{ current_page|add:'-1' }}" class="btn btn-sm btn-outline-secondary" title="{% trans 'Previous page' %}">
                  <i class="bi bi-chevron-left"></i>
                </a>
              {% else %}
                <button class="btn btn-sm btn-outline-secondary" disabled title="{% trans 'Previous page' %}">
                  <i class="bi bi-chevron-left"></i>
                </button>
              {% endif %}
              
              <span class="px-3" style="min-width: 80px; text-align: center;">
                <strong>{{ current_page }}</strong> / <strong>{{ cl.paginator.num_pages }}</strong>
              </span>
              
              {% if current_page < cl.paginator.num_pages %}
                <a href="?p={{ current_page|add:'1' }}" class="btn btn-sm btn-outline-secondary" title="{% trans 'Next page' %}">
                  <i class="bi bi-chevron-right"></i>
                </a>
              {% else %}
                <button class="btn btn-sm btn-outline-secondary" disabled title="{% trans 'Next page' %}">
                  <i class="bi bi-chevron-right"></i>
                </button>
              {% endif %}
            {% endwith %}
          </nav>
        </div>
        {% endif %}

      {% else %}
        <div class="empty-state">
          <p>{% trans "No items to display." %}</p>
        </div>
      {% endif %}
    </div>

  </div>
</div>

<script type="text/javascript" async>
  document.addEventListener('DOMContentLoaded', function() {
    // View toggle functionality
    const viewButtons = document.querySelectorAll('.view-btn');
    const gridView = document.querySelector('.grid-view');
    const listView = document.querySelector('.list-view');

    viewButtons.forEach(button => {
      button.addEventListener('click', function() {
        const viewType = this.getAttribute('data-view');
        
        // Reset all checkboxes when switching views
        const actionSelectCheckboxes = document.querySelectorAll('.action-select');
        actionSelectCheckboxes.forEach(checkbox => {
          checkbox.checked = false;
        });
        
        // Reset select all checkbox
        if (actionToggle) {
          actionToggle.checked = false;
        }
        
        // Update active button
        viewButtons.forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');

        // Update active view
        if (viewType === 'grid') {
          gridView.classList.add('active');
          listView.classList.remove('active');
          localStorage.setItem('adminViewType', 'grid');
        } else {
          gridView.classList.remove('active');
          listView.classList.add('active');
          localStorage.setItem('adminViewType', 'list');
        }
        
        // Update counter display after view switch
        updateCounter();
      });
    });

    // Remember user's view preference - set on load without clicking (to avoid re-trigger)
    const savedView = localStorage.getItem('adminViewType') || 'list';
    const savedButton = document.querySelector(`[data-view="${savedView}"]`);
    if (savedButton) {
      // Apply view without triggering click event
      viewButtons.forEach(btn => btn.classList.remove('active'));
      savedButton.classList.add('active');
      if (savedView === 'grid') {
        gridView.classList.add('active');
        listView.classList.remove('active');
      } else {
        gridView.classList.remove('active');
        listView.classList.add('active');
      }
    }

    // Selection counter and checkbox functionality
    const actionToggle = document.getElementById('action-toggle');
    const actionCounter = document.querySelector('.action-counter');
    const selectAcrossField = document.querySelector('.select-across');
    const changelistForm = document.getElementById('changelist-form');

    function getVisibleCheckboxes() {
      // Only get checkboxes from the currently active view
      const isGridActive = gridView.classList.contains('active');
      if (isGridActive) {
        return Array.from(gridView.querySelectorAll('.action-select'));
      } else {
        return Array.from(listView.querySelectorAll('.action-select'));
      }
    }

    function updateCounter() {
      const checked = getVisibleCheckboxes().filter(cb => cb.checked).length;
      if (actionCounter) {
        if (checked > 0) {
          actionCounter.textContent = `${checked} item${checked !== 1 ? 's' : ''} selected`;
          actionCounter.style.display = 'block';
        } else {
          actionCounter.style.display = 'none';
        }
      }
    }

    function attachCheckboxListeners() {
      const checkboxes = getVisibleCheckboxes();
      checkboxes.forEach(checkbox => {
        // Remove existing listeners by cloning
        const newCheckbox = checkbox.cloneNode(true);
        checkbox.parentNode.replaceChild(newCheckbox, checkbox);
      });
      
      // Re-attach listeners to current view checkboxes
      const currentCheckboxes = getVisibleCheckboxes();
      currentCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
          updateCounter();
          // Update the "select all" checkbox state
          if (actionToggle) {
            const uncheckedCount = currentCheckboxes.filter(cb => !cb.checked).length;
            actionToggle.checked = uncheckedCount === 0 && currentCheckboxes.length > 0;
          }
        });
      });
    }

    // Select all functionality
    if (actionToggle) {
      actionToggle.addEventListener('change', function() {
        const checkboxes = getVisibleCheckboxes();
        checkboxes.forEach(checkbox => {
          checkbox.checked = this.checked;
        });
        updateCounter();
      });
    }

    // Attach listeners when view changes
    const originalViewClick = viewButtons[0].onclick;
    viewButtons.forEach(button => {
      const originalHandler = button.onclick;
      button.addEventListener('click', function() {
        // Reset checkboxes on view switch
        const allCheckboxes = document.querySelectorAll('.action-select');
        allCheckboxes.forEach(checkbox => {
          checkbox.checked = false;
        });
        if (actionToggle) {
          actionToggle.checked = false;
        }
        
        // Reset grid select-all checkbox
        const gridSelectAll = document.querySelector('.grid-select-all');
        if (gridSelectAll) {
          gridSelectAll.checked = false;
        }
        
        setTimeout(() => {
          attachCheckboxListeners();
          attachGridSelectAllListener();
          updateCounter();
        }, 0);
      });
    });

    // Grid view select-all functionality
    function attachGridSelectAllListener() {
      const gridSelectAll = document.querySelector('.grid-select-all');
      if (gridSelectAll && gridView.classList.contains('active')) {
        gridSelectAll.addEventListener('change', function() {
          const checkboxes = getVisibleCheckboxes();
          checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
          });
          updateCounter();
        });
      }
    }

    // Initialize checkbox listeners
    attachCheckboxListeners();
    attachGridSelectAllListener();

    // Form submission: ensure select_across is set correctly
    if (changelistForm) {
      changelistForm.addEventListener('submit', function(e) {
        const selectedCheckboxes = getVisibleCheckboxes().filter(cb => cb.checked);
        if (selectedCheckboxes.length === 0) {
          e.preventDefault();
          alert('Please select at least one item.');
          return false;
        }
      });
    }

    // Initialize counter display
    updateCounter();
  });
</script>

{% endwith %}
{% endwith %}

{% endblock content %}
