{% extends "base.html" %}

{% block title %}{{ person.name }} - Biblical Family Tree - KJV Study{% endblock %}
{% block description %}{{ person.name }} in the biblical genealogy from Adam to Jesus Christ.{% endblock %}

{% block head %}
<style>
{% set female_names = ['eve', 'sarah', 'rebekah', 'rachel', 'leah', 'ruth', 'mary', 'tamar', 'rahab', 'bathsheba', 'dinah', 'keturah', 'hagar', 'zilpah', 'bilhah', 'jochebed', 'miriam', 'deborah', 'hannah', 'abigail', 'esther', 'naomi', 'naamah', 'milcah', 'adah', 'zillah', 'asenath', 'basemath'] %}

.person-page {
    max-width: 55%;
}

@media (max-width: 768px) {
    .person-page {
        max-width: 100%;
    }
}

.person-nav {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid #ddd;
    font-size: 0.9rem;
}

.person-nav a {
    text-decoration: none;
    color: #555;
}

.person-nav a:hover {
    color: #000;
}

.person-nav .nav-spacer {
    flex: 1;
}

/* Main person card */
.person-main-card {
    padding: 1.5rem;
    border: 1px solid #ddd;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    background: #fff;
}

.person-main-card.male {
    border-left: 5px solid #3b6ea5;
}

.person-main-card.female {
    border-left: 5px solid #a55b80;
}

