{% extends "base.html" %}

{% block title %}{{ plan.name }} - KJV Study{% endblock %}
{% block description %}{{ plan.description }}{% endblock %}

{% block head %}
<style>
.plan-overview {
    max-width: 60%;
    font-size: 1.2rem;
    line-height: 1.9;
    margin: 1.5rem 0;
    padding: 1rem;
    border-left: 3px solid var(--border-color-darker);
    background: var(--code-bg);
}

.plan-stats {
    display: flex;
    gap: 2rem;
    margin: 1.5rem 0;
    max-width: 60%;
}

.stat-item {
    padding: 1rem;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    flex: 1;
}

.stat-value {
    font-size: 2rem;
    font-weight: 600;
    color: var(--link-color);
}

.stat-label {
    font-size: 0.9rem;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.intro-text {
    max-width: 60%;
    font-size: 1.2rem;
    line-height: 1.9;
    margin: 1rem 0;
}

.plan-actions {
    display: flex;
    gap: 1rem;
    margin: 1rem 0 1.5rem;
    flex-wrap: wrap;
}

.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);
}

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

/* Progress bar */
.progress-section {
    margin: 1.5rem 0;
    max-width: 60%;
}

.progress-bar-container {
    background: var(--code-bg);
    border-radius: 4px;
    height: 24px;
    overflow: hidden;
    border: 1px solid var(--border-color);
}

.progress-bar {
    height: 100%;
    background: var(--link-color);
    transition: width 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 0.8rem;
    font-weight: 600;
}

.progress-text {
    margin-top: 0.5rem;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

/* Day navigation */
.day-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin: 1.5rem 0;
    padding: 1rem;
    background: var(--code-bg);
    border-radius: 4px;
    max-width: 90%;
}

.day-nav a {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    font-size: 0.8rem;
    color: var(--text-secondary);
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: 3px;
    text-decoration: none;
    transition: all 0.15s;
    min-width: 28px;
    text-align: center;
}

.day-nav a:hover {
    border-color: var(--link-color);
    color: var(--link-color);
}

.day-nav a.completed {
    background: #4a7c59;
    color: white;
    border-color: #4a7c59;
}

/* Day entries */
.reading-day {
    margin: 1.5rem 0;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    overflow: hidden;
}

.reading-day.completed {
    border-color: #4a7c59;
}

.day-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 0.75rem 1rem;
    background: var(--code-bg);
    cursor: pointer;
    user-select: none;
}

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

.day-checkbox {
    width: 20px;
    height: 20px;
    cursor: pointer;
    accent-color: var(--link-color);
}

.day-number {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--link-color);
    min-width: 70px;
}

.day-readings {
    display: flex;
    flex-wrap: wrap;
    gap: 0.3rem;
    margin-right: auto;
}

.day-readings span {
    padding: 0.2rem 0.5rem;
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: 3px;
    font-size: 0.85rem;
    color: var(--text-color);
}

.day-theme {
    font-style: italic;
    color: var(--text-secondary);
    font-size: 0.9rem;
    margin-left: 1rem;
}

.day-toggle {
    font-size: 1.2rem;
    color: var(--text-secondary);
    transition: transform 0.2s;
    transform: rotate(-90deg);
}

.day-toggle.expanded {
    transform: rotate(0deg);
}

/* Scripture content */
.day-content {
    display: none;
    padding: 1rem;
    border-top: 1px solid var(--border-color);
}

.day-content.expanded {
    display: block;
}

.day-content.loading {
    display: block;
    text-align: center;
    padding: 2rem;
    color: var(--text-secondary);
}

.chapter-section {
    margin: 1.5rem 0;
}

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

.chapter-heading {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-color);
    margin-bottom: 0.75rem;
    padding-bottom: 0.4rem;
    border-bottom: 1px solid var(--border-color);
}

.chapter-heading a {
    color: inherit;
    text-decoration: none;
}

.chapter-heading a:hover {
    color: var(--link-color);
}

.verse-text {
    line-height: 1.85;
    text-align: justify;
}

.verse-num {
    font-weight: 600;
    color: var(--text-secondary);
    font-size: 0.8rem;
    vertical-align: super;
    margin-right: 0.1rem;
}

@media print {
    .plan-actions,
    .action-btn,
    .day-nav,
    .progress-section,
    .day-checkbox {
        display: none;
    }
    .day-content {
        display: block !important;
    }
}

@media (max-width: 768px) {
    .plan-overview,
    .plan-stats,
    .intro-text,
    .progress-section {
        max-width: 100%;
    }
    .day-nav {
        max-width: 100%;
    }
    .day-header {
        flex-wrap: wrap;
    }
    .day-theme {
        order: 3;
        width: 100%;
        margin-top: 0.5rem;
    }
}

