{# Default ui_lang values if not provided by context processor #}
{% if ui_lang is not defined %}
{% set ui_lang = {'next_button': 'Next', 'previous_button': 'Previous', 'labeled_badge': 'Labeled', 'not_labeled_badge': 'Not labeled', 'submit_button': 'Submit', 'progress_label': 'Progress', 'go_button': 'Go', 'logout': 'Logout', 'loading': 'Loading annotation interface...', 'error_heading': 'Error', 'retry_button': 'Retry', 'adjudicate': 'Adjudicate'} %}
{% endif %}
<!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') }}">

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

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

    <!-- Spreadsheet Display Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='spreadsheet-display.css') }}">

    <!-- Format Display Styles (document, code, etc.) -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/format-displays.css') }}">

    <!-- Document Bounding Box Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='document-bbox.css') }}">

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

    <!-- Display Logic Styles (conditional schema branching) -->
    <link rel="stylesheet" href="{{ url_for('static', filename='display-logic.css') }}">

    <!-- Coreference Chain Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/coreference.css') }}">

    <!-- Segmentation Tool Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/segmentation.css') }}">

    <!-- Conversation Tree Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/conversation-tree.css') }}">

    <!-- Video Tracking Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/tracking.css') }}">

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

    <!-- Entity Linking Styles (knowledge base linking) -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/entity-linking.css') }}">

    <!-- Tiered Annotation Styles (ELAN-style hierarchical annotation) -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/tiered-annotation.css') }}">

    {% if agent_proxy_enabled | default(false) %}
    <!-- Agent Chat Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/agent-chat.css') }}">
    {% endif %}

    {% if chat_enabled | default(false) %}
    <!-- LLM Chat Sidebar Styles -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/llm-chat-sidebar.css') }}?v=1">
    {% endif %}

    <!-- 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>

    <!-- Project-level base CSS (injected from base_css config option) -->
    {{ PROJECT_BASE_CSS | safe }}
</head>

