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

{% block title %}{{ title }}{% endblock %}

{% block extra_css %}
<style>
    .frequency-plan {
        margin-top: 30px;
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 8px;
    }
    
    .frequency-chart-container {
        position: relative;
        background: white;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 20px;
        height: 400px;
    }
    
    .legend {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        margin-top: 15px;
    }
    
    .legend-item {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    
    .legend-color {
        width: 20px;
        height: 20px;
        border-radius: 3px;
    }
    
    .chart-controls {
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }
    
    .chart-controls button {
        padding: 5px 15px;
        font-size: 0.9rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-3">
    <div class="row mb-3">
        <div class="col-12">
            <h2>{{ title }}</h2>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form method="post" novalidate>
                        {% csrf_token %}
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="{{ form.name.id_for_label }}" class="form-label">
                                        {{ form.name.label }} <span class="text-danger">*</span>
                                    </label>
                                    {{ form.name }}
                                    {% if form.name.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.name.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.name.help_text %}
                                        <div class="form-text">{{ form.name.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="{{ form.alternative_name.id_for_label }}" class="form-label">
                                        {{ form.alternative_name.label }}
                                    </label>
                                    {{ form.alternative_name }}
                                    {% if form.alternative_name.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.alternative_name.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.alternative_name.help_text %}
                                        <div class="form-text">{{ form.alternative_name.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="{{ form.location_place.id_for_label }}" class="form-label">
                                        {{ form.location_place.label }}
                                    </label>
                                    {{ form.location_place }}
                                    {% if form.location_place.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.location_place.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.location_place.help_text %}
                                        <div class="form-text">{{ form.location_place.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="{{ form.norad.id_for_label }}" class="form-label">
                                        {{ form.norad.label }}
                                    </label>
                                    {{ form.norad }}
                                    {% if form.norad.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.norad.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.norad.help_text %}
                                        <div class="form-text">{{ form.norad.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="{{ form.international_code.id_for_label }}" class="form-label">
                                        {{ form.international_code.label }}
                                    </label>
                                    {{ form.international_code }}
                                    {% if form.international_code.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.international_code.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.international_code.help_text %}
                                        <div class="form-text">{{ form.international_code.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="{{ form.undersat_point.id_for_label }}" class="form-label">
                                        {{ form.undersat_point.label }}
                                    </label>
                                    {{ form.undersat_point }}
                                    {% if form.undersat_point.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.undersat_point.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.undersat_point.help_text %}
                                        <div class="form-text">{{ form.undersat_point.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="{{ form.launch_date.id_for_label }}" class="form-label">
                                        {{ form.launch_date.label }}
                                    </label>
                                    {{ form.launch_date }}
                                    {% if form.launch_date.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.launch_date.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.launch_date.help_text %}
                                        <div class="form-text">{{ form.launch_date.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="mb-3">
                                    <label for="{{ form.band.id_for_label }}" class="form-label">
                                        {{ form.band.label }}
                                    </label>
                                    {{ form.band }}
                                    {% if form.band.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.band.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.band.help_text %}
                                        <div class="form-text">{{ form.band.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="mb-3">
                                    <label for="{{ form.url.id_for_label }}" class="form-label">
                                        {{ form.url.label }}
                                    </label>
                                    {{ form.url }}
                                    {% if form.url.errors %}
                                        <div class="invalid-feedback d-block">
                                            {{ form.url.errors.0 }}
                                        </div>
                                    {% endif %}
                                    {% if form.url.help_text %}
                                        <div class="form-text">{{ form.url.help_text }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="{{ form.comment.id_for_label }}" class="form-label">
                                {{ form.comment.label }}
                            </label>
                            {{ form.comment }}
                            {% if form.comment.errors %}
                                <div class="invalid-feedback d-block">
                                    {{ form.comment.errors.0 }}
                                </div>
                            {% endif %}
                            {% if form.comment.help_text %}
                                <div class="form-text">{{ form.comment.help_text }}</div>
                            {% endif %}
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                               Сохранить
                            </button>
                            <a href="{% url 'mainapp:satellite_list' %}" class="btn btn-secondary">
                                Отмена
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    {% if action == 'update' and transponders %}
    <!-- Frequency Plan Visualization -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h4>Частотный план</h4>
                    <p class="text-muted">Визуализация транспондеров спутника по частотам. <span style="color: #0d6efd;">■</span> Downlink (синий), <span style="color: #fd7e14;">■</span> Uplink (оранжевый). Используйте колесико мыши для масштабирования, наведите курсор на полосу для подробной информации и связи с парным каналом.</p>
                    
                    <div class="frequency-plan">
                        <div class="chart-controls">
                            <button type="button" class="btn btn-sm btn-outline-primary" id="resetZoom">
                                <i class="bi bi-arrow-clockwise"></i> Сбросить масштаб
                            </button>
                            <!-- <button type="button" class="btn btn-sm btn-outline-secondary" id="zoomIn">
                                <i class="bi bi-zoom-in"></i> Увеличить
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" id="zoomOut">
                                <i class="bi bi-zoom-out"></i> Уменьшить
                            </button> -->
                        </div>
                        
                        <div class="frequency-chart-container">
                            <canvas id="frequencyChart"></canvas>
                        </div>
                        
                        <!-- <div class="legend">
                            <div class="legend-item">
                                <div class="legend-color" style="background-color: #0d6efd;"></div>
                                <span>H - Горизонтальная</span>
                            </div>
                            <div class="legend-item">
                                <div class="legend-color" style="background-color: #198754;"></div>
                                <span>V - Вертикальная</span>
                            </div>
                            <div class="legend-item">
                                <div class="legend-color" style="background-color: #dc3545;"></div>
                                <span>L - Левая круговая</span>
                            </div>
                            <div class="legend-item">
                                <div class="legend-color" style="background-color: #ffc107;"></div>
                                <span>R - Правая круговая</span>
                            </div>
                            <div class="legend-item">
                                <div class="legend-color" style="background-color: #6c757d;"></div>
                                <span>Другая</span>
                            </div>
                        </div> -->
                        
                        <div class="mt-3">
                            <p><strong>Всего транспондеров:</strong> {{ transponder_count }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
{% if action == 'update' and transponders %}
<script>
// Transponder data from Django
const transpondersData = {{ transponders|safe }};

// Chart state
let canvas, ctx, container;
let zoomLevelUL = 1;
let zoomLevelDL = 1;
let panOffsetUL = 0;
let panOffsetDL = 0;
let isDragging = false;
let dragStartX = 0;
let dragStartOffsetUL = 0;
let dragStartOffsetDL = 0;
let dragArea = null; // 'uplink' or 'downlink'
let hoveredTransponder = null;
let transponderRects = [];

// Frequency ranges for uplink and downlink
let minFreqUL, maxFreqUL, freqRangeUL;
let minFreqDL, maxFreqDL, freqRangeDL;
let originalMinFreqUL, originalMaxFreqUL, originalFreqRangeUL;
let originalMinFreqDL, originalMaxFreqDL, originalFreqRangeDL;

// Layout variables (need to be global for event handlers)
let uplinkStartY, uplinkHeight, downlinkStartY, downlinkHeight;

function initializeFrequencyChart() {
    if (!transpondersData || transpondersData.length === 0) {
        return;
    }
    
    canvas = document.getElementById('frequencyChart');
    if (!canvas) return;
    
    container = canvas.parentElement;
    ctx = canvas.getContext('2d');
    
    // Calculate frequency ranges separately for uplink and downlink
    minFreqUL = Infinity;
    maxFreqUL = -Infinity;
    minFreqDL = Infinity;
    maxFreqDL = -Infinity;
    
    transpondersData.forEach(t => {
        // Downlink
        const dlStartFreq = t.downlink - (t.frequency_range / 2);
        const dlEndFreq = t.downlink + (t.frequency_range / 2);
        minFreqDL = Math.min(minFreqDL, dlStartFreq);
        maxFreqDL = Math.max(maxFreqDL, dlEndFreq);
        
        // Uplink (if exists)
        if (t.uplink) {
            const ulStartFreq = t.uplink - (t.frequency_range / 2);
            const ulEndFreq = t.uplink + (t.frequency_range / 2);
            minFreqUL = Math.min(minFreqUL, ulStartFreq);
            maxFreqUL = Math.max(maxFreqUL, ulEndFreq);
        }
    });
    
    // Add 2% padding for downlink
    const paddingDL = (maxFreqDL - minFreqDL) * 0.04;
    minFreqDL -= paddingDL;
    maxFreqDL += paddingDL;
    
    // Add 2% padding for uplink (if exists)
    if (maxFreqUL !== -Infinity) {
        const paddingUL = (maxFreqUL - minFreqUL) * 0.04;
        minFreqUL -= paddingUL;
        maxFreqUL += paddingUL;
    }
    
    // Store original values
    originalMinFreqDL = minFreqDL;
    originalMaxFreqDL = maxFreqDL;
    originalFreqRangeDL = maxFreqDL - minFreqDL;
    freqRangeDL = originalFreqRangeDL;
    
    originalMinFreqUL = minFreqUL;
    originalMaxFreqUL = maxFreqUL;
    originalFreqRangeUL = maxFreqUL - minFreqUL;
    freqRangeUL = originalFreqRangeUL;
    
    // Setup event listeners
    canvas.addEventListener('wheel', handleWheel, { passive: false });
    canvas.addEventListener('mousedown', handleMouseDown);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mouseup', handleMouseUp);
    canvas.addEventListener('mouseleave', handleMouseLeave);
    
    renderChart();
}

function renderChart() {
    if (!canvas || !ctx) return;
    
    // Set canvas size
    const dpr = window.devicePixelRatio || 1;
    const rect = container.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
    ctx.scale(dpr, dpr);
    
    // Clear canvas
    ctx.clearRect(0, 0, width, height);
    
    // Layout constants
    const leftMargin = 60;
    const rightMargin = 20;
    const topMargin = 60;
    const middleMargin = 60; // Space between UL and DL sections
    const bottomMargin = 40;
    const chartWidth = width - leftMargin - rightMargin;
    const availableHeight = height - topMargin - middleMargin - bottomMargin;
    
    // Split available height between UL and DL
    uplinkHeight = availableHeight * 0.48;
    downlinkHeight = availableHeight * 0.48;
    
    // Group transponders by polarization (use first letter only)
    const polarizationGroups = {};
    transpondersData.forEach(t => {
        let pol = t.polarization || '-';
        // Take only first letter for abbreviation
        pol = pol.charAt(0).toUpperCase();
        if (!polarizationGroups[pol]) {
            polarizationGroups[pol] = [];
        }
        polarizationGroups[pol].push(t);
    });
    
    const polarizations = Object.keys(polarizationGroups);
    const rowHeightUL = uplinkHeight / polarizations.length;
    const rowHeightDL = downlinkHeight / polarizations.length;
    
    // Calculate visible frequency ranges with zoom and pan for UL
    const visibleFreqRangeUL = freqRangeUL / zoomLevelUL;
    const centerFreqUL = (minFreqUL + maxFreqUL) / 2;
    const visibleMinFreqUL = centerFreqUL - visibleFreqRangeUL / 2 + panOffsetUL;
    const visibleMaxFreqUL = centerFreqUL + visibleFreqRangeUL / 2 + panOffsetUL;
    
    // Calculate visible frequency ranges with zoom and pan for DL
    const visibleFreqRangeDL = freqRangeDL / zoomLevelDL;
    const centerFreqDL = (minFreqDL + maxFreqDL) / 2;
    const visibleMinFreqDL = centerFreqDL - visibleFreqRangeDL / 2 + panOffsetDL;
    const visibleMaxFreqDL = centerFreqDL + visibleFreqRangeDL / 2 + panOffsetDL;
    
    uplinkStartY = topMargin;
    downlinkStartY = topMargin + uplinkHeight + middleMargin;
    
    // Draw UPLINK frequency axis
    ctx.strokeStyle = '#dee2e6';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(leftMargin, uplinkStartY);
    ctx.lineTo(width - rightMargin, uplinkStartY);
    ctx.stroke();
    
    // Draw UPLINK frequency labels and grid
    ctx.fillStyle = '#6c757d';
    ctx.font = '11px sans-serif';
    ctx.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;
        
        // Draw tick
        ctx.beginPath();
        ctx.moveTo(x, uplinkStartY);
        ctx.lineTo(x, uplinkStartY - 5);
        ctx.stroke();
        
        // Draw grid line
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
        ctx.beginPath();
        ctx.moveTo(x, uplinkStartY);
        ctx.lineTo(x, uplinkStartY + uplinkHeight);
        ctx.stroke();
        ctx.strokeStyle = '#dee2e6';
        
        // Draw label
        ctx.fillText(freq.toFixed(1), x, uplinkStartY - 10);
    }
    
    // Draw UPLINK axis title
    ctx.fillStyle = '#000';
    ctx.font = 'bold 12px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('Uplink Частота (МГц)', width / 2, uplinkStartY - 25);
    
    // Draw DOWNLINK frequency axis
    ctx.strokeStyle = '#dee2e6';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(leftMargin, downlinkStartY);
    ctx.lineTo(width - rightMargin, downlinkStartY);
    ctx.stroke();
    
    // Draw DOWNLINK frequency labels and grid
    ctx.fillStyle = '#6c757d';
    ctx.font = '11px sans-serif';
    ctx.textAlign = 'center';
    
    for (let i = 0; i <= numTicks; i++) {
        const freq = visibleMinFreqDL + (visibleMaxFreqDL - visibleMinFreqDL) * i / numTicks;
        const x = leftMargin + chartWidth * i / numTicks;
        
        // Draw tick
        ctx.beginPath();
        ctx.moveTo(x, downlinkStartY);
        ctx.lineTo(x, downlinkStartY - 5);
        ctx.stroke();
        
        // Draw grid line
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
        ctx.beginPath();
        ctx.moveTo(x, downlinkStartY);
        ctx.lineTo(x, downlinkStartY + downlinkHeight);
        ctx.stroke();
        ctx.strokeStyle = '#dee2e6';
        
        // Draw label
        ctx.fillText(freq.toFixed(1), x, downlinkStartY - 10);
    }
    
    // Draw DOWNLINK axis title
    ctx.fillStyle = '#000';
    ctx.font = 'bold 12px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('Downlink Частота (МГц)', width / 2, downlinkStartY - 25);
    
    // Draw polarization label
    ctx.save();
    ctx.translate(15, height / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.textAlign = 'center';
    ctx.fillText('Поляризация', 0, 0);
    ctx.restore();
    
    // Clear transponder rects for hover detection
    transponderRects = [];
    
    // Draw transponders
    polarizations.forEach((pol, index) => {
        const group = polarizationGroups[pol];
        const downlinkColor = '#0000ff';
        const uplinkColor = '#fd7e14';
        
        // Uplink row (now on top)
        const uplinkY = uplinkStartY + index * rowHeightUL;
        const uplinkBarHeight = rowHeightUL * 0.8;
        const uplinkBarY = uplinkY + (rowHeightUL - uplinkBarHeight) / 2;
        
        // Downlink row (now on bottom)
        const downlinkY = downlinkStartY + index * rowHeightDL;
        const downlinkBarHeight = rowHeightDL * 0.8;
        const downlinkBarY = downlinkY + (rowHeightDL - downlinkBarHeight) / 2;
        
        // Draw polarization label for UL section
        ctx.fillStyle = '#000';
        ctx.font = 'bold 14px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText(pol, leftMargin - 25, uplinkBarY + uplinkBarHeight / 2 + 4);
        
        // Draw polarization label for DL section
        ctx.fillText(pol, leftMargin - 25, downlinkBarY + downlinkBarHeight / 2 + 4);
        
        // Draw separator lines between polarization groups
        if (index < polarizations.length - 1) {
            ctx.strokeStyle = '#adb5bd';
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(leftMargin, uplinkY + rowHeightUL);
            ctx.lineTo(width - rightMargin, uplinkY + rowHeightUL);
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(leftMargin, downlinkY + rowHeightDL);
            ctx.lineTo(width - rightMargin, downlinkY + rowHeightDL);
            ctx.stroke();
        }
        
        // Draw uplink transponders (now first, on top)
        group.forEach(t => {
            if (!t.uplink) return; // Skip if no uplink data
            
            const startFreq = t.uplink - (t.frequency_range / 2);
            const endFreq = t.uplink + (t.frequency_range / 2);
            
            // Check if transponder is visible in UL range
            if (endFreq < visibleMinFreqUL || startFreq > visibleMaxFreqUL) {
                return;
            }
            
            // Calculate position using UL axis
            const x1 = leftMargin + ((startFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
            const x2 = leftMargin + ((endFreq - visibleMinFreqUL) / (visibleMaxFreqUL - visibleMinFreqUL)) * chartWidth;
            const barWidth = x2 - x1;
            
            // Skip if too small
            if (barWidth < 1) return;
            
            const isHovered = hoveredTransponder && hoveredTransponder.transponder.name === t.name;
            
            // Draw uplink bar
            ctx.fillStyle = uplinkColor;
            ctx.fillRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
            
            // Draw border (thicker if hovered)
            ctx.strokeStyle = isHovered ? '#000' : '#fff';
            ctx.lineWidth = isHovered ? 3 : 1;
            ctx.strokeRect(x1, uplinkBarY, barWidth, uplinkBarHeight);
            
            // Draw name if there's space
            if (barWidth > 40) {
                ctx.fillStyle = '#fff';
                ctx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
                ctx.textAlign = 'center';
                ctx.fillText(t.name, x1 + barWidth / 2, uplinkBarY + uplinkBarHeight / 2 + 3);
            }
            
            // Store for hover detection
            transponderRects.push({
                x: x1,
                y: uplinkBarY,
                width: barWidth,
                height: uplinkBarHeight,
                transponder: t,
                type: 'uplink',
                centerX: x1 + barWidth / 2
            });
        });
        
        // Draw downlink transponders (now second, on bottom)
        group.forEach(t => {
            const startFreq = t.downlink - (t.frequency_range / 2);
            const endFreq = t.downlink + (t.frequency_range / 2);
            
            // Check if transponder is visible in DL range
            if (endFreq < visibleMinFreqDL || startFreq > visibleMaxFreqDL) {
                return;
            }
            
            // Calculate position using DL axis
            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 = hoveredTransponder && hoveredTransponder.transponder.name === t.name;
            
            // Draw downlink bar
            ctx.fillStyle = downlinkColor;
            ctx.fillRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
            
            // Draw border (thicker if hovered)
            ctx.strokeStyle = isHovered ? '#000' : '#fff';
            ctx.lineWidth = isHovered ? 3 : 1;
            ctx.strokeRect(x1, downlinkBarY, barWidth, downlinkBarHeight);
            
            // Draw name if there's space
            if (barWidth > 40) {
                ctx.fillStyle = '#fff';
                ctx.font = isHovered ? 'bold 10px sans-serif' : '9px sans-serif';
                ctx.textAlign = 'center';
                ctx.fillText(t.name, x1 + barWidth / 2, downlinkBarY + downlinkBarHeight / 2 + 3);
            }
            
            // Store for hover detection
            transponderRects.push({
                x: x1,
                y: downlinkBarY,
                width: barWidth,
                height: downlinkBarHeight,
                transponder: t,
                type: 'downlink',
                centerX: x1 + barWidth / 2
            });
        });
    });
    
    // Draw connection line between downlink and uplink when hovering
    if (hoveredTransponder) {
        drawConnectionLine(hoveredTransponder);
        drawTooltip(hoveredTransponder);
    }
}

function drawConnectionLine(rectInfo) {
    const t = rectInfo.transponder;
    if (!t.uplink) return; // No uplink to connect
    
    // Find both downlink and uplink rects for this transponder
    const downlinkRect = transponderRects.find(r => r.transponder.name === t.name && r.type === 'downlink');
    const uplinkRect = transponderRects.find(r => r.transponder.name === t.name && r.type === 'uplink');
    
    if (!downlinkRect || !uplinkRect) return;
    
    // Draw connecting line
    const x1 = downlinkRect.centerX;
    const y1 = downlinkRect.y + downlinkRect.height;
    const x2 = uplinkRect.centerX;
    const y2 = uplinkRect.y;
    
    ctx.save();
    ctx.strokeStyle = '#ffc107';
    ctx.lineWidth = 2;
    ctx.setLineDash([5, 3]);
    ctx.globalAlpha = 0.8;
    
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    
    ctx.restore();
}

function drawTooltip(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
    ];
    
    // Add frequency conversion info for uplink
    if (isUplink && t.downlink && t.uplink) {
        const conversion = t.downlink - t.uplink;
        lines.push('Перенос: ' + conversion.toFixed(3) + ' МГц');
    }
    
    // Calculate tooltip size
    ctx.font = '12px sans-serif';
    const padding = 10;
    const lineHeight = 16;
    let maxWidth = 0;
    lines.forEach(line => {
        const width = ctx.measureText(line).width;
        maxWidth = Math.max(maxWidth, width);
    });
    
    const tooltipWidth = maxWidth + padding * 2;
    const tooltipHeight = lines.length * lineHeight + padding * 2;
    
    // Position tooltip
    const mouseX = rectInfo._mouseX || canvas.width / 2;
    const mouseY = rectInfo._mouseY || canvas.height / 2;
    let tooltipX = mouseX + 15;
    let tooltipY = mouseY - tooltipHeight - 15; // Always show above cursor
    
    // Keep tooltip in bounds horizontally
    if (tooltipX + tooltipWidth > canvas.width) {
        tooltipX = mouseX - tooltipWidth - 15;
    }
    
    // If tooltip goes above canvas, show below cursor instead
    if (tooltipY < 0) {
        tooltipY = mouseY + 15;
    }
    
    // Draw tooltip background
    ctx.fillStyle = 'rgba(0, 0, 0, 0.9)';
    ctx.fillRect(tooltipX, tooltipY, tooltipWidth, tooltipHeight);
    
    // Draw tooltip text
    ctx.fillStyle = '#fff';
    ctx.font = 'bold 12px sans-serif';
    ctx.textAlign = 'left';
    ctx.fillText(lines[0], tooltipX + padding, tooltipY + padding + 12);
    
    ctx.font = '11px sans-serif';
    for (let i = 1; i < lines.length; i++) {
        ctx.fillText(lines[i], tooltipX + padding, tooltipY + padding + 12 + i * lineHeight);
    }
}

function handleWheel(e) {
    e.preventDefault();
    
    const rect = canvas.getBoundingClientRect();
    const mouseY = e.clientY - rect.top;
    
    // Determine which area we're zooming
    const isUplinkArea = mouseY < (uplinkStartY + uplinkHeight);
    
    const delta = e.deltaY > 0 ? 0.9 : 1.1;
    
    if (isUplinkArea) {
        const newZoom = Math.max(1, Math.min(20, zoomLevelUL * delta));
        if (newZoom !== zoomLevelUL) {
            zoomLevelUL = newZoom;
            
            // Adjust pan to keep center
            const maxPan = (originalFreqRangeUL * (zoomLevelUL - 1)) / (2 * zoomLevelUL);
            panOffsetUL = Math.max(-maxPan, Math.min(maxPan, panOffsetUL));
            
            renderChart();
        }
    } else {
        const newZoom = Math.max(1, Math.min(20, zoomLevelDL * delta));
        if (newZoom !== zoomLevelDL) {
            zoomLevelDL = newZoom;
            
            // Adjust pan to keep center
            const maxPan = (originalFreqRangeDL * (zoomLevelDL - 1)) / (2 * zoomLevelDL);
            panOffsetDL = Math.max(-maxPan, Math.min(maxPan, panOffsetDL));
            
            renderChart();
        }
    }
}

function handleMouseDown(e) {
    const rect = canvas.getBoundingClientRect();
    const mouseY = e.clientY - rect.top;
    
    // Determine which area we're dragging
    dragArea = mouseY < (uplinkStartY + uplinkHeight) ? 'uplink' : 'downlink';
    
    isDragging = true;
    dragStartX = e.clientX;
    dragStartOffsetUL = panOffsetUL;
    dragStartOffsetDL = panOffsetDL;
    canvas.style.cursor = 'grabbing';
}

function handleMouseMove(e) {
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    if (isDragging) {
        const dx = e.clientX - dragStartX;
        
        if (dragArea === 'uplink') {
            const freqPerPixel = (freqRangeUL / zoomLevelUL) / (rect.width - 80);
            panOffsetUL = dragStartOffsetUL - dx * freqPerPixel;
            
            // Limit pan
            const maxPan = (originalFreqRangeUL * (zoomLevelUL - 1)) / (2 * zoomLevelUL);
            panOffsetUL = Math.max(-maxPan, Math.min(maxPan, panOffsetUL));
        } else {
            const freqPerPixel = (freqRangeDL / zoomLevelDL) / (rect.width - 80);
            panOffsetDL = dragStartOffsetDL - dx * freqPerPixel;
            
            // Limit pan
            const maxPan = (originalFreqRangeDL * (zoomLevelDL - 1)) / (2 * zoomLevelDL);
            panOffsetDL = Math.max(-maxPan, Math.min(maxPan, panOffsetDL));
        }
        
        renderChart();
    } else {
        // Check hover
        let found = null;
        for (const tr of transponderRects) {
            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 !== hoveredTransponder) {
            hoveredTransponder = found;
            canvas.style.cursor = found ? 'pointer' : 'default';
            renderChart();
        } else if (found) {
            found._mouseX = mouseX;
            found._mouseY = mouseY;
        }
    }
}

function handleMouseUp() {
    isDragging = false;
    canvas.style.cursor = hoveredTransponder ? 'pointer' : 'default';
}

function handleMouseLeave() {
    isDragging = false;
    hoveredTransponder = null;
    canvas.style.cursor = 'default';
    renderChart();
}

function resetZoom() {
    zoomLevelUL = 1;
    zoomLevelDL = 1;
    panOffsetUL = 0;
    panOffsetDL = 0;
    renderChart();
}

function zoomIn() {
    zoomLevelUL = Math.min(20, zoomLevelUL * 1.2);
    zoomLevelDL = Math.min(20, zoomLevelDL * 1.2);
    renderChart();
}

function zoomOut() {
    zoomLevelUL = Math.max(1, zoomLevelUL / 1.2);
    zoomLevelDL = Math.max(1, zoomLevelDL / 1.2);
    if (zoomLevelUL === 1) {
        panOffsetUL = 0;
    }
    if (zoomLevelDL === 1) {
        panOffsetDL = 0;
    }
    renderChart();
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    initializeFrequencyChart();
    
    // Control buttons
    document.getElementById('resetZoom').addEventListener('click', resetZoom);
    // document.getElementById('zoomIn').addEventListener('click', zoomIn);
    // document.getElementById('zoomOut').addEventListener('click', zoomOut);
});

// Re-render on window resize
let resizeTimeout;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(renderChart, 250);
});
</script>
{% endif %}
{% endblock %}
