@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'My Wishlist')

@section('left_sidebar')
@include('front_end.pages.courses.courses_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Header Section -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center">
                            <a href="{{ route('student.dashboard') }}" class="text-white me-3">
                                <i class="fas fa-arrow-left fa-lg"></i>
                            </a>
                            <div>
                                <h4 class="mb-0 text-white">My Wishlist</h4>
                                <p class="mb-0 text-white">{{ $wishlist->total() }} courses saved for later</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container py-5">
        @if($wishlist->count() > 0)
            <!-- Search Bar -->
            <div class="row mb-4">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text bg-white">
                            <i class="fas fa-search"></i>
                        </span>
                        <input type="text" class="form-control" id="searchWishlist" placeholder="Search your wishlist">
                        <button class="btn btn-primary" type="button" id="searchButton">Search</button>
                    </div>
                </div>
                <div class="col-md-4">
                    <select class="form-select" id="sortWishlist">
                        <option value="newest">Recently Added</option>
                        <option value="oldest">Oldest First</option>
                        <option value="a-z">Title: A-Z</option>
                        <option value="z-a">Title: Z-A</option>
                        <option value="price-low">Price: Low to High</option>
                        <option value="price-high">Price: High to Low</option>
                    </select>
                </div>
            </div>

            <!-- Wishlist Courses -->
            <div class="row g-4" id="wishlistGrid">
                @foreach($wishlist as $item)
                <div class="col-md-6 col-lg-4 wishlist-item">
                    <div class="card h-100 border-0 shadow-sm hover-shadow transition-all">
                        <a href="{{ route('courses.show', $item->course->slug) }}">
                            <img src="{{ $item->course->thumbnail ? asset('storage/' . $item->course->thumbnail) : asset('assets/images/course-placeholder.jpg') }}" 
                                 class="card-img-top" alt="{{ $item->course->title }}">
                        </a>
                        @if($item->course->discount_price && $item->course->discount_ends_at > now())
                        <div class="position-absolute top-0 end-0 bg-danger text-white px-2 py-1 m-2 rounded">
                            {{ round((($item->course->price - $item->course->discount_price) / $item->course->price) * 100) }}% OFF
                        </div>
                        @endif
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="badge bg-{{ $item->course->level == 'beginner' ? 'success' : ($item->course->level == 'intermediate' ? 'warning' : 'danger') }}">
                                    {{ ucfirst($item->course->level) }}
                                </span>
                                <small class="text-muted">Added {{ $item->created_at->diffForHumans() }}</small>
                            </div>
                            <h5 class="card-title mb-2">
                                <a href="{{ route('courses.show', $item->course->slug) }}" class="text-decoration-none text-dark course-title">{{ $item->course->title }}</a>
                            </h5>
                            <p class="text-muted small mb-3">
                                <i class="fas fa-user-tie me-1"></i> <span class="instructor-name">{{ $item->course->instructor->name ?? 'Unknown Instructor' }}</span>
                            </p>
                            
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="text-warning">
                                    <div class="course-rating" data-rating="{{ $item->course->average_rating }}"></div>
                                    <span class="ms-1 text-muted small">{{ number_format($item->course->average_rating, 1) }} ({{ $item->course->reviews_count ?? 0 }})</span>
                                </div>
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-users me-1 text-muted small"></i>
                                    <span class="text-muted small">{{ $item->course->total_students ?? 0 }}</span>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center mt-3">
                                <div class="course-price">
                                    @if($item->course->price == 0)
                                    <span class="h5 text-success fw-bold">Free</span>
                                    @elseif($item->course->discount_price && $item->course->discount_ends_at > now())
                                    <span class="h5 fw-bold">${{ number_format($item->course->discount_price, 2) }}</span>
                                    <del class="text-muted ms-2">${{ number_format($item->course->price, 2) }}</del>
                                    <div class="small text-danger">
                                        <i class="fas fa-clock me-1"></i>Sale ends in {{ now()->diffInDays($item->course->discount_ends_at) }} days
                                    </div>
                                    @else
                                    <span class="h5 fw-bold">${{ number_format($item->course->price, 2) }}</span>
                                    @endif
                                </div>
                                <form action="{{ route('student.removeFromWishlist', $item->id) }}" method="POST">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-outline-danger" data-bs-toggle="tooltip" title="Remove from wishlist">
                                        <i class="fas fa-heart-broken me-1"></i>Remove
                                    </button>
                                </form>
                            </div>
                        </div>
                        <div class="card-footer bg-white border-top-0 p-4">
                            <div class="row g-2">
                                <div class="col-12">
                                    <a href="{{ route('courses.enroll', $item->course->slug) }}" class="btn btn-primary w-100">
                                        @if($item->course->price == 0)
                                        <i class="fas fa-unlock-alt me-2"></i>Enroll for Free
                                        @else
                                        <i class="fas fa-shopping-cart me-2"></i>Enroll Now
                                        @endif
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>

            <!-- Pagination -->
            <div class="d-flex justify-content-center mt-5">
                {{ $wishlist->links('pagination::bootstrap-5') }}
            </div>
        @else
            <!-- Empty Wishlist State -->
            <div class="text-center py-5">
                <i class="fas fa-heart fa-4x text-danger opacity-50 mb-4"></i>
                <h4>Your wishlist is empty</h4>
                <p class="text-muted mb-4">Save courses you're interested in by clicking the heart icon on course cards.</p>
                <a href="{{ route('courses.index') }}" class="btn btn-primary">Browse Courses</a>
            </div>
        @endif
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // Initialize star ratings
        $('.course-rating').each(function() {
            const rating = $(this).data('rating');
            $(this).rateYo({
                rating: rating,
                readOnly: true,
                starWidth: "18px"
            });
        });
        
        // Initialize tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Search functionality
        $('#searchButton').on('click', function() {
            const searchTerm = $('#searchWishlist').val().toLowerCase();
            
            $('.wishlist-item').each(function() {
                const courseTitle = $(this).find('.course-title').text().toLowerCase();
                const instructorName = $(this).find('.instructor-name').text().toLowerCase();
                
                if (courseTitle.includes(searchTerm) || instructorName.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
        
        // Reset search when selecting sort
        $('#sortWishlist').on('change', function() {
            $('#searchWishlist').val('');
            $('.wishlist-item').show();
        });
        
        // Sort functionality
        $('#sortWishlist').on('change', function() {
            const sortValue = $(this).val();
            const courseCards = $('.wishlist-item').get();
            
            courseCards.sort(function(a, b) {
                switch(sortValue) {
                    case 'a-z':
                        const titleA = $(a).find('.course-title').text().toUpperCase();
                        const titleB = $(b).find('.course-title').text().toUpperCase();
                        return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
                        
                    case 'z-a':
                        const titleADesc = $(a).find('.course-title').text().toUpperCase();
                        const titleBDesc = $(b).find('.course-title').text().toUpperCase();
                        return (titleADesc > titleBDesc) ? -1 : (titleADesc < titleBDesc) ? 1 : 0;
                        
                    case 'price-low':
                        const priceTextA = $(a).find('.course-price .h5').text().replace('$', '').replace('Free', '0');
                        const priceTextB = $(b).find('.course-price .h5').text().replace('$', '').replace('Free', '0');
                        const priceA = parseFloat(priceTextA) || 0;
                        const priceB = parseFloat(priceTextB) || 0;
                        return priceA - priceB;
                        
                    case 'price-high':
                        const priceHighTextA = $(a).find('.course-price .h5').text().replace('$', '').replace('Free', '0');
                        const priceHighTextB = $(b).find('.course-price .h5').text().replace('$', '').replace('Free', '0');
                        const priceHighA = parseFloat(priceHighTextA) || 0;
                        const priceHighB = parseFloat(priceHighTextB) || 0;
                        return priceHighB - priceHighA;
                        
                    case 'oldest':
                        // We don't have direct access to date added in DOM, this is simplified
                        // In reality, you might want to add data attributes with timestamps
                        return 1; // Reverse of 'newest'
                        
                    case 'newest':
                    default:
                        return -1; // Default sorting (newest first)
                }
            });
            
            // Reattach sorted items
            const parent = $('#wishlistGrid');
            $.each(courseCards, function(index, item) {
                parent.append(item);
            });
        });
    });
</script>
@endpush
@endsection