/* Large font mode - template-specific rules (shared rules in base.html) */
[data-font-size="large"] .stat-value {
    font-size: 2.5rem;
}
[data-font-size="large"] .stat-label {
    font-size: 1.1rem;
}
[data-font-size="large"] .progress-text {
    font-size: 1.1rem;
}
[data-font-size="large"] .day-nav a {
    font-size: 1rem;
    padding: 0.35rem 0.6rem;
}
[data-font-size="large"] .day-number {
    font-size: 1.3rem;
}
[data-font-size="large"] .day-readings span {
    font-size: 1.05rem;
}
[data-font-size="large"] .day-theme {
    font-size: 1.1rem;
}
[data-font-size="large"] .chapter-heading {
    font-size: 1.3rem;
}
</style>
{% endblock %}

{% block content %}
<h1>{{ plan.name }}</h1>
<p class="subtitle">{{ plan.description }}</p>

<div class="plan-actions">
    {% if pdf_available and pdf_url %}
    <a href="{{ pdf_url }}" 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>
    {% endif %}
    <button class="action-btn" onclick="resetProgress()">
        <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
        Reset Progress
    </button>
</div>

<section>
    <div class="plan-stats">
        <div class="stat-item">
            <div class="stat-value">{{ plan.duration_days }}</div>
            <div class="stat-label">Days</div>
        </div>
        <div class="stat-item">
            <div class="stat-value">{{ (plan.duration_days / 7) | round | int }}</div>
            <div class="stat-label">Weeks</div>
        </div>
        <div class="stat-item">
            <div class="stat-value" id="completed-count">0</div>
            <div class="stat-label">Completed</div>
        </div>
    </div>

    <div class="progress-section">
        <div class="progress-bar-container">
            <div class="progress-bar" id="progress-bar" style="width: 0%">0%</div>
        </div>
        <p class="progress-text" id="progress-text">Start reading to track your progress</p>
    </div>

    <div class="plan-overview">
        {{ plan.overview }}
    </div>
</section>

<section>
    <h2>Reading Schedule</h2>
    <p class="intro-text">Click a day to expand and load the Scripture text. Check the box to mark as read.</p>

    <div class="day-nav" id="day-nav">
        {% for day in days_data %}
        <a href="#day-{{ day.day }}" id="nav-{{ day.day }}">{{ day.day }}</a>
        {% endfor %}
    </div>
</section>

{% for day in days_data %}
<div class="reading-day" id="day-{{ day.day }}" data-day="{{ day.day }}">
    <div class="day-header" onclick="toggleDay({{ day.day }}, event)">
        <input type="checkbox" class="day-checkbox" id="check-{{ day.day }}" onclick="event.stopPropagation(); markDay({{ day.day }})">
        <span class="day-number">Day {{ day.day }}</span>
        <span class="day-readings">
            {% for reading in day.readings %}<span>{{ reading }}</span>{% endfor %}
        </span>
        <span class="day-theme">{{ day.theme }}</span>
        <span class="day-toggle" id="toggle-{{ day.day }}">▼</span>
    </div>
    <div class="day-content" id="content-{{ day.day }}"></div>
</div>
{% endfor %}

<section>
    <h2>How to Use This Plan</h2>
    <p class="intro-text"><span class="newthought">Consistency matters more</span> than perfection. If you miss a day, simply continue where you left off rather than attempting to catch up through extended readings. The goal is sustainable Scripture engagement, not merely completing a schedule.</p>

    <p class="intro-text">Your progress is saved automatically in your browser. Check each day as you complete it to track your journey through Scripture.</p>
</section>

<section>
    <p><a href="/reading-plans">← Back to all reading plans</a></p>
</section>

