{% extends "base.html" %}

{% block title %}Starred Passages & Pages - KJV Study{% endblock %}
{% block description %}Your starred passages and pages from KJV Study.{% endblock %}

{% block head %}
<style>
.stars-container {
    max-width: 750px;
}

/* Header area */
.stars-header {
    margin-bottom: 2.5rem;
}

.stars-header h1 {
    margin-bottom: 0.5rem;
}

.stars-subtitle {
    color: var(--text-secondary);
    font-size: 1.1rem;
    margin: 0;
}

.stars-count {
    display: inline-block;
    background: var(--code-bg);
    color: var(--text-secondary);
    font-size: 0.8rem;
    padding: 0.2rem 0.6rem;
    border-radius: 12px;
    margin-left: 0.75rem;
    vertical-align: middle;
}

/* Toolbar */
.stars-toolbar {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border-color);
}

.stars-sort {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.stars-sort-label {
    font-size: 0.8rem;
    color: var(--text-tertiary);
    text-transform: uppercase;
    letter-spacing: 0.03em;
}

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

/* Empty state */
.stars-empty {
    text-align: center;
    padding: 4rem 2rem;
}

.stars-empty-icon {
    font-size: 3rem;
    margin-bottom: 1.5rem;
    opacity: 0.3;
}

.stars-empty-title {
    font-size: 1.4rem;
    font-weight: 500;
    margin-bottom: 1rem;
    color: var(--text-color);
}

.stars-empty-text {
    color: var(--text-secondary);
    line-height: 1.8;
    margin-bottom: 0.75rem;
    font-size: 1rem;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;
}

.stars-empty-hint {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    margin-top: 1.5rem;
    padding: 0.75rem 1.25rem;
    background: var(--code-bg);
    border-radius: 6px;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.stars-empty-hint kbd {
    display: inline-block;
    padding: 0.15rem 0.4rem;
    font-family: inherit;
    font-size: 0.85rem;
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: 3px;
}

.stars-cta {
    margin-top: 2.5rem;
    padding-top: 2rem;
    border-top: 1px solid var(--border-color);
}

.stars-cta-title {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-tertiary);
    margin-bottom: 0.75rem;
}

.stars-cta a {
    font-weight: 500;
    font-size: 1.05rem;
}

.stars-cta-desc {
    color: var(--text-secondary);
    font-size: 0.95rem;
    margin-top: 0.25rem;
}

.stars-empty-note {
    font-size: 0.85rem;
    color: var(--text-tertiary);
    margin-top: 3rem;
    max-width: 450px;
    margin-left: auto;
    margin-right: auto;
    line-height: 1.6;
}

/* Groups */
.stars-group {
    margin-bottom: 1.5rem;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;
}

.stars-group-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 1rem;
    background: var(--code-bg);
    cursor: pointer;
    user-select: none;
    transition: background 0.15s;
}

.stars-group-header:hover {
    background: var(--border-color);
}

.stars-group-toggle {
    font-size: 0.65rem;
    color: var(--text-tertiary);
    transition: transform 0.2s ease;
    margin-right: 0.5rem;
}

.stars-group.collapsed .stars-group-toggle {
    transform: rotate(-90deg);
}

