@extends('siswa.layout')

@section('content')

<div x-data="{ sidebarOpen: true }"
     class="relative bg-white rounded-2xl shadow overflow-hidden">

    <!-- ================= TOP BAR DESKTOP ================= -->
    <div id="topbar-desktop" class="flex items-center justify-between px-6 py-4 border-b">
        <div class="flex items-center gap-3">
            <a href="{{ route('siswa.dashboard') }}"
               class="inline-flex items-center gap-2 px-3 py-2 rounded-lg
                      bg-gray-100 hover:bg-gray-200 text-gray-600 hover:text-gray-900
                      text-sm font-medium transition-colors duration-150">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none"
                     viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
                </svg>
                Kembali
            </a>

            <h1 class="font-semibold text-lg text-gray-800 truncate">
                {{ $lesson->title }}
            </h1>
        </div>
    </div>

    <!-- ================= MAIN DESKTOP ================= -->
    {{--
        FIX #4: Hapus fixed position hardcode top-[73px] di sidebar.
        Gunakan flex layout biasa; sidebar mengikuti tinggi konten secara alami.
        Sidebar tetap sticky agar tetap terlihat saat scroll.
    --}}
    <div class="relative flex min-h-[75vh]">

        <!-- ================= CONTENT DESKTOP ================= -->
        <section class="flex-1 p-10 min-w-0">

            <h2 class="text-3xl font-bold mb-4 text-gray-900">
                {{ $lesson->title }}
            </h2>

            @if($lesson->available_at && now()->lt($lesson->available_at))
                <div class="mb-8 p-4 bg-yellow-50 border border-yellow-300 rounded-xl text-yellow-800">
                    Materi ini dapat dibuka pada:
                    <strong>
                        {{ $lesson->available_at->translatedFormat('d F Y H:i') }}
                    </strong>
                </div>
            @endif

            {{-- ================= CONTENT AREA ================= --}}
            <div class="mb-14">

                {{-- Frame TV Style --}}
                <div class="w-full max-w-6xl mx-auto
                            bg-gradient-to-b from-gray-900 to-black
                            p-3 rounded-2xl shadow-2xl shadow-black/40">

                    <div class="w-full rounded-xl overflow-hidden bg-black">
                        {{--
                            FIX #2: Konten dipindah ke partial _content.blade.php
                            agar tidak duplikasi antara desktop & mobile.
                            Termasuk FIX #3 (regex videoId) ada di dalam partial tersebut.
                        --}}
                        @include('siswa.modul._content')
                    </div>
                </div>

            </div>

            {{-- ACTION BAR DESKTOP --}}
            <div class="mt-16 flex justify-between items-center flex-wrap gap-4">

                {{-- KIRI --}}
                <div>
                    @if($isCompleted)
                        <span class="text-green-600 font-semibold">
                            Materi telah diselesaikan
                        </span>
                    @endif
                </div>

                {{-- KANAN --}}
                <div class="flex gap-4">

                    @if(! $isCompleted)

                        <form method="POST"
                              action="{{ route('siswa.modul.selesai', $lesson->id) }}">
                            @csrf

@php
$hasDuration = !empty($lesson->duration);
$isVideo     = $lesson->content_type === 'video';
$lockFinish  = $isVideo || $hasDuration;
@endphp

                            <button
                                id="btn-selesai"
                                @if($lockFinish) disabled @endif
                                class="px-6 py-3 rounded-lg transition
                                {{ $lockFinish
                                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                    : 'bg-gray-900 text-white hover:bg-gray-700'
                                }}">
                                Tandai Selesai
                            </button>
                            
@if($hasDuration)
<script>
(function(){

    const btn = document.getElementById('btn-selesai');
    if(!btn) return;

    const lessonId = {{ $lesson->id }};
    let remaining  = {{ $lesson->duration }} * 60;

    let timer   = null;
    let started = false;

    function startTimer(){

        if(started) return;
        started = true;

        timer = setInterval(function(){

            if(document.hidden) return;

            remaining--;

            fetch('/siswa/lesson/'+lessonId+'/duration',{
                method:'POST',
                headers:{
                    'X-CSRF-TOKEN':'{{ csrf_token() }}',
                    'Content-Type':'application/json'
                },
                body:JSON.stringify({seconds:1})
            }).catch(()=>{});

            btn.innerText = "Tandai Selesai ("+remaining+"s)";

            if(remaining <= 0){
                clearInterval(timer);

                btn.disabled = false;
                btn.innerText = "Tandai Selesai";

                btn.classList.remove('bg-gray-300','text-gray-500','cursor-not-allowed');
                btn.classList.add('bg-gray-900','text-white','hover:bg-gray-700');
            }

        },1000);
    }

    // =======================
    // 🔥 VIDEO START LISTENER
    // =======================
    window.addEventListener('yt-playing', startTimer);

    // =======================
    // 🔥 PDF / TEXT START LISTENER
    // =======================
    window.addEventListener('lesson-interact', startTimer);

})();
</script>
@endif
                        </form>

                    @elseif($nextLesson)

                        @if($nextLesson->is_locked)
                            <a href="{{ route('siswa.dashboard') }}"
                               class="bg-gray-900 text-white px-6 py-3 rounded-lg hover:bg-gray-700">
                                Kembali ke Dashboard
                            </a>
                        @else
                            @php
                                $nextUrl = match($nextLesson->type){
                                    'lesson' => route('siswa.modul.show', $nextLesson->id),
                                    'quiz'   => route('siswa.quiz.intro', $nextLesson->id),
                                    'task'   => route('siswa.task.show', $nextLesson->id),
                                    default  => route('siswa.dashboard')
                                };
                            @endphp
                            
                            <a href="{{ $nextUrl }}"
                               class="bg-gray-900 text-white px-6 py-3 rounded-lg hover:bg-gray-700">
                                Lanjut ke Materi →
                            </a>
                        @endif

                    @else
                        <a href="{{ route('siswa.dashboard') }}"
                           class="bg-gray-900 text-white px-6 py-3 rounded-lg hover:bg-gray-700">
                            Kembali ke Dashboard
                        </a>
                    @endif

                </div>

            </div>
        </section>

        {{-- SIDEBAR DESKTOP --}}
        @include('siswa.modul.sidebar-desktop')

    </div>
</div>

@endsection