{% extends "base.html" %}

{% block title %}{{ story.title }} - Bible Stories - KJV Study{% endblock %}
{% block description %}{{ story.description }}{% endblock %}

{% block og_type %}article{% endblock %}
{% block og_title %}{{ story.title }} - Bible Story{% endblock %}
{% block og_description %}{{ story.description }}{% endblock %}
{% block og_image %}https://kjvstudy.org/og/story/{{ story.slug }}.png{% endblock %}
{% block twitter_image %}https://kjvstudy.org/og/story/{{ story.slug }}.png{% endblock %}

{% block structured_data %}
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": {{ story.title | tojson }},
  "description": {{ story.description | tojson }},
  "author": {
    "@type": "Organization",
    "name": "KJV Study"
  },
  "publisher": {
    "@type": "Organization",
    "name": "KJV Study",
    "url": "https://kjvstudy.org"
  },
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "https://kjvstudy.org{{ request.url.path }}"
  },
  "about": {
    "@type": "Thing",
    "name": "Bible Story"
  }
}
</script>
<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": "Bible Stories",
      "item": "https://kjvstudy.org/stories"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": {{ story.title | tojson }}
    }
  ]
}
</script>
{% endblock %}

{% block head %}
<style>
/* Story header */
.story-header {
    margin-bottom: 2rem;
}
.story-header .category-link {
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--link-color);
    text-decoration: none;
}
.story-header .category-link:hover {
    text-decoration: underline;
}
.story-header h1 {
    margin: 0.5rem 0;
}
.story-header .description {
    font-size: 1.2rem;
    color: var(--text-secondary, #555);
    line-height: 1.6;
    max-width: 55ch;
}
.story-actions {
    display: flex;
    gap: 0.75rem;
    margin-top: 2rem;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    color: var(--text-secondary, #666);
    background: var(--code-bg, #f8f8f8);
    border: 1px solid var(--border-color, #ddd);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
}
.action-btn:hover {
    background: var(--bg-color, #fff);
    border-color: var(--link-color);
    color: var(--link-color);
    text-decoration: none;
}
.action-btn svg {
    width: 16px;
    height: 16px;
}
.action-btn.playing {
    background: var(--link-color);
    color: white;
    border-color: var(--link-color);
}

/* Story metadata grid */
.story-meta {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin: 2rem 0;
    padding: 1.5rem;
    background: var(--code-bg, #f8f8f8);
    border-radius: 6px;
}
.meta-section h4 {
    margin: 0 0 0.5rem 0;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-secondary, #888);
}
.meta-section ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
.meta-section li {
    margin: 0.25rem 0;
    font-size: 0.95rem;
}
.meta-section .scripture-ref {
    color: var(--link-color);
}
.meta-section .tag {
    display: inline-block;
    padding: 0.2rem 0.6rem;
    margin: 0.2rem 0.2rem 0.2rem 0;
    border-radius: 3px;
    font-size: 0.85rem;
}
.meta-section .tag.character {
    background: #e8f4f8;
    color: #2a6f8f;
}
.meta-section .tag.theme {
    background: #f0f4e8;
    color: #5a7a2a;
}

/* Story divider */
hr.story-divider {
    border: 0;
    height: 0;
    text-align: center;
    margin: 2.5rem 0;
}
hr.story-divider::before {
    content: "* * *";
    font-size: 1rem;
    letter-spacing: 0.6em;
    color: var(--text-secondary, #888);
}

/* Kids callout */
.kids-callout {
    background: linear-gradient(135deg, #f5f0ff 0%, #efe8ff 100%);
    border-left: 4px solid #8b5cf6;
    padding: 1.5rem 2rem;
    margin: 2.5rem 0;
    border-radius: 0 6px 6px 0;
}
.kids-callout h3 {
    margin: 0 0 0.5rem 0;
    color: #6d28d9;
    font-size: 1.1rem;
}
.kids-callout p {
    margin: 0;
    color: var(--text-secondary, #555);
}
.kids-callout a {
    color: #7c3aed;
    font-weight: 600;
}
/* Dark mode kids callout */
[data-theme="dark"] .kids-callout {
    background: linear-gradient(135deg, #2d2640 0%, #1f1a2e 100%);
    border-left-color: #a78bfa;
}
[data-theme="dark"] .kids-callout h3 {
    color: #c4b5fd;
}
[data-theme="dark"] .kids-callout a {
    color: #a78bfa;
}

/* Story navigation */
.story-nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 3rem;
    padding-top: 1.5rem;
    border-top: 1px solid var(--border-color, #ddd);
    gap: 1rem;
}
.story-nav .nav-prev,
.story-nav .nav-next {
    flex: 1;
    max-width: 40%;
}
.story-nav .nav-prev {
    text-align: left;
}
.story-nav .nav-next {
    text-align: right;
}
.story-nav .nav-center {
    text-align: center;
}
.story-nav .nav-label {
    display: block;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-secondary, #888);
    margin-bottom: 0.25rem;
}
.story-nav .nav-title {
    font-size: 0.95rem;
    color: var(--link-color);
    text-decoration: none;
}
.story-nav .nav-title:hover {
    text-decoration: underline;
}
.story-nav .nav-disabled {
    color: var(--text-secondary, #ccc);
}

/* Print styles */
@media print {
    .story-meta,
    .kids-callout,
    .story-nav,
    .story-actions {
        display: none;
    }

    .story-header .category-link {
        display: none;
    }

    h1 {
        font-size: 1.8rem;
        margin-bottom: 0.5rem;
    }

    .story-header .description {
        font-size: 1rem;
        margin-bottom: 1.5rem;
    }

    section p {
        font-size: 11pt;
        line-height: 1.6;
    }
}

/* Large font mode */
[data-font-size="large"] .story-header .description {
    font-size: 1.5rem;
}
[data-font-size="large"] .meta-section h4 {
    font-size: 1rem;
}
[data-font-size="large"] .meta-section li {
    font-size: 1.2rem;
}
[data-font-size="large"] .meta-section .tag {
    font-size: 1.05rem;
    padding: 0.3rem 0.75rem;
}
[data-font-size="large"] .kids-callout h3 {
    font-size: 1.3rem;
}
[data-font-size="large"] .kids-callout p {
    font-size: 1.15rem;
}
[data-font-size="large"] .action-btn {
    font-size: 1.1rem;
    padding: 0.6rem 1.2rem;
}
[data-font-size="large"] .story-nav .nav-title {
    font-size: 1.15rem;
}
</style>
{% endblock %}

{% block content %}
<article>
    <header class="story-header">
        <a href="/stories#{{ story.category_slug }}" class="category-link">{{ story.category_name }}</a>
        <h1>{{ story.title }}</h1>
        <p class="description">{{ story.description }}</p>
    </header>

    <div class="story-meta">
        <div class="meta-section">
            <h4>Scripture</h4>
            <ul>
                {% for verse in story.verses %}
                {% set ref_parts = verse.split(' ') %}
                {% if ref_parts|length >= 2 %}
                    {% set chapter_verse = ref_parts[-1] %}
                    {% set book = ' '.join(ref_parts[:-1]) %}
                    {% if ':' in chapter_verse %}
                        {% set chapter = chapter_verse.split(':')[0] %}
                        {% set verse_part = chapter_verse.split(':')[1] %}
                        {% if '-' in verse_part %}
                            <li><a href="/book/{{ book }}/chapter/{{ chapter }}#verse-{{ verse_part }}" class="scripture-ref">{{ verse }}</a></li>
                        {% else %}
                            <li><a href="/book/{{ book }}/chapter/{{ chapter }}#verse-{{ verse_part }}" class="scripture-ref">{{ verse }}</a></li>
                        {% endif %}
                    {% elif '-' in chapter_verse %}
                        {% set chapter = chapter_verse.split('-')[0] %}
                        <li><a href="/book/{{ book }}/chapter/{{ chapter }}" class="scripture-ref">{{ verse }}</a></li>
                    {% else %}
                        <li><a href="/book/{{ book }}/chapter/{{ chapter_verse }}" class="scripture-ref">{{ verse }}</a></li>
                    {% endif %}
                {% else %}
                    <li class="scripture-ref">{{ verse }}</li>
                {% endif %}
                {% endfor %}
            </ul>
        </div>
        <div class="meta-section">
            <h4>Key Characters</h4>
            <div>
                {% for character in story.characters %}
                <span class="tag character">{{ character }}</span>
                {% endfor %}
            </div>
        </div>
        <div class="meta-section">
            <h4>Themes</h4>
            <div>
                {% for theme in story.themes %}
                <span class="tag theme">{{ theme }}</span>
                {% endfor %}
            </div>
        </div>
    </div>

    <hr class="story-divider">

    <section>
        {% for paragraph in story.narrative.split('\n\n') %}
        {% if loop.first %}
        <p><span class="newthought">{{ paragraph.split(' ')[:3] | join(' ') }}</span> {{ paragraph.split(' ')[3:] | join(' ') }}</p>
        {% else %}
        <p>{{ paragraph }}</p>
        {% endif %}
        {% endfor %}
    </section>

    <aside class="kids-callout">
        <h3>Reading with Children?</h3>
        <p>This story is also available in a kid-friendly version: <a href="/stories/{{ story.slug }}/kids">{{ story.kids_title }}</a> — written with simpler language and engaging narration perfect for young readers or family devotions.</p>
    </aside>

    <div class="story-actions">
        <button class="action-btn listen-btn" id="story-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>
        <a href="/stories/{{ story.slug }}/pdf" class="action-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>
            Download PDF
        </a>
    </div>
</article>

<nav class="story-nav">
    <div class="nav-prev">
        {% if prev_story %}
        <span class="nav-label">Previous Story</span>
        <a href="/stories/{{ prev_story.slug }}" class="nav-title">← {{ prev_story.title }}</a>
        {% else %}
        <span class="nav-label">Previous Story</span>
        <span class="nav-disabled">← No previous story</span>
        {% endif %}
    </div>
    <div class="nav-center">
        <a href="/stories" class="nav-title">All Stories</a>
    </div>
    <div class="nav-next">
        {% if next_story %}
        <span class="nav-label">Next Story</span>
        <a href="/stories/{{ next_story.slug }}" class="nav-title">{{ next_story.title }} →</a>
        {% else %}
        <span class="nav-label">Next Story</span>
        <span class="nav-disabled">No next story →</span>
        {% endif %}
    </div>
</nav>

<script>
(function() {
    // Listen button - read story aloud
    var listenBtn = document.getElementById('story-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 story text from paragraphs
            var paragraphs = document.querySelectorAll('article section p');
            var text = Array.from(paragraphs).map(function(p) {
                return p.textContent.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;
            }
        });
    }

    // Collect paragraphs, kids callout, and action buttons for up/down navigation (skip story meta so speech focuses on narrative)
    var elements = Array.from(document.querySelectorAll('article section p, .kids-callout, .story-actions .action-btn'));
    // Find the index of the first paragraph (to start selection there)
    var firstParagraphIndex = elements.findIndex(function(el) { return el.tagName === 'P'; });
    var selectedIndex = -1;

    function selectElement(index) {
        // Remove previous selection
        if (selectedIndex >= 0 && selectedIndex < elements.length) {
            elements[selectedIndex].style.outline = '';
            elements[selectedIndex].style.outlineOffset = '';
            elements[selectedIndex].classList.remove('selected');
        }

        selectedIndex = Math.max(0, Math.min(index, elements.length - 1));

        // Add selection to new element
        elements[selectedIndex].style.outline = '2px solid #4a7c59';
        elements[selectedIndex].style.outlineOffset = '8px';
        elements[selectedIndex].classList.add('selected');
        elements[selectedIndex].scrollIntoView({ behavior: 'auto', block: 'center' });
    }

    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 (KJVNav.isSelectionOffScreen(elements, selectedIndex)) {
                selectElement(KJVNav.findFirstVisibleIndex(elements));
            } else {
                // Start at first paragraph, not metadata
                selectElement(selectedIndex < 0 ? firstParagraphIndex : selectedIndex + 1);
            }
        } else if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            if (KJVNav.isSelectionOffScreen(elements, selectedIndex)) {
                selectElement(KJVNav.findFirstVisibleIndex(elements));
            } else if (selectedIndex <= 0) {
                selectElement(0);
            } else {
                selectElement(selectedIndex - 1);
            }
        } else if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            history.back();
        } else if (e.key === 'ArrowRight' || e.key === 'l') {
            e.preventDefault();
            var nextLink = document.querySelector('.nav-next .nav-title');
            if (nextLink) window.location.href = nextLink.href;
        } else if (e.key === '[') {
            e.preventDefault();
            var prevLink = document.querySelector('.nav-prev .nav-title');
            if (prevLink) window.location.href = prevLink.href;
        } else if (e.key === ']') {
            e.preventDefault();
            var nextLink = document.querySelector('.nav-next .nav-title');
            if (nextLink) window.location.href = nextLink.href;
        } else if (e.key === 'Enter' && selectedIndex >= 0) {
            e.preventDefault();
            var el = elements[selectedIndex];
            // Check if the element itself is a link (like PDF button)
            if (el.tagName === 'A' && el.href) {
                window.location.href = el.href;
            } else {
                var link = el.querySelector('a');
                if (link) window.location.href = link.href;
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            if (selectedIndex >= 0 && selectedIndex < elements.length) {
                elements[selectedIndex].style.outline = '';
                elements[selectedIndex].style.outlineOffset = '';
                elements[selectedIndex].classList.remove('selected');
            }
            selectedIndex = -1;
        }
    });
})();
</script>
{% endblock %}