<body>
    <!-- Header navigation bar -->
    <nav class="potato-navbar" role="navigation">
        <div class="navbar-inner">
            <div class="navbar-brand">
                {% if header_logo_url %}
                <img class="header-logo" src="{{ header_logo_url }}" alt="Logo">
                {% endif %}
                <span class="task-name">{{annotation_task_name}}</span>
            </div>

            <div class="navbar-center">
                <div class="annotation-status-indicator" id="annotation-status">
                    <span class="status-badge {{ 'labeled' if instance_has_annotations else 'unlabeled' }}">
                        {{ ui_lang.labeled_badge if instance_has_annotations else ui_lang.not_labeled_badge }}
                    </span>
                </div>

                <div class="navbar-divider"></div>

                <div class="progress-section">
                    <span class="progress-label">{{ ui_lang.progress_label }}</span>
                    <span class="fw-medium" id="progress-counter">{{finished}}/{{total_count}}</span>
                </div>

                <div class="navbar-divider"></div>

                <div class="nav-controls">
                    <button type="button" class="nav-control-btn" id="jump-unannotated-prev-btn"
                            onclick="jumpToUnannotatedPrev()" title="Previous unannotated">
                        <i class="fas fa-backward"></i>
                    </button>
                    <button type="button" class="nav-control-btn" id="jump-unannotated-btn"
                            onclick="jumpToUnannotated()" title="Next unannotated">
                        <i class="fas fa-forward"></i>
                    </button>
                </div>

                <div class="navbar-divider"></div>

                <div class="goto-section">
                    <input type="number" id="go_to" placeholder="#"
                           value="" min="0" max="{{total_count}}" required
                           onfocusin="user_input()" onfocusout="user_input_leave()">
                    <button type="button" class="goto-btn" id="go-to-btn">{{ ui_lang.go_button }}</button>
                </div>
            </div>

            <div class="navbar-end">
                {% if is_adjudicator %}
                <a href="/adjudicate" class="adjudicate-btn" title="Adjudication Mode">
                    <i class="fas fa-gavel"></i> {{ ui_lang.adjudicate }}
                </a>
                {% endif %}
                <div class="user-pill">
                    <span class="username" id="username-display">{{username}}</span>
                    <a href="/logout" class="logout-btn">{{ ui_lang.logout }}</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <!-- Main annotation area -->
        <div id="task_layout" class="shadcn-card mb-2 {% if has_image_annotation or has_video_annotation or has_audio_annotation %}media-annotation{% else %}text-annotation{% endif %}">
            <div class="shadcn-card-content">
                <!-- Loading state -->
                <div id="loading-state" class="text-center py-5">
                    <div class="loading-spinner mb-3"></div>
                    <p>{{ ui_lang.loading }}</p>
                </div>

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

                <!-- Main content area -->
                <div id="main-content" style="display: none;">
                    {% if annotation_instructions | default('') %}
                    <details class="annotation-instructions-banner" open>
                        <summary>Annotation Instructions (click to collapse)</summary>
                        <div class="annotation-instructions-content">
                            {{ annotation_instructions | safe }}
                        </div>
                    </details>
                    {% endif %}
                    <!-- Instance display area -->
                    <div class="mb-4">
                        {% if has_instance_display | default(false) %}
                        <!-- New instance_display mode: explicit content display configuration -->
                        {{ display_html | safe }}
                        <!-- Hidden element for legacy JS compatibility -->
                        <div id="instance-text" style="display: none;">
                            <div id="text-content" data-original-text="{{instance_plain_text | sanitize_html}}">{{instance | sanitize_html}}</div>
                        </div>
                        {% elif 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 %}
                        {% if is_annotation_page %}
                                <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;">
                                    <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 id="span-overlays" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: none; z-index: 2;">
                                        </div>
                                    </div>
                                </div>
                            {% else %}
                                <div id="instance-text" style="display: none;">
                                    <div id="text-content" data-original-text=""></div>
                                </div>
                            {% endif %}
                        {% 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>

                    <!-- Structured data elements (var_elems) -->
                    {{ var_elems | safe }}
                </div>
            </div>
        </div>

        <!-- Navigation buttons -->
        <div class="potato-nav">
            <button class="shadcn-button shadcn-button-outline" id="prev-btn" onclick="navigateToPrevious()">
                <i class="fas fa-arrow-left me-2"></i>{{ ui_lang.previous_button }}
            </button>
            <button class="shadcn-button shadcn-button-primary" id="next-btn" onclick="navigateToNext()">
                {{ ui_lang.next_button }}<i class="fas fa-arrow-right ms-2"></i>
            </button>
        </div>

        <!-- Footer -->
        <footer class="potato-footer">
            Powered by <a href="https://potatoannotator.com/" target="_blank" rel="noopener noreferrer">Potato</a>
            <span class="footer-sep">&middot;</span>
            <a href="https://github.com/davidjurgens/potato" target="_blank" rel="noopener noreferrer">GitHub</a>
            <span class="footer-sep">&middot;</span>
            <a href="https://github.com/davidjurgens/potato#cite-us" target="_blank" rel="noopener noreferrer">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 }},
            is_annotation_page: {{ 'true' if is_annotation_page else 'false' }},
            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=7"></script>
    <script src="{{ url_for('static', filename='ai_assistant_manager.js') }}?v=1"></script>
    <!-- Display Logic Manager (conditional schema branching) - must load before annotation.js -->
    <script src="{{ url_for('static', filename='display-logic.js') }}?v=1"></script>
    <!-- Instance display manager (for new instance_display configuration) -->
    {% if has_instance_display | default(false) %}
    <script src="{{ url_for('static', filename='instance-display.js') }}?v=2"></script>
    {% endif %}
    <script src="{{ url_for('static', filename='annotation.js') }}?v=20"></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>
    <!-- Visual AI Assistant for image/video annotation (loaded conditionally) -->
    {% if ai_enabled %}
    <script src="{{ url_for('static', filename='visual_ai_assistant.js') }}?v=1"></script>
    <!-- Option Highlight Manager for dimming less-likely options -->
    <script src="{{ url_for('static', filename='option_highlight_manager.js') }}?v=2"></script>
    {% endif %}

    <!-- 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>

    <!-- Span link manager -->
    <script src="{{ url_for('static', filename='span-link-manager.js') }}?v=7"></script>

    <!-- Event annotation manager -->
    <script src="{{ url_for('static', filename='event-annotation.js') }}?v=1"></script>

    <!-- Entity linking for knowledge bases (Wikidata, UMLS) -->
    <script src="{{ url_for('static', filename='entity-linking.js') }}?v=1"></script>

    <!-- Coreference chain manager -->
    <script src="{{ url_for('static', filename='coreference-manager.js') }}?v=1"></script>

    <!-- Segmentation tools -->
    <script src="{{ url_for('static', filename='segmentation-tools.js') }}?v=1"></script>

    <!-- Conversation tree interaction -->
    <script src="{{ url_for('static', filename='conversation-tree.js') }}?v=1"></script>

    <!-- Video tracking interpolation and UI -->
    <script src="{{ url_for('static', filename='tracking-interpolation.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='tracking-ui.js') }}?v=1"></script>

    <!-- Triage annotation manager -->
    <script src="{{ url_for('static', filename='triage.js') }}?v=1"></script>

    <!-- Tiered annotation manager (ELAN-style hierarchical annotation) -->
    <script src="{{ url_for('static', filename='tiered-annotation.js') }}?v=1"></script>

    <!-- Document bounding box annotation -->
    <script src="{{ url_for('static', filename='document-bbox.js') }}?v=2"></script>

    <!-- PDF bounding box annotation -->
    <script src="{{ url_for('static', filename='pdf-bbox.js') }}?v=2"></script>

    {% if agent_proxy_enabled | default(false) %}
    <!-- Agent Chat UI -->
    <script src="{{ url_for('static', filename='agent-chat.js') }}?v=1"></script>
    {% endif %}

    {% if chat_enabled | default(false) %}
    <!-- LLM Chat Sidebar -->
    <script src="{{ url_for('static', filename='llm-chat-sidebar.js') }}?v=1"></script>
    {% endif %}

    <!-- Web Agent Trace Viewer (overlays + step navigation) -->
    <script src="{{ url_for('static', filename='web-agent-overlays.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='web-agent-viewer.js') }}?v=1"></script>
    <script src="{{ url_for('static', filename='web-agent-playback.js') }}?v=1"></script>
    <!-- Web Agent Interaction Recorder (creation mode) -->
    <script src="{{ url_for('static', filename='web-agent-recorder.js') }}?v=1"></script>
    <!-- Live Agent Viewer (real-time agent interaction) -->
    {% if live_agent_enabled | default(false) %}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/live-agent.css') }}?v=1">
    <script src="{{ url_for('static', filename='live-agent-viewer.js') }}?v=1"></script>
    {% endif %}

    <!-- 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>