@extends('layouts.student')

@section('title', 'Practice Exercises - ' . $chapter->title . ' - ' . $book->title)

@push('styles')
<style>
    .practice-container {
        background: #1a1a1a;
        min-height: calc(100vh - 80px);
        display: flex;
        gap: 20px;
        padding: 20px;
    }

    .practice-header {
        background: #2d2d2d;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        border: 1px solid #404040;
    }

    .practice-header h1 {
        color: #4a9eff;
        font-size: 24px;
        margin-bottom: 10px;
    }

    .practice-header .chapter-info {
        color: #888;
        font-size: 14px;
    }

    .practice-header .back-link {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #4a9eff;
        text-decoration: none;
        margin-bottom: 15px;
        transition: all 0.3s;
    }

    .practice-header .back-link:hover {
        color: #6bb6ff;
    }

    /* Left Column - Practice List */
    .practice-list-column {
        width: 350px;
        background: #2d2d2d;
        border-radius: 8px;
        padding: 20px;
        border: 1px solid #404040;
        overflow-y: auto;
        max-height: calc(100vh - 100px);
        position: sticky;
        top: 80px;
        transition: all 0.3s ease;
    }

    .practice-list-column.collapsed {
        width: 60px;
        padding: 20px 10px;
        overflow: hidden;
    }

    .practice-list-column.collapsed .practice-header,
    .practice-list-column.collapsed .practice-list-header,
    .practice-list-column.collapsed .practice-list,
    .practice-list-column.collapsed .no-practices {
        display: none;
    }

    .practice-list-column.collapsed .back-link {
        display: none;
    }

    .collapse-toggle-btn {
        position: absolute;
        top: 20px;
        right: 20px;
        background: #1a1a1a;
        border: 1px solid #404040;
        color: #4a9eff;
        width: 32px;
        height: 32px;
        border-radius: 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
        z-index: 10;
    }

    .collapse-toggle-btn:hover {
        background: #252525;
        border-color: #4a9eff;
    }

    .practice-list-column.collapsed .collapse-toggle-btn {
        right: 10px;
    }

    .practice-list-header {
        color: #4a9eff;
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .practice-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .practice-list-item {
        background: #1a1a1a;
        border: 1px solid #404040;
        border-radius: 6px;
        padding: 15px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .practice-list-item:hover {
        border-color: #4a9eff;
        background: #252525;
    }

    .practice-list-item.active {
        border-color: #4a9eff;
        background: #252525;
        box-shadow: 0 0 0 2px rgba(74, 158, 255, 0.2);
    }

    .practice-list-item-title {
        color: #e0e0e0;
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 5px;
    }

    .practice-list-item-description {
        color: #888;
        font-size: 12px;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    /* Right Column - Code View and DartPad */
    .practice-content-column {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .code-view-section {
        background: #2d2d2d;
        border-radius: 8px;
        padding: 25px;
        border: 1px solid #404040;
        min-height: 300px;
    }

    .code-view-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .code-view-title {
        color: #4a9eff;
        font-size: 20px;
        font-weight: 600;
    }

    .code-view-description {
        color: #888;
        margin-bottom: 20px;
        line-height: 1.6;
    }

    .code-display {
        background: #1a1a1a;
        border: 1px solid #404040;
        border-radius: 6px;
        padding: 20px;
        overflow-x: auto;
    }

    .code-display pre {
        margin: 0;
        color: #e0e0e0;
        font-family: 'Courier New', monospace;
        font-size: 14px;
        line-height: 1.6;
        white-space: pre-wrap;
        word-wrap: break-word;
    }

    .code-display code {
        color: #e0e0e0;
        background: transparent;
    }

    .dartpad-section {
        background: #2d2d2d;
        border-radius: 8px;
        padding: 25px;
        border: 1px solid #404040;
        flex: 1;
        min-height: 400px;
        max-height: calc(100vh - 200px);
        display: flex;
        flex-direction: column;
        position: relative;
        overflow: hidden;
    }

    .dartpad-resize-handle {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 8px;
        cursor: ns-resize;
        background: transparent;
        z-index: 5;
    }

    .dartpad-resize-handle:hover {
        background: rgba(74, 158, 255, 0.2);
    }

    .dartpad-resize-handle::after {
        content: '';
        position: absolute;
        top: 3px;
        left: 50%;
        transform: translateX(-50%);
        width: 40px;
        height: 2px;
        background: #4a9eff;
        border-radius: 2px;
        opacity: 0;
        transition: opacity 0.3s;
    }

    .dartpad-resize-handle:hover::after {
        opacity: 1;
    }

    .dartpad-header {
        color: #4a9eff;
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
    }

    .dartpad-header-actions {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .fullscreen-btn {
        background: #1a1a1a;
        border: 1px solid #404040;
        color: #4a9eff;
        padding: 8px 12px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: all 0.3s;
    }

    .fullscreen-btn:hover {
        background: #252525;
        border-color: #4a9eff;
    }

    /* Fullscreen Mode */
    .practice-container.fullscreen-mode {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 9999;
        padding: 0;
        background: #1a1a1a;
    }

    .practice-container.fullscreen-mode .practice-list-column {
        display: none;
    }

    .practice-container.fullscreen-mode .code-view-section {
        display: none;
    }

    .practice-container.fullscreen-mode .practice-content-column {
        width: 100%;
        height: 100vh;
        padding: 20px;
    }

    .practice-container.fullscreen-mode .dartpad-section {
        height: 100%;
        max-height: 100%;
        min-height: 100%;
        resize: none;
    }

    .practice-container.fullscreen-mode .dartpad-container {
        height: calc(100% - 60px);
    }

    .practice-container.fullscreen-mode .dartpad-iframe {
        min-height: 100%;
        height: 100%;
    }

    .dartpad-container {
        flex: 1;
        border-radius: 6px;
        overflow: hidden;
        border: 1px solid #404040;
        background: #1a1a1a;
    }

    .dartpad-iframe {
        width: 100%;
        height: 100%;
        min-height: 600px;
        border: none;
        background: #fff;
    }

    .no-practice-selected {
        text-align: center;
        padding: 60px 20px;
        color: #888;
    }

    .no-practice-selected i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #404040;
    }

    .no-practice-selected h3 {
        color: #e0e0e0;
        margin-bottom: 10px;
    }

    .no-practices {
        text-align: center;
        padding: 60px 20px;
        color: #888;
    }

    .no-practices i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #404040;
    }

    .no-practices h3 {
        color: #e0e0e0;
        margin-bottom: 10px;
    }

    @media (max-width: 1024px) {
        .practice-container {
            flex-direction: column;
        }

        .practice-list-column {
            width: 100%;
            position: relative;
            max-height: 400px;
        }

        .practice-list-column.collapsed {
            width: 100%;
            max-height: 60px;
            padding: 10px 20px;
        }

        .dartpad-iframe {
            min-height: 500px;
        }

        .dartpad-section {
            resize: none;
        }

        .dartpad-resize-handle {
            display: none;
        }

        .fullscreen-text {
            display: none;
        }
    }
</style>
@endpush

@section('content')
<div class="practice-container">
    <!-- Left Column: Practice List -->
    <div class="practice-list-column" id="practiceListColumn">
        <button class="collapse-toggle-btn" id="collapseToggleBtn" title="Collapse/Expand">
            <i class="fas fa-chevron-left" id="collapseIcon"></i>
        </button>
        <div class="practice-header">
            <a href="{{ route('student.books.chapters.read', ['book' => $book->id, 'chapter' => $chapter->id]) }}" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to Chapter
            </a>
            <h1><i class="fas fa-code"></i> Practice</h1>
            <div class="chapter-info">
                <strong>{{ $chapter->title }}</strong>
            </div>
        </div>

        @if($practicesCount > 0)
            <div class="practice-list-header">
                <i class="fas fa-list"></i> Fundamentals to Try
            </div>
            <div class="practice-list">
                @foreach($practicesCollection as $index => $practice)
                    <div class="practice-list-item" 
                         onclick="selectPractice({{ $index }})" 
                         id="practice-item-{{ $index }}"
                         data-practice-index="{{ $index }}">
                        <div class="practice-list-item-title">
                            {{ is_array($practice) ? $practice['title'] : $practice->title }}
                        </div>
                        @php
                            $description = is_array($practice) ? ($practice['description'] ?? '') : ($practice->description ?? '');
                        @endphp
                        @if($description)
                            <div class="practice-list-item-description">
                                {{ $description }}
                            </div>
                        @endif
                    </div>
                @endforeach
            </div>
        @else
            <div class="no-practices">
                <i class="fas fa-code"></i>
                <h3>No Practice Exercises</h3>
                <p>No practice exercises found in this chapter.</p>
            </div>
        @endif
    </div>

    <!-- Right Column: Code View and DartPad -->
    <div class="practice-content-column">
        @if($practicesCount > 0)
            <!-- Code View Section -->
            <div class="code-view-section" id="codeViewSection">
                <div class="code-view-header">
                    <div class="code-view-title" id="codeViewTitle">
                        <i class="fas fa-eye"></i> Watch the Code Example
                    </div>
                </div>
                <div class="code-view-description" id="codeViewDescription">
                    Select a practice exercise from the left to view the code example.
                </div>
                <div class="code-display" id="codeDisplay">
                    <pre><code id="codeContent">// Select a practice exercise to see the code example</code></pre>
                </div>
            </div>

            <!-- DartPad Section -->
            <div class="dartpad-section" id="dartpadSection">
                <div class="dartpad-resize-handle" id="dartpadResizeHandle"></div>
                <div class="dartpad-header">
                    <div>
                        <i class="fas fa-code"></i> DartPad Editor
                    </div>
                    <div class="dartpad-header-actions">
                        <button class="fullscreen-btn" id="fullscreenBtn" title="Toggle Fullscreen">
                            <i class="fas fa-expand" id="fullscreenIcon"></i>
                            <span id="fullscreenText" class="fullscreen-text">Fullscreen</span>
                        </button>
                    </div>
                </div>
                <div class="dartpad-container">
                    <iframe
                        class="dartpad-iframe"
                        src="https://dartpad.dev/embed-dart.html?theme=dark"
                        id="dartpad-iframe"
                        allow="clipboard-read; clipboard-write"
                        sandbox="allow-scripts allow-same-origin allow-forms">
                    </iframe>
                </div>
            </div>
        @else
            <div class="no-practices">
                <i class="fas fa-code"></i>
                <h3>No Practice Exercises Available</h3>
                <p>Practice exercises for this chapter will be added soon.</p>
            </div>
        @endif
    </div>
</div>

@push('scripts')
@php
    $practicesForJs = $practicesCollection->map(function($practice) {
        if (is_array($practice)) {
            return $practice;
        }
        return [
            'id' => $practice->id ?? null,
            'title' => $practice->title ?? '',
            'description' => $practice->description ?? '',
            'code' => ($practice->type ?? 'dart') === 'flutter' ? ($practice->flutter_code ?? '') : ($practice->dart_code ?? ''),
            'type' => $practice->type ?? 'dart',
            'instructions' => $practice->instructions ?? '',
        ];
    })->values()->all();
@endphp
<script>
    const practices = @json($practicesForJs);
    let selectedPracticeIndex = null;

    function selectPractice(index) {
        selectedPracticeIndex = index;
        const practice = practices[index];

        if (!practice) return;

        // Update active state
        document.querySelectorAll('.practice-list-item').forEach(item => {
            item.classList.remove('active');
        });
        const practiceItem = document.getElementById('practice-item-' + index);
        if (practiceItem) {
            practiceItem.classList.add('active');
        }

        // Update code view
        const codeViewTitle = document.getElementById('codeViewTitle');
        const codeViewDescription = document.getElementById('codeViewDescription');
        const codeContent = document.getElementById('codeContent');
        
        if (codeViewTitle) {
            codeViewTitle.innerHTML = '<i class="fas fa-eye"></i> ' + (practice.title || 'Code Example');
        }
        
        if (codeViewDescription) {
            codeViewDescription.textContent = practice.description || practice.instructions || 'Watch the code example above and retype it in the DartPad editor below. Then run it to see the results.';
        }
        
        if (codeContent) {
            codeContent.textContent = practice.code || '// No code example available';
        }

        // Show instructions if available
        if (practice.instructions && practice.instructions !== practice.description) {
            const instructionsHtml = '<div style="background: #1a1a1a; border-left: 3px solid #4a9eff; padding: 15px; margin-top: 15px; border-radius: 4px;"><h4 style="color: #4a9eff; margin-bottom: 10px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;"><i class="fas fa-info-circle"></i> Instructions</h4><p style="color: #e0e0e0; margin: 0; line-height: 1.6; white-space: pre-line;">' + practice.instructions + '</p></div>';
            if (codeViewDescription) {
                codeViewDescription.innerHTML = (practice.description || '') + instructionsHtml;
            }
        }

        // Scroll code view into view
        const codeViewSection = document.getElementById('codeViewSection');
        if (codeViewSection) {
            codeViewSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        // Update DartPad iframe based on type
        const iframe = document.getElementById('dartpad-iframe');
        if (iframe) {
            if (practice.type === 'flutter') {
                iframe.src = 'https://dartpad.dev/embed-flutter.html?theme=dark';
            } else {
                iframe.src = 'https://dartpad.dev/embed-dart.html?theme=dark';
            }
        }

        // Note: DartPad doesn't support direct code injection via postMessage in embedded mode
        // Students will need to manually type the code, which is the intended learning approach
    }

    // Select first practice by default
    document.addEventListener('DOMContentLoaded', function() {
        if (practices && practices.length > 0) {
            selectPractice(0);
        }

        // Collapsible sidebar functionality
        const collapseToggleBtn = document.getElementById('collapseToggleBtn');
        const practiceListColumn = document.getElementById('practiceListColumn');
        const collapseIcon = document.getElementById('collapseIcon');
        const practiceContainer = document.querySelector('.practice-container');

        if (collapseToggleBtn && practiceListColumn) {
            collapseToggleBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                practiceListColumn.classList.toggle('collapsed');
                
                if (practiceListColumn.classList.contains('collapsed')) {
                    collapseIcon.className = 'fas fa-chevron-right';
                    collapseToggleBtn.title = 'Expand';
                } else {
                    collapseIcon.className = 'fas fa-chevron-left';
                    collapseToggleBtn.title = 'Collapse';
                }
            });
        }

        // Resizable DartPad section
        const dartpadSection = document.getElementById('dartpadSection');
        const dartpadResizeHandle = document.getElementById('dartpadResizeHandle');
        let isResizing = false;
        let startY = 0;
        let startHeight = 0;

        if (dartpadResizeHandle && dartpadSection) {
            dartpadResizeHandle.addEventListener('mousedown', function(e) {
                isResizing = true;
                startY = e.clientY;
                startHeight = parseInt(document.defaultView.getComputedStyle(dartpadSection).height, 10);
                document.body.style.cursor = 'ns-resize';
                document.body.style.userSelect = 'none';
                e.preventDefault();
            });

            document.addEventListener('mousemove', function(e) {
                if (!isResizing) return;
                
                const height = startHeight - (e.clientY - startY);
                const minHeight = 300;
                const maxHeight = window.innerHeight - 200;
                
                if (height >= minHeight && height <= maxHeight) {
                    dartpadSection.style.height = height + 'px';
                    dartpadSection.style.flex = 'none';
                }
            });

            document.addEventListener('mouseup', function() {
                if (isResizing) {
                    isResizing = false;
                    document.body.style.cursor = '';
                    document.body.style.userSelect = '';
                }
            });
        }

        // Fullscreen functionality
        const fullscreenBtn = document.getElementById('fullscreenBtn');
        const fullscreenIcon = document.getElementById('fullscreenIcon');
        const fullscreenText = document.getElementById('fullscreenText');
        let isFullscreen = false;

        if (fullscreenBtn && practiceContainer) {
            fullscreenBtn.addEventListener('click', function() {
                isFullscreen = !isFullscreen;
                practiceContainer.classList.toggle('fullscreen-mode');
                
                if (isFullscreen) {
                    fullscreenIcon.className = 'fas fa-compress';
                    fullscreenText.textContent = 'Exit Fullscreen';
                    fullscreenBtn.title = 'Exit Fullscreen';
                } else {
                    fullscreenIcon.className = 'fas fa-expand';
                    fullscreenText.textContent = 'Fullscreen';
                    fullscreenBtn.title = 'Toggle Fullscreen';
                }
            });

            // Exit fullscreen on Escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && isFullscreen) {
                    fullscreenBtn.click();
                }
            });
        }
    });
</script>
@endpush
@endsection
