{% extends 'base.html' %}
{% load quality_tags %}

{% block title %}Товары и комплекты{% endblock %}

{% block content %}
{% csrf_token %}
<div class="container-fluid mt-4">
    <h2 class="mb-4">
        <i class="bi bi-box-seam"></i> Товары и комплекты
    </h2>

    <!-- Панель фильтрации и действий -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
                <h5 class="card-title mb-0 me-3">
                    <i class="bi bi-funnel-fill"></i> Фильтры
                </h5>
                <div class="btn-toolbar" role="toolbar">
                    {% if action_buttons %}
                        {% for button in action_buttons %}
                        <a href="{{ button.url }}" class="btn {{ button.class|default:'btn-primary' }} btn-sm me-2 mb-2 mb-md-0">
                            {% if button.icon %}<i class="bi bi-{{ button.icon }}"></i>{% endif %}
                            {{ button.text }}
                        </a>
                        {% endfor %}
                    {% endif %}
                    
                    <!-- Кнопка импорта товаров -->
                    <a href="{% url 'products:product-import' %}" class="btn btn-outline-primary btn-sm me-2 mb-2 mb-md-0">
                        <i class="bi bi-upload"></i> Импорт
                    </a>
                </div>
            </div>

            <hr class="my-3">

            <form method="get" id="filterForm">
                <div class="row g-2">
                    <!-- Поиск -->
                    <div class="col-12 col-md-4">
                        <label for="search" class="form-label small mb-1">Поиск</label>
                        <input type="text" class="form-control form-control-sm" id="search" name="search"
                               placeholder="Название, артикул..."
                               value="{{ filters.current.search|default:'' }}">
                    </div>

                    <!-- Тип -->
                    <div class="col-6 col-md-1">
                        <label for="type" class="form-label small mb-1">Тип</label>
                        <select class="form-select form-select-sm" id="type" name="type">
                            <option value="all" {% if filters.current.type == 'all' %}selected{% endif %}>Все</option>
                            <option value="products" {% if filters.current.type == 'products' %}selected{% endif %}>Товары</option>
                            <option value="kits" {% if filters.current.type == 'kits' %}selected{% endif %}>Комплекты</option>
                        </select>
                    </div>

                    <!-- Категория -->
                    <div class="col-6 col-md-2">
                        <label for="category" class="form-label small mb-1">Категория</label>
                        <select class="form-select form-select-sm" id="category" name="category">
                            <option value="">Все</option>
                            {% for category in filters.categories %}
                            <option value="{{ category.id }}" {% if filters.current.category == category.id|stringformat:"s" %}selected{% endif %}>
                                {{ category.name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- Статус -->
                    <div class="col-6 col-md-1">
                        <label for="status" class="form-label small mb-1">Статус</label>
                        <select class="form-select form-select-sm" id="status" name="status">
                            <option value="">Все</option>
                            {% for status_value, status_name in item_statuses %}
                            <option value="{{ status_value }}" {% if filters.current.status == status_value %}selected{% endif %}>
                                {{ status_name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- Со скидкой -->
                    <div class="col-6 col-md-1">
                        <label class="form-label small mb-1">Скидка</label>
                        <select class="form-select form-select-sm" id="has_discount" name="has_discount">
                            <option value="">—</option>
                            <option value="1" {% if filters.current.has_discount == '1' %}selected{% endif %}>Да</option>
                        </select>
                    </div>

                    <!-- Маркетинг -->
                    <div class="col-12 col-md-3">
                        <label class="form-label small mb-1">Маркетинг</label>
                        <div class="btn-group w-100 d-flex" role="group" style="flex-wrap: wrap;">
                            <input type="checkbox" class="btn-check" id="is_new" name="is_new" value="1"
                                   {% if filters.current.is_new == '1' %}checked{% endif %}
                                   onchange="document.getElementById('filterForm').submit()">
                            <label class="btn btn-outline-warning btn-sm flex-fill" for="is_new" title="Новинки"
                                   style="white-space: normal; text-align: center; font-size: 0.75rem;">
                                <i class="bi bi-stars d-block"></i> Новинки
                            </label>

                            <input type="checkbox" class="btn-check" id="is_popular" name="is_popular" value="1"
                                   {% if filters.current.is_popular == '1' %}checked{% endif %}
                                   onchange="document.getElementById('filterForm').submit()">
                            <label class="btn btn-outline-danger btn-sm flex-fill" for="is_popular" title="Популярные"
                                   style="white-space: normal; text-align: center; font-size: 0.75rem;">
                                <i class="bi bi-fire d-block"></i> Популярные
                            </label>

                            <input type="checkbox" class="btn-check" id="is_special" name="is_special" value="1"
                                   {% if filters.current.is_special == '1' %}checked{% endif %}
                                   onchange="document.getElementById('filterForm').submit()">
                            <label class="btn btn-outline-success btn-sm flex-fill" for="is_special" title="Акции"
                                   style="white-space: normal; text-align: center; font-size: 0.75rem;">
                                <i class="bi bi-percent d-block"></i> Акции
                            </label>
                        </div>
                    </div>
                </div>

                <div class="row g-2">
                    <!-- Цена -->
                    <div class="col-12 col-md-6">
                        <label class="form-label small mb-1">Цена</label>
                        <div class="input-group input-group-sm">
                            <input type="number" class="form-control" id="price_from" name="price_from" placeholder="От"
                                   value="{{ filters.current.price_from|default:'' }}" min="0" step="0.01">
                            <span class="input-group-text">—</span>
                            <input type="number" class="form-control" id="price_to" name="price_to" placeholder="До"
                                   value="{{ filters.current.price_to|default:'' }}" min="0" step="0.01">
                        </div>
                    </div>

                    <!-- В наличии -->
                    <div class="col-4 col-md-1">
                        <label for="in_stock" class="form-label small mb-1">Наличие</label>
                        <select class="form-select form-select-sm" id="in_stock" name="in_stock">
                            <option value="">—</option>
                            <option value="1" {% if filters.current.in_stock == '1' %}selected{% endif %}>Да</option>
                            <option value="0" {% if filters.current.in_stock == '0' %}selected{% endif %}>Нет</option>
                        </select>
                    </div>

                    <!-- Теги -->
                    <div class="col-4 col-md-2">
                        <label for="tags" class="form-label small mb-1">Теги</label>
                        <select class="form-select form-select-sm" id="tags" name="tags" multiple size="1">
                            {% for tag in filters.tags %}
                            <option value="{{ tag.id }}" {% if tag.id in filters.current.tags %}selected{% endif %}>
                                {{ tag.name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- per_page -->
                    <div class="col-4 col-md-1">
                        <label for="per_page" class="form-label small mb-1">На стр.</label>
                        <select class="form-select form-select-sm" id="per_page" name="per_page" onchange="this.form.submit()">
                            <option value="20" {% if filters.current.per_page == '20' %}selected{% endif %}>20</option>
                            <option value="50" {% if filters.current.per_page == '50' %}selected{% endif %}>50</option>
                            <option value="100" {% if filters.current.per_page == '100' %}selected{% endif %}>100</option>
                        </select>
                    </div>

                    <!-- Кнопки -->
                    <div class="col-12 col-md-2">
                        <label class="form-label small mb-1 d-none d-md-block">&nbsp;</label>
                        <div class="d-flex gap-1">
                            <button type="submit" class="btn btn-primary btn-sm flex-fill">
                                OK
                            </button>
                            <a href="{% url 'products:products-list' %}" class="btn btn-outline-secondary btn-sm">
                                X
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    {% if items %}
    <!-- Инструментальная панель для пакетных действий -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="d-flex align-items-center gap-3">
            {% if is_paginated %}
                <span class="text-muted">
                    Показано {{ page_obj.start_index }}–{{ page_obj.end_index }} из {{ page_obj.paginator.count }}
                </span>
            {% else %}
                <span class="text-muted">Всего: {{ items|length }}</span>
            {% endif %}
            
            <!-- Dropdown для выбора всех отфильтрованных -->
            <div class="btn-group" id="select-all-dropdown-group" style="display: none;">
                <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" 
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-check2-square"></i> Выбрать
                </button>
                <ul class="dropdown-menu">
                    <li>
                        <a class="dropdown-item" href="#" onclick="document.getElementById('select-all-checkbox').click(); return false;">
                            <i class="bi bi-check2"></i> Все на странице
                        </a>
                    </li>
                    {% if is_paginated %}
                    <li>
                        <a class="dropdown-item" href="#" onclick="window.BatchSelection.selectAllFiltered(); return false;">
                            <i class="bi bi-check2-all"></i> Все отфильтрованные ({{ page_obj.paginator.count }})
                        </a>
                    </li>
                    {% endif %}
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <a class="dropdown-item" href="#" onclick="window.BatchSelection.clearSelection(); return false;">
                            <i class="bi bi-x-square"></i> Снять выбор
                        </a>
                    </li>
                </ul>
            </div>
        </div>
        <div class="dropdown d-flex align-items-center gap-2" id="batch-actions-wrapper" style="position: relative;">
            <button type="button" class="btn btn-light dropdown-toggle border" id="batch-actions-btn" disabled
                    data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bi bi-gear-fill"></i> Действия над выбранными (<span id="selection-count">0</span>)
            </button>
            <span class="badge bg-secondary" id="batch-actions-hint" style="position: absolute; top: 100%; left: 0; margin-top: 4px; z-index: 10; white-space: nowrap; display: none;">Сначала выберите товары</span>
            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="batch-actions-btn">
                <li>
                    <a class="dropdown-item" href="#" id="bulk-category-action">
                        <i class="bi bi-bookmark-fill"></i> Изменить категории
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                {% if recommerce_integration_enabled %}
                <li>
                    <a class="dropdown-item" href="#" id="bulk-recommerce-sync">
                        <i class="bi bi-arrow-repeat"></i> Синхронизация с Recommerce
                    </a>
                </li>
                {% endif %}
            </ul>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-striped table-hover align-middle">
            <thead class="table-dark">
                <tr>
                    <th style="width: 50px;">
                        <input type="checkbox" id="select-all-checkbox" class="form-check-input" 
                               title="Выбрать все на странице">
                    </th>
                    <th style="width: 80px;">Фото</th>
                    <th>Название</th>
                    <th style="width: 120px;">Артикул</th>
                    <th style="width: 80px;">Тип</th>
                    <th>Категория</th>
                    <th style="width: 100px;">Внешняя кат.</th>
                    <th style="width: 150px;">Теги</th>
                    <th style="width: 130px;">Цена</th>
                    <th style="width: 120px;">Остаток</th>
                    <th style="width: 100px;">Статус</th>
                    <th style="width: 150px;">Действия</th>
                </tr>
            </thead>
            <tbody>
                {% for item in items %}
                <tr>
                    <td>
                        <input type="checkbox" name="selected_items"
                               value="{{ item.item_type }}:{{ item.pk }}"
                               class="form-check-input item-checkbox"
                               data-item-type="{{ item.item_type }}"
                               data-item-id="{{ item.pk }}"
                               data-item-name="{{ item.name }}">
                    </td>
                    <td>
                        {% if item.photos.all %}
                            {% with photo=item.photos.first %}
                                <img src="{{ photo.get_thumbnail_url }}" alt="{{ item.name }}" 
                                     class="img-thumbnail rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            {% endwith %}
                        {% else %}
                            <span class="text-muted small">Нет фото</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <a href="{% url 'products:product-detail' item.pk %}">{{ item.name }}</a>
                        {% else %}
                            <a href="{% url 'products:productkit-detail' item.pk %}">{{ item.name }}</a>
                        {% endif %}
                        <div class="mt-1">
                            {% if item.is_new %}<span class="badge bg-warning text-dark" style="font-size: 0.65rem;">Новинка</span>{% endif %}
                            {% if item.is_popular %}<span class="badge bg-danger" style="font-size: 0.65rem;">Популярный</span>{% endif %}
                            {% if item.is_special %}<span class="badge bg-success" style="font-size: 0.65rem;">Акция</span>{% endif %}
                        </div>
                    </td>
                    <td><code class="small">{{ item.sku }}</code></td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <span class="badge bg-success" title="Товар"><i class="bi bi-box"></i></span>
                        {% else %}
                            <span class="badge bg-info" title="Комплект"><i class="bi bi-box-seam"></i></span>
                        {% endif %}
                    </td>
                    <td>
                        {% for category in item.categories.all %}
                            <span class="badge bg-secondary">{{ category.name }}</span>
                        {% empty %}
                            <span class="text-muted">-</span>
                        {% endfor %}
                    </td>
                    <td>
                        {% if item.external_category %}
                            <span class="badge bg-warning text-dark" title="{{ item.external_category.name }}">
                                <i class="bi bi-star-fill"></i> {{ item.external_category.name|truncatechars:15 }}
                            </span>
                        {% else %}
                            <span class="text-muted">—</span>
                        {% endif %}
                    </td>
                    <td title="{% if item.tags.all|length %}{% for t in item.tags.all %}{{ t.name }}{% if not forloop.last %}, {% endif %}{% endfor %}{% else %}-{% endif %}">
                        {% for tag in item.tags.all|slice:":2" %}
                            <span class="badge bg-primary">{{ tag.name }}</span>
                        {% empty %}
                            <span class="text-muted">-</span>
                        {% endfor %}
                        {% with total=item.tags.all|length %}
                            {% if total > 2 %}
                                <span class="text-muted">…</span>
                            {% endif %}
                        {% endwith %}
                    </td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <div class="price-edit-container">
                                {% if item.sale_price %}
                                    <div class="text-decoration-line-through text-muted small">{{ item.price|floatformat:2 }} руб.</div>
                                    {% if user.is_superuser or user.tenant_role.role.code == 'owner' or user.tenant_role.role.code == 'manager' %}
                                        <strong class="text-danger editable-price"
                                                data-product-id="{{ item.pk }}"
                                                data-field="sale_price"
                                                data-current-value="{{ item.sale_price }}"
                                                title="Цена со скидкой (клик для редактирования)"
                                                style="cursor: pointer;">
                                            {{ item.sale_price|floatformat:2 }} руб.
                                        </strong>
                                    {% else %}
                                        <strong class="text-danger">
                                            {{ item.sale_price|floatformat:2 }} руб.
                                        </strong>
                                    {% endif %}
                                {% else %}
                                    {% if user.is_superuser or user.tenant_role.role.code == 'owner' or user.tenant_role.role.code == 'manager' %}
                                        <strong class="editable-price"
                                                data-product-id="{{ item.pk }}"
                                                data-field="price"
                                                data-current-value="{{ item.price }}"
                                                title="Цена продажи (клик для редактирования)"
                                                style="cursor: pointer;">
                                            {{ item.price|floatformat:2 }} руб.
                                        </strong>
                                    {% else %}
                                        <strong>
                                            {{ item.price|floatformat:2 }} руб.
                                        </strong>
                                    {% endif %}
                                {% endif %}
                            </div>
                        {% else %}
                            {# Для комплектов редактирование не поддерживается #}
                            {% if item.sale_price %}
                                <div class="text-decoration-line-through text-muted small">{{ item.price|floatformat:2 }} руб.</div>
                                <strong class="text-danger">{{ item.sale_price|floatformat:2 }} руб.</strong>
                            {% else %}
                                <strong>{{ item.price|floatformat:2 }} руб.</strong>
                            {% endif %}
                        {% endif %}
                    </td>
                    <td>
                        {% if item.item_type == 'product' %}
                            <strong class="{% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">{{ item.total_free|floatformat:-2 }}</strong>{% if item.total_reserved > 0 %}<small class="text-muted"> / {{ item.total_available|floatformat:-2 }}</small>
                                <small class="text-warning d-block">{{ item.total_reserved|floatformat:-2 }} в резерве</small>
                            {% endif %}
                        {% elif item.item_type == 'kit' %}
                            <strong class="{% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">{{ item.total_free|floatformat:0 }}</strong> <small class="text-muted">компл.</small>
                        {% else %}
                            <span class="text-muted">-</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.status == 'active' %}
                            <span class="badge bg-success">Активный</span>
                        {% elif item.status == 'archived' %}
                            <span class="badge bg-warning text-dark">Архивный</span>
                        {% elif item.status == 'discontinued' %}
                            <span class="badge bg-danger">Снят</span>
                        {% else %}
                            <span class="badge bg-secondary">{{ item.get_status_display }}</span>
                        {% endif %}
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            {% if item.item_type == 'product' %}
                                <a href="{% url 'products:product-detail' item.pk %}" 
                                   class="btn btn-outline-info" title="Просмотр">
                                    <i class="bi bi-eye"></i>
                                </a>
                                {% if perms.products.change_product %}
                                <a href="{% url 'products:product-update' item.pk %}" 
                                   class="btn btn-outline-primary" title="Изменить">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                {% endif %}
                                {% if perms.products.delete_product %}
                                <a href="{% url 'products:product-delete' item.pk %}" 
                                   class="btn btn-outline-danger" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </a>
                                {% endif %}
                            {% else %}
                                <a href="{% url 'products:productkit-detail' item.pk %}" 
                                   class="btn btn-outline-info" title="Просмотр">
                                    <i class="bi bi-eye"></i>
                                </a>
                                {% if perms.products.change_productkit %}
                                <a href="{% url 'products:productkit-update' item.pk %}" 
                                   class="btn btn-outline-primary" title="Изменить">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                {% endif %}
                                {% if perms.products.delete_productkit %}
                                <a href="{% url 'products:productkit-delete' item.pk %}" 
                                   class="btn btn-outline-danger" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </a>
                                {% endif %}
                            {% endif %}
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    {% if is_paginated %}
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page=1{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Первая
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Предыдущая
                    </a>
                </li>
            {% endif %}

            <li class="page-item active">
                <span class="page-link">Страница {{ page_obj.number }} из {{ page_obj.paginator.num_pages }}</span>
            </li>

            {% if page_obj.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Следующая
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                        Последняя
                    </a>
                </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
    {% else %}
    <div class="alert alert-info">
        <h4><i class="bi bi-info-circle"></i> Товары не найдены</h4>
        <p>В данный момент нет товаров или комплектов, соответствующих выбранным фильтрам.</p>
        <div class="mt-3">
            {% if perms.products.add_product %}
            <a href="{% url 'products:product-create' %}" class="btn btn-primary me-2">
                <i class="bi bi-plus-circle"></i> Создать товар
            </a>
            {% endif %}
            {% if perms.products.add_productkit %}
            <a href="{% url 'products:productkit-create' %}" class="btn btn-outline-primary">
                <i class="bi bi-plus-circle"></i> Создать комплект
            </a>
            {% endif %}
        </div>
    </div>
    {% endif %}
</div>

{% include "products/includes/recommerce_sync_modal.html" %}

<!-- Модальное окно для массового изменения категорий -->
<div class="modal fade" id="bulkCategoryModal" tabindex="-1" aria-labelledby="bulkCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkCategoryModalLabel">
                    <i class="bi bi-bookmark-fill"></i> Изменить категории для выбранных товаров
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <!-- Информация о выбранных товарах -->
                <div class="alert alert-info mb-3">
                    <i class="bi bi-info-circle"></i> <strong>Выбрано:</strong> <span id="selectedItemsCount">0</span> товаров
                    <span id="selectedItemsBreakdown" class="ms-2 text-muted"></span>
                </div>

                <!-- Режим изменения категорий -->
                <div class="mb-4">
                    <label class="form-label fw-bold">Что сделать с категориями выбранных товаров?</label>

                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeAdd" value="add" checked>
                        <label class="form-check-label" for="bulkCategoryModeAdd">
                            Добавить выбранные категории к существующим
                        </label>
                    </div>

                    <div class="form-check mt-2">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeReplace" value="replace">
                        <label class="form-check-label" for="bulkCategoryModeReplace">
                            Заменить существующие категории выбранными
                        </label>
                    </div>

                    <div class="form-check mt-2">
                        <input class="form-check-input" type="radio" name="bulkCategoryMode"
                               id="bulkCategoryModeClear" value="clear">
                        <label class="form-check-label text-danger" for="bulkCategoryModeClear">
                            <strong>Удалить все категории</strong>
                        </label>
                    </div>

                    <div id="bulkCategoryModeHint" class="form-text text-muted mt-2">
                        Добавленные категории будут присоединены к уже существующим.
                    </div>
                </div>

                <!-- Выбор категорий -->
                <div class="mb-3" id="bulkCategoryListSection">
                    <label class="form-label fw-bold">Выберите категории:</label>
                    
                    <!-- Поиск по категориям -->
                    <input type="text" class="form-control mb-2" id="categorySearchInput" 
                           placeholder="Поиск категорий...">
                    
                    <!-- Список категорий -->
                    <div id="categoryListContainer" style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 0.25rem; padding: 0.5rem;">
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Загрузка...</span>
                            </div>
                            <div class="mt-2 text-muted">Загрузка категорий...</div>
                        </div>
                    </div>
                </div>

                <!-- Секция ВНЕШНЕЙ категории для интеграций -->
                <div class="mb-4 border-top pt-3">
                    <label class="form-label fw-bold">
                        <i class="bi bi-star-fill text-warning"></i>
                        Внешняя категория (для интеграций)
                    </label>
                    <p class="small text-muted mb-2">
                        Внешняя категория используется при экспорте на внешние площадки (Recommerce, WooCommerce и др.)
                    </p>
                    
                    <!-- Выбор внешней категории -->
                    <div class="mb-2">
                        <select class="form-select" id="externalCategorySelect">
                            <option value="">— Не выбрана —</option>
                            {% for category in filters.categories %}
                            <option value="{{ category.id }}">{{ category.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    
                    <!-- Чекбокс для очистки -->
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="clearExternalCategory">
                        <label class="form-check-label text-danger" for="clearExternalCategory">
                            <strong>Очистить внешнюю категорию</strong>
                        </label>
                    </div>
                </div>

                <!-- Сообщения об ошибках -->
                <div id="bulkCategoryError" class="alert alert-danger d-none" role="alert"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle"></i> Отмена
                </button>
                <button type="button" class="btn btn-primary" id="applyBulkCategoriesBtn" disabled>
                    <i class="bi bi-check2-circle"></i> Применить
                </button>
            </div>
        </div>
    </div>
</div>

<style>
#batch-actions-wrapper[data-hint="true"]:hover #batch-actions-hint {
    display: inline-block !important;
}

/* Стили для редактируемых цен */
.editable-price {
    cursor: pointer;
    transition: color 0.2s ease;
}

.editable-price:hover {
    color: #0d6efd !important;
    text-decoration: underline;
}

.price-edit-container {
    min-height: 2.5rem;
}
</style>

{% endblock %}

{% block extra_js %}
{% load static %}
<script src="{% static 'products/js/inline-price-edit.js' %}?v=1.5"></script>
<script src="{% static 'products/js/batch-selection.js' %}?v=1.5"></script>
<script src="{% static 'products/js/bulk-category-modal.js' %}?v=1.6"></script>
<script src="{% static 'products/js/recommerce-sync.js' %}?v=1.2"></script>
<script>
// Проверка состояния интеграции Recommerce
document.addEventListener('DOMContentLoaded', function() {
    const syncBtn = document.getElementById('bulk-recommerce-sync');
    if (syncBtn) {
        syncBtn.addEventListener('click', function(e) {
            {% if not recommerce_integration_enabled %}
            e.preventDefault();
            alert('Интеграция с Recommerce отключена. Включите её в настройках.');
            return false;
            {% endif %}
        });
    }
});
</script>
{% endblock %}
