{% extends "base.html" %}

{% block title %}Bible Stories for Kids - KJV Study{% endblock %}
{% block description %}Explore {{ story_count }} kid-friendly Bible stories from Creation to the early Church, perfect for family devotions and Sunday school.{% endblock %}

{% block og_type %}website{% endblock %}
{% block og_title %}Bible Stories for Kids - KJV Study{% endblock %}
{% block og_description %}Explore {{ story_count }} kid-friendly Bible stories from Creation to the early Church, perfect for family devotions and Sunday school.{% endblock %}

{% block head %}
<style>
.kids-page-header {
    background: linear-gradient(135deg, #dbeafe 0%, #ede9fe 50%, #fce7f3 100%);
    padding: 2.5rem;
    border-radius: 16px;
    margin-bottom: 2rem;
    text-align: center;
}
.kids-page-header h1 {
    color: #4338ca;
    margin: 0 0 0.5rem 0;
    font-size: 2.5rem;
}
.kids-page-header .subtitle {
    color: #6366f1;
    font-size: 1.1rem;
    margin: 0;
}
.kids-page-header .intro {
    max-width: 600px;
    margin: 1rem auto 0;
    color: #4b5563;
    line-height: 1.6;
}
.adult-link {
    display: inline-block;
    margin-top: 1rem;
    color: #7c3aed;
    text-decoration: none;
    font-size: 0.9rem;
}
.adult-link:hover {
    text-decoration: underline;
}

.toc-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 0.75rem;
    margin: 1.5rem 0;
}
.toc-item {
    padding: 0.75rem 1rem;
    background: linear-gradient(135deg, #f0f9ff 0%, #faf5ff 100%);
    border-left: 4px solid #8b5cf6;
    border-radius: 0 8px 8px 0;
    font-size: 0.95rem;
}
.toc-item a {
    text-decoration: none;
    color: #4338ca;
    font-weight: 500;
}
.toc-item a:hover {
    text-decoration: underline;
}
.toc-item .count {
    color: #9ca3af;
    font-size: 0.8rem;
    display: block;
    margin-top: 0.25rem;
}

.story-search {
    max-width: 400px;
    margin: 1.5rem auto;
    position: relative;
}
.story-search input {
    width: 100%;
    padding: 0.75rem 1rem;
    font-size: 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 25px;
    background: #fff;
}
.story-search input:focus {
    outline: none;
    border-color: #8b5cf6;
}
.story-search input::placeholder {
    color: #9ca3af;
}
.story-search-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #fff;
    border: 2px solid #e5e7eb;
    border-top: none;
    border-radius: 0 0 16px 16px;
    max-height: 350px;
    overflow-y: auto;
    z-index: 1000;
    display: none;
    box-shadow: 0 4px 12px rgba(139, 92, 246, 0.15);
}
.story-search-dropdown.show {
    display: block;
}
.search-result-category {
    padding: 0.5rem 1rem 0.25rem;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: #9ca3af;
    background: linear-gradient(135deg, #f0f9ff 0%, #faf5ff 100%);
    border-bottom: 1px solid #e5e7eb;
}
.search-result-item {
    display: block;
    padding: 0.6rem 1rem;
    text-decoration: none;
    color: #4338ca;
    border-bottom: 1px solid #e5e7eb;
    cursor: pointer;
    transition: background 0.15s;
}
.search-result-item:hover,
.search-result-item.selected {
    background: linear-gradient(135deg, #f0f9ff 0%, #faf5ff 100%);
}
.search-result-item:last-child {
    border-bottom: none;
    border-radius: 0 0 14px 14px;
}
.search-result-title {
    font-weight: 500;
    font-size: 0.95rem;
}
.search-result-subtitle {
    font-size: 0.8rem;
    color: #9ca3af;
    margin-top: 0.1rem;
}

.stories-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1.25rem;
    margin: 1.5rem 0;
}

.kids-story-card {
    display: block;
    background: #fff;
    border: 2px solid #e5e7eb;
    border-radius: 16px;
    padding: 1.5rem;
    text-decoration: none;
    color: inherit;
    transition: all 0.2s ease;
}
.kids-story-card:hover,
.kids-story-card:focus-visible {
    border-color: #8b5cf6;
    box-shadow: 0 4px 12px rgba(139, 92, 246, 0.15);
    transform: translateY(-2px);
}
.kids-story-card.hidden {
    display: none;
}
.kids-story-card h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.2rem;
    line-height: 1.3;
    color: #4338ca;
}
.kids-story-card .description {
    font-size: 0.95rem;
    color: #6b7280;
    margin-bottom: 1rem;
    line-height: 1.5;
}
.kids-story-card .scripture {
    font-size: 0.85rem;
    color: #8b5cf6;
    margin-bottom: 0.75rem;
}

