@extends('layouts.appLayout')

@section('title', $course->title)
@section('nav_title', 'Course Chapter')

@section('content')
    <div class="container my-4">

        {{-- Breadcrumbs --}}
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb bg-transparent px-0">
                <li class="breadcrumb-item"><a href="{{ route('myProfilePage') }}">Profile</a></li>
                <li class="breadcrumb-item"><a href="{{ route('myCoursesPage') }}">My Courses</a></li>
                <li class="breadcrumb-item"><a href="{{ route('showCourseInfo', ['id' => $course->id]) }}">Course info</a></li>
                <li class="breadcrumb-item active" aria-current="page">{{ $course->title }}</li>
            </ol>
        </nav>

        {{-- Header --}}
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="text-white mb-0">{{ $course->title }}</h1>
            <a href="{{ route('showCourseInfo', ['id' => $course->id]) }}" class="btn btn3">
                <i class="fas fa-arrow-left me-2"></i>Back to course info
            </a>
        </div>

        <h2 class="chapter-heading">
            <span class="textOrange">Chapter {{ $chapterData['chapter_number'] }}:</span>
            <span class="text-white">{{ $chapterData['title'] }}</span>
        </h2>
        <br>


        <div class="chapter-content">
            {!! $chapterData['content'] !!}
        </div>

        <br><h3>Exercises</h3><br>

        @foreach($chapterData['exercises'] as $exe)
            @php
                $completed = $exe['status'] === 'completed';
            @endphp

            <div class="exercise mb-4 {{ $completed ? 'completed' : '' }}"
                data-exercise-id="{{ $exe['exercise_id'] }}"
                data-exercise-type="{{ $exe['type'] }}">

                <p><strong>#{{ $exe['exercise_number'] }}</strong> – {{ $exe['question'] }}</p>

                @if(! $completed)
                    {{-- NO completado --}}
                    @switch($exe['type'])
                        @case('input')
                            <input type="text"
                                name="exercise_{{ $exe['exercise_id'] }}"
                                class="form-control inputTextLong"/>
                            @break
                        @case('radio')
                            @foreach($exe['options'] as $opt)
                                <div class="form-check">
                                    <input class="form-check-input inputRadioPurple"
                                        type="radio"
                                        name="exercise_{{ $exe['exercise_id'] }}"
                                        id="opt_{{ $opt['option_id'] }}"
                                        value="{{ $opt['option_id'] }}">
                                    <label class="form-check-label">
                                        {{ $opt['answer'] }}
                                    </label>
                                </div>
                            @endforeach
                            @break

                        @case('checkbox')
                            @foreach($exe['options'] as $opt)
                                <div class="form-check">
                                    <input class="form-check-input inputCheckboxPurple"
                                        type="checkbox"
                                        name="exercise_{{ $exe['exercise_id'] }}[]"
                                        id="opt_{{ $opt['option_id'] }}"
                                        value="{{ $opt['option_id'] }}">
                                    <label class="form-check-label">
                                        {{ $opt['answer'] }}
                                    </label>
                                </div>
                            @endforeach
                            @break
                    @endswitch

                    {{-- Botón para enviar la respuesta --}}
                    <button class="btn btn2 btn-sm mt-2 answer-btn">Submit Answer</button>

                @else
                    {{-- SÍ completado --}}
                    @switch($exe['type'])
                        @case('input')
                            @php $val = $exe['options'][0]['answer'] ?? ''; @endphp
                            <input
                                type="text"
                                class="form-control inputTextLong"
                                value="{{ $val }}"
                                readonly
                            />
                            @break

                        @case('radio')
                            @foreach($exe['options'] as $opt)
                                <div class="form-check">
                                    <input class="form-check-input inputRadioPurple"
                                        type="radio"
                                        name="exercise_{{ $exe['exercise_id'] }}"
                                        id="opt_{{ $opt['option_id'] }}"
                                        value="{{ $opt['option_id'] }}"
                                        {{ (isset($opt['is_correct']) && $opt['is_correct']) ? 'checked' : '' }}
                                        disabled>
                                    <label class="form-check-label"
                                        for="opt_{{ $opt['option_id'] }}">
                                        {{ $opt['answer'] }}
                                    </label>
                                </div>
                            @endforeach
                            @break

                        @case('checkbox')
                            @foreach($exe['options'] as $opt)
                                <div class="form-check">
                                    <input class="form-check-input inputCheckboxPurple"
                                        type="checkbox"
                                        name="exercise_{{ $exe['exercise_id'] }}[]"
                                        id="opt_{{ $opt['option_id'] }}"
                                        value="{{ $opt['option_id'] }}"
                                        {{ (isset($opt['is_correct']) && $opt['is_correct']) ? 'checked' : '' }}
                                        disabled>
                                    <label class="form-check-label"
                                        for="opt_{{ $opt['option_id'] }}">
                                        {{ $opt['answer'] }}
                                    </label>
                                </div>
                            @endforeach
                            @break
                    @endswitch
                @endif

            </div>
        @endforeach {{-- aquí cerramos el bucle --}}

        @php
            $allCompleted = collect($chapterData['exercises'])
                ->every(fn($e) => $e['status'] === 'completed');
        @endphp

        <div class="d-flex justify-content-between mt-4">
            {{-- Previous Chapter --}}
            @if($prev)
                <a href="{{ route('course.chapter.show', ['id' => $prev->id]) }}"
                class="btn btn1 btn-outline-secondary">
                    ← Previous Chapter
                </a>
            @else
                <span></span>
            @endif

            {{-- Next / Go to Exam --}}
            @if($next)
                @if($isCurrent)
                    {{-- Si estamos en el capítulo actual, siempre usamos el POST para “avanzar” o “ir al examen” --}}
                    <form action="{{ route('course.chapter.next', ['chapterId' => $chapterData['chapter_id']]) }}"
                        method="POST" class="text-center">
                        @csrf
                        <button id="next-chapter-btn"
                                class="btn btn3 {{ $allCompleted ? '' : 'd-none' }}"
                                type="submit">
                            {{ $next->is_exam ? 'Go to Exam →' : 'Advance Chapter →' }}
                        </button>
                    </form>
                @else
                    {{-- Si es un capítulo anterior, mostramos simplemente un link GET --}}
                    @if($next->is_exam)
                        <a href="{{ route('course.chapter.exam', ['chapterId' => $next->id]) }}"
                        class="btn btn3">
                            Go to Exam →
                        </a>
                    @else
                        <a href="{{ route('course.chapter.show', ['id' => $next->id]) }}"
                        class="btn btn3">
                            Next Chapter →
                        </a>
                    @endif
                @endif
            @endif
        </div>

    </div>

    {{-- --------------- PROGRESS SIDEBAR --------------- --}}
    @php
        // Encontramos el índice del capítulo actual (el numero del capitulo que esta viendo)
        $currentIndex = collect($courseProgress)->pluck('chapter_id')->search($chapterData['chapter_id']);

        // Buscamos el índice del último capítulo completado (ignorando exámenes)
        $lastCompletedIndex = collect($courseProgress)
        ->filter(fn($ch) => !$ch['is_exam'] && $ch['has_progress']) // Solo capítulos no examen con progreso
        ->keys()
        ->last();

        // Altura de la linea verde que son los completados menos uno
        $lineFillHeight = ($lastCompletedIndex > 0) ? ($lastCompletedIndex - 1) * 54 : 0;
    @endphp

    {{-- Sidebar de progreso --}}
    <div id="progressContainer" class="progress-sidebar shadow-lg">
        <a class="progressSideBarBTN" id="progressSideBarBTN">
            <i class="fa-solid fa-list-check"></i>
        </a>
        <div title="{{ $course->title }}" class="courseTitle-progressSidebar p-3 pt-1 pb-1">{{ $course->title }}</div>
        <div class="p-3 progressContent">
            <!-- Barra de progreso vertical -->
            <div class="vertical-progress-bar" style="height: {{ (count($courseProgress) - 1) * 54 + 26 }}px;">
                <!-- Línea de fondo que cubre toda la altura de la barra -->
                <div class="progress-line-background"></div>

                <!-- Línea de progreso verde que se ajusta a la altura calculada para la línea verde -->
                <div class="progress-line-fill" style="height: {{ $lineFillHeight }}px;"></div>

                <!-- Iteramos sobre cada capítulo del curso -->
                @foreach ($courseProgress as $index => $chapter)
                    @php
                        // Verificamos si este capítulo está antes del capítulo actual
                        $isBeforeCurrent = $index < $lastCompletedIndex;

                        // Verificamos si este es el capítulo actual
                        $isCurrent = $index === $currentIndex;

                        // Verificamos si es un examen
                        $isExam = $chapter['is_exam'];
                    @endphp

                    <a class="progress-item"
                        @if(($isBeforeCurrent || $index === $lastCompletedIndex) && !$isCurrent)
                            href="{{ route('course.chapter.show', ['id' => $chapter['chapter_id']]) }}"
                        @endif
                    >
                        <div class="progress-circle
                            {{ $isBeforeCurrent ? 'completed makeBiggerCircle-progress' : '' }}
                            {{ $isCurrent ? 'current NOTmakeBiggerCircle-progress' : '' }}
                            {{ $index === $lastCompletedIndex ? 'user-progress makeBiggerCircle-progress' : '' }}
                            {{ $isExam === true ? 'progressCircleExam' : '' }}">
                            {!! $isExam === true ? "<i class='fa-solid fa-file-alt'></i>" : $chapter['chapter_number'] !!}
                        </div>
                        <div class="chapterProgress-title">
                            <span class="chapterProgress-text" title="{{ $chapter['chapter_title'] }}">{{ $chapter['chapter_title'] }}</span>
                        </div>
                    </a>
                @endforeach
            </div>
        </div>
    </div>

    {{-- Incluimos la IA --}}
    @include('components.ai-assistant')

@endsection

@push('scripts')
    <script src="{{ asset('js/exercise.js') }}" defer></script>
    <script src="{{ asset('js/progressBar_sidebar.js') }}"></script>
    <script src="{{ asset('js/components/ai-chat.js') }}"></script>
@endpush