<script>
(function() {
    var planId = '{{ plan_id }}';
    var totalDays = {{ total_days }};
    var storageKey = 'reading-plan-' + planId;
    var loadedDays = {}; // Track which days have been loaded

    // Load saved progress
    function loadProgress() {
        var saved = localStorage.getItem(storageKey);
        return saved ? JSON.parse(saved) : { completed: [], expanded: [] };
    }

    // Save progress
    function saveProgress(data) {
        localStorage.setItem(storageKey, JSON.stringify(data));
    }

    // Render scripture text into a day's content div
    function renderDayContent(day, data) {
        var content = document.getElementById('content-' + day);
        if (!content || !data.text) return;

        var html = '';
        data.text.forEach(function(section) {
            html += '<div class="chapter-section">';
            html += '<div class="chapter-heading">';
            html += '<a href="/book/' + section.book + '/chapter/' + section.chapter + '">' + section.reference + '</a>';
            html += '</div>';
            html += '<div class="verse-text">';
            section.verses.forEach(function(verse) {
                html += '<sup class="verse-num">' + verse.verse + '</sup>' + verse.text + ' ';
            });
            html += '</div></div>';
        });

        content.innerHTML = html;
        content.classList.remove('loading');
        loadedDays[day] = true;
    }

    // Load day text from API
    function loadDayText(day) {
        if (loadedDays[day]) return Promise.resolve();

        var content = document.getElementById('content-' + day);
        content.innerHTML = 'Loading Scripture text...';
        content.classList.add('loading');

        return fetch('/api/reading-plans/' + planId + '/day/' + day)
            .then(function(response) {
                if (!response.ok) throw new Error('Failed to load');
                return response.json();
            })
            .then(function(data) {
                renderDayContent(day, data);
            })
            .catch(function(err) {
                content.innerHTML = 'Failed to load Scripture text. <a href="javascript:void(0)" onclick="loadDayText(' + day + ')">Try again</a>';
                content.classList.remove('loading');
            });
    }

    // Update UI based on saved state
    function updateUI() {
        var data = loadProgress();
        var completedCount = data.completed.length;

        // Update checkboxes and day styling
        for (var i = 1; i <= totalDays; i++) {
            var checkbox = document.getElementById('check-' + i);
            var dayEl = document.getElementById('day-' + i);
            var navEl = document.getElementById('nav-' + i);

            if (checkbox && data.completed.indexOf(i) !== -1) {
                checkbox.checked = true;
                if (dayEl) dayEl.classList.add('completed');
                if (navEl) navEl.classList.add('completed');
            } else {
                if (checkbox) checkbox.checked = false;
                if (dayEl) dayEl.classList.remove('completed');
                if (navEl) navEl.classList.remove('completed');
            }
        }

        // Update progress bar
        var percent = Math.round((completedCount / totalDays) * 100);
        var progressBar = document.getElementById('progress-bar');
        var progressText = document.getElementById('progress-text');
        var completedEl = document.getElementById('completed-count');

        if (progressBar) {
            progressBar.style.width = percent + '%';
            progressBar.textContent = percent + '%';
        }
        if (completedEl) {
            completedEl.textContent = completedCount;
        }
        if (progressText) {
            if (completedCount === 0) {
                progressText.textContent = 'Start reading to track your progress';
            } else if (completedCount === totalDays) {
                progressText.textContent = 'Congratulations! You\'ve completed the plan!';
            } else {
                var remaining = totalDays - completedCount;
                progressText.textContent = remaining + ' day' + (remaining === 1 ? '' : 's') + ' remaining';
            }
        }
    }

    // Restore expanded state on load
    function restoreExpandedState() {
        var data = loadProgress();
        data.expanded.forEach(function(day) {
            var content = document.getElementById('content-' + day);
            var toggle = document.getElementById('toggle-' + day);
            if (content) {
                content.classList.add('expanded');
                if (toggle) toggle.classList.add('expanded');
                loadDayText(day);
            }
        });
    }

    // Toggle day expansion
    window.toggleDay = function(day, event) {
        if (event && event.target.classList.contains('day-checkbox')) return;

        var content = document.getElementById('content-' + day);
        var toggle = document.getElementById('toggle-' + day);
        var data = loadProgress();

        if (content.classList.contains('expanded')) {
            content.classList.remove('expanded');
            toggle.classList.remove('expanded');
            var idx = data.expanded.indexOf(day);
            if (idx > -1) data.expanded.splice(idx, 1);
        } else {
            content.classList.add('expanded');
            toggle.classList.add('expanded');
            if (data.expanded.indexOf(day) === -1) data.expanded.push(day);
            loadDayText(day);
        }
        saveProgress(data);
    };

    // Mark day as complete/incomplete
    // When checking a day, mark all previous days as complete
    // When unchecking a day, uncheck all subsequent days
    window.markDay = function(day) {
        var data = loadProgress();
        var isCompleted = data.completed.indexOf(day) !== -1;

        if (isCompleted) {
            // Unchecking: remove this day and all days after it
            data.completed = data.completed.filter(function(d) {
                return d < day;
            });
        } else {
            // Checking: add this day and all days before it
            for (var i = 1; i <= day; i++) {
                if (data.completed.indexOf(i) === -1) {
                    data.completed.push(i);
                }
            }
        }
        saveProgress(data);
        updateUI();
    };

    // Reset all progress
    window.resetProgress = function() {
        if (confirm('Reset all progress for this reading plan?')) {
            localStorage.removeItem(storageKey);
            loadedDays = {};
            // Collapse all
            for (var i = 1; i <= totalDays; i++) {
                var content = document.getElementById('content-' + i);
                var toggle = document.getElementById('toggle-' + i);
                if (content) {
                    content.classList.remove('expanded');
                    content.innerHTML = '';
                }
                if (toggle) toggle.classList.remove('expanded');
            }
            updateUI();
        }
    };

    // Make loadDayText globally available for retry links
    window.loadDayText = loadDayText;

    // Initialize
    updateUI();
    restoreExpandedState();

    // Keyboard navigation
    var days = Array.from(document.querySelectorAll('.reading-day'));
    var selectedDayIndex = -1;
    var selectedSectionIndex = -1; // -1 means day header selected, 0+ means section within expanded day
    var inExpandedMode = false;

    function clearSelection() {
        // Clear day selection
        if (selectedDayIndex >= 0 && selectedDayIndex < days.length) {
            days[selectedDayIndex].style.outline = '';
            // Clear any section selection
            var sections = days[selectedDayIndex].querySelectorAll('.chapter-section');
            sections.forEach(function(s) { s.style.outline = ''; });
        }
    }

    function selectDay(index) {
        clearSelection();
        inExpandedMode = false;
        selectedSectionIndex = -1;
        selectedDayIndex = Math.max(0, Math.min(index, days.length - 1));
        days[selectedDayIndex].style.outline = '2px solid #4a7c59';
        days[selectedDayIndex].style.outlineOffset = '4px';
        days[selectedDayIndex].scrollIntoView({ behavior: 'auto', block: 'center' });
    }

    function selectSection(sectionIndex) {
        if (selectedDayIndex < 0) return;
        var content = document.getElementById('content-' + days[selectedDayIndex].dataset.day);
        if (!content || !content.classList.contains('expanded')) return;

        var sections = content.querySelectorAll('.chapter-section');
        if (sections.length === 0) return;

        // Clear previous section highlight
        sections.forEach(function(s) { s.style.outline = ''; });
        days[selectedDayIndex].style.outline = '';

        selectedSectionIndex = Math.max(0, Math.min(sectionIndex, sections.length - 1));
        inExpandedMode = true;
        sections[selectedSectionIndex].style.outline = '2px solid #4a7c59';
        sections[selectedSectionIndex].style.outlineOffset = '4px';
        sections[selectedSectionIndex].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 currentDay = selectedDayIndex >= 0 ? days[selectedDayIndex] : null;
        var isExpanded = currentDay && document.getElementById('content-' + currentDay.dataset.day).classList.contains('expanded');

        if (e.key === 'ArrowDown' || e.key === 'j') {
            e.preventDefault();
            if (inExpandedMode && isExpanded) {
                // Navigate within sections
                var content = document.getElementById('content-' + currentDay.dataset.day);
                var sections = content.querySelectorAll('.chapter-section');
                if (selectedSectionIndex < sections.length - 1) {
                    selectSection(selectedSectionIndex + 1);
                } else {
                    // Move to next day
                    selectDay(selectedDayIndex + 1);
                }
            } else {
                selectDay(selectedDayIndex < 0 ? 0 : selectedDayIndex + 1);
            }
        } else if (e.key === 'ArrowUp' || e.key === 'k') {
            e.preventDefault();
            if (inExpandedMode && isExpanded) {
                if (selectedSectionIndex > 0) {
                    selectSection(selectedSectionIndex - 1);
                } else {
                    // Back to day header
                    selectDay(selectedDayIndex);
                }
            } else {
                if (selectedDayIndex <= 0) selectDay(0);
                else selectDay(selectedDayIndex - 1);
            }
        } else if (e.key === 'ArrowLeft' || e.key === 'h') {
            e.preventDefault();
            if (inExpandedMode) {
                // Exit section mode, go back to day
                selectDay(selectedDayIndex);
            } else {
                history.back();
            }
        } else if (e.key === 'ArrowRight' || e.key === 'l') {
            e.preventDefault();
            if (selectedDayIndex >= 0 && isExpanded && !inExpandedMode) {
                // Enter section navigation
                selectSection(0);
            }
        } else if ((e.key === 'Enter' || e.key === ' ') && selectedDayIndex >= 0) {
            e.preventDefault();
            if (inExpandedMode) {
                // Click the chapter link
                var content = document.getElementById('content-' + currentDay.dataset.day);
                var sections = content.querySelectorAll('.chapter-section');
                if (sections[selectedSectionIndex]) {
                    var link = sections[selectedSectionIndex].querySelector('.chapter-heading a');
                    if (link) link.click();
                }
            } else {
                var dayNum = parseInt(currentDay.dataset.day);
                toggleDay(dayNum);
            }
        } else if (e.key === 'x' && selectedDayIndex >= 0) {
            e.preventDefault();
            var dayNum = parseInt(currentDay.dataset.day);
            markDay(dayNum);
            updateUI();
        } else if (e.key === 'Escape') {
            e.preventDefault();
            if (inExpandedMode) {
                selectDay(selectedDayIndex);
            } else if (selectedDayIndex >= 0) {
                clearSelection();
                selectedDayIndex = -1;
            }
        }
    });
})();
</script>
{% endblock %}
