{% extends "base.html" %}

{% block title %}{{ book }} {{ chapter }} - KJV Bible{% endblock %}

{% block description %}Read {{ book }} chapter {{ chapter }} from the King James Version Bible. {{ verses[0].text[:100] if verses and verses|length > 0 else '' }}...{% endblock %}

{% block og_image %}https://kjvstudy.org/og/chapter/{{ book | urlencode }}/{{ chapter }}.png{% endblock %}
{% block twitter_image %}https://kjvstudy.org/og/chapter/{{ book | urlencode }}/{{ chapter }}.png{% endblock %}

{% block structured_data %}
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Home",
      "item": "https://kjvstudy.org"
    },
    {
      "@type": "ListItem",
      "position": 2,
      "name": "Books",
      "item": "https://kjvstudy.org/books"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": {{ book | tojson }},
      "item": "https://kjvstudy.org/book/{{ book | urlencode }}"
    },
    {
      "@type": "ListItem",
      "position": 4,
      "name": "Chapter {{ chapter }}"
    }
  ]
}
</script>
{% endblock %}

{% block head %}
<style>
/* Anchor offset for sticky breadcrumb */
[id^="verse-"] {
    scroll-margin-top: 5rem;
}

/* Poetry formatting (Psalms, Job, Proverbs, etc.) */
.poetry-chapter p.verse-line {
    display: block;
    margin-bottom: 0.5em;
    line-height: 1.7;
    width: 55%;
}

