@extends('layouts.app')

@section('page_title', 'Our Gallery')
@section('page_subtitle', 'Capturing moments of impact and community action across the globe.')

@section('content')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" />

<section class="section gallery-section dark" style="padding-top: 40px;">
    <div class="container">
        <div class="page-header" style="text-align: center; margin-bottom: 50px;">
            <div style="display: flex; gap: 15px; align-items: center; justify-content: center;">
                @auth
                    <button type="button" id="toggle-select-mode" class="button button-secondary" style="background: #444;">Select Multiple</button>
                    <a class="button button-primary" href="{{ route('gallery.upload') }}">+ Upload New Media</a>
                @endauth
            </div>
        </div>

        @auth
            <div id="bulk-actions" style="display: none; margin-bottom: 20px; background: #1a1a1a; padding: 20px; border-radius: 8px; border: 1px solid #333; text-align: center;">
                <span id="selected-count" style="color: #fff; margin-right: 20px; font-weight: 600;">0 items selected</span>
                <button type="button" id="select-all" class="button button-secondary" style="padding: 8px 20px; font-size: 0.9rem;">Select All</button>
                <form action="{{ route('gallery.bulk-destroy') }}" method="POST" id="bulk-delete-form" style="display: inline-block; margin-left: 10px;" onsubmit="return confirm('Are you sure you want to delete the selected items?')">
                    @csrf
                    @method('DELETE')
                    <div id="selected-ids-container"></div>
                    <button type="submit" class="button button-secondary" style="background: #ff4d4d; color: #fff; padding: 8px 20px; font-size: 0.9rem; border: none;">Delete Selected</button>
                </form>
                <button type="button" id="cancel-selection" class="button button-secondary" style="padding: 8px 20px; font-size: 0.9rem; margin-left: 10px;">Cancel</button>
            </div>
        @endauth

        @if(!$groups->isEmpty())
            <div class="gallery-filters" style="margin-bottom: 40px; display: flex; gap: 15px; flex-wrap: wrap; justify-content: center;">
                <a href="{{ route('gallery') }}" class="filter-btn {{ !request('group') ? 'active' : '' }}">All Photos</a>
                @foreach($groups as $group)
                    <a href="{{ route('gallery', ['group' => $group->slug]) }}" class="filter-btn {{ request('group') == $group->slug ? 'active' : '' }}">
                        {{ $group->name }} ({{ $group->items_count }})
                    </a>
                @endforeach
            </div>
        @endif

        @if(session('success'))
            <div class="alert alert-success">{{ session('success') }}</div>
        @endif

        @if($items->isEmpty())
            <div class="empty-state">
                <div style="font-size: 4rem; margin-bottom: 20px;">📸</div>
                <p>No gallery items yet. Add a photo or video to start showcasing our work.</p>
            </div>
        @else
            <div class="masonry-grid">
                @foreach($items as $item)
                    <div class="masonry-item" data-id="{{ $item->id }}">
                        @auth
                            <div class="selection-checkbox" style="display: none; position: absolute; top: 15px; left: 15px; z-index: 10;">
                                <input type="checkbox" class="gallery-item-check" value="{{ $item->id }}" style="width: 25px; height: 25px; cursor: pointer; accent-color: #00bcd4;">
                            </div>
                        @endauth
                        @if($item->type === 'image')
                            <a href="{{ asset('storage/' . $item->file_path) }}" class="glightbox" data-glightbox="title: {{ $item->title }}; description: {{ $item->description }}">
                                <div class="media-container">
                                    <img src="{{ asset('storage/' . $item->file_path) }}" alt="{{ $item->title }}">
                                    <div class="media-overlay">
                                        <div class="overlay-content">
                                            <h3>{{ $item->title }}</h3>
                                            @if($item->description)
                                                <p>{{ Str::limit($item->description, 60) }}</p>
                                            @endif
                                            <span class="view-btn">View Photo</span>
                                            @auth
                                                <form action="{{ route('gallery.destroy', $item) }}" method="POST" style="margin-top: 15px;" onsubmit="return confirm('Are you sure you want to delete this photo?')">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="button button-secondary" style="background: #ff4d4d; color: #fff; padding: 5px 15px; font-size: 0.8rem; border: none;">Delete</button>
                                                </form>
                                            @endauth
                                        </div>
                                    </div>
                                </div>
                            </a>
                        @else
                            <a href="{{ asset('storage/' . $item->file_path) }}" class="glightbox" data-glightbox="title: {{ $item->title }}; description: {{ $item->description }}">
                                <div class="media-container video-type">
                                    <video src="{{ asset('storage/' . $item->file_path) }}"></video>
                                    <div class="play-icon">▶</div>
                                    <div class="media-overlay">
                                        <div class="overlay-content">
                                            <h3>{{ $item->title }}</h3>
                                            @if($item->description)
                                                <p>{{ Str::limit($item->description, 60) }}</p>
                                            @endif
                                            <span class="view-btn">Play Video</span>
                                            @auth
                                                <form action="{{ route('gallery.destroy', $item) }}" method="POST" style="margin-top: 15px;" onsubmit="return confirm('Are you sure you want to delete this video?')">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="button button-secondary" style="background: #ff4d4d; color: #fff; padding: 5px 15px; font-size: 0.8rem; border: none;">Delete</button>
                                                </form>
                                            @endauth
                                        </div>
                                    </div>
                                </div>
                            </a>
                        @endif
                    </div>
                @endforeach
            </div>
        @endif
    </div>
