@extends('layouts.app')

@section('title', 'My Playlists | ' . config('app.name'))

@section('extra_styles')
    <style>
        .playlist-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 24px;
            margin: -24px -24px 20px;
            background: var(--bg-secondary);
            border-bottom: 1px solid var(--border-color);
            position: sticky;
            top: 56px;
            z-index: 90;
        }

        .playlist-title {
            font-size: 20px;
            font-weight: 500;
            margin: 0;
        }

        @media (max-width: 768px) {
            .playlist-header {
                position: relative !important;
                top: auto !important;
                margin: -16px -16px 16px !important;
                padding: 12px 16px !important;
            }
        }

        .playlist-card {
            display: flex;
            gap: 16px;
            padding: 12px;
            border-radius: 12px;
            background: var(--bg-secondary);
            transition: background 0.2s;
            text-decoration: none;
            color: inherit;
        }

        .playlist-card:hover {
            background: var(--border-color);
        }

        .playlist-thumbnail {
            width: 160px;
            height: 90px;
            border-radius: 8px;
            overflow: hidden;
            background: #333;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .playlist-thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .playlist-thumbnail .placeholder {
            font-size: 32px;
            color: var(--text-secondary);
        }

        .playlist-info {
            flex: 1;
            min-width: 0;
        }

        .playlist-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .playlist-meta {
            font-size: 14px;
            color: var(--text-secondary);
        }

        .playlist-description {
            font-size: 13px;
            color: var(--text-secondary);
            margin-top: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .playlist-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 16px;
        }


        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }

        .empty-icon {
            font-size: 64px;
            color: var(--text-secondary);
            margin-bottom: 16px;
        }

        .empty-title {
            font-size: 20px;
            margin-bottom: 8px;
        }

        .empty-text {
            color: var(--text-secondary);
            margin-bottom: 20px;
        }

        @media (max-width: 576px) {
            .playlist-grid {
                grid-template-columns: 1fr;
            }

            .playlist-card {
                flex-direction: column;
            }

            .playlist-thumbnail {
                width: 100%;
                height: 120px;
            }
        }
    </style>
@endsection

