

<?php $__env->startSection('title', $chapter->title . ' - ' . $book->title); ?>

<?php $__env->startPush('styles'); ?>
<!-- Prism.js for code highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="<?php echo e(asset('css/book-reader-styles.css')); ?>">
<style>
    .book-reader-container {
        display: flex;
        min-height: calc(100vh - 80px);
        background: #0f0f0f;
    }

    .book-sidebar {
        width: 300px;
        background: linear-gradient(180deg, #1a1a1a 0%, #151515 100%);
        border-right: 1px solid #2a2a2a;
        padding: 20px;
        overflow-y: auto;
        position: sticky;
        top: 60px;
        height: calc(100vh - 60px);
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.3);
    }

    .book-content-area {
        flex: 1;
        padding: 0;
        overflow-y: auto;
        max-width: 1200px;
        margin: 0 auto;
        background: #0f0f0f;
    }

    /* Enhanced Toolbar */
    .book-toolbar {
        background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
        padding: 20px 30px;
        border-bottom: 2px solid #4a9eff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: sticky;
        top: 60px;
        z-index: 100;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(10px);
    }

    .toolbar-section {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .toolbar-group {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 0 12px;
        border-right: 1px solid #404040;
    }

    .toolbar-group:last-child {
        border-right: none;
    }

    .toolbar-btn {
        background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%);
        border: 1px solid #404040;
        color: #e0e0e0;
        padding: 10px 18px;
        border-radius: 8px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        display: inline-flex;
        align-items: center;
        gap: 8px;
        text-decoration: none;
        white-space: nowrap;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }

    .toolbar-btn:hover {
        background: linear-gradient(135deg, #4a9eff 0%, #3a8eef 100%);
        border-color: #4a9eff;
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(74, 158, 255, 0.4);
    }

    .toolbar-btn:active {
        transform: translateY(0);
    }

    .toolbar-btn.active {
        background: linear-gradient(135deg, #4a9eff 0%, #3a8eef 100%);
        border-color: #4a9eff;
        color: white;
        box-shadow: 0 4px 12px rgba(74, 158, 255, 0.4);
    }

    .toolbar-btn.primary {
        background: linear-gradient(135deg, #4a9eff 0%, #3a8eef 100%);
        border-color: #4a9eff;
        color: white;
    }

    .toolbar-btn.primary:hover {
        background: linear-gradient(135deg, #3a8eef 0%, #2a7eef 100%);
        box-shadow: 0 6px 16px rgba(74, 158, 255, 0.5);
    }

    .toolbar-btn.success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        border-color: #10b981;
        color: white;
    }

    .toolbar-btn.success:hover {
        background: linear-gradient(135deg, #059669 0%, #047857 100%);
        box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
    }

    .toolbar-btn:disabled,
    .toolbar-btn.disabled {
        opacity: 0.5;
        cursor: not-allowed;
        pointer-events: none;
    }

    .chapter-nav {
        display: flex;
        gap: 8px;
    }

    .chapter-nav-btn {
        background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%);
        border: 1px solid #404040;
        color: #e0e0e0;
        padding: 10px 20px;
        border-radius: 8px;
        text-decoration: none;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        display: inline-flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }

    .chapter-nav-btn:hover:not(:disabled) {
        background: linear-gradient(135deg, #4a9eff 0%, #3a8eef 100%);
        border-color: #4a9eff;
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(74, 158, 255, 0.4);
    }

    .chapter-nav-btn:disabled {
        opacity: 0.4;
        cursor: not-allowed;
    }

    .sidebar-section {
        margin-bottom: 30px;
    }

    .sidebar-section-title {
        color: #4a9eff;
        font-size: 13px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1.5px;
        margin-bottom: 15px;
        padding-bottom: 12px;
        border-bottom: 2px solid #4a9eff;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .chapter-list-item {
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 6px;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 12px;
        border: 1px solid transparent;
    }

    .chapter-list-item:hover {
        background: rgba(74, 158, 255, 0.1);
        border-color: rgba(74, 158, 255, 0.3);
    }

    .chapter-list-item.active {
        background: linear-gradient(135deg, rgba(74, 158, 255, 0.2) 0%, rgba(74, 158, 255, 0.1) 100%);
        border-left: 4px solid #4a9eff;
        padding-left: 8px;
    }

    .chapter-list-item a {
        color: #e0e0e0;
        text-decoration: none;
        flex: 1;
        font-size: 14px;
        line-height: 1.5;
    }

    .chapter-list-item.active a {
        color: #4a9eff;
        font-weight: 600;
    }

    .chapter-number-badge {
        background: linear-gradient(135deg, #4a9eff 0%, #3a8eef 100%);
        color: white;
        width: 28px;
        height: 28px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 700;
        box-shadow: 0 2px 8px rgba(74, 158, 255, 0.3);
        flex-shrink: 0;
    }

    .chapter-list-item.active .chapter-number-badge {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
    }

    /* Enhanced Chapter Content */
    #chapter-content {
        background: #0f0f0f;
        padding: 50px 60px;
        border-radius: 0;
        line-height: 1.8;
        color: #e0e0e0;
    }

    /* Enhanced Code Blocks */
    #chapter-content pre {
        background: #1a1a1a !important;
        border: 1px solid #2a2a2a;
        border-left: 4px solid #4a9eff;
        border-radius: 12px;
        padding: 24px;
        overflow-x: auto;
        margin: 30px 0;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        position: relative;
    }

    #chapter-content pre code {
        background: transparent !important;
        border: none;
        color: #e0e0e0;
        padding: 0;
        font-size: 14px;
        line-height: 1.7;
        font-family: 'Fira Code', 'Consolas', 'Monaco', 'Courier New', monospace;
    }

    #chapter-content code:not(pre code) {
        background: rgba(74, 158, 255, 0.15);
        border: 1px solid rgba(74, 158, 255, 0.3);
        color: #4a9eff;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 14px;
        font-family: 'Fira Code', 'Consolas', 'Monaco', 'Courier New', monospace;
    }

    /* Copy Code Button */
    #chapter-content pre {
        position: relative;
    }

    .code-copy-btn {
        position: absolute;
        top: 12px;
        right: 12px;
        background: rgba(74, 158, 255, 0.2);
        border: 1px solid rgba(74, 158, 255, 0.4);
        color: #4a9eff;
        padding: 6px 12px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s;
        opacity: 0;
        pointer-events: none;
    }

    #chapter-content pre:hover .code-copy-btn {
        opacity: 1;
        pointer-events: all;
    }

    .code-copy-btn:hover {
        background: rgba(74, 158, 255, 0.3);
        border-color: #4a9eff;
        transform: scale(1.05);
    }

    .code-copy-btn.copied {
        background: rgba(16, 185, 129, 0.2);
        border-color: #10b981;
        color: #10b981;
    }

    /* Notes Panel */
    .notes-panel {
        position: fixed;
        right: -400px;
        top: 60px;
        width: 400px;
        height: calc(100vh - 60px);
        background: linear-gradient(180deg, #1a1a1a 0%, #151515 100%);
        border-left: 2px solid #4a9eff;
        padding: 25px;
        overflow-y: auto;
        transition: right 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        z-index: 200;
        box-shadow: -4px 0 20px rgba(0, 0, 0, 0.5);
    }

    .notes-panel.active {
        right: 0;
    }

    .note-item {
        background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%);
        border: 1px solid #404040;
        border-radius: 10px;
        padding: 18px;
        margin-bottom: 15px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }

    .note-header {
        display: flex;
        justify-content: space-between;
        align-items: start;
        margin-bottom: 12px;
    }

    .note-content {
        color: #e0e0e0;
        font-size: 14px;
        line-height: 1.7;
        margin-bottom: 10px;
    }

    .note-highlight {
        background: rgba(74, 158, 255, 0.15);
        border-left: 3px solid #4a9eff;
        padding: 10px 12px;
        border-radius: 4px;
        font-size: 12px;
        color: #4a9eff;
        margin-top: 8px;
    }

    .note-actions {
        display: flex;
        gap: 8px;
    }

    .note-action-btn {
        background: transparent;
        border: 1px solid #404040;
        color: #888;
        padding: 6px 12px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s;
    }

    .note-action-btn:hover {
        border-color: #4a9eff;
        color: #4a9eff;
        background: rgba(74, 158, 255, 0.1);
    }

    .note-form {
        background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%);
        border: 1px solid #404040;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }

    .note-form textarea {
        width: 100%;
        background: #0f0f0f;
        border: 1px solid #404040;
        border-radius: 8px;
        padding: 14px;
        color: #e0e0e0;
        font-size: 14px;
        resize: vertical;
        min-height: 120px;
        margin-bottom: 12px;
        font-family: inherit;
        transition: border-color 0.3s;
    }

    .note-form textarea:focus {
        outline: none;
        border-color: #4a9eff;
        box-shadow: 0 0 0 3px rgba(74, 158, 255, 0.1);
    }

    /* Responsive */
    @media (max-width: 1024px) {
        .book-sidebar {
            display: none;
        }

        .notes-panel {
            width: 100%;
            right: -100%;
        }

        .book-toolbar {
            flex-wrap: wrap;
            gap: 10px;
        }

        .toolbar-group {
            border-right: none;
            border-bottom: 1px solid #404040;
            padding-bottom: 10px;
            margin-bottom: 10px;
        }
    }

    @media (max-width: 768px) {
        #chapter-content {
            padding: 30px 20px;
        }

        .book-toolbar {
            padding: 15px 20px;
        }

        .toolbar-btn {
            padding: 8px 14px;
            font-size: 13px;
        }
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="book-reader-container">
    <!-- Sidebar -->
    <aside class="book-sidebar">
        <div class="sidebar-section">
            <div class="sidebar-section-title">
                <i class="fas fa-list"></i> Table of Contents
            </div>
            <div class="chapter-list">
                <?php $__currentLoopData = $allChapters; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="chapter-list-item <?php echo e($ch->id === $chapter->id ? 'active' : ''); ?>">
                        <span class="chapter-number-badge"><?php echo e($ch->chapter_number); ?></span>
                        <a href="<?php echo e(route('student.books.chapters.read', ['book' => $book->id, 'chapter' => $ch->id])); ?>">
                            <?php echo e($ch->title); ?>

                        </a>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-section-title">
                <i class="fas fa-bookmark"></i> Bookmarks (<?php echo e($bookmarks->count()); ?>)
            </div>
            <?php if($bookmarks->count() > 0): ?>
                <?php $__currentLoopData = $bookmarks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bookmark): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="chapter-list-item">
                        <i class="fas fa-bookmark" style="color: #ffc107;"></i>
                        <a href="javascript:void(0)" onclick="scrollToPosition(<?php echo e($bookmark->position); ?>)">
                            <?php echo e($bookmark->title ?? 'Bookmark'); ?>

                        </a>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php else: ?>
                <p style="color: #888; font-size: 13px; padding: 10px;">No bookmarks yet</p>
            <?php endif; ?>
        </div>
    </aside>

    <!-- Main Content -->
    <div class="book-content-area">
        <!-- Enhanced Toolbar -->
        <div class="book-toolbar">
            <div class="toolbar-section">
                <!-- Navigation Group -->
                <div class="toolbar-group">
                    <a href="<?php echo e(route('student.books.show', $book)); ?>" class="toolbar-btn">
                        <i class="fas fa-arrow-left"></i> <span>Back</span>
                    </a>
                </div>
                
                <!-- Chapter Navigation Group -->
                <div class="toolbar-group">
                    <?php if($previousChapter): ?>
                        <a href="<?php echo e(route('student.books.chapters.read', ['book' => $book->id, 'chapter' => $previousChapter->id])); ?>" class="chapter-nav-btn">
                            <i class="fas fa-chevron-left"></i> <span>Previous</span>
                        </a>
                    <?php else: ?>
                        <span class="chapter-nav-btn disabled">
                            <i class="fas fa-chevron-left"></i> <span>Previous</span>
                        </span>
                    <?php endif; ?>
                    <?php if($nextChapter): ?>
                        <a href="<?php echo e(route('student.books.chapters.read', ['book' => $book->id, 'chapter' => $nextChapter->id])); ?>" class="chapter-nav-btn">
                            <span>Next</span> <i class="fas fa-chevron-right"></i>
                        </a>
                    <?php else: ?>
                        <span class="chapter-nav-btn disabled">
                            <span>Next</span> <i class="fas fa-chevron-right"></i>
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="toolbar-section">
                <!-- Actions Group -->
                <div class="toolbar-group">
                    <a href="<?php echo e(route('student.books.chapters.practice', ['book' => $book->id, 'chapter' => $chapter->id])); ?>" 
                       class="toolbar-btn primary">
                        <i class="fas fa-code"></i> <span>Practice</span>
                    </a>
                    <a href="<?php echo e(route('student.books.chapters.download', ['book' => $book->id, 'chapter' => $chapter->id])); ?>" 
                       class="toolbar-btn download-pdf-btn" 
                       data-book-id="<?php echo e($book->id); ?>"
                       data-chapter-id="<?php echo e($chapter->id); ?>">
                        <i class="fas fa-download"></i> <span>Download</span>
                    </a>
                </div>

                <!-- Notes & Bookmarks Group -->
                <div class="toolbar-group">
                    <button class="toolbar-btn" onclick="toggleNotesPanel()" id="notesToggleBtn">
                        <i class="fas fa-sticky-note"></i> <span>Notes</span>
                        <?php if($notes->count() > 0): ?>
                            <span style="background: #4a9eff; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px; margin-left: 4px;">
                                <?php echo e($notes->count()); ?>

                            </span>
                        <?php endif; ?>
                    </button>
                    <button class="toolbar-btn" onclick="createBookmark()">
                        <i class="fas fa-bookmark"></i> <span>Bookmark</span>
                    </button>
                </div>

                <!-- Complete Button -->
                <div class="toolbar-group">
                    <button class="toolbar-btn <?php echo e($progress->is_completed ? 'success active' : ''); ?>" 
                            onclick="markAsComplete()" 
                            id="completeBtn">
                        <i class="fas fa-check-circle"></i> 
                        <span><?php echo e($progress->is_completed ? 'Completed' : 'Mark Complete'); ?></span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Chapter Content -->
        <div id="chapter-content" class="restyled-book-content">
            <?php echo $chapterContent; ?>

        </div>
    </div>

    <!-- Notes Panel -->
    <div class="notes-panel" id="notesPanel">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #4a9eff;">
            <h3 style="color: #4a9eff; margin: 0; font-size: 18px; font-weight: 600;">
                <i class="fas fa-sticky-note"></i> My Notes
            </h3>
            <button onclick="toggleNotesPanel()" style="background: transparent; border: none; color: #888; cursor: pointer; font-size: 22px; transition: color 0.3s;" onmouseover="this.style.color='#4a9eff'" onmouseout="this.style.color='#888'">
                <i class="fas fa-times"></i>
            </button>
        </div>

        <!-- Note Form -->
        <div class="note-form">
            <h4 style="color: #e0e0e0; margin-bottom: 15px; font-size: 16px; font-weight: 600;">Add New Note</h4>
            <form id="noteForm">
                <?php echo csrf_field(); ?>
                <textarea id="noteContent" placeholder="Type your note here..." required></textarea>
                <input type="hidden" id="highlightedText" value="">
                <input type="hidden" id="notePosition" value="0">
                <button type="submit" class="toolbar-btn primary" style="width: 100%; justify-content: center;">
                    <i class="fas fa-save"></i> Save Note
                </button>
            </form>
        </div>

        <!-- Notes List -->
        <div id="notesList">
            <?php $__currentLoopData = $notes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $note): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="note-item" data-note-id="<?php echo e($note->id); ?>">
                    <div class="note-header">
                        <span style="color: #888; font-size: 12px;">
                            <?php echo e($note->created_at->format('M d, Y h:i A')); ?>

                        </span>
                        <div class="note-actions">
                            <button class="note-action-btn" onclick="editNote(<?php echo e($note->id); ?>)" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="note-action-btn" onclick="deleteNote(<?php echo e($note->id); ?>)" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="note-content"><?php echo e($note->content); ?></div>
                    <?php if($note->highlighted_text): ?>
                        <div class="note-highlight">
                            <i class="fas fa-quote-left"></i> <?php echo e(Str::limit($note->highlighted_text, 100)); ?>

                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<!-- Prism.js for code highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/toolbar/prism-toolbar.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>