.characters-row {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin-bottom: 1rem;
}
.character-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    background: linear-gradient(135deg, #dbeafe, #e0e7ff);
    padding: 0.3rem 0.6rem;
    border-radius: 15px;
    font-size: 0.8rem;
    color: #3730a3;
}
.character-badge::before {
    content: "\2605";
    font-size: 0.6rem;
}

.theme-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin-bottom: 1rem;
}
.theme-badge {
    background: linear-gradient(135deg, #fef3c7, #fde68a);
    padding: 0.3rem 0.6rem;
    border-radius: 15px;
    font-size: 0.8rem;
    color: #92400e;
}


.category-section.hidden {
    display: none;
}
.toc-item.hidden {
    display: none;
}
.category-section {
    margin-bottom: 3rem;
}
.category-section h2 {
    color: #4338ca;
    border-bottom: 3px solid #e0e7ff;
    padding-bottom: 0.5rem;
}
.category-description {
    font-size: 1rem;
    color: #6b7280;
    margin-bottom: 1rem;
    max-width: 65ch;
}

.no-results {
    display: none;
    padding: 2rem;
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-radius: 12px;
    color: #92400e;
    text-align: center;
    font-size: 1.1rem;
}
.no-results.visible {
    display: block;
}

/* Dark mode styles */
[data-theme="dark"] .kids-page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2d1f4e 50%, #3d1f3a 100%);
}
[data-theme="dark"] .kids-page-header h1 {
    color: #a5b4fc;
}
[data-theme="dark"] .kids-page-header .subtitle {
    color: #c4b5fd;
}
[data-theme="dark"] .kids-page-header .intro {
    color: #d1d5db;
}
[data-theme="dark"] .adult-link {
    color: #c4b5fd;
}
[data-theme="dark"] .toc-item {
    background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
    border-left-color: #8b5cf6;
}
[data-theme="dark"] .toc-item a {
    color: #a5b4fc;
}
[data-theme="dark"] .toc-item .count {
    color: #9ca3af;
}
[data-theme="dark"] .story-search input {
    background: #252525;
    border-color: #404040;
    color: #e5e7eb;
}
[data-theme="dark"] .story-search input::placeholder {
    color: #6b7280;
}
[data-theme="dark"] .story-search-dropdown {
    background: #252525;
    border-color: #404040;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}
[data-theme="dark"] .search-result-category {
    background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
    border-bottom-color: #404040;
    color: #9ca3af;
}
[data-theme="dark"] .search-result-item {
    color: #a5b4fc;
    border-bottom-color: #404040;
}
[data-theme="dark"] .search-result-item:hover,
[data-theme="dark"] .search-result-item.selected {
    background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
}
[data-theme="dark"] .search-result-subtitle {
    color: #9ca3af;
}
[data-theme="dark"] .kids-story-card {
    background: #252525;
    border-color: #404040;
}
[data-theme="dark"] .kids-story-card:hover,
[data-theme="dark"] .kids-story-card:focus-visible {
    border-color: #8b5cf6;
    box-shadow: 0 4px 12px rgba(139, 92, 246, 0.25);
}
[data-theme="dark"] .kids-story-card h3 {
    color: #a5b4fc;
}
[data-theme="dark"] .kids-story-card .description {
    color: #d1d5db;
}
[data-theme="dark"] .kids-story-card .scripture {
    color: #c4b5fd;
}
[data-theme="dark"] .character-badge {
    background: linear-gradient(135deg, #1e3a5f, #2a2f5f);
    color: #93c5fd;
}
[data-theme="dark"] .theme-badge {
    background: linear-gradient(135deg, #4a3f1a, #3a3520);
    color: #fcd34d;
}
[data-theme="dark"] .category-section h2 {
    color: #a5b4fc;
    border-bottom-color: #3730a3;
}
[data-theme="dark"] .category-description {
    color: #d1d5db;
}
[data-theme="dark"] .no-results {
    background: linear-gradient(135deg, #4a3f1a 0%, #3a3520 100%);
    color: #fcd34d;
}

/* System preference dark mode */
@media (prefers-color-scheme: dark) {
    html:not([data-theme="light"]) .kids-page-header {
        background: linear-gradient(135deg, #1e3a5f 0%, #2d1f4e 50%, #3d1f3a 100%);
    }
    html:not([data-theme="light"]) .kids-page-header h1 {
        color: #a5b4fc;
    }
    html:not([data-theme="light"]) .kids-page-header .subtitle {
        color: #c4b5fd;
    }
    html:not([data-theme="light"]) .kids-page-header .intro {
        color: #d1d5db;
    }
    html:not([data-theme="light"]) .adult-link {
        color: #c4b5fd;
    }
    html:not([data-theme="light"]) .toc-item {
        background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
        border-left-color: #8b5cf6;
    }
    html:not([data-theme="light"]) .toc-item a {
        color: #a5b4fc;
    }
    html:not([data-theme="light"]) .toc-item .count {
        color: #9ca3af;
    }
    html:not([data-theme="light"]) .story-search input {
        background: #252525;
        border-color: #404040;
        color: #e5e7eb;
    }
    html:not([data-theme="light"]) .story-search input::placeholder {
        color: #6b7280;
    }
    html:not([data-theme="light"]) .story-search-dropdown {
        background: #252525;
        border-color: #404040;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
    }
    html:not([data-theme="light"]) .search-result-category {
        background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
        border-bottom-color: #404040;
        color: #9ca3af;
    }
    html:not([data-theme="light"]) .search-result-item {
        color: #a5b4fc;
        border-bottom-color: #404040;
    }
    html:not([data-theme="light"]) .search-result-item:hover,
    html:not([data-theme="light"]) .search-result-item.selected {
        background: linear-gradient(135deg, #1e2a3a 0%, #2a1f3a 100%);
    }
    html:not([data-theme="light"]) .search-result-subtitle {
        color: #9ca3af;
    }
    html:not([data-theme="light"]) .kids-story-card {
        background: #252525;
        border-color: #404040;
    }
    html:not([data-theme="light"]) .kids-story-card:hover,
    html:not([data-theme="light"]) .kids-story-card:focus-visible {
        border-color: #8b5cf6;
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.25);
    }
    html:not([data-theme="light"]) .kids-story-card h3 {
        color: #a5b4fc;
    }
    html:not([data-theme="light"]) .kids-story-card .description {
        color: #d1d5db;
    }
    html:not([data-theme="light"]) .kids-story-card .scripture {
        color: #c4b5fd;
    }
    html:not([data-theme="light"]) .character-badge {
        background: linear-gradient(135deg, #1e3a5f, #2a2f5f);
        color: #93c5fd;
    }
    html:not([data-theme="light"]) .theme-badge {
        background: linear-gradient(135deg, #4a3f1a, #3a3520);
        color: #fcd34d;
    }
    html:not([data-theme="light"]) .category-section h2 {
        color: #a5b4fc;
        border-bottom-color: #3730a3;
    }
    html:not([data-theme="light"]) .category-description {
        color: #d1d5db;
    }
    html:not([data-theme="light"]) .no-results {
        background: linear-gradient(135deg, #4a3f1a 0%, #3a3520 100%);
        color: #fcd34d;
    }
}

/* Large font mode for kids story cards (category-description in base.html) */
[data-font-size="large"] .kids-story-card h3 {
    font-size: 1.6rem;
}
[data-font-size="large"] .kids-story-card .description {
    font-size: 1.2rem;
    line-height: 1.6;
}
[data-font-size="large"] .kids-story-card .scripture {
    font-size: 1.1rem;
}
[data-font-size="large"] .character-badge,
[data-font-size="large"] .theme-badge {
    font-size: 1rem;
    padding: 0.4rem 0.75rem;
}
[data-font-size="large"] .toc-item {
    font-size: 1.1rem;
}
[data-font-size="large"] .toc-item .count {
    font-size: 0.95rem;
}
</style>
{% endblock %}

{% block content %}
<header class="kids-page-header">
    <h1>Bible Stories for Kids</h1>
    <p class="subtitle">{{ story_count }} stories across {{ category_count }} categories</p>
    <p class="intro">These Bible stories are written just for you! They tell amazing true stories from God's Word in a way that's easy to understand and fun to read.</p>
    <a href="/stories" class="adult-link">Looking for the grown-up versions?</a>
</header>

<div class="story-search">
    <input type="text" id="story-search" placeholder="Search for a story..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
    <div id="story-search-dropdown" class="story-search-dropdown"></div>
</div>

<section>
    <h3>Categories</h3>
    <div class="toc-grid">
        {% for category in categories %}
        <div class="toc-item" data-category="{{ category.slug }}">
            <a href="#{{ category.slug }}">{{ category.category }}</a>
            <span class="count">{{ category.stories|length }} stories</span>
        </div>
        {% endfor %}
    </div>
</section>

<div class="no-results" id="no-results">
    No stories found. Try a different search!
</div>

{% for category in categories %}
<section id="{{ category.slug }}" class="category-section">
    <h2>{{ category.category }}</h2>
    <p class="category-description">{{ category.description }}</p>

    <div class="stories-grid">
        {% for story in category.stories %}
        {% if story.kids_narrative %}
        <a class="kids-story-card" href="/stories/{{ story.slug }}/kids" data-title="{{ story.kids_title|default(story.title)|lower }}" data-description="{{ story.kids_description|default(story.description)|lower }}" data-characters="{{ story.characters|join(' ')|lower }}" data-themes="{{ story.themes|join(' ')|lower }}">
            <h3>{{ story.kids_title or story.title }}</h3>
            <p class="description">{{ story.kids_description or story.description }}</p>
            <div class="scripture">
                {% for verse in story.verses[:2] %}{{ verse }}{% if not loop.last %}, {% endif %}{% endfor %}{% if story.verses|length > 2 %} +{{ story.verses|length - 2 }} more{% endif %}
            </div>
            <div class="characters-row">
                {% for character in story.characters[:4] %}
                <span class="character-badge">{{ character }}</span>
                {% endfor %}
            </div>
            <div class="theme-badges">
                {% for theme in story.themes[:3] %}
                <span class="theme-badge">{{ theme }}</span>
                {% endfor %}
            </div>
        </a>
        {% endif %}
        {% endfor %}
    </div>
</section>
{% endfor %}

<nav style="text-align: center; margin-top: 2rem;">
    <a href="/stories" class="adult-link">View All Stories (Grown-up Versions)</a>
    <span style="margin: 0 1rem; color: #d1d5db;">|</span>
    <a href="/" class="adult-link">Home</a>
</nav>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var searchInput = document.getElementById('story-search');
    var dropdown = document.getElementById('story-search-dropdown');
    var stories = document.querySelectorAll('.kids-story-card');
    var categorySections = document.querySelectorAll('.category-section');
    var tocItems = document.querySelectorAll('.toc-item');
    var noResults = document.getElementById('no-results');
    var currentResults = [];
    var selectedIndex = -1;

    function filterStories(query) {
        if (!query) {
            stories.forEach(function(s) { s.classList.remove('hidden'); });
            categorySections.forEach(function(c) { c.classList.remove('hidden'); });
            tocItems.forEach(function(t) { t.classList.remove('hidden'); });
            noResults.classList.remove('visible');
            return;
        }

        var matchCount = 0;
        stories.forEach(function(story) {
            var title = story.dataset.title || '';
            var description = story.dataset.description || '';
            var characters = story.dataset.characters || '';
            var themes = story.dataset.themes || '';

            var matches = title.includes(query) ||
                         description.includes(query) ||
                         characters.includes(query) ||
                         themes.includes(query);

            if (matches) {
                story.classList.remove('hidden');
                matchCount++;
            } else {
                story.classList.add('hidden');
            }
        });

        categorySections.forEach(function(category) {
            var categoryId = category.id;
            var visibleStories = category.querySelectorAll('.kids-story-card:not(.hidden)');
            var isEmpty = visibleStories.length === 0;

            if (isEmpty) {
                category.classList.add('hidden');
            } else {
                category.classList.remove('hidden');
            }

            // Also hide/show corresponding TOC item
            tocItems.forEach(function(tocItem) {
                if (tocItem.dataset.category === categoryId) {
                    if (isEmpty) {
                        tocItem.classList.add('hidden');
                    } else {
                        tocItem.classList.remove('hidden');
                    }
                }
            });
        });

        if (matchCount === 0) {
            noResults.classList.add('visible');
        } else {
            noResults.classList.remove('visible');
        }
    }

    function getMatchingStories(query) {
        var matches = [];
        stories.forEach(function(story) {
            var title = story.dataset.title || '';
            var description = story.dataset.description || '';
            var characters = story.dataset.characters || '';
            var themes = story.dataset.themes || '';

            if (title.includes(query) || description.includes(query) ||
                characters.includes(query) || themes.includes(query)) {
                // The story card itself is the anchor tag
                var storyTitle = story.querySelector('h3');
                var storyDesc = story.querySelector('.description');
                if (storyTitle) {
                    matches.push({
                        title: storyTitle.textContent,
                        url: story.href,
                        description: storyDesc ? storyDesc.textContent.substring(0, 50) + '...' : ''
                    });
                }
            }
        });
        return matches.slice(0, 8);
    }

    function showDropdown(html) {
        dropdown.innerHTML = html;
        dropdown.classList.add('show');
    }

    function hideDropdown() {
        dropdown.classList.remove('show');
        currentResults = [];
        selectedIndex = -1;
    }

    function updateSelection() {
        var items = dropdown.querySelectorAll('.search-result-item');
        items.forEach(function(item, i) {
            if (i === selectedIndex) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }

    function renderDropdown(query) {
        var html = '';
        currentResults = [];

        var matchingStories = getMatchingStories(query.toLowerCase());
        if (matchingStories.length > 0) {
            html += '<div class="search-result-category">Stories</div>';
            matchingStories.forEach(function(story) {
                currentResults.push(story.url);
                var isSelected = currentResults.length === 1;
                html += '<a href="' + story.url + '" class="search-result-item' + (isSelected ? ' selected' : '') + '">';
                html += '<div class="search-result-title">' + story.title + '</div>';
                if (story.description) {
                    html += '<div class="search-result-subtitle">' + story.description + '</div>';
                }
                html += '</a>';
            });
        }

        if (html) {
            selectedIndex = currentResults.length > 0 ? 0 : -1;
            showDropdown(html);
        } else {
            hideDropdown();
        }
    }

    searchInput.addEventListener('input', function() {
        var query = this.value.trim();

        filterStories(query.toLowerCase());

        if (query.length < 2) {
            hideDropdown();
            return;
        }

        renderDropdown(query);
    });

    searchInput.addEventListener('keydown', function(e) {
        if (!dropdown.classList.contains('show')) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            selectedIndex = Math.min(selectedIndex + 1, currentResults.length - 1);
            updateSelection();
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            selectedIndex = Math.max(selectedIndex - 1, -1);
            updateSelection();
        } else if (e.key === 'Enter' && selectedIndex >= 0 && currentResults[selectedIndex]) {
            e.preventDefault();
            window.location.href = currentResults[selectedIndex];
        } else if (e.key === 'Escape') {
            hideDropdown();
        }
    });

    document.addEventListener('click', function(e) {
        if (!dropdown.contains(e.target) && e.target !== searchInput) {
            hideDropdown();
        }
    });

    // Keyboard navigation for story cards (2D grid)
    var visibleStories = function() {
        return Array.from(document.querySelectorAll('.kids-story-card:not(.hidden)'));
    };
    var selectedCardIndex = -1;

    function getGridColumns() {
        var grid = document.querySelector('.stories-grid');
        if (!grid) return 1;
        var style = getComputedStyle(grid);
        var cols = style.gridTemplateColumns.split(' ').length;
        return cols || 1;
    }

    function selectStoryCard(index) {
        var cards = visibleStories();
        if (cards.length === 0) return;

        if (selectedCardIndex >= 0 && selectedCardIndex < cards.length) {
            cards[selectedCardIndex].style.outline = '';
            cards[selectedCardIndex].style.outlineOffset = '';
            cards[selectedCardIndex].classList.remove('selected');
        }

        selectedCardIndex = Math.max(0, Math.min(index, cards.length - 1));
        cards[selectedCardIndex].style.outline = '2px solid #8b5cf6';
        cards[selectedCardIndex].style.outlineOffset = '4px';
        cards[selectedCardIndex].classList.add('selected');
        cards[selectedCardIndex].scrollIntoView({ behavior: 'auto', block: 'center' });
    }

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

        var cards = visibleStories();
        if (cards.length === 0) return;

        var cols = getGridColumns();

        if (e.key === 'ArrowDown' || e.key === 'j') {
            e.preventDefault();
            if (selectedCardIndex < 0) selectStoryCard(0);
            else selectStoryCard(selectedCardIndex + cols);
        } else if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            if (selectedCardIndex < 0) selectStoryCard(0);
            else if (selectedCardIndex - cols >= 0) selectStoryCard(selectedCardIndex - cols);
        } else if (e.key === 'ArrowRight' || e.key === 'l') {
            e.preventDefault();
            if (selectedCardIndex < 0) selectStoryCard(0);
            else selectStoryCard(selectedCardIndex + 1);
        } else if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            if (selectedCardIndex <= 0) history.back();
            else selectStoryCard(selectedCardIndex - 1);
        } else if (e.key === 'Enter' && selectedCardIndex >= 0) {
            e.preventDefault();
            var cards = visibleStories();
            if (cards[selectedCardIndex]) {
                window.location.href = cards[selectedCardIndex].href;
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            var cards = visibleStories();
            if (selectedCardIndex >= 0 && selectedCardIndex < cards.length) {
                cards[selectedCardIndex].style.outline = '';
                cards[selectedCardIndex].style.outlineOffset = '';
                cards[selectedCardIndex].classList.remove('selected');
            }
            selectedCardIndex = -1;
        }
    });
});
</script>
{% endblock %}
