{% extends 'mainapp/base.html' %}
{% load permission_tags %}

{% block title %}Список спутников{% endblock %}

{% block extra_css %}
<style>
    .table-responsive tr.selected {
        background-color: #d4edff;
    }
    .sticky-top {
        position: sticky;
        top: 0;
        z-index: 10;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-3">
    <div class="row mb-3">
        <div class="col-12">
            <h2>Список спутников</h2>
        </div>
    </div>

    <!-- Toolbar -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center gap-3">
                        <!-- Search bar -->
                        <div style="min-width: 200px; flex-grow: 1; max-width: 400px;">
                            <div class="input-group">
                                <input type="text" id="toolbar-search" class="form-control" placeholder="Поиск..."
                                    value="{{ search_query|default:'' }}">
                                <button type="button" class="btn btn-outline-primary"
                                    onclick="performSearch()">Найти</button>
                                <button type="button" class="btn btn-outline-secondary"
                                    onclick="clearSearch()">Очистить</button>
                            </div>
                        </div>

                        <!-- Items per page select -->
                        <div>
                            <label for="items-per-page" class="form-label mb-0">Показать:</label>
                            <select name="items_per_page" id="items-per-page"
                                class="form-select form-select-sm d-inline-block" style="width: auto;"
                                onchange="updateItemsPerPage()">
                                {% for option in available_items_per_page %}
                                <option value="{{ option }}" 
                                    {% if option == 'Все' and items_per_page >= 10000 %}selected
                                    {% elif option|stringformat:"s" == items_per_page|stringformat:"s" %}selected
                                    {% endif %}>
                                    {{ option }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- Action buttons -->
                        <div class="d-flex gap-2">
                            {% if user|has_perm:'satellite_create' %}
                            <a href="{% url 'mainapp:satellite_create' %}" class="btn btn-success btn-sm" title="Создать">
                                <i class="bi bi-plus-circle"></i> Создать
                            </a>
                            {% endif %}
                            {% if user|has_perm:'satellite_delete' %}
                            <button type="button" class="btn btn-danger btn-sm" title="Удалить"
                                onclick="deleteSelectedSatellites()">
                                <i class="bi bi-trash"></i> Удалить
                            </button>
                            {% endif %}
                        </div>

                        <!-- Add to List Button -->
                        <div>
                            <button class="btn btn-outline-success btn-sm" type="button" onclick="addSelectedToList()">
                                <i class="bi bi-plus-circle"></i> Добавить к
                            </button>
                        </div>

                        <!-- Selected Items Counter Button -->
                        <div>
                            <button class="btn btn-outline-info btn-sm" type="button" data-bs-toggle="offcanvas"
                                data-bs-target="#selectedSatellitesOffcanvas" aria-controls="selectedSatellitesOffcanvas">
                                <i class="bi bi-list-check"></i> Список
                                <span id="selectedSatelliteCounter" class="badge bg-info" style="display: none;">0</span>
                            </button>
                        </div>

                        <!-- Filter Toggle Button -->
                        <div>
                            <button class="btn btn-outline-primary btn-sm" type="button" data-bs-toggle="offcanvas" 
                                data-bs-target="#offcanvasFilters" aria-controls="offcanvasFilters">
                                <i class="bi bi-funnel"></i> Фильтры
                                <span id="filterCounter" class="badge bg-danger" style="display: none;">0</span>
                            </button>
                        </div>

                        <!-- Pagination -->
                        <div class="ms-auto">
                            {% include 'mainapp/components/_pagination.html' with page_obj=page_obj show_info=True %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Offcanvas Filter Panel -->
    <div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasFilters" aria-labelledby="offcanvasFiltersLabel">
        <div class="offcanvas-header">
            <h5 class="offcanvas-title" id="offcanvasFiltersLabel">Фильтры</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
        </div>
        <div class="offcanvas-body">
            <form method="get" id="filter-form">
                <!-- Location Place Selection -->
                <div class="mb-2">
                    <label class="form-label">Комплекс:</label>
                    <select name="location_place" class="form-select form-select-sm mb-2" multiple size="3">
                        {% for value, label in location_places %}
                        <option value="{{ value }}" {% if value in selected_location_places %}selected{% endif %}>
                            {{ label }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Band Selection - Multi-select -->
                <div class="mb-2">
                    <label class="form-label">Диапазон:</label>
                    <div class="d-flex justify-content-between mb-1">
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                            onclick="selectAllOptions('band_id', true)">Выбрать</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                            onclick="selectAllOptions('band_id', false)">Снять</button>
                    </div>
                    <select name="band_id" class="form-select form-select-sm mb-2" multiple size="6">
                        {% for band in bands %}
                        <option value="{{ band.id }}" {% if band.id in selected_bands %}selected{% endif %}>
                            {{ band.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- NORAD ID Filter -->
                <div class="mb-2">
                    <label class="form-label">NORAD ID:</label>
                    <input type="number" name="norad_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ norad_min|default:'' }}">
                    <input type="number" name="norad_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ norad_max|default:'' }}">
                </div>

                <!-- Undersat Point Filter -->
                <div class="mb-2">
                    <label class="form-label">Подспутниковая точка, градусы:</label>
                    <input type="number" step="0.01" name="undersat_point_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ undersat_point_min|default:'' }}">
                    <input type="number" step="0.01" name="undersat_point_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ undersat_point_max|default:'' }}">
                </div>

                <!-- Transponder Count Filter -->
                <div class="mb-2">
                    <label class="form-label">Количество транспондеров:</label>
                    <input type="number" name="transponder_count_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ transponder_count_min|default:'' }}">
                    <input type="number" name="transponder_count_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ transponder_count_max|default:'' }}">
                </div>

                <!-- Launch Date Filter -->
                <div class="mb-2">
                    <label class="form-label">Дата запуска:</label>
                    <input type="date" name="launch_date_from" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ launch_date_from|default:'' }}">
                    <input type="date" name="launch_date_to" class="form-control form-control-sm"
                        placeholder="До" value="{{ launch_date_to|default:'' }}">
                </div>

                <!-- Creation Date Filter -->
                <div class="mb-2">
                    <label class="form-label">Дата создания:</label>
                    <input type="date" name="date_from" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ date_from|default:'' }}">
                    <input type="date" name="date_to" class="form-control form-control-sm"
                        placeholder="До" value="{{ date_to|default:'' }}">
                </div>

                <!-- Apply Filters and Reset Buttons -->
                <div class="d-grid gap-2 mt-2">
                    <button type="submit" class="btn btn-primary btn-sm">Применить</button>
                    <a href="?" class="btn btn-secondary btn-sm">Сбросить</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Main Table -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 75vh; overflow-y: auto;">
                        <table class="table table-striped table-hover table-sm table-bordered" style="font-size: 0.85rem;">
                            <thead class="table-dark sticky-top">
                                <tr>
                                    <th scope="col" class="text-center" style="width: 3%;">
                                        <input type="checkbox" id="select-all" class="form-check-input">
                                    </th>
                                    <th scope="col" class="text-center" style="min-width: 60px;">
                                        <a href="javascript:void(0)" onclick="updateSort('id')" class="text-white text-decoration-none">
                                            ID
                                            {% if sort == 'id' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-id' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 150px;">
                                        <a href="javascript:void(0)" onclick="updateSort('name')" class="text-white text-decoration-none">
                                            Название
                                            {% if sort == 'name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 150px;">
                                        <a href="javascript:void(0)" onclick="updateSort('alternative_name')" class="text-white text-decoration-none">
                                            Альт. название
                                            {% if sort == 'alternative_name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-alternative_name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 80px;">
                                        <a href="javascript:void(0)" onclick="updateSort('location_place')" class="text-white text-decoration-none">
                                            Комплекс
                                            {% if sort == 'location_place' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-location_place' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">
                                        <a href="javascript:void(0)" onclick="updateSort('norad')" class="text-white text-decoration-none">
                                            NORAD ID
                                            {% if sort == 'norad' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-norad' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('international_code')" class="text-white text-decoration-none">
                                            Международный код
                                            {% if sort == 'international_code' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-international_code' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">Диапазоны</th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('undersat_point')" class="text-white text-decoration-none">
                                            Подспутниковая точка
                                            {% if sort == 'undersat_point' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-undersat_point' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">
                                        <a href="javascript:void(0)" onclick="updateSort('launch_date')" class="text-white text-decoration-none">
                                            Дата запуска
                                            {% if sort == 'launch_date' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-launch_date' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 150px;">Ссылка</th>
                                    <th scope="col" class="text-center" style="min-width: 80px;">
                                        <a href="javascript:void(0)" onclick="updateSort('transponder_count')" class="text-white text-decoration-none">
                                            Транспондеры
                                            {% if sort == 'transponder_count' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-transponder_count' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('created_at')" class="text-white text-decoration-none">
                                            Создано
                                            {% if sort == 'created_at' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-created_at' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('updated_at')" class="text-white text-decoration-none">
                                            Обновлено
                                            {% if sort == 'updated_at' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-updated_at' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" class="text-center" style="min-width: 100px;">Действия</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for satellite in processed_satellites %}
                                <tr>
                                    <td class="text-center">
                                        <input type="checkbox" class="form-check-input item-checkbox"
                                            value="{{ satellite.id }}">
                                    </td>
                                    <td class="text-center">{{ satellite.id }}</td>
                                    <td>{{ satellite.name }}</td>
                                    <td>{{ satellite.alternative_name|default:"-" }}</td>
                                    <td>{{ satellite.location_place }}</td>
                                    <td>{{ satellite.norad }}</td>
                                    <td>{{ satellite.international_code|default:"-" }}</td>
                                    <td>{{ satellite.bands }}</td>
                                    <td>{{ satellite.undersat_point }}</td>
                                    <td>{{ satellite.launch_date }}</td>
                                    <td>
                                        {% if satellite.url != '-' %}
                                        <a href="{{ satellite.url }}" target="_blank" rel="noopener noreferrer">
                                            <i class="bi bi-link-45deg"></i> Ссылка
                                        </a>
                                        {% else %}
                                        -
                                        {% endif %}
                                    </td>
                                    <td class="text-center">{{ satellite.transponder_count }}</td>
                                    <td>{{ satellite.created_at|date:"d.m.Y H:i" }}</td>
                                    <td>{{ satellite.updated_at|date:"d.m.Y H:i" }}</td>
                                    <td class="text-center">
                                        <div class="d-flex gap-1 justify-content-center">
                                            {% if user|has_perm:'satellite_edit' %}
                                                <a href="{% url 'mainapp:satellite_update' satellite.id %}" 
                                                   class="btn btn-sm btn-outline-warning"
                                                   title="Редактировать спутник">
                                                    <i class="bi bi-pencil"></i>
                                                </a>
                                            {% else %}
                                                <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="Недостаточно прав">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                            {% endif %}
                                            {% if satellite.transponder_count > 0 %}
                                                <button type="button" class="btn btn-sm btn-outline-info" 
                                                        onclick="showFrequencyPlan({{ satellite.id }})"
                                                        title="Частотный план">
                                                    <i class="bi bi-bar-chart"></i>
                                                </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="15" class="text-center text-muted">Нет данных для отображения</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{% include 'mainapp/components/_frequency_plan_modal.html' %}

<!-- Selected Satellites Offcanvas -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="selectedSatellitesOffcanvas" aria-labelledby="selectedSatellitesOffcanvasLabel" style="width: 90%;">
    <div class="offcanvas-header bg-info text-white">
        <h5 class="offcanvas-title" id="selectedSatellitesOffcanvasLabel">
             Список выбранных спутников
            <span class="badge bg-light text-dark ms-2" id="selectedSatellitesCount">0</span>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
    </div>
    <div class="offcanvas-body p-0">
        <!-- Toolbar for selected satellites -->
        <div class="p-3 bg-light border-bottom">
            <div class="d-flex gap-2 align-items-center">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeSelectedSatellites()">
                    <i class="bi bi-trash"></i> Удалить из списка
                </button>
                <div class="ms-auto text-muted">
                    Всего спутников: <strong><span id="selectedSatellitesTotalCount">0</span></strong>
                </div>
            </div>
        </div>

        <!-- Table with selected satellites -->
        <div class="table-responsive" style="max-height: calc(100vh - 180px); overflow-y: auto;">
            <table class="table table-striped table-hover table-sm table-bordered mb-0" style="font-size: 0.85rem;">
                <thead class="table-dark sticky-top">
                    <tr>
                        <th scope="col" class="text-center" style="width: 3%;">
                            <input type="checkbox" id="select-all-selected-satellites" class="form-check-input" 
                                onchange="toggleAllSelectedSatellites(this)">
                        </th>
                        <th scope="col" style="min-width: 150px;">Название</th>
                        <th scope="col" style="min-width: 150px;">Альт. название</th>
                        <th scope="col" style="min-width: 80px;">Комплекс</th>
                        <th scope="col" style="min-width: 100px;">NORAD ID</th>
                        <th scope="col" style="min-width: 120px;">Международный код</th>
                        <th scope="col" style="min-width: 120px;">Диапазоны</th>
                        <th scope="col" style="min-width: 120px;">Подспутниковая точка</th>
                        <th scope="col" style="min-width: 100px;">Дата запуска</th>
                        <th scope="col" class="text-center" style="min-width: 80px;">Транспондеры</th>
                        <th scope="col" style="min-width: 120px;">Создано</th>
                        <th scope="col" style="min-width: 120px;">Обновлено</th>
                    </tr>
                </thead>
                <tbody id="selected-satellites-table-body">
                    <!-- Rows will be populated by JavaScript -->
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const originalPopulateSelectedSatellitesTable = populateSelectedSatellitesTable;
populateSelectedSatellitesTable = function() {
    originalPopulateSelectedSatellitesTable();
    
    // Update count displays
    const count = window.selectedSatellites ? window.selectedSatellites.length : 0;
    const countElement = document.getElementById('selectedSatellitesCount');
    const totalCountElement = document.getElementById('selectedSatellitesTotalCount');
    
    if (countElement) {
        countElement.textContent = count;
    }
    if (totalCountElement) {
        totalCountElement.textContent = count;
    }
};
let lastCheckedIndex = null;

function updateRowHighlight(checkbox) {
    const row = checkbox.closest('tr');
    if (checkbox.checked) {
        row.classList.add('selected');
    } else {
        row.classList.remove('selected');
    }
}

function handleCheckboxClick(e) {
    if (e.shiftKey && lastCheckedIndex !== null) {
        const checkboxes = document.querySelectorAll('.item-checkbox');
        const currentIndex = Array.from(checkboxes).indexOf(e.target);
        const startIndex = Math.min(lastCheckedIndex, currentIndex);
        const endIndex = Math.max(lastCheckedIndex, currentIndex);

        for (let i = startIndex; i <= endIndex; i++) {
            checkboxes[i].checked = e.target.checked;
            updateRowHighlight(checkboxes[i]);
        }
    } else {
        updateRowHighlight(e.target);
    }
    lastCheckedIndex = Array.from(document.querySelectorAll('.item-checkbox')).indexOf(e.target);
}

// Function to delete selected satellites
function deleteSelectedSatellites() {
    const checkedCheckboxes = document.querySelectorAll('.item-checkbox:checked');

    if (checkedCheckboxes.length === 0) {
        alert('Пожалуйста, выберите хотя бы один спутник для удаления');
        return;
    }

    const selectedIds = [];
    checkedCheckboxes.forEach(checkbox => {
        selectedIds.push(checkbox.value);
    });

    const url = '{% url "mainapp:delete_selected_satellites" %}' + '?ids=' + selectedIds.join(',');
    window.location.href = url;
}

// Search functionality
function performSearch() {
    const searchValue = document.getElementById('toolbar-search').value.trim();
    const urlParams = new URLSearchParams(window.location.search);
    
    if (searchValue) {
        urlParams.set('search', searchValue);
    } else {
        urlParams.delete('search');
    }
    
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

function clearSearch() {
    document.getElementById('toolbar-search').value = '';
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.delete('search');
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

document.getElementById('toolbar-search').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        performSearch();
    }
});

// Items per page functionality
function updateItemsPerPage() {
    const itemsPerPage = document.getElementById('items-per-page').value;
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('items_per_page', itemsPerPage);
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

// Sorting functionality
function updateSort(field) {
    const urlParams = new URLSearchParams(window.location.search);
    const currentSort = urlParams.get('sort');
    
    let newSort;
    if (currentSort === field) {
        newSort = '-' + field;
    } else if (currentSort === '-' + field) {
        newSort = field;
    } else {
        newSort = field;
    }
    
    urlParams.set('sort', newSort);
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

// Function to select/deselect all options in a select element
function selectAllOptions(selectName, selectAll) {
    const selectElement = document.querySelector(`select[name="${selectName}"]`);
    if (selectElement) {
        for (let i = 0; i < selectElement.options.length; i++) {
            selectElement.options[i].selected = selectAll;
        }
    }
}

// Filter counter functionality
function updateFilterCounter() {
    const form = document.getElementById('filter-form');
    const formData = new FormData(form);
    let filterCount = 0;

    for (const [key, value] of formData.entries()) {
        if (value && value.trim() !== '') {
            if (key === 'band_id') {
                continue;
            }
            filterCount++;
        }
    }
    
    // Count selected options in multi-select fields
    const bandSelect = document.querySelector('select[name="band_id"]');
    if (bandSelect) {
        const selectedOptions = Array.from(bandSelect.selectedOptions).filter(opt => opt.selected);
        if (selectedOptions.length > 0) {
            filterCount++;
        }
    }

    const counterElement = document.getElementById('filterCounter');
    if (counterElement) {
        if (filterCount > 0) {
            counterElement.textContent = filterCount;
            counterElement.style.display = 'inline';
        } else {
            counterElement.style.display = 'none';
        }
    }
}

// Initialize selected satellites array from localStorage
function loadSelectedSatellitesFromStorage() {
    try {
        const storedItems = localStorage.getItem('selectedSatellites');
        if (storedItems) {
            window.selectedSatellites = JSON.parse(storedItems);
        } else {
            window.selectedSatellites = [];
        }
    } catch (e) {
        console.error('Error loading selected satellites from storage:', e);
        window.selectedSatellites = [];
    }
}

// Function to save selected satellites to localStorage
window.saveSelectedSatellitesToStorage = function () {
    try {
        localStorage.setItem('selectedSatellites', JSON.stringify(window.selectedSatellites));
    } catch (e) {
        console.error('Error saving selected satellites to storage:', e);
    }
}

// Function to update the selected satellites counter
window.updateSelectedSatelliteCounter = function () {
    const counterElement = document.getElementById('selectedSatelliteCounter');
    if (window.selectedSatellites && window.selectedSatellites.length > 0) {
        counterElement.textContent = window.selectedSatellites.length;
        counterElement.style.display = 'inline';
    } else {
        counterElement.style.display = 'none';
    }
}

// Function to add selected satellites to the list
window.addSelectedToList = function () {
    const checkedCheckboxes = document.querySelectorAll('.item-checkbox:checked');

    if (checkedCheckboxes.length === 0) {
        alert('Пожалуйста, выберите хотя бы один спутник для добавления в список');
        return;
    }

    // Get the data for each selected row and add to the selectedSatellites array
    checkedCheckboxes.forEach(checkbox => {
        const row = checkbox.closest('tr');
        const satelliteId = checkbox.value;

        const satelliteExists = window.selectedSatellites.some(item => item.id === satelliteId);
        if (!satelliteExists) {
            const rowData = {
                id: satelliteId,
                name: row.cells[2].textContent,
                alternative_name: row.cells[3].textContent,
                location_place: row.cells[4].textContent,
                norad: row.cells[5].textContent,
                international_code: row.cells[6].textContent,
                bands: row.cells[7].textContent,
                undersat_point: row.cells[8].textContent,
                launch_date: row.cells[9].textContent,
                transponder_count: row.cells[11].textContent,
                created_at: row.cells[12].textContent,
                updated_at: row.cells[13].textContent,
            };

            window.selectedSatellites.push(rowData);
        }
    });

    // Update the counter
    if (typeof updateSelectedSatelliteCounter === 'function') {
        updateSelectedSatelliteCounter();
    }

    // Save selected satellites to localStorage
    saveSelectedSatellitesToStorage();

    // Clear selections in the main table
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = false;
        updateRowHighlight(checkbox);
    });
    const selectAllCheckbox = document.getElementById('select-all');
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = false;
    }
}

// Function to populate the selected satellites table in the offcanvas
function populateSelectedSatellitesTable() {
    const tableBody = document.getElementById('selected-satellites-table-body');
    if (!tableBody) return;

    // Clear existing rows
    tableBody.innerHTML = '';

    // Add rows for each selected satellite
    window.selectedSatellites.forEach((item, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="text-center">
                <input type="checkbox" class="form-check-input selected-satellite-checkbox" value="${item.id}">
            </td>
            <td>${item.name}</td>
            <td>${item.alternative_name}</td>
            <td>${item.location_place}</td>
            <td>${item.norad}</td>
            <td>${item.international_code}</td>
            <td>${item.bands}</td>
            <td>${item.undersat_point}</td>
            <td>${item.launch_date}</td>
            <td class="text-center">${item.transponder_count}</td>
            <td>${item.created_at}</td>
            <td>${item.updated_at}</td>
        `;
        tableBody.appendChild(row);
    });
}

// Function to remove selected satellites from the list
function removeSelectedSatellites() {
    const checkboxes = document.querySelectorAll('#selected-satellites-table-body .selected-satellite-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Пожалуйста, выберите хотя бы один спутник для удаления из списка');
        return;
    }

    // Get IDs of satellites to remove
    const idsToRemove = Array.from(checkboxes).map(checkbox => checkbox.value);

    // Remove satellites from the selectedSatellites array
    window.selectedSatellites = window.selectedSatellites.filter(item => !idsToRemove.includes(item.id));

    // Save selected satellites to localStorage
    saveSelectedSatellitesToStorage();

    // Update the counter and table
    if (typeof updateSelectedSatelliteCounter === 'function') {
        updateSelectedSatelliteCounter();
    }
    populateSelectedSatellitesTable();
}

// Function to toggle all checkboxes in the selected satellites table
function toggleAllSelectedSatellites(checkbox) {
    const checkboxes = document.querySelectorAll('#selected-satellites-table-body .selected-satellite-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
    });
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all');
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');

    if (selectAllCheckbox && itemCheckboxes.length > 0) {
        selectAllCheckbox.addEventListener('change', function () {
            itemCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
                updateRowHighlight(checkbox);
            });
        });

        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
            });
            
            checkbox.addEventListener('click', handleCheckboxClick);
        });
    }

    // Load selected satellites from localStorage
    loadSelectedSatellitesFromStorage();
    updateSelectedSatelliteCounter();

    // Update the selected satellites table when the offcanvas is shown
    const offcanvasSatellitesElement = document.getElementById('selectedSatellitesOffcanvas');
    if (offcanvasSatellitesElement) {
        offcanvasSatellitesElement.addEventListener('show.bs.offcanvas', function () {
            populateSelectedSatellitesTable();
        });
    }

    updateFilterCounter();

    const form = document.getElementById('filter-form');
    if (form) {
        const inputFields = form.querySelectorAll('input[type="text"], input[type="number"], input[type="date"]');
        inputFields.forEach(input => {
            input.addEventListener('input', updateFilterCounter);
            input.addEventListener('change', updateFilterCounter);
        });

        const selectFields = form.querySelectorAll('select');
        selectFields.forEach(select => {
            select.addEventListener('change', updateFilterCounter);
        });
    }

    const offcanvasElement = document.getElementById('offcanvasFilters');
    if (offcanvasElement) {
        offcanvasElement.addEventListener('show.bs.offcanvas', updateFilterCounter);
    }
});

// Frequency Plan Modal functionality
let modalCanvas, modalCtx, modalContainer;
let modalZoomLevelUL = 1;
let modalZoomLevelDL = 1;
let modalPanOffsetUL = 0;
let modalPanOffsetDL = 0;
let modalIsDragging = false;
let modalDragStartX = 0;
let modalDragStartOffsetUL = 0;
let modalDragStartOffsetDL = 0;
let modalDragArea = null;
let modalHoveredTransponder = null;
let modalTransponderRects = [];
let modalTranspondersData = [];

let modalMinFreqUL, modalMaxFreqUL, modalFreqRangeUL;
let modalMinFreqDL, modalMaxFreqDL, modalFreqRangeDL;
let modalOriginalMinFreqUL, modalOriginalMaxFreqUL, modalOriginalFreqRangeUL;
let modalOriginalMinFreqDL, modalOriginalMaxFreqDL, modalOriginalFreqRangeDL;

let modalUplinkStartY, modalUplinkHeight, modalDownlinkStartY, modalDownlinkHeight;

function showFrequencyPlan(satelliteId) {
    const modal = new bootstrap.Modal(document.getElementById('frequencyPlanModal'));
    
    // Reset modal state
    document.getElementById('modalLoadingSpinner').style.display = 'block';
    document.getElementById('modalFrequencyContent').style.display = 'none';
    document.getElementById('modalNoData').style.display = 'none';
    
    modal.show();
    
    // Fetch transponder data
    fetch(`/api/satellite/${satelliteId}/transponders/`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('modalLoadingSpinner').style.display = 'none';
            
            if (data.transponders && data.transponders.length > 0) {
                modalTranspondersData = data.transponders;
                document.getElementById('modalTransponderCount').textContent = data.count;
                document.getElementById('modalFrequencyContent').style.display = 'block';
                
                // Initialize chart after modal is shown
                setTimeout(() => {
                    initializeModalFrequencyChart();
                }, 100);
            } else {
                document.getElementById('modalNoData').style.display = 'block';
            }
        })
        .catch(error => {
            console.error('Error fetching transponder data:', error);
            document.getElementById('modalLoadingSpinner').style.display = 'none';
            document.getElementById('modalNoData').style.display = 'block';
        });
}

function initializeModalFrequencyChart() {
    if (!modalTranspondersData || modalTranspondersData.length === 0) {
        return;
    }
    
    modalCanvas = document.getElementById('modalFrequencyChart');
    if (!modalCanvas) return;
    
    modalContainer = modalCanvas.parentElement;
    modalCtx = modalCanvas.getContext('2d');
    
    // Calculate frequency ranges
    modalMinFreqUL = Infinity;
    modalMaxFreqUL = -Infinity;
    modalMinFreqDL = Infinity;
    modalMaxFreqDL = -Infinity;
    
    modalTranspondersData.forEach(t => {
        const dlStartFreq = t.downlink - (t.frequency_range / 2);
        const dlEndFreq = t.downlink + (t.frequency_range / 2);
        modalMinFreqDL = Math.min(modalMinFreqDL, dlStartFreq);
        modalMaxFreqDL = Math.max(modalMaxFreqDL, dlEndFreq);
        
        if (t.uplink) {
            const ulStartFreq = t.uplink - (t.frequency_range / 2);
            const ulEndFreq = t.uplink + (t.frequency_range / 2);
            modalMinFreqUL = Math.min(modalMinFreqUL, ulStartFreq);
            modalMaxFreqUL = Math.max(modalMaxFreqUL, ulEndFreq);
        }
    });
    
    // Add padding
    const paddingDL = (modalMaxFreqDL - modalMinFreqDL) * 0.04;
    modalMinFreqDL -= paddingDL;
    modalMaxFreqDL += paddingDL;
    
    if (modalMaxFreqUL !== -Infinity) {
        const paddingUL = (modalMaxFreqUL - modalMinFreqUL) * 0.04;
        modalMinFreqUL -= paddingUL;
        modalMaxFreqUL += paddingUL;
    }
    
    // Store original values
    modalOriginalMinFreqDL = modalMinFreqDL;
    modalOriginalMaxFreqDL = modalMaxFreqDL;
    modalOriginalFreqRangeDL = modalMaxFreqDL - modalMinFreqDL;
    modalFreqRangeDL = modalOriginalFreqRangeDL;
    
    modalOriginalMinFreqUL = modalMinFreqUL;
    modalOriginalMaxFreqUL = modalMaxFreqUL;
    modalOriginalFreqRangeUL = modalMaxFreqUL - modalMinFreqUL;
    modalFreqRangeUL = modalOriginalFreqRangeUL;
    
    // Reset zoom and pan
    modalZoomLevelUL = 1;
    modalZoomLevelDL = 1;
    modalPanOffsetUL = 0;
    modalPanOffsetDL = 0;
    
    // Setup event listeners
    modalCanvas.addEventListener('wheel', handleModalWheel, { passive: false });
    modalCanvas.addEventListener('mousedown', handleModalMouseDown);
    modalCanvas.addEventListener('mousemove', handleModalMouseMove);
    modalCanvas.addEventListener('mouseup', handleModalMouseUp);
    modalCanvas.addEventListener('mouseleave', handleModalMouseLeave);
    
    renderModalChart();
}

function renderModalChart() {
    if (!modalCanvas || !modalCtx) return;
    
    const dpr = window.devicePixelRatio || 1;
    const rect = modalContainer.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    
    modalCanvas.width = width * dpr;
    modalCanvas.height = height * dpr;
    modalCanvas.style.width = width + 'px';
    modalCanvas.style.height = height + 'px';
    modalCtx.scale(dpr, dpr);
    
    modalCtx.clearRect(0, 0, width, height);
    
    const leftMargin = 60;
    const rightMargin = 20;
    const topMargin = 60;
    const middleMargin = 60;
    const bottomMargin = 40;
    const chartWidth = width - leftMargin - rightMargin;
    const availableHeight = height - topMargin - middleMargin - bottomMargin;
    
    modalUplinkHeight = availableHeight * 0.48;
    modalDownlinkHeight = availableHeight * 0.48;
    
    // Group by polarization
    const polarizationGroups = {};
    modalTranspondersData.forEach(t => {
        let pol = t.polarization || '-';
        pol = pol.charAt(0).toUpperCase();
        if (!polarizationGroups[pol]) {
            polarizationGroups[pol] = [];
        }
        polarizationGroups[pol].push(t);
    });
    
    const polarizations = Object.keys(polarizationGroups);
    const rowHeightUL = modalUplinkHeight / polarizations.length;
    const rowHeightDL = modalDownlinkHeight / polarizations.length;
    
    // Calculate visible ranges
    const visibleFreqRangeUL = modalFreqRangeUL / modalZoomLevelUL;
    const centerFreqUL = (modalMinFreqUL + modalMaxFreqUL) / 2;
    const visibleMinFreqUL = centerFreqUL - visibleFreqRangeUL / 2 + modalPanOffsetUL;
    const visibleMaxFreqUL = centerFreqUL + visibleFreqRangeUL / 2 + modalPanOffsetUL;
    
    const visibleFreqRangeDL = modalFreqRangeDL / modalZoomLevelDL;
    const centerFreqDL = (modalMinFreqDL + modalMaxFreqDL) / 2;
    const visibleMinFreqDL = centerFreqDL - visibleFreqRangeDL / 2 + modalPanOffsetDL;
    const visibleMaxFreqDL = centerFreqDL + visibleFreqRangeDL / 2 + modalPanOffsetDL;
    
    modalUplinkStartY = topMargin;
    modalDownlinkStartY = topMargin + modalUplinkHeight + middleMargin;
    
    // Draw UPLINK axis
    modalCtx.strokeStyle = '#dee2e6';
    modalCtx.lineWidth = 1;
    modalCtx.beginPath();
    modalCtx.moveTo(leftMargin, modalUplinkStartY);
    modalCtx.lineTo(width - rightMargin, modalUplinkStartY);
    modalCtx.stroke();
    
    modalCtx.fillStyle = '#6c757d';
    modalCtx.font = '11px sans-serif';
    modalCtx.textAlign = 'center';
    
    const numTicks = 10;
    for (let i = 0; i <= numTicks; i++) {
        const freq = visibleMinFreqUL + (visibleMaxFreqUL - visibleMinFreqUL) * i / numTicks;
        const x = leftMargin + chartWidth * i / numTicks;
        
        modalCtx.beginPath();
        modalCtx.moveTo(x, modalUplinkStartY);
        modalCtx.lineTo(x, modalUplinkStartY - 5);
        modalCtx.stroke();
        
        modalCtx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
        modalCtx.beginPath();
        modalCtx.moveTo(x, modalUplinkStartY);
        modalCtx.lineTo(x, modalUplinkStartY + modalUplinkHeight);
        modalCtx.stroke();
        modalCtx.strokeStyle = '#dee2e6';
        
        modalCtx.fillText(freq.toFixed(1), x, modalUplinkStartY - 10);
    }
    
    modalCtx.fillStyle = '#000';
    modalCtx.font = 'bold 12px sans-serif';
    modalCtx.textAlign = 'center';
    modalCtx.fillText('Uplink Частота (МГц)', width / 2, modalUplinkStartY - 25);
    
    // Draw DOWNLINK axis
    modalCtx.strokeStyle = '#dee2e6';
    modalCtx.lineWidth = 1;
    modalCtx.beginPath();
    modalCtx.moveTo(leftMargin, modalDownlinkStartY);
    modalCtx.lineTo(width - rightMargin, modalDownlinkStartY);
    modalCtx.stroke();
    
    modalCtx.fillStyle = '#6c757d';
    modalCtx.font = '11px sans-serif';
    modalCtx.textAlign = 'center';
    
    for (let i = 0; i <= numTicks; i++) {
        const freq = visibleMinFreqDL + (visibleMaxFreqDL - visibleMinFreqDL) * i / numTicks;
        const x = leftMargin + chartWidth * i / numTicks;
        
        modalCtx.beginPath();
        modalCtx.moveTo(x, modalDownlinkStartY);
        modalCtx.lineTo(x, modalDownlinkStartY - 5);
        modalCtx.stroke();
        
        modalCtx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
        modalCtx.beginPath();
        modalCtx.moveTo(x, modalDownlinkStartY);
        modalCtx.lineTo(x, modalDownlinkStartY + modalDownlinkHeight);
        modalCtx.stroke();
        modalCtx.strokeStyle = '#dee2e6';
        
        modalCtx.fillText(freq.toFixed(1), x, modalDownlinkStartY - 10);
    }
    
    modalCtx.fillStyle = '#000';
    modalCtx.font = 'bold 12px sans-serif';
    modalCtx.textAlign = 'center';
    modalCtx.fillText('Downlink Частота (МГц)', width / 2, modalDownlinkStartY - 25);
    
    modalCtx.save();
    modalCtx.translate(15, height / 2);
    modalCtx.rotate(-Math.PI / 2);
    modalCtx.textAlign = 'center';
    modalCtx.fillText('Поляризация', 0, 0);
    modalCtx.restore();
    
    modalTransponderRects = [];
    
    // Draw transponders
    polarizations.forEach((pol, index) => {
        const group = polarizationGroups[pol];
        const downlinkColor = '#0d6efd';
        const uplinkColor = '#fd7e14';
        
        const uplinkY = modalUplinkStartY + index * rowHeightUL;
        const uplinkBarHeight = rowHeightUL * 0.8;
        const uplinkBarY = uplinkY + (rowHeightUL - uplinkBarHeight) / 2;
        
        const downlinkY = modalDownlinkStartY + index * rowHeightDL;
        const downlinkBarHeight = rowHeightDL * 0.8;
        const downlinkBarY = downlinkY + (rowHeightDL - downlinkBarHeight) / 2;
        
        modalCtx.fillStyle = '#000';
        modalCtx.font = 'bold 14px sans-serif';
        modalCtx.textAlign = 'center';
        modalCtx.fillText(pol, leftMargin - 25, uplinkBarY + uplinkBarHeight / 2 + 4);
        modalCtx.fillText(pol, leftMargin - 25, downlinkBarY + downlinkBarHeight / 2 + 4);
        
        if (index < polarizations.length - 1) {
            modalCtx.strokeStyle = '#adb5bd';
            modalCtx.lineWidth = 1;
            modalCtx.beginPath();
            modalCtx.moveTo(leftMargin, uplinkY + rowHeightUL);
            modalCtx.lineTo(width - rightMargin, uplinkY + rowHeightUL);
            modalCtx.stroke();
            
            modalCtx.beginPath();
            modalCtx.moveTo(leftMargin, downlinkY + rowHeightDL);
            modalCtx.lineTo(width - rightMargin, downlinkY + rowHeightDL);
            modalCtx.stroke();
        }
        
        // Draw uplink transponders
        group.forEach(t => {
            if (!t.uplink) return;
            
            const startFreq = t.uplink - (t.frequency_range / 2);
            const endFreq = t.uplink + (t.frequency_range / 2);
            
            if (endFreq < visibleMinFreqUL || startFreq > visibleMaxFreqUL) {
                return;
            }
            
            const x1 = leftMargin + ((startFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
            const x2 = leftMargin + ((endFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
            const barWidth = x2 - x1;
            
            if (barWidth < 1) return;
            
            const isHovered = modalHoveredTransponder && modalHoveredTransponder.transponder.name === t.name;
            
            modalCtx.fillStyle = uplinkColor;
            modalCtx.fillRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
            
            modalCtx.strokeStyle = isHovered ? '#000' : '#fff';
            modalCtx.lineWidth = isHovered ? 3 : 1;
            modalCtx.strokeRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
            
            if (barWidth > 40) {
                modalCtx.fillStyle = '#fff';
                modalCtx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
                modalCtx.textAlign = 'center';
                modalCtx.fillText(t.name, x1 + barWidth / 2, uplinkBarY + uplinkBarHeight / 2 + 3);
            }
            
            modalTransponderRects.push({
                x: x1,
                y: uplinkBarY,
                width: barWidth,
                height: uplinkBarHeight,
                transponder: t,
                type: 'uplink',
                centerX: x1 + barWidth / 2
            });
        });
        
        // Draw downlink transponders
        group.forEach(t => {
            const startFreq = t.downlink - (t.frequency_range / 2);
            const endFreq = t.downlink + (t.frequency_range / 2);
            
            if (endFreq < visibleMinFreqDL || startFreq > visibleMaxFreqDL) {
                return;
            }
            
            const x1 = leftMargin + ((startFreq - visibleMinFreqDL) / (visibleMaxFreqDL - visibleMinFreqDL)) * chartWidth;
            const x2 = leftMargin + ((endFreq - visibleMinFreqDL) / (visibleMaxFreqDL - visibleMinFreqDL)) * chartWidth;
            const barWidth = x2 - x1;
            
            if (barWidth < 1) return;
            
            const isHovered = modalHoveredTransponder && modalHoveredTransponder.transponder.name === t.name;
            
            modalCtx.fillStyle = downlinkColor;
            modalCtx.fillRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
            
            modalCtx.strokeStyle = isHovered ? '#000' : '#fff';
            modalCtx.lineWidth = isHovered ? 3 : 1;
            modalCtx.strokeRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
            
            if (barWidth > 40) {
                modalCtx.fillStyle = '#fff';
                modalCtx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
                modalCtx.textAlign = 'center';
                modalCtx.fillText(t.name, x1 + barWidth / 2, downlinkBarY + downlinkBarHeight / 2 + 3);
            }
            
            modalTransponderRects.push({
                x: x1,
                y: downlinkBarY,
                width: barWidth,
                height: downlinkBarHeight,
                transponder: t,
                type: 'downlink',
                centerX: x1 + barWidth / 2
            });
        });
    });
    
    if (modalHoveredTransponder) {
        drawModalConnectionLine(modalHoveredTransponder);
        drawModalTooltip(modalHoveredTransponder);
    }
}

function drawModalConnectionLine(rectInfo) {
    const t = rectInfo.transponder;
    if (!t.uplink) return;
    
    const downlinkRect = modalTransponderRects.find(r => r.transponder.name === t.name && r.type === 'downlink');
    const uplinkRect = modalTransponderRects.find(r => r.transponder.name === t.name && r.type === 'uplink');
    
    if (!downlinkRect || !uplinkRect) return;
    
    const x1 = downlinkRect.centerX;
    const y1 = downlinkRect.y + downlinkRect.height;
    const x2 = uplinkRect.centerX;
    const y2 = uplinkRect.y;
    
    modalCtx.save();
    modalCtx.strokeStyle = '#ffc107';
    modalCtx.lineWidth = 2;
    modalCtx.setLineDash([5, 3]);
    modalCtx.globalAlpha = 0.8;
    
    modalCtx.beginPath();
    modalCtx.moveTo(x1, y1);
    modalCtx.lineTo(x2, y2);
    modalCtx.stroke();
    
    modalCtx.restore();
}

function drawModalTooltip(rectInfo) {
    const t = rectInfo.transponder;
    const isUplink = rectInfo.type === 'uplink';
    const freq = isUplink ? t.uplink : t.downlink;
    const startFreq = freq - (t.frequency_range / 2);
    const endFreq = freq + (t.frequency_range / 2);
    
    const lines = [
        t.name,
        'Тип: ' + (isUplink ? 'Uplink' : 'Downlink'),
        'Диапазон: ' + startFreq.toFixed(3) + ' - ' + endFreq.toFixed(3) + ' МГц',
        'Центр: ' + freq.toFixed(3) + ' МГц',
        'Полоса: ' + t.frequency_range.toFixed(3) + ' МГц',
        'Поляризация: ' + t.polarization,
        'Зона: ' + t.zone_name
    ];
    
    if (isUplink && t.downlink && t.uplink) {
        const conversion = t.downlink - t.uplink;
        lines.push('Перенос: ' + conversion.toFixed(3) + ' МГц');
    }
    
    modalCtx.font = '12px sans-serif';
    const padding = 10;
    const lineHeight = 16;
    let maxWidth = 0;
    lines.forEach(line => {
        const width = modalCtx.measureText(line).width;
        maxWidth = Math.max(maxWidth, width);
    });
    
    const tooltipWidth = maxWidth + padding * 2;
    const tooltipHeight = lines.length * lineHeight + padding * 2;
    
    const mouseX = rectInfo._mouseX || modalCanvas.width / 2;
    const mouseY = rectInfo._mouseY || modalCanvas.height / 2;
    let tooltipX = mouseX + 15;
    let tooltipY = mouseY - tooltipHeight - 15;
    
    if (tooltipX + tooltipWidth > modalCanvas.width) {
        tooltipX = mouseX - tooltipWidth - 15;
    }
    
    if (tooltipY < 0) {
        tooltipY = mouseY + 15;
    }
    
    modalCtx.fillStyle = 'rgba(0, 0, 0, 0.9)';
    modalCtx.fillRect(tooltipX, tooltipY, tooltipWidth, tooltipHeight);
    
    modalCtx.fillStyle = '#fff';
    modalCtx.font = 'bold 12px sans-serif';
    modalCtx.textAlign = 'left';
    modalCtx.fillText(lines[0], tooltipX + padding, tooltipY + padding + 12);
    
    modalCtx.font = '11px sans-serif';
    for (let i = 1; i < lines.length; i++) {
        modalCtx.fillText(lines[i], tooltipX + padding, tooltipY + padding + 12 + i * lineHeight);
    }
}

function handleModalWheel(e) {
    e.preventDefault();
    
    const rect = modalCanvas.getBoundingClientRect();
    const mouseY = e.clientY - rect.top;
    
    const isUplinkArea = mouseY < (modalUplinkStartY + modalUplinkHeight);
    
    const delta = e.deltaY > 0 ? 0.9 : 1.1;
    
    if (isUplinkArea) {
        const newZoom = Math.max(1, Math.min(20, modalZoomLevelUL * delta));
        if (newZoom !== modalZoomLevelUL) {
            modalZoomLevelUL = newZoom;
            
            const maxPan = (modalOriginalFreqRangeUL * (modalZoomLevelUL - 1)) / (2 * modalZoomLevelUL);
            modalPanOffsetUL = Math.max(-maxPan, Math.min(maxPan, modalPanOffsetUL));
            
            renderModalChart();
        }
    } else {
        const newZoom = Math.max(1, Math.min(20, modalZoomLevelDL * delta));
        if (newZoom !== modalZoomLevelDL) {
            modalZoomLevelDL = newZoom;
            
            const maxPan = (modalOriginalFreqRangeDL * (modalZoomLevelDL - 1)) / (2 * modalZoomLevelDL);
            modalPanOffsetDL = Math.max(-maxPan, Math.min(maxPan, modalPanOffsetDL));
            
            renderModalChart();
        }
    }
}

function handleModalMouseDown(e) {
    const rect = modalCanvas.getBoundingClientRect();
    const mouseY = e.clientY - rect.top;
    
    modalDragArea = mouseY < (modalUplinkStartY + modalUplinkHeight) ? 'uplink' : 'downlink';
    
    modalIsDragging = true;
    modalDragStartX = e.clientX;
    modalDragStartOffsetUL = modalPanOffsetUL;
    modalDragStartOffsetDL = modalPanOffsetDL;
    modalCanvas.style.cursor = 'grabbing';
}

function handleModalMouseMove(e) {
    const rect = modalCanvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    if (modalIsDragging) {
        const dx = e.clientX - modalDragStartX;
        
        if (modalDragArea === 'uplink') {
            const freqPerPixel = (modalFreqRangeUL / modalZoomLevelUL) / (rect.width - 80);
            modalPanOffsetUL = modalDragStartOffsetUL - dx * freqPerPixel;
            
            const maxPan = (modalOriginalFreqRangeUL * (modalZoomLevelUL - 1)) / (2 * modalZoomLevelUL);
            modalPanOffsetUL = Math.max(-maxPan, Math.min(maxPan, modalPanOffsetUL));
        } else {
            const freqPerPixel = (modalFreqRangeDL / modalZoomLevelDL) / (rect.width - 80);
            modalPanOffsetDL = modalDragStartOffsetDL - dx * freqPerPixel;
            
            const maxPan = (modalOriginalFreqRangeDL * (modalZoomLevelDL - 1)) / (2 * modalZoomLevelDL);
            modalPanOffsetDL = Math.max(-maxPan, Math.min(maxPan, modalPanOffsetDL));
        }
        
        renderModalChart();
    } else {
        let found = null;
        for (const tr of modalTransponderRects) {
            if (mouseX >= tr.x && mouseX <= tr.x + tr.width &&
                mouseY >= tr.y && mouseY <= tr.y + tr.height) {
                found = tr;
                found._mouseX = mouseX;
                found._mouseY = mouseY;
                break;
            }
        }
        
        if (found !== modalHoveredTransponder) {
            modalHoveredTransponder = found;
            modalCanvas.style.cursor = found ? 'pointer' : 'default';
            renderModalChart();
        } else if (found) {
            found._mouseX = mouseX;
            found._mouseY = mouseY;
        }
    }
}

function handleModalMouseUp() {
    modalIsDragging = false;
    modalCanvas.style.cursor = modalHoveredTransponder ? 'pointer' : 'default';
}

function handleModalMouseLeave() {
    modalIsDragging = false;
    modalHoveredTransponder = null;
    modalCanvas.style.cursor = 'default';
    renderModalChart();
}

function resetModalZoom() {
    modalZoomLevelUL = 1;
    modalZoomLevelDL = 1;
    modalPanOffsetUL = 0;
    modalPanOffsetDL = 0;
    renderModalChart();
}

// Setup reset button
document.addEventListener('DOMContentLoaded', function() {
    const resetBtn = document.getElementById('modalResetZoom');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetModalZoom);
    }
});
</script>

{% endblock %}