@section('content')
    <div class="playlist-header">
        <h1 class="playlist-title">My Playlists</h1>
        <button class="action-btn action-btn-primary" onclick="openCreatePlaylistModal()">
            <i class="bi bi-plus-lg"></i> New Playlist
        </button>
    </div>

    @if($playlists->isEmpty())
        <div class="empty-state">
            <i class="bi bi-collection-play empty-icon"></i>
            <h2 class="empty-title">No playlists yet</h2>
            <p class="empty-text">Create your first playlist to organize your favorite videos.</p>
            <button class="action-btn action-btn-primary" onclick="openCreatePlaylistModal()">
                <i class="bi bi-plus-lg"></i> Create Playlist
            </button>
        </div>
    @else
        <div class="playlist-grid">
            @foreach($playlists as $playlist)
                <a href="{{ route('playlists.show', $playlist->id) }}" class="playlist-card">
                    <div class="playlist-thumbnail">
                        @if($playlist->thumbnail_url)
                            <img src="{{ $playlist->thumbnail_url }}" alt="{{ $playlist->name }}">
                        @else
                            <span class="placeholder">
                                <i class="bi bi-collection-play"></i>
                            </span>
                        @endif
                    </div>
                    <div class="playlist-info">
                        <div class="playlist-name">{{ $playlist->name }}</div>
                        <div class="playlist-meta">
                            {{ $playlist->video_count }} videos • {{ $playlist->formatted_duration }} • {{ \Illuminate\Support\Number::abbreviate($playlist->view_count, precision: 1) }} views
                        </div>
                        @if($playlist->description)
                            <div class="playlist-description">{{ $playlist->description }}</div>
                        @endif
                    </div>
                </a>
            @endforeach
        </div>
    @endif

    <!-- Create Playlist Modal - Modern YouTube Style -->
    <div id="createPlaylistModal" class="playlist-create-modal-overlay" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 9999; align-items: center; justify-content: center; backdrop-filter: blur(2px);">
        <div class="playlist-create-modal-content" style="background: #282828; border-radius: 12px; width: 90%; max-width: 480px; box-shadow: 0 8px 32px rgba(0,0,0,0.5); overflow: hidden; animation: modalSlideIn 0.2s ease;">
            <!-- Header -->
            <div class="playlist-create-modal-header" style="display: flex; justify-content: space-between; align-items: center; padding: 20px 24px; border-bottom: 1px solid #3f3f3f;">
                <h2 style="font-size: 18px; font-weight: 600; margin: 0; color: #fff;">Create new playlist</h2>
                <button type="button" id="closeCreatePlaylistModalBtn" style="background: transparent; border: none; color: #aaa; cursor: pointer; font-size: 24px; padding: 4px; line-height: 1; border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; transition: all 0.2s;">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>

            <!-- Body -->
            <div style="padding: 24px;">
                <form id="createPlaylistForm" enctype="multipart/form-data">
                    @csrf
                    <!-- Thumbnail Upload -->
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; color: #fff;">Thumbnail</label>
                        <div id="playlist-thumbnail-dropzone" class="playlist-thumbnail-dropzone" style="border: 2px dashed #3f3f3f; border-radius: 12px; padding: 20px; text-align: center; cursor: pointer; transition: all 0.2s; background: #1a1a1a;"
                            onmouseover="this.style.borderColor='#e61e1e'; this.style.background='rgba(230,30,30,0.05)'"
                            onmouseout="this.style.borderColor='#3f3f3f'; this.style.background='#1a1a1a'">
                            <input type="file" name="thumbnail" id="playlist-thumbnail-input" accept="image/*" style="display: none;">
                            <div id="playlist-thumbnail-default">
                                <div style="font-size: 36px; color: #666; margin-bottom: 8px;">
                                    <i class="bi bi-card-image"></i>
                                </div>
                                <p style="color: #aaa; font-size: 13px; margin: 0 0 4px;">Click to upload thumbnail</p>
                                <p style="color: #555; font-size: 11px; margin: 0;">JPG, PNG, GIF, WebP (max 5MB)</p>
                            </div>
                            <div id="playlist-thumbnail-preview" class="playlist-thumbnail-preview" style="display: none;">
                                <img id="playlist-thumbnail-img" src="" alt="Thumbnail preview" style="max-width: 100%; max-height: 160px; border-radius: 8px; object-fit: cover;">
                                <button type="button" onclick="removePlaylistThumbnail(event)" style="position: absolute; top: -8px; right: -8px; width: 24px; height: 24px; background: #e61e1e; color: white; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px;">
                                    <i class="bi bi-x"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Playlist Name -->
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; color: #fff;">Name *</label>
                        <input type="text" name="name" required
                            placeholder="Enter playlist name"
                            style="width: 100%; padding: 12px 14px; border: 1px solid #3f3f3f; border-radius: 8px; background: #121212; color: #fff; font-size: 14px; outline: none; transition: border-color 0.2s; box-sizing: border-box;"
                            onfocus="this.style.borderColor = '#e61e1e';"
                            onblur="this.style.borderColor = '#3f3f3f';">
                    </div>

                    <!-- Description -->
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px; color: #fff;">Description</label>
                        <textarea name="description" rows="3"
                            placeholder="Add a description (optional)"
                            style="width: 100%; padding: 12px 14px; border: 1px solid #3f3f3f; border-radius: 8px; background: #121212; color: #fff; font-size: 14px; outline: none; transition: border-color 0.2s; resize: none; box-sizing: border-box;"
                            onfocus="this.style.borderColor = '#e61e1e';"
                            onblur="this.style.borderColor = '#3f3f3f';"></textarea>
                    </div>

                    <!-- Visibility -->
                    <div class="form-group" style="margin-bottom: 24px;">
                        <label style="display: block; margin-bottom: 10px; font-weight: 500; font-size: 14px; color: #fff;">Visibility</label>
                        <div style="display: flex; flex-direction: column; gap: 8px;">
                            <label style="display: flex; align-items: center; gap: 12px; cursor: pointer; padding: 10px 12px; border-radius: 8px; border: 1px solid #3f3f3f; transition: border-color 0.2s; background: #1a1a1a;">
                                <input type="radio" name="visibility" value="public" style="accent-color: #e61e1e; cursor: pointer; width: 16px; height: 16px;">
                                <div>
                                    <div style="display: flex; align-items: center; gap: 6px; color: #fff; font-size: 14px; font-weight: 500;"><i class="bi bi-globe"></i> Public</div>
                                    <div style="color: #aaa; font-size: 12px; margin-top: 2px;">Anyone can search for and view this playlist</div>
                                </div>
                            </label>
                            <label style="display: flex; align-items: center; gap: 12px; cursor: pointer; padding: 10px 12px; border-radius: 8px; border: 1px solid #3f3f3f; transition: border-color 0.2s; background: #1a1a1a;">
                                <input type="radio" name="visibility" value="unlisted" style="accent-color: #e61e1e; cursor: pointer; width: 16px; height: 16px;">
                                <div>
                                    <div style="display: flex; align-items: center; gap: 6px; color: #fff; font-size: 14px; font-weight: 500;"><i class="bi bi-link-45deg"></i> Unlisted</div>
                                    <div style="color: #aaa; font-size: 12px; margin-top: 2px;">Anyone with the link can view, but it won't appear in search</div>
                                </div>
                            </label>
                            <label style="display: flex; align-items: center; gap: 12px; cursor: pointer; padding: 10px 12px; border-radius: 8px; border: 1px solid #3f3f3f; transition: border-color 0.2s; background: #1a1a1a;">
                                <input type="radio" name="visibility" value="private" checked style="accent-color: #e61e1e; cursor: pointer; width: 16px; height: 16px;">
                                <div>
                                    <div style="display: flex; align-items: center; gap: 6px; color: #fff; font-size: 14px; font-weight: 500;"><i class="bi bi-lock-fill"></i> Private</div>
                                    <div style="color: #aaa; font-size: 12px; margin-top: 2px;">Only you can view this playlist</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button type="button" onclick="closeCreatePlaylistModal()" class="action-btn">
                            Cancel
                        </button>
                        <button type="submit" class="action-btn action-btn-primary">
                            <i class="bi bi-plus-lg"></i> <span>Create</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