@media (max-width: 760px) {
    .poetry-chapter p.verse-line {
        width: 100%;
    }

    p[id^="verse-"] {
        font-size: 1.4rem !important;
        line-height: 2 !important;
    }

    /* Verse numbers: larger tap target */
    a.verse-number-link {
        display: inline-block;
        min-width: 32px;
        min-height: 32px;
        padding: 4px 8px;
        margin-right: 4px;
        font-size: 1rem;
        text-align: center;
        vertical-align: baseline;
        border-radius: 4px;
        background: var(--code-bg, #f5f5f5);
    }

    a.verse-number-link,
    a.verse-number-link:visited,
    a.verse-number-link:hover,
    a.verse-number-link:active {
        text-decoration: none !important;
        border-bottom: none !important;
    }

    a.verse-number-link:active {
        background: var(--border-color-darker, #ccc);
    }

    /* Section headings */
    .section-heading {
        font-size: 1.1rem;
        margin-top: 2rem;
        margin-bottom: 1rem;
    }

}

.poetry-chapter .stanza-break {
    margin-top: 3.5em;
}

/* Stanza break with section heading - wrapper gets the break styling */
.poetry-chapter .stanza-break-with-heading {
    margin-top: 3.5em;
}

.poetry-chapter .stanza-break-with-heading .section-heading {
    margin-top: 0;
}

/* Red Letter Edition - Words of Christ */
.words-of-christ {
    color: #c41e3a;
}

/* Dark mode for .words-of-christ is in base.html */

/* Links inside red letter text should also be red */
.words-of-christ a {
    color: #c41e3a;
    text-decoration: underline;
}

[data-theme="dark"] .words-of-christ a {
    color: #ff6b6b;
}

/* Prevent sidenotes from inheriting red color */
.words-of-christ .sidenote,
.words-of-christ .marginnote,
.words-of-christ .sidenote-number,
.words-of-christ label.sidenote-number {
    color: var(--text-color);
}

/* Prevent links in sidenotes from being red */
.words-of-christ .sidenote a,
.words-of-christ .marginnote a {
    color: var(--link-color, #0066cc);
}

[data-theme="dark"] .words-of-christ .sidenote,
[data-theme="dark"] .words-of-christ .marginnote,
[data-theme="dark"] .words-of-christ .sidenote-number,
[data-theme="dark"] .words-of-christ label.sidenote-number {
    color: var(--text-color);
}

[data-theme="dark"] .words-of-christ .sidenote a,
[data-theme="dark"] .words-of-christ .marginnote a {
    color: var(--link-color, #6db3f2);
}

.sidenote,
.marginnote {
    max-height: 150px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

/* Highlight sidenote when its checkbox is checked */
.margin-toggle:checked + .sidenote,
.margin-toggle:checked + .marginnote {
    background-color: rgba(255, 237, 160, 0.3);
    border-left: 3px solid rgba(255, 193, 7, 0.6);
    padding-left: 0.5rem;
    margin-left: -0.5rem;
}

[data-theme="dark"] .margin-toggle:checked + .sidenote,
[data-theme="dark"] .margin-toggle:checked + .marginnote {
    background-color: rgba(255, 193, 7, 0.15);
    border-left: 3px solid rgba(255, 193, 7, 0.5);
}

.sidenote.expanded,
.marginnote.expanded {
    max-height: none;
    overflow: visible;
}

.sidenote.truncated:not(.expanded)::after,
.marginnote.truncated:not(.expanded)::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 60px;
    background: linear-gradient(to bottom, transparent, var(--bg-color));
    pointer-events: none;
}

.marginnote {
    margin-top: 0.3rem;
    margin-bottom: 1rem;
}

/* Word studies: collapsed by default, show only word + Greek term */
.sidenote.word-study {
    max-height: none;
    overflow: visible;
    cursor: pointer;
}

.sidenote.word-study .word-study-details {
    display: none !important;
}

.sidenote.word-study.expanded .word-study-details {
    display: inline !important;
}

/* Show expand indicator for collapsed word studies */
.sidenote.word-study:not(.expanded)::after {
    content: " ▸";
    font-size: 0.8em;
    color: var(--text-secondary);
}

.sidenote.word-study.expanded::after {
    content: "";
}

/* Prevent sidenotes from pushing each other horizontally */
.sidenote, .marginnote {
    clear: right;
    margin-bottom: 1rem;
}

/* Cross-refs: collapsed by default, show just first ref per group */
.sidenote.cross-refs {
    cursor: pointer;
}

/* Extra refs hidden by default */
.sidenote.cross-refs .xref-extra {
    display: none;
}

/* Show extra refs when expanded */
.sidenote.cross-refs.expanded .xref-extra {
    display: inline;
}

/* Hide the +N indicator when expanded */
.sidenote.cross-refs.expanded .xref-more {
    display: none;
}

.xref-more {
    font-size: 0.85em;
    color: var(--text-secondary);
    font-style: italic;
    cursor: pointer;
}

@media (max-width: 760px) {
    .sidenote,
    .marginnote {
        max-height: 120px;
    }
}

hr {
    border: 0;
    height: 0;
    text-align: center;
    margin: 2em 0;
}

hr::before {
    content: "⁂";
    font-size: 1.5rem;
    letter-spacing: 0.6em;
    color: var(--text-color);
}

/* Section headings - like study Bible pericopes */
.section-heading {
    font-family: et-book, Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;
    font-size: 1.1rem;
    font-weight: normal;
    font-style: italic;
    color: var(--text-secondary, #666);
    margin: 1.8rem 0 0.6rem 0;
    padding: 0;
    border: none;
    letter-spacing: 0.02em;
}

.section-heading:first-child {
    margin-top: 0;
}

[data-theme="dark"] .section-heading {
    color: #a0a0a0;
}

.verse-number-link {
    font-family: et-book-roman-old-style;
    font-size: 1rem;
    vertical-align: super;
    text-decoration: none;
    color: inherit;
    position: relative;
    top: -0.5rem;
    left: 0.1rem;
    margin-right: 0.2rem;
    user-select: none;
}

.verse-number-link:hover {
    color: #111;
    text-decoration: underline;
}

/* Verses have normal text selection cursor */
p[id^="verse-"] {
    cursor: text;
}

/* Keyboard navigation selected verse */
p[id^="verse-"].selected {
    background: rgba(74, 124, 89, 0.1);
    margin-left: -1rem;
    padding-left: 1rem;
    border-left: 3px solid #4a7c59;
    transition: all 0.15s ease;
}

[data-theme="dark"] p[id^="verse-"].selected {
    background: rgba(107, 155, 122, 0.15);
    border-left-color: #6b9b7a;
}

/* Keyboard navigation selected action button */
.action-btn.selected {
    outline: 2px solid #4a7c59;
    outline-offset: 4px;
}

[data-theme="dark"] .action-btn.selected {
    outline-color: #6b9b7a;
}

.verse-number-link.has-commentary {
    color: #c41e3a !important;
}

[data-theme="dark"] .verse-number-link.has-commentary {
    color: #ff6b6b !important;
}

/* Prevent sidenote numbers from appearing too close to verse numbers */
.verse-number-link + label.sidenote-number {
    margin-left: 0.3rem;
}

.chapter-nav {
    max-width: 60%;
    margin: 2rem 0;
    padding: 1.5rem 0;
}

.chapter-nav-controls {
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
}

.chapter-nav-btn {
    padding: 0.5rem 1rem;
    font-size: 0.95rem;
    font-weight: 600;
    background: var(--bg-color);
    color: var(--text-color);
    border: 1px solid var(--border-color-darker);
    border-radius: 4px;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-block;
}

.chapter-nav-btn:hover {
    background: var(--code-bg);
    border-color: var(--text-secondary);
    color: var(--link-hover);
}

.chapter-nav-btn.secondary {
    background: transparent;
    color: var(--text-secondary);
    border: 1px solid var(--border-color);
}

.chapter-nav-btn.secondary:hover {
    background: var(--code-bg);
    border-color: var(--border-color-darker);
    color: var(--text-color);
}

.chapter-select {
    padding: 0.5rem;
    font-size: 0.95rem;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    background: var(--bg-color);
    color: var(--text-color);
    font-family: inherit;
    cursor: pointer;
}

.chapter-select:focus {
    outline: none;
    border-color: var(--link-color);
}

.nav-help {
    font-size: 0.85rem;
    color: var(--text-secondary);
    font-style: italic;
    margin-top: 0.75rem;
}

.chapter-actions {
    margin: 1.5rem 0 1rem;
    display: flex;
    gap: 0.5rem;
}

.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.45rem 0.9rem;
    font-size: 0.9rem;
    color: var(--text-secondary);
    background: var(--code-bg);
    border: 1px solid var(--border-color);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
}

.action-btn:hover {
    background: var(--bg-color);
    border-color: var(--link-color);
    color: var(--link-color);
    text-decoration: none;
}

.action-btn svg {
    width: 16px;
    height: 16px;
}

.interlinear-btn:hover {
    border-color: #4a7c59;
    color: #4a7c59;
}

@media print {
    .chapter-actions,
    .action-btn {
        display: none;
    }
}

/* Mobile optimizations */
@media (max-width: 768px) {
    .chapter-nav {
        max-width: calc(100% - 2rem);
        padding: 1rem;
        margin: 1.5rem 0;
    }

    .chapter-nav-controls {
        gap: 0.75rem;
    }

    .chapter-nav-btn {
        padding: 0.75rem 1rem;
        font-size: 1rem;
        min-height: 44px;
        text-align: center;
    }

    .chapter-select {
        padding: 0.75rem;
        font-size: 1rem;
        min-height: 44px;
        flex: 1;
    }

    .nav-help {
        display: none;
    }

    .chapter-actions {
        gap: 0.5rem;
        flex-wrap: wrap;
    }

    .action-btn {
        padding: 0.6rem 0.8rem;
        font-size: 0.85rem;
        min-height: 44px;
    }

    .verse-number-link {
        font-size: 0.85rem;
        padding: 0.25rem;
        margin-right: 0.15rem;
    }
}

@media (max-width: 480px) {
    .chapter-nav-controls {
        flex-direction: column;
        gap: 0.5rem;
    }

    .chapter-nav-btn {
        width: 100%;
    }

    .chapter-select {
        width: 100%;
    }

    .chapter-actions {
        justify-content: center;
    }

    .action-btn {
        flex: 1;
        justify-content: center;
    }
}
</style>
{% endblock %}

{% block content %}
<script>
// Use chapter-specific reader logic; disable global resource reader on this page
document.body.dataset.resourceReader = 'false';
</script>
<h1>{{ book }} {{ chapter }}</h1>
<p class="subtitle"><a href="/books">Authorized King James Version</a></p>

<div class="chapter-actions">
    <a href="/book/{{ book }}/chapter/{{ chapter }}/interlinear" class="action-btn interlinear-btn">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
        </svg>
        Interlinear
    </a>
    {% if pdf_available %}
    <a href="/book/{{ book }}/chapter/{{ chapter }}/pdf" class="action-btn pdf-btn">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        PDF
    </a>
    {% endif %}
    <button class="action-btn listen-btn" id="chapter-listen-btn">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
        </svg>
        Listen
    </button>
</div>

<section{% if is_poetry %} class="poetry-chapter"{% endif %}>
{% for verse in verses %}
{% set commentary = commentaries[verse.verse] if commentaries and verse.verse in commentaries else none %}
{% set has_commentary = commentary and (commentary.get('is_enhanced') or commentary.get('analysis')) %}
{% set has_stanza_break = is_poetry and verse.verse in stanza_breaks %}
{% set has_section_heading = section_headings and verse.verse in section_headings %}
    {% if has_stanza_break and has_section_heading %}
    <div class="stanza-break-with-heading">
    <h3 class="section-heading">{{ section_headings[verse.verse] }}</h3>
    {% elif has_section_heading %}
    <h3 class="section-heading">{{ section_headings[verse.verse] }}</h3>
    {% elif has_stanza_break %}
    {# stanza break without heading - handled on verse p tag #}
    {% endif %}
    <p id="verse-{{ verse.verse }}"{% if is_poetry %} class="verse-line{% if has_stanza_break and not has_section_heading %} stanza-break{% endif %}"{% endif %}>
        <a href="/book/{{ book }}/chapter/{{ chapter }}/verse/{{ verse.verse }}" class="verse-number-link{% if has_commentary %} has-commentary{% endif %}">{{ verse.verse }}</a> {{ verse.text | red_letter(book, chapter, verse.verse) | inject_word_markers(commentary.word_studies if commentary else [], verse.verse, commentary.word_study_auto_expand if commentary else false) | safe }}
        {% if commentary %}
            {% if commentary.cross_reference_groups %}
                {# Flatten refs with their group info for counting #}
                {% set ns = namespace(all_refs=[], ref_count=0) %}
                {% for group in commentary.cross_reference_groups %}
                    {% for ref in group.refs %}
                        {% set ns.all_refs = ns.all_refs + [{'ref': ref, 'group': group.description, 'group_idx': loop.index0, 'is_first_in_group': loop.first}] %}
                        {% set ns.ref_count = ns.ref_count + 1 %}
                    {% endfor %}
                {% endfor %}
                {% set total_refs = ns.ref_count %}
                {# Show all if 6 or fewer (avoid "+1"), otherwise show 5 with expand #}
                {% set preview_count = total_refs if total_refs <= 6 else 5 %}
                {% set extra_count = total_refs - preview_count %}
                <label for="sn-{{ verse.verse }}-xrefs" class="margin-toggle sidenote-number"></label>
                <input type="checkbox" id="sn-{{ verse.verse }}-xrefs" class="margin-toggle"/>
                <span class="sidenote cross-refs{% if commentary.xref_auto_expand %} expanded{% endif %}">{% for item in ns.all_refs[:preview_count] %}{% if item.is_first_in_group %}{% if not loop.first %}. {% endif %}<strong>{{ item.group }}:</strong> {% endif %}<a href="{{ item.ref.url }}">{{ item.ref.display }}</a>{% if not loop.last and not ns.all_refs[loop.index].is_first_in_group %}, {% endif %}{% endfor %}{% if extra_count > 0 %}<span class="xref-extra">{% for item in ns.all_refs[preview_count:] %}{% if item.is_first_in_group %}. <strong>{{ item.group }}:</strong> {% elif loop.first %}, {% endif %}<a href="{{ item.ref.url }}">{{ item.ref.display }}</a>{% if not loop.last and not ns.all_refs[preview_count + loop.index].is_first_in_group %}, {% endif %}{% endfor %}</span><span class="xref-more"> +{{ extra_count }}</span>{% endif %}</span>
            {% endif %}
        {% endif %}
    </p>
    {% if has_stanza_break and has_section_heading %}
    </div>
    {% endif %}
    {% endfor %}
</section>

<nav class="chapter-nav">
    <div class="chapter-nav-controls">
        {% if chapter > 1 %}
        <a href="/book/{{ book }}/chapter/{{ chapter - 1 }}" class="chapter-nav-btn" id="prev-chapter">
            ← Previous
        </a>
        {% endif %}

        <select class="chapter-select" onchange="if(this.value) window.location.href=this.value">
            <option value="">Jump to chapter...</option>
            {% for ch in chapters %}
            <option value="/book/{{ book }}/chapter/{{ ch }}"{% if ch == chapter %} selected{% endif %}>
                Chapter {{ ch }}
            </option>
            {% endfor %}
        </select>

        {% if chapter < chapters|length %}
        <a href="/book/{{ book }}/chapter/{{ chapter + 1 }}" class="chapter-nav-btn" id="next-chapter">
            Next →
        </a>
        {% endif %}

        <a href="/book/{{ book }}" class="chapter-nav-btn secondary">
            {{ book }}
        </a>
    </div>
    <div class="nav-help">
        Tip: ↑/↓ to select verses • Enter to open • double-click verse text • ? for more shortcuts
    </div>
</nav>

{% if pdf_available %}
{% endif %}

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Listen button - read chapter aloud
    var listenBtn = document.getElementById('chapter-listen-btn');
    var isListening = false;

    if (listenBtn) {
        listenBtn.addEventListener('click', function() {
            if (isListening) {
                if (window.KJVSpeech) window.KJVSpeech.stop();
                listenBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" /></svg> Listen';
                isListening = false;
                return;
            }

            // Gather all verse text
            var verses = document.querySelectorAll('p[id^="verse-"]');
            var text = Array.from(verses).map(function(v) {
                return v.textContent.replace(/^\d+\s*/, '').trim();
            }).join('. ');

            if (window.KJVSpeech && text) {
                window.KJVSpeech.speak(text);
                listenBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z" /></svg> Stop';
                isListening = true;
            }
        });
    }

    // Function to link verse references
    function linkVerseReferences(element) {
        let html = element.innerHTML;

        // Match patterns like "Verse 1", "Verses 1-5", "verse 12", etc.
        html = html.replace(/\b(Verse|verse)s?\s+(\d+)(?:-(\d+))?\b/g, function(match, word, start, end) {
            if (end) {
                return '<a href="#verse-' + start + '-' + end + '">' + match + '</a>';
            } else {
                return '<a href="#verse-' + start + '">' + match + '</a>';
            }
        });

        element.innerHTML = html;
    }

    const sidenotes = document.querySelectorAll('.sidenote, .marginnote');

    // Make sidenotes and marginnotes expandable and link verse references
    sidenotes.forEach(function(sidenote) {
        // Check if content is actually truncated
        if (sidenote.scrollHeight > sidenote.clientHeight) {
            sidenote.classList.add('truncated');
        }

        sidenote.addEventListener('click', function(e) {
            // Don't expand if clicking a link
            if (e.target.tagName !== 'A') {
                this.classList.toggle('expanded');
            }
        });

        linkVerseReferences(sidenote);
    });

    // Handle verse ranges in URL hash
    function highlightVerses() {
        const hash = window.location.hash.substring(1); // Remove the #
        if (hash.startsWith('verse-')) {
            const versePart = hash.substring(6); // Remove 'verse-'
            const rangeParts = versePart.split('-');

            if (rangeParts.length === 2) {
                // Verse range (e.g., verse-22-23)
                const start = parseInt(rangeParts[0]);
                const end = parseInt(rangeParts[1]);

                for (let i = start; i <= end; i++) {
                    const verseEl = document.getElementById('verse-' + i);
                    if (verseEl) {
                        verseEl.style.backgroundColor = 'rgba(255, 235, 59, 0.2)';
                    }
                }

                // Scroll to first verse
                const firstVerse = document.getElementById('verse-' + start);
                if (firstVerse) {
                    firstVerse.scrollIntoView({ behavior: 'auto', block: 'center' });
                }
            } else {
                // Single verse
                const verseEl = document.getElementById('verse-' + versePart);
                if (verseEl) {
                    verseEl.style.backgroundColor = 'rgba(255, 235, 59, 0.2)';
                    verseEl.scrollIntoView({ behavior: 'auto', block: 'center' });
                }
            }
        }
    }

    highlightVerses();
    window.addEventListener('hashchange', highlightVerses);

    // Two-zone navigation: action buttons and verses
    const actionButtons = Array.from(document.querySelectorAll('.chapter-actions .action-btn'));
    const verses = document.querySelectorAll('p[id^="verse-"]');
    let selectedVerseIndex = -1;
    let selectedActionIndex = -1;
    let inActionZone = false;
    let chapterReader = { active: false, index: -1, utterance: null };

    // Initialize from hash if present (e.g., #verse-24)
    function initFromHash() {
        const hash = window.location.hash;
        if (hash && hash.startsWith('#verse-')) {
            const verseNum = parseInt(hash.substring(7));
            if (!isNaN(verseNum)) {
                // Find the index of this verse
                for (let i = 0; i < verses.length; i++) {
                    const verseId = verses[i].id;
                    if (verseId === 'verse-' + verseNum) {
                        selectedVerseIndex = i;
                        verses[i].classList.add('selected');
                        break;
                    }
                }
            }
        }
    }

    initFromHash();

    function clearAllSelections() {
        if (selectedVerseIndex >= 0 && selectedVerseIndex < verses.length) {
            verses[selectedVerseIndex].classList.remove('selected');
        }
        actionButtons.forEach(btn => btn.classList.remove('selected'));
    }

    function selectAction(index) {
        clearAllSelections();
        inActionZone = true;
        selectedActionIndex = Math.max(0, Math.min(index, actionButtons.length - 1));
        selectedVerseIndex = -1;
        actionButtons[selectedActionIndex].classList.add('selected');
        actionButtons[selectedActionIndex].scrollIntoView({
            behavior: 'auto',
            block: 'center'
        });
    }

    function selectVerse(index) {
        clearAllSelections();
        inActionZone = false;
        selectedActionIndex = -1;

        // Update index with bounds checking
        selectedVerseIndex = Math.max(0, Math.min(index, verses.length - 1));

        // Add selection to new verse
        verses[selectedVerseIndex].classList.add('selected');

        // Scroll into view with instant behavior to prevent stuttering when holding down keys
        verses[selectedVerseIndex].scrollIntoView({
            behavior: 'auto',
            block: 'center'
        });
    }

    function getVerseText(verseEl) {
        const clone = verseEl.cloneNode(true);
        clone.querySelectorAll('.sidenote, .marginnote, .sidenote-number, .margin-toggle').forEach(el => el.remove());
        let text = clone.textContent || clone.innerText || '';
        text = text.replace(/^\s*\d+\s*/, '').trim();
        return text;
    }

    function stopChapterReading() {
        if ('speechSynthesis' in window) {
            speechSynthesis.cancel();
        }
        chapterReader.active = false;
        chapterReader.index = -1;
        chapterReader.utterance = null;
    }

    function readVerseAt(index) {
        if (!('speechSynthesis' in window)) return;
        if (index < 0 || index >= verses.length) {
            stopChapterReading();
            return;
        }

        const text = getVerseText(verses[index]);
        if (!text) {
            readVerseAt(index + 1);
            return;
        }

        const utter = new SpeechSynthesisUtterance(text);
        const voices = speechSynthesis.getVoices();
        const englishVoice = voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en') && v.name.includes('Daniel')) ||
                             voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en-gb')) ||
                             voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en'));
        if (englishVoice) utter.voice = englishVoice;

        utter.onend = function() {
            readVerseAt(index + 1);
        };
        utter.onerror = function() {
            stopChapterReading();
        };

        chapterReader.active = true;
        chapterReader.index = index;
        chapterReader.utterance = utter;

        speechSynthesis.cancel();
        speechSynthesis.speak(utter);
    }

    function startChapterReading() {
        if (!('speechSynthesis' in window)) return;
        if (chapterReader.active) {
            stopChapterReading();
            return;
        }
        if (window.KJVSpeech && typeof window.KJVSpeech.stop === 'function') {
            window.KJVSpeech.stop();
        }
        const startIndex = selectedVerseIndex >= 0 ? selectedVerseIndex : 0;
        readVerseAt(startIndex);
    }

    // Keyboard navigation for chapters and verses
    document.addEventListener('keydown', function(e) {
        // Don't trigger if user is typing
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') {
            return;
        }
        // Don't handle if sidebar navigation is active
        if (KJVNav.sidebarActive) return;

        // Up arrow or k: Previous item
        if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            if (inActionZone) {
                // Move within action buttons or stay at first
                if (selectedActionIndex > 0) {
                    selectAction(selectedActionIndex - 1);
                }
            } else if (selectedVerseIndex === 0 && actionButtons.length > 0) {
                // At first verse, move to action buttons
                selectAction(actionButtons.length - 1);
            } else if (selectedVerseIndex < 0) {
                // No selection, start at first verse (viewport-aware)
                selectVerse(KJVNav.findFirstVisibleIndex(Array.from(verses)));
            } else if (KJVNav.isSelectionOffScreen(Array.from(verses), selectedVerseIndex)) {
                selectVerse(KJVNav.findFirstVisibleIndex(Array.from(verses)));
            } else {
                selectVerse(selectedVerseIndex - 1);
            }
        }

        // Down arrow or j: Next item
        if (e.key === 'ArrowDown' || e.key === 'j') {
            e.preventDefault();
            if (inActionZone) {
                // Move within action buttons or to verses
                if (selectedActionIndex < actionButtons.length - 1) {
                    selectAction(selectedActionIndex + 1);
                } else {
                    // Move to first verse
                    selectVerse(0);
                }
            } else if (selectedVerseIndex < 0) {
                // No selection, start at first verse (initial down starts with verses, not actions)
                selectVerse(KJVNav.findFirstVisibleIndex(Array.from(verses)));
            } else if (KJVNav.isSelectionOffScreen(Array.from(verses), selectedVerseIndex)) {
                selectVerse(KJVNav.findFirstVisibleIndex(Array.from(verses)));
            } else {
                selectVerse(selectedVerseIndex + 1);
            }
        }

        // Enter: Navigate to selected item
        if (e.key === 'Enter') {
            e.preventDefault();
            if (inActionZone && selectedActionIndex >= 0) {
                window.location.href = actionButtons[selectedActionIndex].href;
            } else if (selectedVerseIndex >= 0) {
                const link = verses[selectedVerseIndex].querySelector('.verse-number-link');
                if (link) window.location.href = link.href;
            }
        }

        // Left arrow or h: Navigate action buttons or go back
        if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            if (inActionZone) {
                // Move between action buttons
                if (selectedActionIndex > 0) {
                    selectAction(selectedActionIndex - 1);
                }
            } else {
                history.back();
            }
        }

        // Right arrow or l: Navigate action buttons or chapters
        if (e.key === 'ArrowRight' || e.key === 'l') {
            if (inActionZone) {
                // Move between action buttons
                e.preventDefault();
                if (selectedActionIndex < actionButtons.length - 1) {
                    selectAction(selectedActionIndex + 1);
                }
            } else {
                const nextBtn = document.getElementById('next-chapter');
                if (nextBtn) {
                    e.preventDefault();
                    window.location.href = nextBtn.href;
                }
            }
        }

        // Escape: Clear selection
        if (e.key === 'Escape') {
            e.preventDefault();
            clearAllSelections();
            selectedVerseIndex = -1;
            selectedActionIndex = -1;
            inActionZone = false;
            stopChapterReading();
        }

        // i: Go to interlinear view
        if (e.key === 'i') {
            e.preventDefault();
            var interlinearBtn = document.querySelector('.interlinear-btn');
            if (interlinearBtn) window.location.href = interlinearBtn.href;
        }

        // p: Download PDF
        if (e.key === 'p') {
            e.preventDefault();
            var pdfBtn = document.querySelector('.pdf-btn');
            if (pdfBtn) window.location.href = pdfBtn.href;
        }

        // [ : Previous chapter
        if (e.key === '[') {
            e.preventDefault();
            var prevBtn = document.getElementById('prev-chapter');
            if (prevBtn) window.location.href = prevBtn.href;
        }

        // ] : Next chapter
        if (e.key === ']') {
            e.preventDefault();
            var nextBtn = document.getElementById('next-chapter');
            if (nextBtn) window.location.href = nextBtn.href;
        }

        // = : Read whole chapter with autoadvance
        if (!e.metaKey && !e.ctrlKey && !e.altKey && e.key === '=') {
            e.preventDefault();
            startChapterReading();
        }

        // Space: Read selected verse; if none selected, read whole chapter
        if (e.key === ' ') {
            e.preventDefault();
            if (chapterReader.active) {
                stopChapterReading();
                return;
            }
            if (selectedVerseIndex >= 0) {
                if (window.KJVSpeech && typeof window.KJVSpeech.stop === 'function') {
                    window.KJVSpeech.stop();
                }
                var verseEl = verses[selectedVerseIndex];
                var text = getVerseText(verseEl);
                if (window.KJVSpeech && typeof window.KJVSpeech.toggle === 'function') {
                    KJVSpeech.toggle(text);
                }
            } else {
                startChapterReading();
            }
        }
    });

    // Double-click on verse text navigates to verse page (mouse users)
    // Single click allows text selection; green selection is only for keyboard navigation
    verses.forEach((verse, index) => {
        verse.addEventListener('dblclick', function(e) {
            // Let links and labels handle their own clicks
            if (e.target.tagName === 'A' || e.target.tagName === 'LABEL') {
                return;
            }
            // Navigate to verse page on double-click
            const verseNum = verse.id.replace('verse-', '');
            window.location.href = `/book/{{ book }}/chapter/{{ chapter }}/verse/${verseNum}`;
        });
    });

    // Clean copied text to exclude sidenotes, verse numbers, and margin elements
    document.addEventListener('copy', function(e) {
        const selection = window.getSelection();
        if (!selection.rangeCount) return;

        const range = selection.getRangeAt(0);
        const fragment = range.cloneContents();

        // Create a temporary container
        const temp = document.createElement('div');
        temp.appendChild(fragment);

        // Remove sidenotes, marginnotes, labels, and verse number links
        temp.querySelectorAll('.sidenote, .marginnote, .sidenote-number, .margin-toggle, .verse-number-link').forEach(el => el.remove());

        // Process each verse paragraph separately to preserve line breaks between verses
        const verseParagraphs = temp.querySelectorAll('p[id^="verse-"]');
        let cleanText;

        if (verseParagraphs.length > 0) {
            // Multiple verses selected - join with newlines
            const verseTexts = Array.from(verseParagraphs).map(p => {
                return (p.textContent || p.innerText || '').replace(/\s+/g, ' ').trim();
            }).filter(t => t);
            cleanText = verseTexts.join('\n');
        } else {
            // Single partial selection - normalize whitespace
            cleanText = (temp.textContent || temp.innerText || '').replace(/\s+/g, ' ').trim();
        }

        if (cleanText) {
            e.preventDefault();
            e.clipboardData.setData('text/plain', cleanText);
        }
    });

    // Only allow one sidenote to be highlighted at a time
    document.querySelectorAll('.margin-toggle').forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                // Uncheck all other margin-toggle checkboxes
                document.querySelectorAll('.margin-toggle').forEach(function(otherCheckbox) {
                    if (otherCheckbox !== checkbox) {
                        otherCheckbox.checked = false;
                    }
                });
            }
        });
    });

    // Swipe gestures for chapter navigation (mobile)
    let touchStartX = 0;
    let touchEndX = 0;
    const minSwipeDistance = 80;

    document.addEventListener('touchstart', function(e) {
        touchStartX = e.changedTouches[0].screenX;
    }, { passive: true });

    document.addEventListener('touchend', function(e) {
        touchEndX = e.changedTouches[0].screenX;
        const swipeDistance = touchEndX - touchStartX;

        // Swipe right (prev chapter)
        if (swipeDistance > minSwipeDistance) {
            const prevBtn = document.getElementById('prev-chapter');
            if (prevBtn) window.location.href = prevBtn.href;
        }
        // Swipe left (next chapter)
        else if (swipeDistance < -minSwipeDistance) {
            const nextBtn = document.getElementById('next-chapter');
            if (nextBtn) window.location.href = nextBtn.href;
        }
    }, { passive: true });
});
</script>