<script>
    let currentPosition = 0;
    let selectedText = '';

    // Initialize Prism.js for code highlighting
    document.addEventListener('DOMContentLoaded', function() {
        // Highlight all code blocks
        if (window.Prism) {
            document.querySelectorAll('#chapter-content pre code').forEach((block) => {
                Prism.highlightElement(block);
            });
        }

        // Add copy buttons to code blocks
        document.querySelectorAll('#chapter-content pre').forEach((pre) => {
            if (!pre.querySelector('.code-copy-btn')) {
                const copyBtn = document.createElement('button');
                copyBtn.className = 'code-copy-btn';
                copyBtn.innerHTML = '<i class="fas fa-copy"></i> Copy';
                copyBtn.onclick = function() {
                    const code = pre.querySelector('code').textContent;
                    navigator.clipboard.writeText(code).then(() => {
                        copyBtn.innerHTML = '<i class="fas fa-check"></i> Copied!';
                        copyBtn.classList.add('copied');
                        setTimeout(() => {
                            copyBtn.innerHTML = '<i class="fas fa-copy"></i> Copy';
                            copyBtn.classList.remove('copied');
                        }, 2000);
                    });
                };
                pre.appendChild(copyBtn);
            }
        });
    });

    // Track scroll position
    document.addEventListener('scroll', function() {
        currentPosition = window.pageYOffset || document.documentElement.scrollTop;
        
        // Auto-save progress every 5 seconds
        if (Math.floor(currentPosition) % 1000 === 0) {
            saveProgress();
        }
    });

    // Get selected text
    document.addEventListener('mouseup', function() {
        selectedText = window.getSelection().toString().trim();
        if (selectedText) {
            document.getElementById('highlightedText').value = selectedText;
            document.getElementById('notePosition').value = currentPosition;
        }
    });

    // Save progress
    function saveProgress() {
        fetch('<?php echo e(route("student.books.progress.store", ["book" => $book->id, "chapter" => $chapter->id])); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                position: currentPosition,
                is_completed: document.getElementById('completeBtn').classList.contains('active')
            })
        });
    }

    // Mark as complete
    function markAsComplete() {
        const btn = document.getElementById('completeBtn');
        const isCompleted = !btn.classList.contains('active');
        
        fetch('<?php echo e(route("student.books.progress.store", ["book" => $book->id, "chapter" => $chapter->id])); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                position: currentPosition,
                is_completed: isCompleted
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (isCompleted) {
                    btn.classList.add('active', 'success');
                    btn.innerHTML = '<i class="fas fa-check-circle"></i> <span>Completed</span>';
                } else {
                    btn.classList.remove('active', 'success');
                    btn.innerHTML = '<i class="fas fa-check-circle"></i> <span>Mark Complete</span>';
                }
            }
        });
    }

    // Toggle notes panel
    function toggleNotesPanel() {
        document.getElementById('notesPanel').classList.toggle('active');
    }

    // Save note
    document.getElementById('noteForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const content = document.getElementById('noteContent').value;
        const highlightedText = document.getElementById('highlightedText').value;
        const position = document.getElementById('notePosition').value;

        fetch('<?php echo e(route("student.books.notes.store", ["book" => $book->id, "chapter" => $chapter->id])); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                content: content,
                highlighted_text: highlightedText,
                position: position
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            }
        });
    });

    // Delete note
    function deleteNote(noteId) {
        if (!confirm('Are you sure you want to delete this note?')) return;

        fetch(`/student/books/notes/${noteId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.querySelector(`[data-note-id="${noteId}"]`).remove();
            }
        });
    }

    // Create bookmark
    function createBookmark() {
        const title = prompt('Bookmark title (optional):', 'Bookmark');
        if (title === null) return;

        fetch('<?php echo e(route("student.books.bookmarks.store", ["book" => $book->id, "chapter" => $chapter->id])); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                title: title,
                position: currentPosition
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Bookmark created!');
                location.reload();
            }
        });
    }

    // Scroll to position
    function scrollToPosition(position) {
        window.scrollTo({
            top: position,
            behavior: 'smooth'
        });
    }

    // Restore scroll position on load
    window.addEventListener('load', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const position = urlParams.get('position');
        if (position) {
            scrollToPosition(parseInt(position));
        } else if (<?php echo e($progress->last_page_position); ?>) {
            scrollToPosition(<?php echo e($progress->last_page_position); ?>);
        }
    });

    // Mark as complete on load if already completed
    <?php if($progress->is_completed): ?>
        document.getElementById('completeBtn').classList.add('active', 'success');
        document.getElementById('completeBtn').innerHTML = '<i class="fas fa-check-circle"></i> <span>Completed</span>';
    <?php endif; ?>

    // Intercept PDF download clicks to check for outstanding balance
    document.addEventListener('DOMContentLoaded', function() {
        const downloadLinks = document.querySelectorAll('.download-pdf-btn');
        
        downloadLinks.forEach(function(link) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                const bookId = this.getAttribute('data-book-id');
                const chapterId = this.getAttribute('data-chapter-id');
                const downloadUrl = this.getAttribute('href');
                
                // Check for balance via AJAX
                fetch(downloadUrl, {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json, application/pdf, */*',
                    },
                })
                .then(response => {
                    const contentType = response.headers.get('content-type');
                    
                    if (response.status === 403) {
                        // Has outstanding balance - try to parse as JSON
                        return response.json().then(data => {
                            showBalanceModal(data.outstanding_balance);
                        }).catch(() => {
                            // If JSON parsing fails, show generic message
                            showBalanceModal(0);
                        });
                    } else if (response.ok && contentType && contentType.includes('application/pdf')) {
                        // No balance, proceed with PDF download
                        return response.blob().then(blob => {
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            // Extract filename from Content-Disposition header or use default
                            const contentDisposition = response.headers.get('content-disposition');
                            let filename = 'chapter.pdf';
                            if (contentDisposition) {
                                const filenameMatch = contentDisposition.match(/filename="?(.+)"?/i);
                                if (filenameMatch) {
                                    filename = filenameMatch[1];
                                }
                            }
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(a);
                        });
                    } else {
                        // For other responses, try direct download
                        window.location.href = downloadUrl;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    // Fallback: try direct download
                    window.location.href = downloadUrl;
                });
            });
        });
    });

    // Show balance modal function
    function showBalanceModal(balance) {
        // Create or get balance modal
        let modal = document.getElementById('balanceReminderModal');
        
        if (!modal) {
            // Create modal if it doesn't exist
            modal = document.createElement('div');
            modal.id = 'balanceReminderModal';
            modal.style.cssText = 'display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 10000; align-items: center; justify-content: center;';
            modal.innerHTML = `
                <div style="background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%); border-radius: 12px; padding: 30px; max-width: 500px; width: 90%; box-shadow: 0 10px 40px rgba(0,0,0,0.8); border: 2px solid #ff6b6b; position: relative;">
                    <button onclick="closeBalanceModal()" style="position: absolute; top: 15px; right: 15px; background: transparent; border: none; color: #888; font-size: 24px; cursor: pointer; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">
                        <i class="fas fa-times"></i>
                    </button>
                    <div style="text-align: center; margin-bottom: 20px;">
                        <div style="width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%); display: flex; align-items: center; justify-content: center; margin: 0 auto; box-shadow: 0 4px 20px rgba(255, 107, 107, 0.4);">
                            <i class="fas fa-exclamation-triangle" style="font-size: 40px; color: white;"></i>
                        </div>
                    </div>
                    <h2 style="color: #e0e0e0; text-align: center; margin-bottom: 15px; font-size: 24px; font-weight: 600;">Payment Required</h2>
                    <p style="color: #888; text-align: center; margin-bottom: 25px; line-height: 1.6; font-size: 15px;">
                        You have an outstanding balance that needs to be settled before you can download resources.
                    </p>
                    <div style="background: #1a1a1a; border-radius: 8px; padding: 20px; margin-bottom: 25px; border: 1px solid #404040;">
                        <div style="text-align: center;">
                            <div style="color: #888; font-size: 14px; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;">Outstanding Balance</div>
                            <div style="color: #ff6b6b; font-size: 36px; font-weight: 700;" id="balanceAmount">
                                ₵${parseFloat(balance).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            </div>
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px;">
                        <button onclick="closeBalanceModal()" style="flex: 1; padding: 12px; background: #404040; color: #e0e0e0; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500;">
                            <i class="fas fa-times"></i> Close
                        </button>
                        <a href="<?php echo e(route('student.profile.index')); ?>" style="flex: 1; padding: 12px; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; text-align: center; text-decoration: none; display: flex; align-items: center; justify-content: center; gap: 8px;">
                            <i class="fas fa-credit-card"></i> Pay Now
                        </a>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            // Update balance amount
            const balanceAmount = modal.querySelector('#balanceAmount');
            if (balanceAmount) {
                balanceAmount.textContent = '₵' + parseFloat(balance).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            }
        }
        
        // Show modal
        modal.style.display = 'flex';
    }

    // Close balance modal
    function closeBalanceModal() {
        const modal = document.getElementById('balanceReminderModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    // Close modal on outside click
    document.addEventListener('click', function(e) {
        const modal = document.getElementById('balanceReminderModal');
        if (modal && e.target === modal) {
            closeBalanceModal();
        }
    });
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('partials.balance-reminder-modal', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.student', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/iksoftte/portal.afrilen.com/resources/views/student/books/read.blade.php ENDPATH**/ ?>