<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{annotation_task_name}}</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <!-- Custom Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">

    <!-- Span Annotation Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='span-styles.css') }}">

    <!-- Image Annotation Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='image-annotation.css') }}?v=2">

    <!-- Audio Annotation Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='audio-annotation.css') }}?v=2">

    <!-- Video Annotation Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='video-annotation.css') }}">

    <!-- jQuery (required for span annotation) -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>

<body>
    <!-- Header navigation bar -->
    <nav class="navbar sticky-top shadow-sm" style="background-color: var(--primary-color); padding: 0.75rem 1rem; margin-bottom: 1.5rem;">
        <div class="container-fluid d-flex align-items-center">
            <!-- Task name (left aligned) -->
            <div class="navbar-brand">
                <span class="fw-bold" style="color: var(--light-color); font-size: 1.25rem">{{annotation_task_name}}</span>
            </div>

            <!-- Middle section with progress and navigation -->
            <div class="d-flex align-items-center justify-content-center flex-grow-1 gap-4">
                <!-- Progress counter -->
                <div class="d-flex align-items-center" style="color: var(--light-color); margin-right: 40px">
                    <span>Progress: <span class="fw-medium" id="progress-counter">{{finished}}/{{total_count}}</span></span>
                </div>

                <!-- Jump to item form -->
                <div style="margin-left: 40px">
                    <div class="d-flex align-items-center">
                        <label for="go_to" class="me-2" style="color: var(--light-color); margin-bottom: 0">Go to:</label>
                        <input type="number" id="go_to" class="form-control form-control-sm me-2"
                               style="width: 70px; height: 31px; border: none; border-radius: var(--radius);"
                               value="" min="0" required>
                        <button type="button" class="shadcn-button" id="go-to-btn"
                                style="height: 31px; line-height: 1; padding: 0 0.75rem; background-color: var(--light-color); color: var(--primary-color); border: none;">
                            Go
                        </button>
                    </div>
                </div>
            </div>

            <!-- User info and logout (right aligned) -->
            <div class="d-flex align-items-center"
                 style="background-color: rgba(255, 255, 255, 0.15); padding: 0.5rem 1rem; border-radius: var(--radius);">
                <div class="me-3" style="color: var(--light-color)">
                    <span>Logged in as <span class="fw-medium" id="username-display">{{username}}</span></span>
                </div>
                <div class="border-start" style="padding-left: 20px; height: 24px; display: flex; align-items: center;">
                    <a href="/logout" class="shadcn-button"
                       style="background-color: var(--light-color); color: var(--primary-color); height: auto; padding: 0.25rem 0.75rem !important; font-size: 0.875rem; min-width: 60px; text-align: center; border: none; text-decoration: none;">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <!-- Main annotation area -->
        <div id="task_layout" class="shadcn-card mb-4">
            <div class="shadcn-card-content">
                <!-- Loading state -->
                <div id="loading-state" class="text-center py-5">
                    <div class="loading-spinner mb-3"></div>
                    <p>Loading annotation interface...</p>
                </div>

                <!-- Error state -->
                <div id="error-state" class="error-message" style="display: none;">
                    <h5><i class="fas fa-exclamation-triangle me-2"></i>Error</h5>
                    <p id="error-message-text"></p>
                    <button class="shadcn-button shadcn-button-primary" onclick="loadCurrentInstance()">
                        <i class="fas fa-redo me-2"></i>Retry
                    </button>
                </div>

                <!-- Main content area -->
                <div id="main-content" style="display: none;">
                    <!-- Instance text/video -->
                    <div class="mb-4">
                        {% if has_video_annotation | default(false) %}
                        <h5 class="mb-3">Video to Annotate:</h5>
                        <!-- For video annotation, keep the text-content element accessible for JS but visually hidden -->
                        <div id="instance-text" class="instance-text-container" style="position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0);">
                            <div id="text-content" data-original-text="{{instance_plain_text | sanitize_html}}">{{instance | sanitize_html}}</div>
                        </div>
                        {% elif has_audio_annotation | default(false) %}
                        <h5 class="mb-3">Audio to Annotate:</h5>
                        <!-- For audio annotation, keep the text-content element accessible for JS but visually hidden -->
                        <div id="instance-text" class="instance-text-container" style="position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0);">
                            <div id="text-content" data-original-text="{{instance_plain_text | sanitize_html}}">{{instance | sanitize_html}}</div>
                        </div>
                        {% elif has_image_annotation | default(false) %}
                        <!-- For image annotation, hide this section - the image is loaded directly into the annotation canvas -->
                        <!-- Store the image URL in a hidden element for JavaScript to access -->
                        <div id="instance-text" style="display: none;">
                            <div id="text-content" data-original-text="{{instance_plain_text | sanitize_html}}" data-image-url="{{instance | sanitize_html}}">{{instance | sanitize_html}}</div>
                        </div>
                        {% else %}
                        <h5 class="mb-3">Text to Annotate:</h5>
                        <div id="instance-text" class="p-3 border rounded instance-text-container" style="background-color: var(--light-bg); min-height: 100px; position: relative;">
                            <!-- Text content layer for span annotation -->
                            <!-- Note: sanitize_html filter allows safe span annotation HTML while blocking XSS -->
                            <!-- data-original-text uses plain text (no span HTML) for correct position calculations -->
                            <!-- DOM content uses rendered HTML with span tags for visual display -->
                            <div id="text-content" data-original-text="{{instance_plain_text | sanitize_html}}" style="position: relative; z-index: 1; pointer-events: auto;">{{instance | sanitize_html}}</div>
                            <!-- Span overlays layer for span annotation -->
                            <div id="span-overlays" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: none; z-index: 2;">
                                <!-- Individual overlays will have pointer-events: auto -->
                            </div>
                        </div>
                        {% endif %}
                    </div>



                    <!-- Status messages -->
                    <div id="status" class="status" style="display: none;"></div>
                    <!-- Hidden input for instance_id -->
                    <input type="hidden" id="instance_id" name="instance_id" value="{{instance_id}}">

                    <!-- Annotation forms -->
                    <div id="annotation-forms">
                        {{ TASK_LAYOUT }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation buttons -->
        <div class="my-4">
            <div class="d-flex justify-content-between align-items-center">
                <!-- Previous button -->
                <div>
                    <button class="shadcn-button shadcn-button-outline me-2" id="prev-btn" onclick="navigateToPrevious()">
                        <i class="fas fa-arrow-left me-2"></i>Previous
                    </button>
                </div>

                <!-- Next button -->
                <div>
                    <button class="shadcn-button shadcn-button-primary" id="next-btn" onclick="navigateToNext()">
                        Next<i class="fas fa-arrow-right ms-2"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <hr style="color: var(--border)">
        <footer class="py-2 text-center" style="font-size: 0.75rem; color: var(--muted-foreground)">
            Copyright &copy; 2025
            <a href="https://blablablab.si.umich.edu/" style="color: var(--primary); text-decoration: none">Blablablab</a>
            <span class="mx-2">|</span>
            <a href="https://github.com/davidjurgens/potato" style="color: var(--primary); text-decoration: none">Chat with us on GitHub</a>
            <span class="mx-2">|</span>
            <a href="https://github.com/davidjurgens/potato#cite-us" style="color: var(--primary); text-decoration: none">Cite Us</a>
        </footer>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Configuration from server -->
    <script type="text/javascript">
        window.config = {
            annotation_task_name: {{ annotation_task_name | tojson }},
            debug: {{ 'true' if debug_mode else 'false' }},
            ui_debug: {{ 'true' if ui_debug else 'false' }},
            server_debug: {{ 'true' if server_debug else 'false' }},
            debug_phase: {{ debug_phase | tojson if debug_phase else 'null' }},
            api_key: "test_api_key",
            username: {{ username | tojson }},
            ui_config: {}
        };

        // Conditionally enable/disable console logging based on ui_debug setting
        if (!window.config.ui_debug) {
            // Store original console methods
            window._originalConsole = {
                log: console.log,
                debug: console.debug,
                info: console.info,
                warn: console.warn
            };
            // Override with no-ops (keep error for critical issues)
            console.log = function() {};
            console.debug = function() {};
            console.info = function() {};
            // Keep warn for important warnings
        }

        // Helper function to enable UI logging at runtime (for debugging in browser console)
        window.enableUIDebug = function() {
            if (window._originalConsole) {
                console.log = window._originalConsole.log;
                console.debug = window._originalConsole.debug;
                console.info = window._originalConsole.info;
                console.warn = window._originalConsole.warn;
                console.log('UI debug logging enabled');
            }
        };
    </script>
    <script id="ui-config" type="application/json">{% if ui_config %}{{ ui_config | tojson | safe }}{% else %}{}{% endif %}</script>
    <script>
        (function(){
            try {
                var el = document.getElementById('ui-config');
                if (el && el.textContent && el.textContent.trim().length > 0) {
                    window.config.ui_config = JSON.parse(el.textContent);
                }
            } catch (e) { console.warn('Failed to parse ui_config', e); }
        })();
    </script>

    <!-- Load annotation JavaScript -->
    <script src="{{ url_for('static', filename='interaction_tracker.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='span-core.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='ai_assistant_manager.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='annotation.js') }}?v=14"></script>

    <!-- Fabric.js for image annotation (loaded from CDN) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
    <!-- Image annotation manager -->
    <script src="{{ url_for('static', filename='image-annotation.js') }}?v=2"></script>

    <!-- Peaks.js for audio/video annotation (stored locally for reliability) -->
    <script src="{{ url_for('static', filename='peaks.min.js') }}"></script>
    <!-- Audio annotation manager -->
    <script src="{{ url_for('static', filename='audio-annotation.js') }}?v=2"></script>
    <!-- Video annotation manager -->
    <script src="{{ url_for('static', filename='video-annotation.js') }}?v=10"></script>

    <!-- Global keyboard debug (temporary) -->
    <script>
        window.addEventListener('keydown', function(e) {
            console.log('[GLOBAL DEBUG] keydown:', e.key, 'code:', e.code, 'target:', e.target.tagName);
        }, true);
    </script>

    <!-- Instance height limit functionality -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Apply maximum instance height if configured
            if (window.config && window.config.ui_config && window.config.ui_config.max_instance_height) {
                const maxHeight = window.config.ui_config.max_instance_height;
                const instanceTextContainer = document.getElementById('instance-text');

                if (instanceTextContainer) {
                    // Set CSS custom property for max height
                    instanceTextContainer.style.setProperty('--max-instance-height', maxHeight + 'px');

                    // Add the max-height-limited class to enable scrolling
                    instanceTextContainer.classList.add('max-height-limited');

                    console.log('Applied maximum instance height:', maxHeight + 'px');
                }
            }
        });
    </script>
</body>
</html>