{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Media - MediaCMS</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            margin: 0 0 10px 0;
            font-size: 24px;
        }
        .filter-bar {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .media-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 15px;
            margin-bottom: 80px;
        }
        .media-card {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s;
            cursor: pointer;
            border: 2px solid transparent;
        }
        .media-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        .media-card.selected {
            border: 2px solid #2196F3;
            box-shadow: 0 4px 8px rgba(33, 150, 243, 0.3);
        }
        .media-thumbnail-wrapper {
            position: relative;
            width: 100%;
            height: 160px;
            background: #eee;
        }
        .media-thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .checkbox-wrapper {
            position: absolute;
            top: 8px;
            right: 8px;
            background: white;
            border-radius: 4px;
            padding: 2px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .checkbox-wrapper input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        .media-info {
            padding: 12px;
        }
        .media-title {
            font-weight: 600;
            margin: 0 0 5px 0;
            font-size: 14px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .media-meta {
            font-size: 12px;
            color: #666;
        }
        .bottom-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 15px 20px;
            box-shadow: 0 -2px 4px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            z-index: 100;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
        }
        .btn-primary {
            background: #2196F3;
            color: white;
        }
        .btn-primary:hover:not(:disabled) {
            background: #1976D2;
        }
        .btn-primary:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .selected-count {
            color: #666;
            font-size: 14px;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
            grid-column: 1 / -1;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin: 20px 0;
            padding-bottom: 80px;
        }
        .pagination button {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
        }
        .pagination button:hover:not(:disabled) {
            background: #f5f5f5;
        }
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Select MediaCMS Content</h1>
        <p style="margin: 5px 0 0 0; color: #666; font-size: 14px;">Choose media to embed in your content</p>
    </div>

    <div class="filter-bar">
        <label style="cursor: pointer;">
            <input type="checkbox" id="myMediaOnly" {% if request.GET.my_media_only %}checked{% endif %}>
            Show only my media
        </label>
    </div>

    <div class="media-grid">
        {% for media in media_list %}
        <div class="media-card" data-media-id="{{ media.id }}" data-friendly-token="{{ media.friendly_token }}" onclick="toggleMedia('{{ media.friendly_token }}')">
            <div class="media-thumbnail-wrapper">
                {% if media.thumbnail_url %}
                <img src="{{ media.thumbnail_url }}" alt="{{ media.title }}" class="media-thumbnail" loading="lazy">
                {% else %}
                <div class="media-thumbnail" style="display: flex; align-items: center; justify-content: center; background: #e0e0e0;">
                    <span style="font-size: 40px;">🎬</span>
                </div>
                {% endif %}
                <div class="checkbox-wrapper" onclick="event.stopPropagation();">
                    <input type="checkbox" name="media_tokens[]" value="{{ media.friendly_token }}" id="media_{{ media.friendly_token }}">
                </div>
            </div>
            <div class="media-info">
                <h3 class="media-title" title="{{ media.title }}">{{ media.title }}</h3>
                <div class="media-meta">
                    By {{ media.user.name|default:media.user.username }}<br>
                    {{ media.add_date|date:"M d, Y" }}
                </div>
            </div>
        </div>
        {% empty %}
        <div class="empty-state">
            <h3>No media found</h3>
            <p>Try adjusting your filter settings or upload some media first</p>
        </div>
        {% endfor %}
    </div>

    {% if page_obj %}
    <div class="pagination">
        {% if page_obj.has_previous %}
        <button onclick="goToPage({{ page_obj.previous_page_number }})">Previous</button>
        {% else %}
        <button disabled>Previous</button>
        {% endif %}

        <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>

        {% if page_obj.has_next %}
        <button onclick="goToPage({{ page_obj.next_page_number }})">Next</button>
        {% else %}
        <button disabled>Next</button>
        {% endif %}
    </div>
    {% endif %}

    <div class="bottom-bar">
        <span class="selected-count">
            <strong id="selectedCount">0</strong> item(s) selected
        </span>
        <div>
            <button type="button" class="btn btn-primary" id="insertBtn" onclick="insertSelected()" disabled>Insert</button>
        </div>
    </div>

    <script>
        const selectedTokens = new Set();

        function toggleMedia(friendlyToken) {
            const checkbox = document.getElementById('media_' + friendlyToken);
            checkbox.checked = !checkbox.checked;
            updateSelection();
        }

        function updateSelection() {
            selectedTokens.clear();
            const checkboxes = document.querySelectorAll('input[name="media_tokens[]"]');

            checkboxes.forEach(cb => {
                const card = cb.closest('.media-card');
                if (cb.checked) {
                    card.classList.add('selected');
                    selectedTokens.add(cb.value);
                } else {
                    card.classList.remove('selected');
                }
            });

            const count = selectedTokens.size;
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('insertBtn').disabled = count === 0;
        }

        async function insertSelected() {
            if (selectedTokens.size === 0) return;

            const insertBtn = document.getElementById('insertBtn');
            insertBtn.disabled = true;
            insertBtn.textContent = 'Inserting...';

            try {
                // Get embed code for each selected media
                const embedCodes = [];

                for (const token of selectedTokens) {
                    const response = await fetch(`/lti/tinymce-embed/${token}/`);
                    const data = await response.json();

                    if (data.embedCode) {
                        embedCodes.push(data.embedCode);
                    }
                }

                if (embedCodes.length > 0) {
                    // Join multiple embeds with line breaks
                    const fullEmbedCode = embedCodes.join('\n\n');

                    // Send message to parent window (TinyMCE dialog)
                    window.parent.postMessage({
                        type: 'mediacms-embed',
                        embedCode: fullEmbedCode,
                        count: embedCodes.length
                    }, '*');
                }
            } catch (error) {
                console.error('Error inserting media:', error);
                alert('Error inserting media. Please try again.');
                insertBtn.disabled = false;
                insertBtn.textContent = 'Insert';
            }
        }

        function goToPage(pageNum) {
            const url = new URL(window.location);
            url.searchParams.set('page', pageNum);
            window.location = url.toString();
        }

        // Initialize
        document.querySelectorAll('input[name="media_tokens[]"]').forEach(cb => {
            cb.addEventListener('change', function(e) {
                e.stopPropagation();
                updateSelection();
            });
        });

        // My media filter
        document.getElementById('myMediaOnly').addEventListener('change', function() {
            const url = new URL(window.location);
            if (this.checked) {
                url.searchParams.set('my_media_only', 'true');
            } else {
                url.searchParams.delete('my_media_only');
            }
            window.location = url.toString();
        });

        updateSelection();
    </script>
</body>
</html>