<style>
@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-20px) scale(0.95);
    }
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}

/* Header button hover */
#closeCreatePlaylistModalBtn:hover {
    background: #3f3f3f !important;
    color: #fff !important;
}
</style>

@section('scripts')
<script>
// Thumbnail upload handling
const thumbnailDropzone = document.getElementById('playlist-thumbnail-dropzone');
const thumbnailInput = document.getElementById('playlist-thumbnail-input');
const thumbnailDefault = document.getElementById('playlist-thumbnail-default');
const thumbnailPreview = document.getElementById('playlist-thumbnail-preview');
const thumbnailImg = document.getElementById('playlist-thumbnail-img');

// Click to upload — open file picker; cropper will open after file is chosen
thumbnailDropzone.addEventListener('click', function(e) {
    if (e.target.closest('button')) return;
    thumbnailInput.click();
});

// File input change — if cropper is open (result came from cropper), just show preview;
// otherwise preload the file into the cropper and open it.
thumbnailInput.addEventListener('change', function() {
    if (!this.files || !this.files[0]) return;
    const cropperOpen = document.getElementById('tcOverlay_thumb_pl_create')?.classList.contains('open');
    if (cropperOpen) {
        handleThumbnailSelect(this);
        return;
    }
    const file = this.files[0];
    if (typeof window.tcPreload_thumb_pl_create === 'function' &&
        typeof window.openCropperModal_thumb_pl_create === 'function') {
        window.tcPreload_thumb_pl_create(file);
        window.openCropperModal_thumb_pl_create();
    } else {
        handleThumbnailSelect(this);
    }
});

// Drag and drop
thumbnailDropzone.addEventListener('dragover', function(e) {
    e.preventDefault();
    this.style.borderColor = '#e61e1e';
    this.style.background = 'rgba(230,30,30,0.1)';
});

thumbnailDropzone.addEventListener('dragleave', function(e) {
    e.preventDefault();
    this.style.borderColor = '#3f3f3f';
    this.style.background = '#1a1a1a';
});

thumbnailDropzone.addEventListener('drop', function(e) {
    e.preventDefault();
    this.style.borderColor = '#3f3f3f';
    this.style.background = '#1a1a1a';

    if (e.dataTransfer.files.length) {
        const droppedFile = e.dataTransfer.files[0];
        if (typeof window.tcPreload_thumb_pl_create === 'function' &&
            typeof window.openCropperModal_thumb_pl_create === 'function') {
            window.tcPreload_thumb_pl_create(droppedFile);
            window.openCropperModal_thumb_pl_create();
        } else {
            thumbnailInput.files = e.dataTransfer.files;
            handleThumbnailSelect(thumbnailInput);
        }
    }
});

