<?php

require_once __DIR__ . '/app/helpers.php';
require_once __DIR__ . '/app/gallery.php';
require_once __DIR__ . '/app/public-layout.php';
require_once __DIR__ . '/app/analytics.php';

$gallery_title = trim(sparrow_public_setting('gallery_page_title', 'Sparrow & Seed Gallery'));
$gallery_intro = trim(sparrow_public_setting('gallery_page_intro'));
$gallery_per_page = max(1, min(100, (int) sparrow_public_setting('gallery_items_per_page', '40')));
$all_items = sparrow_get_public_gallery_items();
$total_items = count($all_items);
$total_pages = max(1, (int) ceil($total_items / $gallery_per_page));
$page = max(1, min((int) ($_GET['page'] ?? 1), $total_pages));
$items = array_slice($all_items, ($page - 1) * $gallery_per_page, $gallery_per_page);

sparrow_record_analytics_event('page_view', 'page', null, 'Gallery', '', '/gallery.php');

$gallery_css = <<<'CSS'
.public-gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(170px, 210px));
    gap: 14px;
    justify-content: center;
}

.public-gallery-card {
    background: var(--sparrow-card);
    border: 1px solid var(--sparrow-border);
    border-radius: 22px;
    overflow: hidden;
    box-shadow: 0 8px 30px rgba(70, 35, 60, 0.06);
}

.public-gallery-clickable {
    cursor: pointer;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.public-gallery-clickable:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 34px rgba(70, 35, 60, 0.10);
}

.public-gallery-clickable:hover img {
    opacity: 0.95;
}

.public-gallery-clickable:focus {
    outline: 3px solid var(--sparrow-border);
    outline-offset: 3px;
}

.public-gallery-card img {
    display: block;
    width: 100%;
    aspect-ratio: 1 / 1;
    object-fit: cover;
    background: #ffffff;
}

.public-gallery-card-body {
    padding: 11px 12px 13px;
}

.public-gallery-card h2 {
    margin: 0;
    font-size: 15px;
    color: var(--sparrow-purple-dark);
    line-height: 1.25;
}

.public-gallery-category {
    display: inline-block;
    margin-bottom: 7px;
    padding: 3px 8px;
    border-radius: 999px;
    background: var(--sparrow-soft-pink);
    color: var(--sparrow-purple-dark);
    font-size: 11px;
    font-weight: bold;
}

.gallery-empty {
    background: var(--sparrow-card);
    border: 1px solid var(--sparrow-border);
    border-radius: 18px;
    padding: 24px;
    text-align: center;
    color: var(--sparrow-muted);
}

.gallery-lightbox {
    position: fixed;
    inset: 0;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 22px;
    background: rgba(32, 20, 30, 0.78);
    z-index: 9999;
}

.gallery-lightbox.is-open {
    display: flex;
}

.gallery-lightbox-panel {
    position: relative;
    width: min(940px, 100%);
    max-height: 92vh;
    overflow: auto;
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
    border: 1px solid var(--sparrow-border);
}

.gallery-lightbox-image {
    display: block;
    width: 100%;
    max-height: 70vh;
    object-fit: contain;
    background: #fff8fc;
    border-radius: 24px 24px 0 0;
}

.gallery-lightbox-body {
    padding: 18px 20px 22px;
}

.gallery-lightbox-body h2 {
    margin: 0 0 8px;
    color: var(--sparrow-purple-dark);
}

.gallery-lightbox-category {
    display: inline-block;
    margin-bottom: 10px;
    padding: 4px 10px;
    border-radius: 999px;
    background: var(--sparrow-soft-pink);
    color: var(--sparrow-purple-dark);
    font-size: 12px;
    font-weight: bold;
}

.gallery-lightbox-description {
    margin: 0;
    color: var(--sparrow-muted);
    line-height: 1.5;
    white-space: pre-wrap;
}

.gallery-lightbox-close {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 38px;
    height: 38px;
    border: 0;
    border-radius: 999px;
    background: rgba(255, 255, 255, 0.95);
    color: var(--sparrow-purple-dark);
    font-size: 24px;
    line-height: 1;
    cursor: pointer;
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
}

.gallery-lightbox-close:hover {
    background: var(--sparrow-soft-pink);
}

.gallery-pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 24px;
}

.gallery-page-link {
    display: inline-block;
    padding: 8px 12px;
    border-radius: 999px;
    border: 1px solid var(--sparrow-border);
    background: #ffffff;
    color: var(--sparrow-purple-dark);
    text-decoration: none;
    font-weight: bold;
    font-size: 13px;
}

.gallery-page-link:hover,
.gallery-page-link.is-active {
    background: var(--sparrow-soft-pink);
}
CSS;

sparrow_public_header($gallery_title !== '' ? $gallery_title : 'Gallery', 'gallery', $gallery_css);

?>

        <section class="public-card public-hero">
    <h1><?php echo sparrow_escape($gallery_title !== '' ? $gallery_title : 'Gallery'); ?></h1>
    <?php if ($gallery_intro !== ''): ?>
        <p><?php echo nl2br(sparrow_escape($gallery_intro)); ?></p>
    <?php endif; ?>
