{% extends 'base.html' %}

{% block title %}Каталог{% endblock %}

{% block extra_css %}
<style>
    .category-tree {
        font-size: 0.9rem;
    }
    /* Корневые категории без отступов */
    .category-tree > .category-node {
        border-left: none;
        margin-left: 0;
    }
    /* Вложенные категории с отступами */
    .category-children .category-node {
        border-left: 2px solid #e9ecef;
        margin-left: 0.5rem;
    }
    .category-header {
        cursor: pointer;
        padding: 0.5rem 0.75rem;
        border-radius: 0.25rem;
        transition: background-color 0.15s;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .category-header:hover {
        background-color: #f8f9fa;
    }
    .category-header.active {
        background-color: #e7f1ff;
        color: #0d6efd;
    }
    .category-toggle {
        width: 1.25rem;
        text-align: center;
        color: #6c757d;
        transition: transform 0.2s;
    }
    .category-toggle.collapsed {
        transform: rotate(-90deg);
    }
    .category-children {
        padding-left: 1rem;
    }
    .category-items {
        padding-left: 2rem;
        border-left: 1px dashed #dee2e6;
        margin-left: 0.6rem;
    }
    .category-item {
        padding: 0.25rem 0.5rem;
        font-size: 0.85rem;
        color: #495057;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .category-item:hover {
        color: #0d6efd;
    }
    .category-item a {
        text-decoration: none;
        color: inherit;
    }
    .item-badge {
        font-size: 0.65rem;
        padding: 0.15rem 0.35rem;
    }
    /* Режим списка - табличная структура с фиксированными колонками */
    .catalog-list.row {
        gap: 1px !important;
    }
    .catalog-list .catalog-item {
        flex: 0 0 100%;
        max-width: 100%;
        padding: 0 !important;
    }
    .catalog-list .catalog-item .card {
        display: grid;
        grid-template-columns: 50px 1fr 150px 120px 120px;
        align-items: center;
        padding: 0;
        border-radius: 0.25rem;
        overflow: hidden;
        min-height: 50px;
    }
    .catalog-list .catalog-item .card .position-relative {
        height: 50px;
        width: 50px;
        align-self: start;
    }
    .catalog-list .catalog-item .card .position-relative img,
    .catalog-list .catalog-item .card .position-relative > div {
        height: 50px;
        width: 50px;
        border-radius: 0;
        object-fit: cover;
    }
    .catalog-list .catalog-item .card .position-relative .badge {
        display: none;
    }
    .catalog-list .catalog-item .card-body {
        display: contents;
    }
    /* Название товара - ограничиваем 2 строками */
    .catalog-list .catalog-item .product-name {
        padding: 0.4rem 0.5rem;
        line-height: 1.3;
        max-height: 3.4em;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: 0.85rem;
        align-self: center;
    }
    /* Остатки */
    .catalog-list .catalog-item .product-stock {
        padding: 0.4rem 0.25rem;
        text-align: left;
        font-size: 0.8rem;
        align-self: center;
    }
    /* Цена */
    .catalog-list .catalog-item .product-price {
        padding: 0.4rem 0.25rem;
        text-align: left;
        font-size: 0.85rem;
        align-self: center;
    }
    /* Артикул */
    .catalog-list .catalog-item .product-sku {
        padding: 0.4rem 0.5rem 0.4rem 0.25rem;
        text-align: left;
        font-size: 0.8rem;
        align-self: center;
    }
    .catalog-list .catalog-item .card-body .mt-1 {
        margin-top: 0 !important;
    }
    /* Кнопки управления категориями (переименование, добавление подкатегории) */
    .category-rename-btn,
    .category-add-child-btn {
        opacity: 0;
        cursor: pointer;
        color: #6c757d;
        font-size: 0.75rem;
        padding: 2px 4px;
        transition: opacity 0.2s, color 0.15s;
    }
    .category-header:hover .category-rename-btn,
    .category-header:hover .category-add-child-btn {
        opacity: 0.5;
    }
    .category-rename-btn:hover {
        opacity: 1 !important;
        color: #0d6efd;
    }
    .category-add-child-btn:hover {
        opacity: 1 !important;
        color: #198754;
    }
    /* Редактируемые цены */
    .editable-price {
        cursor: pointer;
        padding: 2px 4px;
        border-radius: 3px;
        transition: background-color 0.15s, border-color 0.15s;
        border: 1px solid transparent;
    }
    .editable-price:hover {
        background-color: #f8f9fa;
        border: 1px dashed #dee2e6;
    }
    .editable-price.sale-price:hover {
        background-color: #d1f4e0;
        border-color: #28a745;
    }
    .editable-price.regular-price:hover {
        background-color: #e7f1ff;
        border-color: #0d6efd;
    }
    .price-edit-input {
        width: 90px;
        font-size: 0.85rem;
        padding: 2px 6px;
        border: 2px solid #0d6efd;
        border-radius: 3px;
        text-align: right;
    }
    .price-edit-input:focus {
        outline: none;
        border-color: #0a58ca;
        box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
    }
    .remove-sale-price {
        opacity: 0;
        transition: opacity 0.2s;
    }
    .price-edit-container:hover .remove-sale-price {
        opacity: 0.5;
    }
    .remove-sale-price:hover {
        opacity: 1 !important;
    }
    .add-sale-price {
        opacity: 0;
        transition: opacity 0.2s;
    }
    .price-edit-container:hover .add-sale-price {
        opacity: 1;
    }
    /* Стили для информации об остатках */
    .stock-info {
        font-size: 0.85rem;
    }
    .stock-info i {
        font-size: 0.9rem;
    }
    /* Для режима списка - добавляем правильное выравнивание */
    .catalog-list .catalog-item .stock-info {
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
        white-space: nowrap;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid mt-4 px-4">
    <div class="row">
        <!-- Дерево категорий слева -->
        <div class="col-lg-4 col-md-5">
            <div class="card shadow-sm border-0 mb-3">
                <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                    <strong><i class="bi bi-folder-tree text-primary"></i> Категории</strong>
                    <div class="d-flex gap-2 align-items-center">
                        <i class="bi bi-plus-circle text-success cursor-pointer" id="add-root-category-btn" title="Добавить категорию" style="font-size: 1.2rem; cursor: pointer;"></i>
                        <div class="d-flex gap-1">
                            <button class="btn btn-outline-secondary btn-sm" id="expand-all" style="font-size: 0.75rem;">Развернуть</button>
                            <button class="btn btn-outline-secondary btn-sm" id="collapse-all" style="font-size: 0.75rem;">Свернуть</button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-2 category-tree">
                    {% if category_tree %}
                        {% for node in category_tree %}
                            {% include 'products/catalog_tree_node.html' with node=node %}
                        {% endfor %}
                    {% else %}
                        <div class="text-muted text-center py-3">
                            <i class="bi bi-folder-x"></i> Категорий нет
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Сетка товаров справа -->
        <div class="col-lg-8 col-md-7">
            <!-- Кнопки действий -->
            {% if action_buttons %}
            <div class="mb-3">
                <div class="btn-toolbar" role="toolbar">
                    {% for button in action_buttons %}
                    <a href="{{ button.url }}" class="btn {{ button.class|default:'btn-primary' }} btn-sm me-2 mb-2">
                        {% if button.icon %}<i class="bi bi-{{ button.icon }}"></i>{% endif %}
                        {{ button.text }}
                    </a>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
            
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                    <strong><i class="bi bi-grid-3x3-gap text-primary"></i> Товары и комплекты</strong>
                    <div class="d-flex gap-2 align-items-center">
                        <input type="text" class="form-control form-control-sm" placeholder="Поиск..." id="catalog-search" style="width: 180px;">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-primary btn-sm active" data-filter="all">Все</button>
                            <button class="btn btn-outline-primary btn-sm" data-filter="product">Товары</button>
                            <button class="btn btn-outline-primary btn-sm" data-filter="kit">Комплекты</button>
                        </div>
                        <div class="btn-group btn-group-sm ms-2">
                            <button class="btn btn-outline-secondary btn-sm" id="view-grid" title="Карточки"><i class="bi bi-grid-3x3-gap"></i></button>
                            <button class="btn btn-outline-secondary btn-sm active" id="view-list" title="Список"><i class="bi bi-list-ul"></i></button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row g-3 catalog-list" id="catalog-grid">
                        {% for item in items %}
                        <div class="col-12 catalog-item" data-type="{{ item.item_type }}" data-category-ids="{% for cat in item.cached_categories %}{{ cat.pk }}{% if not forloop.last %},{% endif %}{% endfor %}">
                            <div class="card h-100 shadow-sm border-0">
                                <!-- Фото -->
                                <div class="position-relative">
                                    {% if item.cached_main_photo %}
                                    <img src="{{ item.cached_main_photo.get_thumbnail_url }}" class="card-img-top" alt="{{ item.name }}" style="height: 120px; object-fit: cover;">
                                    {% else %}
                                    <div class="bg-light d-flex align-items-center justify-content-center" style="height: 120px;">
                                        <i class="bi bi-image text-muted fs-2"></i>
                                    </div>
                                    {% endif %}
                                    <span class="badge position-absolute top-0 end-0 m-1 {% if item.item_type == 'kit' %}bg-info{% else %}bg-secondary{% endif %}" style="font-size: 0.65rem;">
                                        {% if item.item_type == 'kit' %}К{% else %}Т{% endif %}
                                    </span>
                                </div>
                                
                                <div class="card-body p-2">
                                    <!-- Название товара (2 строки max) -->
                                    <div class="product-name fw-medium">
                                        {% if item.item_type == 'kit' %}
                                            <a href="{% url 'products:productkit-detail' item.pk %}" class="text-decoration-none">{{ item.name }}</a>
                                        {% else %}
                                            <a href="{% url 'products:product-detail' item.pk %}" class="text-decoration-none">{{ item.name }}</a>
                                        {% endif %}
                                    </div>
                                    
                                    <!-- Остатки -->
                                    <div class="product-stock">
                                        {% if item.item_type == 'product' %}
                                            <small class="stock-info {% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">
                                                <i class="bi bi-box-seam"></i>
                                                <strong>{{ item.total_free|floatformat:"-3" }}</strong>
                                                <span class="text-muted">/ {{ item.total_available|floatformat:"-3" }}</span>
                                            </small>
                                        {% elif item.item_type == 'kit' %}
                                            <small class="stock-info {% if item.total_free > 0 %}text-success{% else %}text-danger{% endif %}">
                                                <i class="bi bi-box-seam"></i>
                                                <strong>{{ item.total_free|floatformat:"0" }}</strong> компл.
                                            </small>
                                        {% endif %}
                                    </div>
                                    
                                    <!-- Цена -->
                                    <div class="product-price">
                                        {% if item.item_type == 'product' %}
                                            <div class="price-edit-container">
                                                {% if item.sale_price %}
                                                    <span class="editable-price sale-price fw-bold text-success small"
                                                          data-product-id="{{ item.pk }}"
                                                          data-field="sale_price"
                                                          data-current-value="{{ item.sale_price }}"
                                                          title="Скидочная цена">
                                                        {{ item.sale_price|floatformat:2 }}
                                                    </span>
                                                    <br>
                                                    <span class="editable-price regular-price text-muted text-decoration-line-through small"
                                                          data-product-id="{{ item.pk }}"
                                                          data-field="price"
                                                          data-current-value="{{ item.price }}"
                                                          title="Обычная цена">
                                                        {{ item.price|floatformat:2 }}
                                                    </span>
                                                {% else %}
                                                    <span class="editable-price fw-bold text-primary small"
                                                          data-product-id="{{ item.pk }}"
                                                          data-field="price"
                                                          data-current-value="{{ item.price }}"
                                                          title="Цена">
                                                        {{ item.price|floatformat:2 }} руб.
                                                    </span>
                                                {% endif %}
                                            </div>
                                        {% else %}
                                            <span class="fw-bold text-primary small">{{ item.actual_price|floatformat:2 }} руб.</span>
                                        {% endif %}
                                    </div>
                                    
                                    <!-- Артикул -->
                                    <div class="product-sku">
                                        <small class="text-muted">{{ item.sku }}</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="col-12 text-center text-muted py-5">
                            <i class="bi bi-box-seam fs-1 opacity-25"></i>
                            <p class="mb-0 mt-2">Каталог пуст</p>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <!-- Пагинация -->
                    {% if is_paginated %}
                    <nav aria-label="Пагинация" class="mt-4">
                        <ul class="pagination justify-content-center mb-0">
                            {% if page_obj.has_previous %}
                                <li class="page-item">
                                    <a class="page-link" href="?page=1">&laquo; Первая</a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}">&lsaquo; Назад</a>
                                </li>
                            {% else %}
                                <li class="page-item disabled">
                                    <span class="page-link">&laquo; Первая</span>
                                </li>
                                <li class="page-item disabled">
                                    <span class="page-link">&lsaquo; Назад</span>
                                </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 }}">Вперед &rsaquo;</a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">Последняя &raquo;</a>
                                </li>
                            {% else %}
                                <li class="page-item disabled">
                                    <span class="page-link">Вперед &rsaquo;</span>
                                </li>
                                <li class="page-item disabled">
                                    <span class="page-link">Последняя &raquo;</span>
                                </li>
                            {% endif %}
                        </ul>
                        <div class="text-center text-muted small mt-2">
                            Показано {{ page_obj.start_index }}–{{ page_obj.end_index }} из {{ page_obj.paginator.count }} товаров
                        </div>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

{% load static %}
<script src="{% static 'products/js/catalog.js' %}"></script>
{% endblock %}