{% if related_content and (related_content.topics or related_content.people or related_content.resources or related_content.stories) %}
<div id="related-resources" style="border-top: 1px solid var(--border-color); padding-top: 2rem; margin-top: 3rem;">
    <h2 id="related-resources-heading">Related Resources</h2>
    <p style="font-size: 0.95rem; color: var(--text-secondary); margin-bottom: 1.5rem;">
        Explore related topics, people, and study resources to deepen your understanding of this chapter.
    </p>

    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1.5rem;">
        {% if related_content.topics %}
        <div>
            <h3 style="font-size: 1rem; margin-bottom: 0.75rem; color: var(--text-secondary);">Topics</h3>
            <ul style="list-style: none; padding: 0; margin: 0;">
                {% for topic in related_content.topics %}
                <li style="margin-bottom: 0.5rem;">
                    <a href="{{ topic.url }}" style="font-size: 0.95rem;">{{ topic.name }}</a>
                </li>
                {% endfor %}
            </ul>
        </div>
        {% endif %}

        {% if related_content.people %}
        <div>
            <h3 style="font-size: 1rem; margin-bottom: 0.75rem; color: var(--text-secondary);">People</h3>
            <ul style="list-style: none; padding: 0; margin: 0;">
                {% for person in related_content.people %}
                <li style="margin-bottom: 0.5rem;">
                    <a href="{{ person.url }}" style="font-size: 0.95rem;">{{ person.name }}</a>
                </li>
                {% endfor %}
            </ul>
        </div>
        {% endif %}

        {% if related_content.resources %}
        <div>
            <h3 style="font-size: 1rem; margin-bottom: 0.75rem; color: var(--text-secondary);">Study Resources</h3>
            <ul style="list-style: none; padding: 0; margin: 0;">
                {% for resource in related_content.resources %}
                <li style="margin-bottom: 0.5rem;">
                    <a href="{{ resource.url }}" style="font-size: 0.95rem;">{{ resource.name }}</a>
                </li>
                {% endfor %}
            </ul>
        </div>
        {% endif %}

        {% if related_content.stories %}
        <div>
            <h3 style="font-size: 1rem; margin-bottom: 0.75rem; color: var(--text-secondary);">Bible Stories</h3>
            <ul style="list-style: none; padding: 0; margin: 0;">
                {% for story in related_content.stories %}
                <li style="margin-bottom: 0.5rem;">
                    <a href="{{ story.url }}" style="font-size: 0.95rem;">{{ story.name }}</a>
                </li>
                {% endfor %}
            </ul>
        </div>
        {% endif %}

    </div>
</div>
{% endif %}

{% endblock %}