</section>

        <?php if (!$items): ?>
            <section class="gallery-empty">
                No gallery items are showing yet.
            </section>
        <?php else: ?>
            <section class="public-gallery-grid">
                <?php foreach ($items as $item): ?>
                    <article
    class="public-gallery-card <?php echo !empty($item['primary_image']) ? 'public-gallery-clickable' : ''; ?>"
    <?php if (!empty($item['primary_image'])): ?>
        role="button"
        tabindex="0"
        data-lightbox-src="<?php echo sparrow_escape(sparrow_url($item['primary_image'])); ?>"
        data-lightbox-title="<?php echo sparrow_escape($item['title']); ?>"
        data-lightbox-category="<?php echo sparrow_escape($item['category']); ?>"
        data-lightbox-description="<?php echo sparrow_escape($item['description'] ?? ''); ?>"
		data-analytics-id="<?php echo (int) $item['id']; ?>"
data-analytics-type="gallery_item"
    <?php endif; ?>
>
                        <?php if (!empty($item['primary_image'])): ?>
    <img
        src="<?php echo sparrow_escape(sparrow_url($item['primary_image'])); ?>"
        alt="<?php echo sparrow_escape($item['title']); ?>"
    >
<?php endif; ?>

                        <div class="public-gallery-card-body">
                            <span class="public-gallery-category">
                                <?php echo sparrow_escape($item['category']); ?>
                            </span>

                            <h2><?php echo sparrow_escape($item['title']); ?></h2>
                        </div>
                    </article>
                <?php endforeach; ?>
            </section>
            <?php if ($total_pages > 1): ?>
                <nav class="gallery-pagination" aria-label="Gallery pages">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <a
                            class="gallery-page-link <?php echo $i === $page ? 'is-active' : ''; ?>"
                            href="<?php echo sparrow_escape(sparrow_url('/gallery.php?page=' . $i)); ?>"
                        ><?php echo $i; ?></a>
                    <?php endfor; ?>
                </nav>
            <?php endif; ?>
        <?php endif; ?>
	
	<div class="gallery-lightbox" id="galleryLightbox" aria-hidden="true">
    <div class="gallery-lightbox-panel" role="dialog" aria-modal="true" aria-labelledby="galleryLightboxTitle">
        <button type="button" class="gallery-lightbox-close" id="galleryLightboxClose" aria-label="Close image">
            &times;
        </button>

        <img src="" alt="" class="gallery-lightbox-image" id="galleryLightboxImage">

        <div class="gallery-lightbox-body">
            <span class="gallery-lightbox-category" id="galleryLightboxCategory"></span>
            <h2 id="galleryLightboxTitle"></h2>
            <p class="gallery-lightbox-description" id="galleryLightboxDescription"></p>
        </div>
    </div>
</div>

<script>
    const analyticsEndpoint = <?php echo json_encode(sparrow_url('/track-analytics.php'), JSON_UNESCAPED_SLASHES); ?>;
    const lightbox = document.getElementById('galleryLightbox');
    const lightboxImage = document.getElementById('galleryLightboxImage');
    const lightboxTitle = document.getElementById('galleryLightboxTitle');
    const lightboxCategory = document.getElementById('galleryLightboxCategory');
    const lightboxDescription = document.getElementById('galleryLightboxDescription');
    const lightboxClose = document.getElementById('galleryLightboxClose');

function trackAnalytics(eventType, entityType, entityId, entityTitle, entityCategory) {
    const payload = {
        event_type: eventType,
        entity_type: entityType,
        entity_id: entityId,
        entity_title: entityTitle,
        entity_category: entityCategory
    };

    try {
        const blob = new Blob([JSON.stringify(payload)], {
            type: 'application/json'
        });

        if (navigator.sendBeacon) {
            navigator.sendBeacon(analyticsEndpoint, blob);
            return;
        }

        fetch(analyticsEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload),
            keepalive: true
        });
    } catch (error) {
        // Analytics should never break the gallery.
    }
}

    function openGalleryLightbox(trigger) {
    const imageSrc = trigger.getAttribute('data-lightbox-src') || '';
    const title = trigger.getAttribute('data-lightbox-title') || '';
    const category = trigger.getAttribute('data-lightbox-category') || '';
    const description = trigger.getAttribute('data-lightbox-description') || '';
	
	trackAnalytics(
    'gallery_lightbox_open',
    trigger.getAttribute('data-analytics-type') || 'gallery_item',
    trigger.getAttribute('data-analytics-id') || '',
    title,
    category
);

        lightboxImage.src = imageSrc;
        lightboxImage.alt = title;
        lightboxTitle.textContent = title;
        lightboxCategory.textContent = category;
        lightboxDescription.textContent = description;

        lightbox.classList.add('is-open');
        lightbox.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
        lightboxClose.focus();
    }

    function closeGalleryLightbox() {
        lightbox.classList.remove('is-open');
        lightbox.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';

        lightboxImage.src = '';
        lightboxImage.alt = '';
    }

    document.querySelectorAll('.public-gallery-clickable').forEach((card) => {
    card.addEventListener('click', () => {
        openGalleryLightbox(card);
    });

    card.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            openGalleryLightbox(card);
        }
    });
});

    lightboxClose.addEventListener('click', closeGalleryLightbox);

    lightbox.addEventListener('click', (event) => {
        if (event.target === lightbox) {
            closeGalleryLightbox();
        }
    });

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && lightbox.classList.contains('is-open')) {
            closeGalleryLightbox();
        }
    });
</script>
<?php sparrow_public_footer(); ?>