.stars-group-title {
    font-size: 0.9rem;
    font-weight: 600;
    color: var(--text-color);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.stars-group-title a {
    color: var(--text-color);
    border-bottom: none;
}

.stars-group-title a:hover {
    color: var(--link-color);
}

.stars-group-count {
    font-size: 0.7rem;
    color: var(--text-tertiary);
    font-weight: 400;
    background: var(--bg-color);
    padding: 0.15rem 0.5rem;
    border-radius: 10px;
}

.stars-group-content {
    padding: 0.5rem 0;
}

.stars-group.collapsed .stars-group-content {
    display: none;
}

.stars-crumb-sep {
    color: var(--text-tertiary);
    margin: 0 0.35rem;
    font-weight: 400;
}

/* List */
.stars-list {
    padding: 0;
    margin: 0;
    list-style: none;
}

.stars-item {
    position: relative;
    margin-bottom: 2px;
    border-radius: 8px;
    transition: all 0.2s ease;
    background: transparent;
}

.stars-item:hover {
    background: var(--code-bg);
}

.stars-item.expanded {
    background: var(--code-bg);
    margin-bottom: 0.75rem;
    box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}

/* Item header */
.stars-item-header {
    display: flex;
    align-items: flex-start;
    padding: 0.875rem 1rem;
    cursor: pointer;
    gap: 0.75rem;
}

.stars-item-star {
    color: #eab308;
    font-size: 0.9rem;
    flex-shrink: 0;
}

.stars-item-toggle {
    color: var(--text-tertiary);
    font-size: 0.55rem;
    transition: transform 0.2s ease;
    flex-shrink: 0;
    margin-left: auto;
    align-self: center;
}

.stars-item.expanded .stars-item-toggle {
    transform: rotate(90deg);
}

.stars-item-content {
    flex: 1;
    min-width: 0;
}

.stars-item-title {
    font-size: 1.05rem;
    font-weight: 600;
    line-height: 1.4;
    margin-bottom: 0.25rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.stars-item-title-text {
    color: var(--text-color);
    cursor: pointer;
    transition: color 0.15s;
}

.stars-item-title-text:hover {
    color: var(--link-color);
}

a.stars-item-title-link,
a.stars-item-title-link:visited,
a.stars-item-title-link:link {
    font-size: 0.9rem;
    font-weight: 400;
    color: #eab308 !important;
    text-decoration: none !important;
    border-bottom: none !important;
}

a.stars-item-title-link:hover {
    color: #facc15 !important;
    text-decoration: none !important;
    border-bottom: none !important;
}

[data-theme="dark"] a.stars-item-title-link,
[data-theme="dark"] a.stars-item-title-link:visited,
[data-theme="dark"] a.stars-item-title-link:link {
    color: #fbbf24 !important;
}

[data-theme="dark"] a.stars-item-title-link:hover {
    color: #fcd34d !important;
}

.stars-item-preview {
    font-size: 0.9rem;
    color: var(--text-secondary);
    line-height: 1.5;
    font-style: italic;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.stars-item-meta {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.stars-item-date {
    display: inline-block;
    font-size: 0.7rem;
    color: var(--text-tertiary);
    background: var(--code-bg);
    padding: 0 0.35rem;
    border-radius: 6px;
    line-height: 1.4;
}

.stars-item-note-indicator {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.65rem;
    font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
    color: #92600f;
    background: #fef3c7;
    padding: 0 0.35rem;
    border-radius: 6px;
    line-height: 1.4;
}

[data-theme="dark"] .stars-item-note-indicator {
    color: #fbbf24;
    background: rgba(251, 191, 36, 0.15);
}

/* Item actions */
.stars-item-actions {
    display: flex;
    gap: 0.25rem;
    opacity: 0;
    transition: opacity 0.15s;
    flex-shrink: 0;
}

.stars-item:hover .stars-item-actions,
.stars-item.expanded .stars-item-actions {
    opacity: 1;
}

.stars-action-btn {
    font-size: 0.8rem;
    color: var(--text-tertiary);
    background: none;
    border: none;
    cursor: pointer;
    padding: 0.35rem 0.6rem;
    border-radius: 4px;
    transition: all 0.15s;
}

.stars-action-btn:hover {
    color: var(--text-color);
    background: var(--border-color);
}

.stars-action-btn.danger:hover {
    color: #c53030;
    background: #fed7d7;
}

[data-theme="dark"] .stars-action-btn.danger:hover {
    color: #fc8181;
    background: rgba(252, 129, 129, 0.15);
}

/* Expanded detail */
.stars-item-detail {
    display: none;
    padding: 0 1rem 1rem 1rem;
}

.stars-item.expanded .stars-item-detail {
    display: block;
}

.stars-detail-section {
    margin-bottom: 1rem;
}

.stars-detail-label {
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-tertiary);
    margin-bottom: 0.4rem;
    font-weight: 500;
}

.stars-description {
    color: var(--text-secondary);
    font-size: 0.95rem;
    line-height: 1.7;
}

.stars-excerpt {
    color: var(--text-secondary);
    font-size: 0.95rem;
    line-height: 1.7;
    font-style: italic;
    border-left: 2px solid var(--border-color);
    padding-left: 1rem;
}

/* Notes */
.stars-note-display {
    font-size: 0.85rem;
    font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
    line-height: 1.6;
    color: var(--text-secondary);
    max-width: 650px;
    white-space: pre-wrap;
    margin-bottom: 0.5rem;
}

.stars-note-add,
.stars-note-edit {
    font-size: 0.8rem;
    color: var(--text-tertiary);
    cursor: pointer;
    text-decoration: none;
}

.stars-note-add:hover,
.stars-note-edit:hover {
    color: var(--link-color);
}

.stars-note {
    width: 100%;
    max-width: 650px;
    min-height: 80px;
    padding: 0.75rem;
    font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
    font-size: 0.85rem;
    line-height: 1.6;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    background: var(--bg-color);
    color: var(--text-color);
    resize: vertical;
    transition: border-color 0.15s, box-shadow 0.15s;
    display: none;
}

.stars-note.editing {
    display: block;
}

.stars-note:focus {
    outline: none;
    border-color: var(--border-color-darker);
    box-shadow: 0 0 0 3px rgba(0,0,0,0.05);
}

.stars-note::placeholder {
    color: var(--text-tertiary);
}

.stars-note-saved {
    font-size: 0.75rem;
    color: var(--text-tertiary);
    margin-top: 0.35rem;
    opacity: 0;
    transition: opacity 0.3s;
}

.stars-note-saved.visible {
    opacity: 1;
}

/* Detail actions */
.stars-detail-actions {
    display: flex;
    gap: 0.75rem;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border-color);
}

.stars-detail-btn {
    font-size: 0.85rem;
    color: var(--text-secondary);
    background: none;
    border: 1px solid var(--border-color);
    cursor: pointer;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    transition: all 0.15s;
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
}

.stars-detail-btn:hover {
    border-color: var(--border-color-darker);
    color: var(--text-color);
}

/* Footer */
.stars-footer {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.stars-footer-info {
    font-size: 0.85rem;
    color: var(--text-tertiary);
}

.stars-clear-btn {
    font-size: 0.85rem;
    color: var(--text-tertiary);
    background: none;
    border: none;
    cursor: pointer;
    padding: 0.4rem 0.75rem;
    border-radius: 4px;
    transition: all 0.15s;
}

.stars-clear-btn:hover {
    color: #c53030;
    background: #fed7d7;
}

[data-theme="dark"] .stars-clear-btn:hover {
    color: #fc8181;
    background: rgba(252, 129, 129, 0.15);
}

/* No results */
.stars-no-results {
    text-align: center;
    padding: 3rem 2rem;
    color: var(--text-secondary);
}

.stars-no-results-icon {
    font-size: 2rem;
    margin-bottom: 1rem;
    opacity: 0.3;
}

/* Keyboard shortcut hints */
kbd {
    display: inline-block;
    padding: 0.15rem 0.4rem;
    font-family: inherit;
    font-size: 0.8em;
    background: var(--code-bg);
    border: 1px solid var(--border-color);
    border-radius: 3px;
    box-shadow: 0 1px 0 var(--border-color);
}
</style>
{% endblock %}

{% block content %}
<div class="stars-container">
    <div id="stars-content">
        <!-- Populated by JavaScript -->
    </div>
</div>

<script>
(function() {
    var currentSearch = '';
    var currentSort = 'recent';

    function getBookmarks() {
        try {
            return JSON.parse(localStorage.getItem('kjvBookmarks') || '[]');
        } catch (e) {
            return [];
        }
    }

    function saveBookmarks(bookmarks) {
        localStorage.setItem('kjvBookmarks', JSON.stringify(bookmarks));
    }

    function formatDate(dateStr) {
        var date = new Date(dateStr);
        var now = new Date();
        var diffMs = now - date;
        var diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays === 0) return 'Today';
        if (diffDays === 1) return 'Yesterday';
        if (diffDays < 7) return diffDays + ' days ago';
        if (diffDays < 30) return Math.floor(diffDays / 7) + ' week' + (Math.floor(diffDays / 7) > 1 ? 's' : '') + ' ago';

        var options = { month: 'short', day: 'numeric' };
        if (date.getFullYear() !== now.getFullYear()) {
            options.year = 'numeric';
        }
        return date.toLocaleDateString('en-US', options);
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function removeBookmark(url, e) {
        if (e) e.stopPropagation();
        var bookmarks = getBookmarks();
        bookmarks = bookmarks.filter(function(b) { return b.url !== url; });
        saveBookmarks(bookmarks);
        renderBookmarks();
    }

    function updateNote(url, note) {
        var bookmarks = getBookmarks();
        var bookmark = bookmarks.find(function(b) { return b.url === url; });
        if (bookmark) {
            bookmark.note = note;
            saveBookmarks(bookmarks);
        }
    }

    function editNote(url) {
        var item = document.querySelector('[data-url="' + url + '"]');
        if (!item) return;

        var display = item.querySelector('.stars-note-display');
        var addLink = item.querySelector('.stars-note-add');
        var editLink = item.querySelector('.stars-note-edit');
        var textarea = item.querySelector('.stars-note');

        if (display) display.style.display = 'none';
        if (addLink) addLink.style.display = 'none';
        if (editLink) editLink.style.display = 'none';
        if (textarea) {
            textarea.classList.add('editing');
            textarea.focus();
        }
    }

    function saveAndCloseNote(url, note) {
        updateNote(url, note);
        // Re-render to show updated state, keeping this item expanded
        var expandedUrl = url;
        renderBookmarks();
        // Re-expand the item
        var item = document.querySelector('[data-url="' + expandedUrl + '"]');
        if (item) {
            item.classList.add('expanded');
        }
        // Show toast
        showNoteSavedToast();
    }

    function showNoteSavedToast() {
        var toast = document.getElementById('bookmark-toast');
        if (!toast) return;

        toast.innerHTML = 'Note saved';
        toast.classList.add('show');

        setTimeout(function() {
            toast.classList.remove('show');
        }, 2000);
    }

    function clearAllBookmarks() {
        if (confirm('Remove all starred pages? This cannot be undone.')) {
            localStorage.removeItem('kjvBookmarks');
            renderBookmarks();
        }
    }

    function toggleItem(url) {
        var item = document.querySelector('[data-url="' + url + '"]');
        if (item) {
            var wasExpanded = item.classList.contains('expanded');
            // Close others
            document.querySelectorAll('.stars-item.expanded').forEach(function(el) {
                el.classList.remove('expanded');
            });
            // Toggle this one
            if (!wasExpanded) {
                item.classList.add('expanded');
            }
        }
    }

    function copyLink(url, e) {
        if (e) e.stopPropagation();
        var fullUrl = window.location.origin + url;
        navigator.clipboard.writeText(fullUrl).then(function() {
            // Could show a toast here
        });
    }

    function getCollapsedGroups() {
        try {
            return JSON.parse(localStorage.getItem('kjvStarsCollapsed') || '[]');
        } catch (e) {
            return [];
        }
    }

    function saveCollapsedGroups(collapsed) {
        localStorage.setItem('kjvStarsCollapsed', JSON.stringify(collapsed));
    }

    function toggleGroup(groupId) {
        var group = document.getElementById(groupId);
        if (!group) return;

        var collapsed = getCollapsedGroups();
        var groupKey = group.querySelector('.stars-group-title').textContent.trim();

        if (group.classList.contains('collapsed')) {
            group.classList.remove('collapsed');
            collapsed = collapsed.filter(function(k) { return k !== groupKey; });
        } else {
            group.classList.add('collapsed');
            if (collapsed.indexOf(groupKey) === -1) {
                collapsed.push(groupKey);
            }
        }
        saveCollapsedGroups(collapsed);
    }

    function restoreCollapsedGroups() {
        var collapsed = getCollapsedGroups();
        document.querySelectorAll('.stars-group').forEach(function(group) {
            var title = group.querySelector('.stars-group-title');
            if (title) {
                var groupKey = title.textContent.trim();
                if (collapsed.indexOf(groupKey) !== -1) {
                    group.classList.add('collapsed');
                }
            }
        });
    }

    function handleSearch(query) {
        currentSearch = query.toLowerCase().trim();
        renderBookmarks();
    }

    function handleSort(sort) {
        currentSort = sort;
        renderBookmarks();
    }

    function handleGlobalNoteKeydown(e) {
        if (e.key === 'Enter') {
            var input = e.target;
            var note = input.value.trim();
            if (note) {
                addGlobalNote(note);
                input.value = '';
            }
        }
    }

    function addGlobalNote(note) {
        var notes = getGlobalNotes();
        notes.unshift({
            text: note,
            date: new Date().toISOString()
        });
        saveGlobalNotes(notes);
        renderBookmarks();
    }

    function getGlobalNotes() {
        try {
            return JSON.parse(localStorage.getItem('kjvStarsNotes') || '[]');
        } catch (e) {
            return [];
        }
    }

    function saveGlobalNotes(notes) {
        localStorage.setItem('kjvStarsNotes', JSON.stringify(notes));
    }

    function removeGlobalNote(index) {
        var notes = getGlobalNotes();
        notes.splice(index, 1);
        saveGlobalNotes(notes);
        renderBookmarks();
    }

    function getGroupBreadcrumbs(breadcrumbs) {
        // Group by the first two meaningful breadcrumbs (e.g., "Books / 1 Corinthians")
        // This keeps chapters and verses of the same book together
        if (!breadcrumbs || breadcrumbs.length === 0) return [];
        // Filter out "Home"
        var filtered = breadcrumbs.filter(function(c) { return c.text !== 'Home'; });
        if (filtered.length === 0) return [];
        // Take first two items max (e.g., "Books" + "1 Corinthians")
        return filtered.slice(0, 2);
    }

    function getBreadcrumbKey(breadcrumbs) {
        var groupCrumbs = getGroupBreadcrumbs(breadcrumbs);
        if (groupCrumbs.length === 0) return '';
        return groupCrumbs.map(function(c) { return c.text; }).join(' > ');
    }

    function renderBreadcrumbPath(breadcrumbs) {
        if (!breadcrumbs || breadcrumbs.length === 0) return 'Other';
        var filtered = breadcrumbs.filter(function(c) { return c.text !== 'Home'; });
        if (filtered.length === 0) return 'Other';
        var html = '';
        filtered.forEach(function(crumb, i) {
            if (i > 0) html += '<span class="stars-crumb-sep">/</span>';
            if (crumb.url) {
                html += '<a href="' + crumb.url + '">' + escapeHtml(crumb.text) + '</a>';
            } else {
                html += escapeHtml(crumb.text);
            }
        });
        return html;
    }

    function filterBookmarks(bookmarks) {
        if (!currentSearch) return bookmarks;
        return bookmarks.filter(function(b) {
            var searchStr = (b.title + ' ' + (b.description || '') + ' ' + (b.note || '')).toLowerCase();
            return searchStr.indexOf(currentSearch) !== -1;
        });
    }

    function sortBookmarks(bookmarks) {
        var sorted = bookmarks.slice();
        if (currentSort === 'recent') {
            sorted.sort(function(a, b) { return new Date(b.date) - new Date(a.date); });
        } else if (currentSort === 'oldest') {
            sorted.sort(function(a, b) { return new Date(a.date) - new Date(b.date); });
        } else if (currentSort === 'alpha') {
            sorted.sort(function(a, b) { return a.title.localeCompare(b.title); });
        }
        return sorted;
    }

    function renderBookmarks() {
        var container = document.getElementById('stars-content');
        var countEl = document.getElementById('stars-count');
        var allBookmarks = getBookmarks();

        // Update count
        if (countEl) {
            countEl.textContent = allBookmarks.length;
        }

        if (allBookmarks.length === 0) {
            container.innerHTML =
                '<div class="stars-empty">' +
                    '<div class="stars-empty-icon">★</div>' +
                    '<p class="stars-empty-title">Start building your collection</p>' +
                    '<p class="stars-empty-text">Star passages and pages as you study to create your own personal library of Scripture and resources.</p>' +
                    '<div class="stars-empty-hint">' +
                        'Press <kbd>⌘</kbd><kbd>S</kbd> or click ☆ to star any page' +
                    '</div>' +
                    '<div class="stars-cta">' +
                        '<div class="stars-cta-title">Suggested starting point</div>' +
                        '<a href="/book/1 Corinthians/chapter/13">1 Corinthians 13</a>' +
                        '<p class="stars-cta-desc">The beloved chapter on the nature and supremacy of love</p>' +
                    '</div>' +
                    '<p class="stars-empty-note">Your starred pages are stored in this browser only. They won\'t sync across devices, and clearing browser data will remove them.</p>' +
                '</div>';
            return;
        }

        // Apply filters and sorting
        var bookmarks = filterBookmarks(allBookmarks);
        bookmarks = sortBookmarks(bookmarks);

        var html = '';

        // Header - only shown when there are stars
        html += '<div class="stars-header">';
        html += '<h1>Starred Pages</h1>';
        html += '</div>';

        // Toolbar - sort only
        html += '<div class="stars-toolbar">';
        html += '<div class="stars-sort">';
        html += '<span class="stars-sort-label">Sort</span>';
        html += '<select class="stars-sort-select" onchange="handleSort(this.value)">';
        html += '<option value="recent"' + (currentSort === 'recent' ? ' selected' : '') + '>Recent</option>';
        html += '<option value="oldest"' + (currentSort === 'oldest' ? ' selected' : '') + '>Oldest</option>';
        html += '<option value="alpha"' + (currentSort === 'alpha' ? ' selected' : '') + '>A-Z</option>';
        html += '</select>';
        html += '</div>';
        html += '</div>';

        if (bookmarks.length === 0) {
            html += '<div class="stars-no-results">';
            html += '<div class="stars-no-results-icon">⌕</div>';
            html += '<p>No starred pages match your search</p>';
            html += '</div>';
            container.innerHTML = html;
            return;
        }

        // Group bookmarks
        var groups = {};
        var groupOrder = [];
        bookmarks.forEach(function(bookmark) {
            var key = getBreadcrumbKey(bookmark.breadcrumbs);
            if (!groups[key]) {
                groups[key] = {
                    breadcrumbs: getGroupBreadcrumbs(bookmark.breadcrumbs),
                    items: []
                };
                groupOrder.push(key);
            }
            groups[key].items.push(bookmark);
        });

        groupOrder.forEach(function(key, groupIndex) {
            var group = groups[key];
            var groupId = 'stars-group-' + groupIndex;
            html += '<div class="stars-group" id="' + groupId + '">';
            html += '<div class="stars-group-header" onclick="toggleGroup(\'' + groupId + '\')">';
            html += '<h3 class="stars-group-title"><span class="stars-group-toggle">▼</span>' + renderBreadcrumbPath(group.breadcrumbs) + '</h3>';
            html += '<span class="stars-group-count">' + group.items.length + '</span>';
            html += '</div>';
            html += '<div class="stars-group-content">';
            html += '<ul class="stars-list">';

            group.items.forEach(function(bookmark) {
                var safeUrl = bookmark.url.replace(/'/g, "\\'");
                var preview = bookmark.description || bookmark.excerpt || '';
                if (preview.length > 120) preview = preview.substring(0, 120) + '...';

                html += '<li class="stars-item" data-url="' + escapeHtml(bookmark.url) + '">';

                // Header
                html += '<div class="stars-item-header" onclick="toggleItem(\'' + safeUrl + '\')">';
                html += '<div class="stars-item-content">';
                html += '<div class="stars-item-title"><span class="stars-item-title-text" onclick="event.stopPropagation(); window.location.href=\'' + safeUrl + '\'">' + escapeHtml(bookmark.title) + '</span><a href="' + bookmark.url + '" class="stars-item-title-link" onclick="event.stopPropagation()">⤴</a></div>';
                html += '<div class="stars-item-meta">';
                html += '<span class="stars-item-date">' + formatDate(bookmark.date) + '</span>';
                if (bookmark.note) {
                    html += '<span class="stars-item-note-indicator">has notes</span>';
                }
                html += '</div>';
                html += '</div>';
                html += '<span class="stars-item-actions">';
                html += '<button class="stars-action-btn" onclick="copyLink(\'' + safeUrl + '\', event)" title="Copy link">copy url</button>';
                html += '</span>';
                html += '<span class="stars-item-toggle">▶</span>';
                html += '</div>';

                // Detail
                html += '<div class="stars-item-detail">';

                if (bookmark.description) {
                    html += '<div class="stars-detail-section">';
                    html += '<div class="stars-detail-label">Description</div>';
                    html += '<div class="stars-description">' + escapeHtml(bookmark.description) + '</div>';
                    html += '</div>';
                }

                if (bookmark.excerpt && bookmark.excerpt !== bookmark.description) {
                    html += '<div class="stars-detail-section">';
                    html += '<div class="stars-detail-label">Excerpt</div>';
                    html += '<div class="stars-excerpt">' + escapeHtml(bookmark.excerpt.substring(0, 300)) + (bookmark.excerpt.length > 300 ? '...' : '') + '</div>';
                    html += '</div>';
                }

                html += '<div class="stars-detail-section">';
                html += '<div class="stars-detail-label">Your Notes</div>';
                if (bookmark.note) {
                    html += '<div class="stars-note-display">' + escapeHtml(bookmark.note) + '</div>';
                    html += '<span class="stars-note-edit" onclick="event.stopPropagation(); editNote(\'' + safeUrl + '\')">[edit note]</span>';
                } else {
                    html += '<span class="stars-note-add" onclick="event.stopPropagation(); editNote(\'' + safeUrl + '\')">[add note]</span>';
                }
                html += '<textarea class="stars-note" data-note-url="' + escapeHtml(bookmark.url) + '" placeholder="Add your thoughts, reflections, or study notes..." onblur="saveAndCloseNote(\'' + safeUrl + '\', this.value)" onclick="event.stopPropagation()">' + escapeHtml(bookmark.note || '') + '</textarea>';
                html += '<div class="stars-note-saved"></div>';
                html += '</div>';

                // Actions in detail
                html += '<div class="stars-detail-section">';
                html += '<button class="stars-action-btn danger" onclick="removeBookmark(\'' + safeUrl + '\', event)" title="Remove">remove star</button>';
                html += '</div>';

                html += '</div>';
                html += '</li>';
            });

            html += '</ul>';
            html += '</div>'; // stars-group-content
            html += '</div>'; // stars-group
        });

        // Footer
        html += '<div class="stars-footer">';
        html += '<span class="stars-footer-info">' + allBookmarks.length + ' starred page' + (allBookmarks.length !== 1 ? 's' : '') + '</span>';
        html += '<button class="stars-clear-btn" onclick="clearAllBookmarks()">Clear all stars</button>';
        html += '</div>';

        container.innerHTML = html;

        // Restore collapsed state
        restoreCollapsedGroups();
    }

    // Make functions global
    window.removeBookmark = removeBookmark;
    window.clearAllBookmarks = clearAllBookmarks;
    window.toggleItem = toggleItem;
    window.updateNote = updateNote;
    window.editNote = editNote;
    window.saveAndCloseNote = saveAndCloseNote;
    window.handleSort = handleSort;
    window.copyLink = copyLink;
    window.toggleGroup = toggleGroup;

    // Initial render
    renderBookmarks();

    // Keyboard navigation
    var selectedIndex = -1;

    function getItems() {
        return Array.from(document.querySelectorAll('.stars-item'));
    }

    function clearSelection() {
        getItems().forEach(function(item) {
            item.style.outline = '';
            item.style.outlineOffset = '';
        });
    }

    function selectItem(index) {
        var items = getItems();
        if (items.length === 0) return;

        clearSelection();
        selectedIndex = Math.max(0, Math.min(index, items.length - 1));
        items[selectedIndex].style.outline = '2px solid #4a7c59';
        items[selectedIndex].style.outlineOffset = '4px';

        // Only scroll if item is out of view
        var rect = items[selectedIndex].getBoundingClientRect();
        if (rect.top < 0 || rect.bottom > window.innerHeight) {
            items[selectedIndex].scrollIntoView({ behavior: 'auto', block: 'nearest' });
        }
    }

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

        var items = getItems();
        if (items.length === 0) return;

        if (e.key === 'ArrowDown' || e.key === 'j') {
            e.preventDefault();
            selectItem(selectedIndex < 0 ? 0 : selectedIndex + 1);
        } else if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            selectItem(selectedIndex <= 0 ? 0 : selectedIndex - 1);
        } else if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            // If selected item is expanded, collapse it
            if (selectedIndex >= 0 && items[selectedIndex] && items[selectedIndex].classList.contains('expanded')) {
                var url = items[selectedIndex].getAttribute('data-url');
                if (url) toggleItem(url);
            } else if (selectedIndex < 0) {
                // Nothing selected, go back
                history.back();
            }
        } else if (e.key === 'ArrowRight' || e.key === 'l') {
            // Expand selected item
            if (selectedIndex >= 0 && items[selectedIndex]) {
                var url = items[selectedIndex].getAttribute('data-url');
                if (url) toggleItem(url);
            }
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (selectedIndex >= 0 && items[selectedIndex]) {
                var link = items[selectedIndex].querySelector('.stars-item-title-link');
                if (link) window.location.href = link.href;
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            clearSelection();
            selectedIndex = -1;
            // Also collapse any expanded items
            document.querySelectorAll('.stars-item.expanded').forEach(function(item) {
                item.classList.remove('expanded');
            });
        } else if (e.key === 'x' || e.key === 'Delete' || e.key === 'Backspace') {
            // Remove selected item
            if (selectedIndex >= 0 && items[selectedIndex]) {
                e.preventDefault();
                var url = items[selectedIndex].getAttribute('data-url');
                if (url) {
                    removeBookmark(url);
                    // Adjust selection after removal
                    items = getItems();
                    if (items.length > 0) {
                        selectedIndex = Math.min(selectedIndex, items.length - 1);
                        selectItem(selectedIndex);
                    } else {
                        selectedIndex = -1;
                    }
                }
            }
        }
    });
})();
</script>
{% endblock %}