function handleThumbnailSelect(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const maxSize = 20 * 1024 * 1024; // 20MB

        // Validate file type
        const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        const validExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];

        let isValidType = validTypes.includes(file.type);
        let fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        if (!isValidType) {
            isValidType = validExtensions.includes(fileExtension);
        }

        if (!isValidType) {
            showPlaylistToast('Invalid image format. Please select JPG, PNG, GIF, or WebP.', 'error');
            return;
        }

        if (file.size > maxSize) {
            showPlaylistToast('File size exceeds 20MB limit. Please select a smaller image.', 'error');
            return;
        }

        // Show preview
        const reader = new FileReader();
        reader.onload = function(e) {
            thumbnailImg.src = e.target.result;
            thumbnailDefault.style.display = 'none';
            thumbnailPreview.style.display = 'block';
            thumbnailPreview.style.position = 'relative';
        };
        reader.readAsDataURL(file);
    }
}

function removePlaylistThumbnail(e) {
    e.preventDefault();
    e.stopPropagation();
    thumbnailInput.value = '';
    thumbnailDefault.style.display = 'block';
    thumbnailPreview.style.display = 'none';
    thumbnailImg.src = '';
}

function openCreatePlaylistModal() {
    document.getElementById('createPlaylistModal').style.display = 'flex';
}

function closeCreatePlaylistModal() {
    document.getElementById('createPlaylistModal').style.display = 'none';
    document.getElementById('createPlaylistForm').reset();
    // Reset thumbnail
    removePlaylistThumbnail({ preventDefault: function(){}, stopPropagation: function(){} });
}

// Close button event listener
document.addEventListener('DOMContentLoaded', function() {
    const closeBtn = document.getElementById('closeCreatePlaylistModalBtn');
    if (closeBtn) {
        closeBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            closeCreatePlaylistModal();
        });
    }
});

// Close modal when clicking outside
document.getElementById('createPlaylistModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeCreatePlaylistModal();
    }
});

// Close on escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('createPlaylistModal');
        if (modal && modal.style.display === 'flex') {
            closeCreatePlaylistModal();
        }
    }
});

// Create playlist form submission
document.getElementById('createPlaylistForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch('{{ route("playlists.store") }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeCreatePlaylistModal();
            window.location.href = '{{ route("playlists.show", "") }}/' + data.playlist.id;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showPlaylistToast('Failed to create playlist. Please try again.', 'error');
    });
});

// Toast notification function
function showPlaylistToast(message, type = 'success') {
    // Remove existing toast if any
    const existing = document.querySelector('.playlist-create-toast');
    if (existing) existing.remove();

    const toast = document.createElement('div');
    toast.className = 'playlist-create-toast';

    const bgColor = type === 'error' ? 'rgba(239, 68, 68, 0.9)' : '#282828';
    const borderColor = type === 'error' ? '#ef4444' : '#4ade80';
    const icon = type === 'error' ? 'bi-exclamation-circle-fill' : 'bi-check-circle-fill';
    const iconColor = type === 'error' ? '#ef4444' : '#4ade80';

    toast.style.cssText = `
        position: fixed;
        bottom: 80px;
        left: 50%;
        transform: translateX(-50%);
        background: ${bgColor};
        color: #fff;
        padding: 14px 24px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        z-index: 10000;
        animation: toastSlideUp 0.3s ease;
        box-shadow: 0 4px 20px rgba(0,0,0,0.4);
        max-width: 90%;
        text-align: center;
        border-left: 4px solid ${borderColor};
        display: flex;
        align-items: center;
        gap: 10px;
    `;

    toast.innerHTML = `
        <i class="bi ${icon}" style="color: ${iconColor}; font-size: 18px;"></i>
        <span>${message}</span>
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'toastSlideDown 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}
</script>
<x-image-cropper
    id="thumb_pl_create"
    :width="448"
    :height="252"
    shape="square"
    target-input="playlist-thumbnail-input"
    preview-img="playlist-thumbnail-img"
    output-width="1280"
    title="Crop Playlist Thumbnail"
/>
@endsection

<style>
@keyframes toastSlideUp {
    from { opacity: 0; transform: translateX(-50%) translateY(20px); }
    to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes toastSlideDown {
    from { opacity: 1; transform: translateX(-50%) translateY(0); }
    to { opacity: 0; transform: translateX(-50%) translateY(20px); }
}
</style>