</section>

<script src="https://cdn.jsdelivr.net/gh/mcstudios/glightbox/dist/js/glightbox.min.js"></script>
<script type="text/javascript">
    const lightbox = GLightbox({
        selector: '.glightbox',
        touchNavigation: true,
        loop: true,
        autoplayVideos: true
    });

    @auth
    // Bulk Selection Logic
    const toggleBtn = document.getElementById('toggle-select-mode');
    const bulkActions = document.getElementById('bulk-actions');
    const checkboxes = document.querySelectorAll('.selection-checkbox');
    const itemChecks = document.querySelectorAll('.gallery-item-check');
    const selectedCount = document.getElementById('selected-count');
    const idsContainer = document.getElementById('selected-ids-container');
    const selectAllBtn = document.getElementById('select-all');
    const cancelBtn = document.getElementById('cancel-selection');
    const masonryItems = document.querySelectorAll('.masonry-item');

    let selectionMode = false;

    function updateSelection() {
        const checked = document.querySelectorAll('.gallery-item-check:checked');
        selectedCount.textContent = `${checked.length} items selected`;
        
        // Update hidden inputs for form
        idsContainer.innerHTML = '';
        checked.forEach(cb => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'ids[]';
            input.value = cb.value;
            idsContainer.appendChild(input);
        });

        // Highlight selected items
        itemChecks.forEach(cb => {
            const parent = cb.closest('.masonry-item');
            if (cb.checked) {
                parent.style.border = '3px solid #00bcd4';
                parent.style.opacity = '0.7';
            } else {
                parent.style.border = 'none';
                parent.style.opacity = '1';
            }
        });
    }

    function toggleMode(enable) {
        selectionMode = enable;
        bulkActions.style.display = enable ? 'block' : 'none';
        checkboxes.forEach(div => div.style.display = enable ? 'block' : 'none');
        
        // Disable lightbox in selection mode
        masonryItems.forEach(item => {
            const link = item.querySelector('.glightbox');
            if (enable) {
                link.onclick = (e) => {
                    e.preventDefault();
                    const cb = item.querySelector('.gallery-item-check');
                    cb.checked = !cb.checked;
                    updateSelection();
                };
            } else {
                link.onclick = null;
                const cb = item.querySelector('.gallery-item-check');
                cb.checked = false;
                item.style.border = 'none';
                item.style.opacity = '1';
            }
        });

        if (!enable) {
            idsContainer.innerHTML = '';
            selectedCount.textContent = '0 items selected';
        }
    }

    toggleBtn.addEventListener('click', () => toggleMode(true));
    cancelBtn.addEventListener('click', () => toggleMode(false));

    itemChecks.forEach(cb => {
        cb.addEventListener('change', updateSelection);
    });

    selectAllBtn.addEventListener('click', () => {
        const allChecked = Array.from(itemChecks).every(cb => cb.checked);
        itemChecks.forEach(cb => cb.checked = !allChecked);
        updateSelection();
    });
    @endauth
</script>
@endsection