.person-main-card.kekule {
    border-color: #d4af37;
    border-left-width: 5px;
    background: linear-gradient(to right, #fffde7, #fff);
}

.person-name {
    font-size: 2rem;
    font-weight: 400;
    margin: 0 0 0.5rem 0;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.person-badge {
    font-size: 0.75rem;
    padding: 0.2rem 0.6rem;
    border-radius: 3px;
    background: #d4af37;
    color: #fff;
    font-weight: 500;
}

.person-subtitle {
    font-size: 1rem;
    color: #666;
    margin-bottom: 1rem;
}

.person-vitals {
    display: flex;
    flex-wrap: wrap;
    gap: 1.5rem;
    font-size: 0.95rem;
}

.vital-item {
    display: flex;
    gap: 0.4rem;
}

.vital-label {
    color: #888;
}

.vital-value {
    font-weight: 500;
}

/* Section cards */
.section-card {
    padding: 1rem 1.25rem;
    border: 1px solid #ddd;
    border-radius: 6px;
    margin-bottom: 1rem;
    background: #fff;
}

.section-card h2 {
    font-size: 1.1rem;
    margin: 0 0 0.75rem 0;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #eee;
    color: #333;
}

/* Family member cards */
.family-grid {
    display: grid;
    gap: 0.75rem;
}

.family-card {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.6rem 0.75rem;
    border: 1px solid #eee;
    border-radius: 4px;
    background: #fafafa;
    transition: background 0.15s ease;
}

.family-card:hover {
    background: #f5f5f5;
}

.family-card.male {
    border-left: 3px solid #3b6ea5;
}

.family-card.female {
    border-left: 3px solid #a55b80;
}

.family-card.kekule {
    border-left-color: #d4af37;
    background: linear-gradient(to right, #fffde7, #fafafa);
}

.family-card-name {
    font-weight: 500;
    flex: 1;
}

.family-card-name a {
    color: inherit;
    text-decoration: none;
}

.family-card-name a:hover {
    text-decoration: underline;
}

.family-card-meta {
    font-size: 0.8rem;
    color: #888;
}

.family-card-badge {
    font-size: 0.7rem;
    padding: 0.1rem 0.4rem;
    border-radius: 2px;
    background: #d4af37;
    color: #fff;
}

/* Verse cards */
.verse-card {
    padding: 0.75rem 1rem;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 0.75rem;
    background: #fafafa;
}

.verse-card-ref {
    font-weight: 500;
    margin-bottom: 0.25rem;
}

.verse-card-ref a {
    color: #4a7c59;
}

.verse-card-text {
    font-style: italic;
    color: #555;
    font-size: 0.9rem;
    line-height: 1.6;
}

/* Biography section */
.biography-text {
    line-height: 1.8;
    font-size: 1rem;
}

.biography-significance {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #eee;
    font-style: italic;
    color: #666;
}

/* Life events */
.event-item {
    display: flex;
    gap: 1rem;
    padding: 0.5rem 0;
    border-bottom: 1px solid #f0f0f0;
}

.event-item:last-child {
    border-bottom: none;
}

.event-age {
    font-weight: 600;
    min-width: 60px;
    color: #4a7c59;
}

.event-desc {
    flex: 1;
}

.event-verse {
    font-size: 0.85rem;
    margin-top: 0.25rem;
}

.event-verse a {
    color: #666;
}

/* Bottom navigation */
.bottom-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    margin-top: 1.5rem;
    padding-top: 1rem;
    border-top: 1px solid #ddd;
}

.bottom-nav a {
    padding: 0.5rem 1rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-decoration: none;
    font-size: 0.9rem;
    color: #555;
    transition: all 0.15s ease;
}

.bottom-nav a:hover {
    background: #f5f5f5;
    border-color: #ccc;
}

.bottom-nav a.primary {
    background: #4a7c59;
    color: #fff !important;
    border-color: #4a7c59;
}

.bottom-nav a.primary:hover {
    background: #3d6a4b;
}

/* Dark mode */
[data-theme="dark"] .person-nav {
    border-bottom-color: #333;
}

[data-theme="dark"] .person-nav a {
    color: #aaa;
}

[data-theme="dark"] .person-nav a:hover {
    color: #fff;
}

[data-theme="dark"] .person-main-card {
    background: #1a1a1a;
    border-color: #333;
}

[data-theme="dark"] .person-main-card.kekule {
    background: linear-gradient(to right, #2a2a1a, #1a1a1a);
}

[data-theme="dark"] .person-name {
    color: #e0e0e0;
}

[data-theme="dark"] .person-subtitle {
    color: #888;
}

[data-theme="dark"] .vital-label {
    color: #888;
}

[data-theme="dark"] .vital-value {
    color: #e0e0e0;
}

[data-theme="dark"] .section-card {
    background: #1a1a1a;
    border-color: #333;
}

[data-theme="dark"] .section-card h2 {
    color: #e0e0e0;
    border-bottom-color: #333;
}

[data-theme="dark"] .family-card {
    background: #252525;
    border-color: #333;
}

[data-theme="dark"] .family-card:hover {
    background: #2a2a2a;
}

[data-theme="dark"] .family-card.kekule {
    background: linear-gradient(to right, #2a2a1a, #252525);
}

[data-theme="dark"] .family-card-name {
    color: #e0e0e0;
}

[data-theme="dark"] .family-card-meta {
    color: #888;
}

[data-theme="dark"] .verse-card {
    background: #252525;
    border-color: #333;
}

[data-theme="dark"] .verse-card-ref {
    color: #e0e0e0;
}

[data-theme="dark"] .verse-card-text {
    color: #bbb;
}

[data-theme="dark"] .biography-text {
    color: #ccc;
}

[data-theme="dark"] .biography-significance {
    color: #888;
    border-top-color: #333;
}

[data-theme="dark"] .event-item {
    border-bottom-color: #333;
}

[data-theme="dark"] .event-desc {
    color: #ccc;
}

[data-theme="dark"] .event-verse a {
    color: #888;
}

[data-theme="dark"] .bottom-nav {
    border-top-color: #333;
}

[data-theme="dark"] .bottom-nav a {
    background: #252525;
    border-color: #444;
    color: #ccc;
}

[data-theme="dark"] .bottom-nav a:hover {
    background: #2a2a2a;
    border-color: #555;
}

[data-theme="dark"] .bottom-nav a.primary {
    background: #4a7c59;
    border-color: #4a7c59;
    color: #fff;
}

[data-theme="dark"] .bottom-nav a.primary:hover {
    background: #3d6a4b;
}
</style>
{% endblock %}

{% block content %}
{% set female_names = ['eve', 'sarah', 'rebekah', 'rachel', 'leah', 'ruth', 'mary', 'tamar', 'rahab', 'bathsheba', 'dinah', 'keturah', 'hagar', 'zilpah', 'bilhah', 'jochebed', 'miriam', 'deborah', 'hannah', 'abigail', 'esther', 'naomi', 'naamah', 'milcah', 'adah', 'zillah', 'asenath', 'basemath'] %}
{% set is_female = person.name|lower in female_names or (female_names | select('in', person.name|lower) | list | length > 0) %}

<div class="person-page">
    <nav class="person-nav">
        <a href="/family-tree">← Family Tree</a>
        {% if person.generation %}
        <a href="/family-tree/generation/{{ person.generation }}">Generation {{ person.generation }}</a>
        {% endif %}
        <span class="nav-spacer"></span>
        <a href="/family-tree/interactive?person={{ person_id }}">Interactive Tree</a>
    </nav>

    <!-- Main Person Card -->
    <div class="person-main-card{% if person.kekule_number is not none %} kekule{% elif is_female %} female{% else %} male{% endif %}">
        <h1 class="person-name">
            {{ person.name }}
            {% if person.kekule_number is not none %}
            <span class="person-badge">Kekulé #{{ person.kekule_number }}</span>
            {% endif %}
        </h1>

        {% if person.generation %}
        <p class="person-subtitle">
            Generation {{ person.generation }} from Adam
            {% if person.kekule_number is not none %} · Ancestor of Jesus Christ{% endif %}
        </p>
        {% endif %}

        <div class="person-vitals">
            {% if person.birth_year != "Unknown" %}
            <div class="vital-item">
                <span class="vital-label">Born:</span>
                <span class="vital-value">{{ person.birth_year }}</span>
            </div>
            {% endif %}
            {% if person.death_year != "Unknown" %}
            <div class="vital-item">
                <span class="vital-label">Died:</span>
                <span class="vital-value">{{ person.death_year }}</span>
            </div>
            {% endif %}
            {% if person.age_at_death != "Unknown" %}
            <div class="vital-item">
                <span class="vital-label">Lifespan:</span>
                <span class="vital-value">{{ person.age_at_death }}</span>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- Biography (if available) -->
    {% if biography %}
    <div class="section-card">
        <h2>Biography</h2>
        <div class="biography-text">{{ biography.summary }}</div>
        {% if biography.significance %}
        <div class="biography-significance">{{ biography.significance }}</div>
        {% endif %}
    </div>
    {% endif %}

    <!-- Life Events (if available) -->
    {% if biography and biography.key_events %}
    <div class="section-card">
        <h2>Life Events</h2>
        {% for event in biography.key_events %}
        <div class="event-item">
            <div class="event-age">Age {{ event.age }}</div>
            <div class="event-desc">
                {{ event.event }}
                {% if event.verse %}
                <div class="event-verse">
                    {% set ref_parts = event.verse.split(' ') %}
                    {% if ref_parts|length >= 2 %}
                        {% set chapter_verse = ref_parts[-1] %}
                        {% if ':' in chapter_verse %}
                            {% set chapter = chapter_verse.split(':')[0] %}
                            {% set verse_part = chapter_verse.split(':')[1] %}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            <a href="/book/{{ book }}/chapter/{{ chapter }}#verse-{{ verse_part }}">{{ event.verse }}</a>
                        {% elif '-' in chapter_verse %}
                            {# Chapter range like "27-28" #}
                            {% set start_chapter = chapter_verse.split('-')[0] %}
                            {% set end_chapter = chapter_verse.split('-')[1] %}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            {{ book }} <a href="/book/{{ book }}/chapter/{{ start_chapter }}">{{ start_chapter }}</a>-<a href="/book/{{ book }}/chapter/{{ end_chapter }}">{{ end_chapter }}</a>
                        {% else %}
                            {# Single chapter like "27" #}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            <a href="/book/{{ book }}/chapter/{{ chapter_verse }}">{{ event.verse }}</a>
                        {% endif %}
                    {% else %}
                        {{ event.verse }}
                    {% endif %}
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <!-- Spouse -->
    {% if person.spouse %}
    <div class="section-card">
        <h2>Spouse</h2>
        <div class="family-grid">
            {% set ns = namespace(spouse_id=None, spouse_data=None) %}
            {% for pid, p in family_tree_data.items() %}
                {% if p.name == person.spouse %}
                    {% set ns.spouse_id = pid %}
                    {% set ns.spouse_data = p %}
                {% endif %}
            {% endfor %}
            {% set spouse_is_female = person.spouse|lower in female_names or (female_names | select('in', person.spouse|lower) | list | length > 0) %}
            <div class="family-card{% if ns.spouse_data and ns.spouse_data.kekule_number is not none %} kekule{% elif spouse_is_female %} female{% else %} male{% endif %}">
                <span class="family-card-name">
                    {% if ns.spouse_id %}
                    <a href="/family-tree/person/{{ ns.spouse_id }}">{{ person.spouse }}</a>
                    {% else %}
                    {{ person.spouse }}
                    {% endif %}
                </span>
                {% if ns.spouse_data %}
                    {% if ns.spouse_data.kekule_number is not none %}
                    <span class="family-card-badge">Kekulé #{{ ns.spouse_data.kekule_number }}</span>
                    {% endif %}
                    {% if ns.spouse_data.age_at_death != "Unknown" %}
                    <span class="family-card-meta">{{ ns.spouse_data.age_at_death }}</span>
                    {% endif %}
                {% endif %}
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Parents -->
    {% if person.parents|length > 0 %}
    <div class="section-card">
        <h2>Parents</h2>
        <div class="family-grid">
            {% for parent_id in person.parents %}
                {% if parent_id in family_tree_data %}
                {% set parent = family_tree_data[parent_id] %}
                {% set parent_is_female = parent.name|lower in female_names or (female_names | select('in', parent.name|lower) | list | length > 0) %}
                <div class="family-card{% if parent.kekule_number is not none %} kekule{% elif parent_is_female %} female{% else %} male{% endif %}">
                    <span class="family-card-name">
                        <a href="/family-tree/person/{{ parent_id }}">{{ parent.name }}</a>
                    </span>
                    {% if parent.kekule_number is not none %}
                    <span class="family-card-badge">Kekulé #{{ parent.kekule_number }}</span>
                    {% endif %}
                    {% if parent.age_at_death != "Unknown" %}
                    <span class="family-card-meta">{{ parent.age_at_death }}</span>
                    {% endif %}
                </div>
                {% endif %}
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Siblings -->
    {% if person.siblings|length > 0 %}
    <div class="section-card">
        <h2>Siblings ({{ person.siblings|length }})</h2>
        <div class="family-grid">
            {% for sibling_id in person.siblings %}
                {% if sibling_id in family_tree_data %}
                {% set sibling = family_tree_data[sibling_id] %}
                {% set sibling_is_female = sibling.name|lower in female_names or (female_names | select('in', sibling.name|lower) | list | length > 0) %}
                <div class="family-card{% if sibling.kekule_number is not none %} kekule{% elif sibling_is_female %} female{% else %} male{% endif %}">
                    <span class="family-card-name">
                        <a href="/family-tree/person/{{ sibling_id }}">{{ sibling.name }}</a>
                    </span>
                    {% if sibling.kekule_number is not none %}
                    <span class="family-card-badge">Kekulé #{{ sibling.kekule_number }}</span>
                    {% endif %}
                    {% if sibling.age_at_death != "Unknown" %}
                    <span class="family-card-meta">{{ sibling.age_at_death }}</span>
                    {% endif %}
                </div>
                {% endif %}
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Children -->
    {% if person.children|length > 0 %}
    <div class="section-card">
        <h2>Children ({{ person.children|length }})</h2>
        <div class="family-grid">
            {% for child_id in person.children %}
                {% if child_id in family_tree_data %}
                {% set child = family_tree_data[child_id] %}
                {% set child_is_female = child.name|lower in female_names or (female_names | select('in', child.name|lower) | list | length > 0) %}
                <div class="family-card{% if child.kekule_number is not none %} kekule{% elif child_is_female %} female{% else %} male{% endif %}">
                    <span class="family-card-name">
                        <a href="/family-tree/person/{{ child_id }}">{{ child.name }}</a>
                    </span>
                    {% if child.kekule_number is not none %}
                    <span class="family-card-badge">Kekulé #{{ child.kekule_number }}</span>
                    {% endif %}
                    {% if child.age_at_death != "Unknown" %}
                    <span class="family-card-meta">{{ child.age_at_death }}</span>
                    {% endif %}
                </div>
                {% endif %}
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Related Scriptures -->
    {% if person.verses %}
    <div class="section-card">
        <h2>Related Scriptures</h2>
        {% for verse in person.verses %}
        <div class="verse-card">
            <div class="verse-card-ref">
                {% if verse.reference %}
                    {% set ref_parts = verse.reference.split(' ') %}
                    {% if ref_parts|length >= 2 %}
                        {% set chapter_verse = ref_parts[-1] %}
                        {% if ':' in chapter_verse %}
                            {% set chapter = chapter_verse.split(':')[0] %}
                            {% set verse_part = chapter_verse.split(':')[1] %}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            <a href="/book/{{ book }}/chapter/{{ chapter }}#verse-{{ verse_part }}">{{ verse.reference }}</a>
                        {% elif '-' in chapter_verse %}
                            {# Chapter range like "27-28" #}
                            {% set start_chapter = chapter_verse.split('-')[0] %}
                            {% set end_chapter = chapter_verse.split('-')[1] %}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            {{ book }} <a href="/book/{{ book }}/chapter/{{ start_chapter }}">{{ start_chapter }}</a>-<a href="/book/{{ book }}/chapter/{{ end_chapter }}">{{ end_chapter }}</a>
                        {% else %}
                            {# Single chapter like "27" #}
                            {% set book = ' '.join(ref_parts[:-1]) %}
                            <a href="/book/{{ book }}/chapter/{{ chapter_verse }}">{{ verse.reference }}</a>
                        {% endif %}
                    {% else %}
                        {{ verse.reference }}
                    {% endif %}
                {% endif %}
            </div>
            {% if verse.text %}
            <div class="verse-card-text">"{{ verse.text }}"</div>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <!-- Bottom Navigation -->
    <div class="bottom-nav">
        <a href="/family-tree">← Family Tree</a>
        {% if person.generation %}
        <a href="/family-tree/generation/{{ person.generation }}">Generation {{ person.generation }}</a>
        {% endif %}
        {% if person.parents|length > 0 %}
        <a href="/family-tree/person/{{ person_id }}/ancestors">View Ancestors</a>
        {% endif %}
        {% if person.children|length > 0 %}
        <a href="/family-tree/person/{{ person_id }}/descendants">View Descendants</a>
        {% endif %}
        <a href="/family-tree/interactive?person={{ person_id }}" class="primary">Interactive Tree</a>
    </div>
</div>

<script>
(function() {
    // Two-level navigation: sections -> items within sections
    const sections = Array.from(document.querySelectorAll('.section-card'));
    const allItems = Array.from(document.querySelectorAll('.biography-text, .biography-significance, .event-item, .family-card, .verse-card'));

    if (sections.length === 0 && allItems.length === 0) return;

    let mode = 'sections'; // 'sections' or 'items'
    let selectedSectionIndex = -1;
    let selectedItemIndex = -1;

    function clearAllSelections() {
        sections.forEach(s => {
            s.style.outline = '';
            s.style.outlineOffset = '';
            s.classList.remove('selected');
        });
        allItems.forEach(i => {
            i.style.outline = '';
            i.style.outlineOffset = '';
            i.classList.remove('selected');
        });
    }

    function selectSection(index) {
        clearAllSelections();
        mode = 'sections';
        selectedSectionIndex = Math.max(0, Math.min(index, sections.length - 1));
        selectedItemIndex = -1;
        sections[selectedSectionIndex].style.outline = '2px solid #4a7c59';
        sections[selectedSectionIndex].style.outlineOffset = '4px';
        sections[selectedSectionIndex].classList.add('selected');
        sections[selectedSectionIndex].scrollIntoView({ behavior: 'auto', block: 'center' });
    }

    function selectItem(index) {
        clearAllSelections();
        mode = 'items';
        selectedItemIndex = Math.max(0, Math.min(index, allItems.length - 1));
        allItems[selectedItemIndex].style.outline = '2px solid #4a7c59';
        allItems[selectedItemIndex].style.outlineOffset = '4px';
        allItems[selectedItemIndex].classList.add('selected');
        allItems[selectedItemIndex].scrollIntoView({ behavior: 'auto', block: 'center' });
    }

    function getItemsInSection(section) {
        return allItems.filter(item => section.contains(item));
    }

    function findFirstItemInSection(section) {
        const items = getItemsInSection(section);
        if (items.length > 0) {
            return allItems.indexOf(items[0]);
        }
        return -1;
    }

    function findSectionForItem(item) {
        for (let i = 0; i < sections.length; i++) {
            if (sections[i].contains(item)) {
                return i;
            }
        }
        return -1;
    }

    function shouldResetToViewport() {
        if (mode === 'sections') {
            return selectedSectionIndex < 0 || !KJVNav.isInViewport(sections[selectedSectionIndex]);
        } else {
            return selectedItemIndex < 0 || !KJVNav.isInViewport(allItems[selectedItemIndex]);
        }
    }

    document.addEventListener('keydown', function(e) {
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
        if (KJVNav.sidebarActive) return;

        if (e.key === 'ArrowDown' || e.key === 'j') {
            e.preventDefault();
            if (shouldResetToViewport()) {
                // Find first visible section
                var visibleIdx = KJVNav.findFirstVisibleIndex(sections);
                selectSection(visibleIdx);
                return;
            }
            if (mode === 'sections') {
                selectSection(selectedSectionIndex + 1);
            } else {
                selectItem(selectedItemIndex + 1);
            }
        } else if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            if (shouldResetToViewport()) {
                var visibleIdx = KJVNav.findFirstVisibleIndex(sections);
                selectSection(visibleIdx);
                return;
            }
            if (mode === 'sections') {
                if (selectedSectionIndex <= 0) {
                    selectSection(0);
                } else {
                    selectSection(selectedSectionIndex - 1);
                }
            } else {
                if (selectedItemIndex <= 0) {
                    // Go back to section mode
                    var sectionIdx = findSectionForItem(allItems[0]);
                    if (sectionIdx >= 0) {
                        selectSection(sectionIdx);
                    }
                } else {
                    selectItem(selectedItemIndex - 1);
                }
            }
        } else if (e.key === 'ArrowRight' || e.key === 'l' || e.key === 'Enter') {
            e.preventDefault();
            if (mode === 'sections' && selectedSectionIndex >= 0) {
                // Drill into section items
                var firstItemIdx = findFirstItemInSection(sections[selectedSectionIndex]);
                if (firstItemIdx >= 0) {
                    selectItem(firstItemIdx);
                }
            } else if (mode === 'items' && selectedItemIndex >= 0) {
                // Follow link if available
                var link = allItems[selectedItemIndex].querySelector('a');
                if (link) window.location.href = link.href;
            }
        } else if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            if (mode === 'items') {
                // Go back to section mode
                var sectionIdx = findSectionForItem(allItems[selectedItemIndex]);
                if (sectionIdx >= 0) {
                    selectSection(sectionIdx);
                } else {
                    mode = 'sections';
                    selectedItemIndex = -1;
                }
            } else {
                history.back();
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            clearAllSelections();
            mode = 'sections';
            selectedSectionIndex = -1;
            selectedItemIndex = -1;
        }
    });
})();
</script>
{% endblock %}
