@extends('layouts.stage_academy_portal')

@section('title', __('stage_academy_portal.my_courses.watch_title'))

@section('body')
    @php
        $locale = app()->getLocale();
        $otherLocale = $locale === 'ar' ? 'en' : 'ar';
        $textDir = $locale === 'ar' ? 'rtl' : 'ltr';
        $active = $active ?? 'my_courses';
        $courseName = $locale === 'ar' ? $course->name_ar : $course->name_en;
    @endphp

    <nav class="navbar navbar-expand-lg navbar-light bg-white bg-opacity-75 border-bottom sap-portal-navbar" style="backdrop-filter: blur(10px);">
        <div class="container">
            <div class="d-flex flex-column">
                <span class="navbar-brand fw-bold mb-0 sap-brand-shine">{{ __('stage_academy_portal.brand') }}</span>
            </div>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sapNavbar" aria-controls="sapNavbar" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="sapNavbar">
                <div class="d-flex flex-column flex-lg-row {{ $locale === 'ar' ? 'flex-lg-row-reverse' : '' }} w-100 align-items-lg-center justify-content-lg-between gap-2 py-2 py-lg-0">
                    <ul class="navbar-nav mb-0">
                        <li class="nav-item">
                            <a class="nav-link {{ $active === 'my_courses' ? 'active fw-semibold' : '' }}" href="{{ route('stage-academy-portal.my-courses') }}">{{ __('stage_academy_portal.nav.my_courses') }}</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link {{ $active === 'profile' ? 'active fw-semibold' : '' }}" href="{{ route('stage-academy-portal.profile') }}">{{ __('stage_academy_portal.nav.profile') }}</a>
                        </li>
                    </ul>

                    <div class="d-flex align-items-center gap-2">
                        <div class="sap-welcome-text d-flex align-items-center gap-2 small text-secondary" dir="{{ $textDir }}">
                            @if(! empty($portalUser->image) && \Illuminate\Support\Facades\Schema::hasColumn('stage_academy_users', 'image'))
                                <img src="{{ asset('storage/'.$portalUser->image) }}" alt="{{ $portalUser->name }}" style="width: 32px; height: 32px; object-fit: cover; border-radius: 50%;">
                            @else
                                <div class="d-flex align-items-center justify-content-center bg-white border rounded-circle" style="width: 32px; height: 32px;">
                                    <i class="bi bi-person-fill text-secondary"></i>
                                </div>
                            @endif
                            <span>{{ __('stage_academy_portal.welcome') }} <strong>{{ $portalUser->name }}</strong></span>
                        </div>
                        <a href="{{ route('lang.switch', $otherLocale) }}" class="btn btn-sm btn-outline-secondary" dir="ltr">
                            {{ strtoupper($otherLocale) }}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <div class="container py-3 py-md-4">
        <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap mb-3">
            <div>
                <div class="fw-bold fs-4">{{ $courseName }}</div>
                @php
                    $courseDescription = $locale === 'ar' ? (string) $course->description_ar : (string) $course->description_en;
                    $courseDescription = trim($courseDescription);
                @endphp
                @if($courseDescription !== '')
                    <div class="text-secondary mt-2 text-break">{{ \Illuminate\Support\Str::limit($courseDescription, 220) }}</div>
                @endif
            </div>
            <a href="{{ route('stage-academy-portal.my-courses') }}" class="btn btn-sm btn-outline-success">
                <i class="bi {{ $locale === 'ar' ? 'bi-arrow-right' : 'bi-arrow-left' }}"></i> {{ __('common.back') }}
            </a>
        </div>

        <div class="row g-3 g-md-4">
            <div class="col-12 col-lg-8">
                <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                    @if($initialVideoUrl !== '')
                        <div class="ratio ratio-16x9 bg-black">
                            <iframe
                                id="sapVideoPlayer"
                                src="{{ $initialVideoUrl }}"
                                title="{{ $courseName }}"
                                allow="autoplay; fullscreen; picture-in-picture"
                                allowfullscreen
                            ></iframe>
                        </div>
                    @else
                        <div class="p-4 p-md-5 text-center text-secondary">
                            <i class="bi bi-camera-video-off fs-2 d-block mb-2"></i>
                            <div class="fw-semibold">{{ __('stage_academy_portal.my_courses.no_lectures_title') }}</div>
                            <div class="mt-1">{{ __('stage_academy_portal.my_courses.no_lectures_body') }}</div>
                        </div>
                    @endif
                </div>
            </div>

            <div class="col-12 col-lg-4">
                <div class="card border-0 shadow-sm rounded-4 h-100">
                    <div class="card-body p-3 p-md-4">
                        <div class="fw-bold mb-3">{{ __('stage_academy_portal.my_courses.lectures_title') }}</div>

                        @if(isset($videos) && $videos->isNotEmpty())
                            <div
                                class="list-group list-group-flush sap-lectures-list"
                                id="sapLecturesList"
                                data-course-id="{{ $course->id }}"
                                data-progress-url="{{ route('stage-academy-portal.progress') }}"
                                data-initial-video-id="{{ (int) ($initialVideoId ?? 0) }}"
                            >
                                @foreach($videos as $index => $video)
                                    @php
                                        $videoTitle = $locale === 'ar' ? $video->name_ar : $video->name_en;
                                        $videoDesc = $locale === 'ar' ? (string) $video->short_description_ar : (string) $video->short_description_en;
                                        $videoDesc = trim($videoDesc);
                                    @endphp
                                    <button
                                        type="button"
                                        class="list-group-item list-group-item-action py-3 {{ $index === 0 ? 'active' : '' }}"
                                        data-video-url="{{ $video->vimeo_url }}"
                                        data-video-id="{{ $video->id }}"
                                    >
                                        <div class="fw-semibold">{{ $videoTitle }}</div>
                                        @if($videoDesc !== '')
                                            <div class="small opacity-75 mt-1 text-break">
                                                {{ \Illuminate\Support\Str::limit($videoDesc, 90) }}
                                            </div>
                                        @endif
                                    </button>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center text-secondary py-4">
                                <i class="bi bi-inbox fs-2 d-block mb-2 opacity-50"></i>
                                <div class="fw-semibold">{{ __('stage_academy_portal.my_courses.no_lectures_title') }}</div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    @if(isset($videos) && $videos->isNotEmpty())
        @push('scripts')
            <script src="https://player.vimeo.com/api/player.js"></script>
            <script>
                (function () {
                    const list = document.getElementById('sapLecturesList');
                    const player = document.getElementById('sapVideoPlayer');
                    if (!list || !player) return;

                    const normalize = (url) => {
                        const raw = (url || '').trim();
                        if (!raw) return '';
                        if (raw.includes('player.vimeo.com/video/')) return raw;
                        try {
                            const u = new URL(raw);
                            const host = (u.hostname || '').toLowerCase();
                            if (!host.includes('vimeo.com')) return raw;

                            const segments = (u.pathname || '').split('/').filter(Boolean);
                            let id = '';
                            let idIndex = -1;
                            segments.forEach((segment, index) => {
                                if (/^\d+$/.test(segment)) {
                                    id = segment;
                                    idIndex = index;
                                }
                            });
                            if (!id) return raw;

                            let hash = u.searchParams.get('h') || '';
                            if (!hash && idIndex >= 0 && segments[idIndex + 1] && /^[a-zA-Z0-9]+$/.test(segments[idIndex + 1]) && !/^\d+$/.test(segments[idIndex + 1])) {
                                hash = segments[idIndex + 1];
                            }

                            let embed = `https://player.vimeo.com/video/${id}`;
                            if (hash) embed += `?h=${hash}`;
                            return embed;
                        } catch (e) {
                            const match = raw.match(/vimeo\.com\/(\d+)(?:\/([a-zA-Z0-9]+))?/);
                            if (match && match[1]) {
                                const id = match[1];
                                const hash = match[2] || '';
                                return hash ? `https://player.vimeo.com/video/${id}?h=${hash}` : `https://player.vimeo.com/video/${id}`;
                            }
                        }

                        return raw;
                    };

                    const csrfMeta = document.querySelector('meta[name="csrf-token"]');
                    const csrf = csrfMeta ? (csrfMeta.getAttribute('content') || '') : '';
                    const progressUrl = (list.dataset.progressUrl || '').trim();
                    const courseId = parseInt(list.dataset.courseId || '0', 10) || 0;
                    let currentVideoId = parseInt(list.dataset.initialVideoId || '0', 10) || 0;
                    let vimeoPlayer = null;
                    let lastSentAt = 0;
                    let lastSentSeconds = 0;
                    let currentDuration = 0;

                    const sendProgress = (watchedSeconds, durationSeconds) => {
                        const watched = Math.max(0, Math.floor(watchedSeconds || 0));
                        const duration = Math.max(0, Math.floor(durationSeconds || 0));
                        if (!currentVideoId || duration <= 0) return;

                        const now = Date.now();
                        if (now - lastSentAt < 3500 && watched < duration - 2) return;

                        lastSentAt = now;

                        fetch(progressUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': csrf,
                                'Accept': 'application/json',
                            },
                            body: JSON.stringify({
                                course_id: courseId,
                                video_id: currentVideoId,
                                watched_seconds: watched,
                                duration_seconds: duration,
                            }),
                        }).catch(() => {});
                    };

                    const bindVimeo = () => {
                        if (!window.Vimeo || !window.Vimeo.Player) return;

                        if (vimeoPlayer) {
                            try {
                                vimeoPlayer.off('timeupdate');
                                vimeoPlayer.off('ended');
                            } catch (e) {}
                        }

                        vimeoPlayer = new Vimeo.Player(player);
                        lastSentAt = 0;
                        lastSentSeconds = 0;
                        currentDuration = 0;

                        vimeoPlayer.getDuration().then((d) => {
                            currentDuration = Math.max(0, Math.floor(d || 0));
                        }).catch(() => {});

                        vimeoPlayer.on('timeupdate', (data) => {
                            const seconds = Math.max(0, Math.floor((data && data.seconds) || 0));
                            const duration = Math.max(0, Math.floor((data && data.duration) || currentDuration || 0));
                            currentDuration = duration || currentDuration;

                            if (seconds <= lastSentSeconds) return;
                            if (seconds - lastSentSeconds < 15 && seconds < duration - 2) return;

                            lastSentSeconds = seconds;
                            sendProgress(seconds, duration);
                        });

                        vimeoPlayer.on('ended', () => {
                            sendProgress(currentDuration || lastSentSeconds, currentDuration);
                        });
                    };

                    const activateButton = (btn) => {
                        list.querySelectorAll('button.list-group-item').forEach((el) => el.classList.remove('active'));
                        btn.classList.add('active');
                    };

                    const loadVideo = (btn) => {
                        const url = normalize(btn.getAttribute('data-video-url'));
                        const videoId = parseInt(btn.getAttribute('data-video-id') || '0', 10);
                        if (!url || !videoId) return;

                        currentVideoId = videoId;
                        player.setAttribute('src', url);
                        activateButton(btn);

                        setTimeout(bindVimeo, 350);
                    };

                    list.addEventListener('click', (e) => {
                        const btn = e.target.closest('button[data-video-url][data-video-id]');
                        if (!btn) return;
                        loadVideo(btn);
                    });

                    bindVimeo();
                })();
            </script>
        @endpush
    @endif
@endsection
