<?php
 
 
 
 
 
 

$aid = (int) $album['id'];
$imgCount = (int) ($album['image_count'] ?? count($images));
$views = (int) ($album['views'] ?? 0);
$favCount = (int) ($album['favorites_count'] ?? 0);
$dateStr = !empty($album['published_at']) ? date('M j, Y', strtotime($album['published_at'])) : (!empty($album['created_at']) ? date('M j, Y', strtotime($album['created_at'])) : '');
$cats = $album['categories'] ?? [];
$tags = $album['tags'] ?? [];
$performers = $album['performers'] ?? [];
$channels = $album['channels'] ?? [];
 
$showViews      = Setting::get('album_show_views', '1') === '1';
$showDate       = Setting::get('album_show_date', '1') === '1';
$showLikes      = Setting::get('album_show_likes', '1') === '1';
$showFavorites  = Setting::get('album_show_favorites', '1') === '1';
$showPornstars  = Setting::get('album_show_pornstars', '1') === '1';
$showChannels   = Setting::get('album_show_channels', '1') === '1';
$showCategories = Setting::get('album_show_categories', '1') === '1';
$showTags       = Setting::get('album_show_tags', '1') === '1';
$allowDownload  = Setting::get('album_allow_download', '1') === '1';
$hasSide = ($showPornstars && !empty($performers)) || ($showChannels && !empty($channels)) || ($showCategories && !empty($cats)) || ($showTags && !empty($tags)) || !empty($album['description']);
 
$bucket = $imgCount <= 1 ? 1 : ($imgCount === 2 ? 2 : ($imgCount === 3 ? 3 : 4));
?>

<div class="album-single">

    <div class="album-head">
        <h1 class="album-head__title"><i class="fa-solid fa-images"></i> <?php echo htmlspecialchars($album['title']); ?></h1>
        <div class="album-head__meta">
            <span><i class="fa-light fa-layer-group"></i> <?php echo Format::number($imgCount) . ' ' . __('images'); ?></span>
            <?php if ($showViews): ?><span><i class="fa-light fa-eye"></i> <?php echo Format::number($views) . ' ' . __('views'); ?></span><?php endif; ?>
            <?php if ($dateStr !== '' && $showDate): ?><span><i class="fa-light fa-clock"></i> <?php echo htmlspecialchars($dateStr); ?></span><?php endif; ?>
        </div>
        <?php if (($showCategories && !empty($cats)) || ($showTags && !empty($tags))): ?>
        <div class="album-head__chips">
            <?php if ($showCategories): foreach (array_slice($cats, 0, 4) as $c): ?>
                <a href="<?php echo url('/album-category/' . htmlspecialchars($c['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($c['name']); ?></a>
            <?php endforeach; endif; ?>
            <?php if ($showTags): foreach (array_slice($tags, 0, 8) as $t): ?>
                <a href="<?php echo url('/album-tag/' . htmlspecialchars($t['slug'])); ?>" class="tag-link">#<?php echo htmlspecialchars($t['name']); ?></a>
            <?php endforeach; endif; ?>
        </div>
        <?php endif; ?>
    </div>

    
    <div class="album-actions">
        <div class="album-actions__nav">
            <?php if (!empty($prevAlbum)): ?>
            <a href="<?php echo url('/album/' . htmlspecialchars($prevAlbum['slug'])); ?>" class="btn btn-outline btn-sm"><i class="fa-solid fa-chevron-left"></i> <?php echo __('previous'); ?></a>
            <?php endif; ?>
        </div>
        <div class="album-actions__center">
            <?php if ($showLikes): ?>
            <button type="button" class="vote-btn like<?php echo ($userVote ?? null) === 'like' ? ' active' : ''; ?>" data-album-id="<?php echo $aid; ?>" data-vote="like" data-csrf="<?php echo Router::csrfToken(); ?>" title="<?php echo __('like'); ?>">
                <i class="fa-regular fa-thumbs-up"></i> <span class="vote-count"><?php echo Format::number((int) ($album['likes'] ?? 0)); ?></span>
            </button>
            <button type="button" class="vote-btn dislike<?php echo ($userVote ?? null) === 'dislike' ? ' active' : ''; ?>" data-album-id="<?php echo $aid; ?>" data-vote="dislike" data-csrf="<?php echo Router::csrfToken(); ?>" title="<?php echo __('dislike'); ?>">
                <i class="fa-regular fa-thumbs-down"></i> <span class="vote-count"><?php echo Format::number((int) ($album['dislikes'] ?? 0)); ?></span>
            </button>
            <?php endif; ?>
            <?php if ($showFavorites): ?>
            <button type="button" class="btn-icon" id="albFavBtn" data-id="<?php echo $aid; ?>" data-csrf="<?php echo Router::csrfToken(); ?>" data-fav="<?php echo $isFavorited ? '1' : '0'; ?>" title="<?php echo __('favorite'); ?>">
                <i class="<?php echo $isFavorited ? 'fa-solid' : 'fa-regular'; ?> fa-heart"></i> <span id="albFavCount"><?php echo Format::number($favCount); ?></span>
            </button>
            <?php endif; ?>
            <button type="button" class="btn-icon" id="albCopyBtn" title="<?php echo __('copy_link'); ?>"><i class="fa-light fa-link"></i></button>
            <button type="button" class="btn-icon" id="albReportBtn" data-album-id="<?php echo $aid; ?>" data-csrf="<?php echo htmlspecialchars(Router::csrfToken()); ?>" title="<?php echo __('report_gallery'); ?>"><i class="fa-light fa-flag"></i></button>
        </div>
        <div class="album-actions__nav album-actions__nav--right">
            <?php if (!empty($nextAlbum)): ?>
            <a href="<?php echo url('/album/' . htmlspecialchars($nextAlbum['slug'])); ?>" class="btn btn-outline btn-sm"><?php echo __('next'); ?> <i class="fa-solid fa-chevron-right"></i></a>
            <?php endif; ?>
        </div>
    </div>

    <div class="album-body">
        
        <?php if ($hasSide): ?>
        <aside class="album-side">
            <?php if ($showPornstars && !empty($performers)): ?>
            <div class="album-panel">
                <div class="album-panel__head"><i class="fa-solid fa-star"></i> <?php echo __('pornstars'); ?></div>
                <div class="album-panel__chips">
                    <?php foreach ($performers as $p): ?>
                        <a href="<?php echo url('/album-pornstar/' . htmlspecialchars($p['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($p['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($showChannels && !empty($channels)): ?>
            <div class="album-panel">
                <div class="album-panel__head"><i class="fa-solid fa-tv"></i> <?php echo __('channels'); ?></div>
                <div class="album-panel__chips">
                    <?php foreach ($channels as $ch): ?>
                        <a href="<?php echo url('/album-channel/' . htmlspecialchars($ch['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($ch['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($showCategories && !empty($cats)): ?>
            <div class="album-panel">
                <div class="album-panel__head"><i class="fa-solid fa-folder"></i> <?php echo __('categories'); ?></div>
                <div class="album-panel__chips">
                    <?php foreach ($cats as $c): ?>
                        <a href="<?php echo url('/album-category/' . htmlspecialchars($c['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($c['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($showTags && !empty($tags)): ?>
            <div class="album-panel">
                <div class="album-panel__head"><i class="fa-solid fa-hashtag"></i> <?php echo __('tags'); ?></div>
                <div class="album-panel__chips">
                    <?php foreach ($tags as $t): ?>
                        <a href="<?php echo url('/album-tag/' . htmlspecialchars($t['slug'])); ?>" class="tag-link">#<?php echo htmlspecialchars($t['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php if (!empty($album['description'])): ?>
            <div class="album-panel">
                <div class="album-panel__head"><i class="fa-solid fa-align-left"></i> <?php echo __('description'); ?></div>
                <div class="album-panel__text"><?php echo nl2br(htmlspecialchars($album['description'])); ?></div>
            </div>
            <?php endif; ?>
        </aside>
        <?php endif; ?>

        
        <main class="album-main">
            <?php Ads::zone('album_top'); ?>
            <?php if (!empty($images)): ?>
            <div class="album-photos album-photos--<?php echo $bucket; ?>" id="albumPhotos" data-album-id="<?php echo $aid; ?>">
                <?php foreach ($images as $i => $im): $ar = (!empty($im['w']) && !empty($im['h'])) ? ('aspect-ratio:' . (int)$im['w'] . '/' . (int)$im['h']) : ''; ?>
                    <a href="<?php echo htmlspecialchars($im['url']); ?>" class="album-photo" data-idx="<?php echo $i; ?>" data-img="<?php echo htmlspecialchars($im['f'] ?? ''); ?>" onclick="albLb.open(<?php echo $i; ?>);return false;">
                        <img src="<?php echo htmlspecialchars($im['url']); ?>" loading="<?php echo $i < 6 ? 'eager' : 'lazy'; ?>" decoding="async" <?php if ($ar !== ''): ?>style="<?php echo $ar; ?>"<?php endif; ?> alt="<?php echo htmlspecialchars($album['title']) . ' ' . ($i + 1); ?>" onerror="this.closest('.album-photo').style.display='none'">
                        <span class="album-photo__idx"><i class="fa-light fa-expand"></i> <?php echo ($i + 1) . '/' . count($images); ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="empty-state"><div class="empty-state__icon"><i class="fa-light fa-image-slash"></i></div><p class="empty-state__text"><?php echo __('no_images_album'); ?></p></div>
            <?php endif; ?>
            <?php Ads::zone('album_bottom'); ?>
        </main>
    </div>

    <?php Ads::zone('album_between_related'); ?>
    <?php if (!empty($related)): ?>
    <div class="album-related">
        <h2 class="section-title" style="text-transform:uppercase;"><?php echo __('related_albums'); ?></h2>
        <div class="album-grid">
            <?php foreach ($related as $rel): ?><?php echo simplyAlbumCard($rel); ?><?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php
    $_cUser = Auth::user();
    $_cReg = Setting::get('registration_enabled', '1') === '1';
    $_cEnabled = Setting::get('comments_enabled', '1') !== '0';
    $comments = $comments ?? [];
    ?>
    <?php if ($_cEnabled): ?>
    <?php Ads::zone('album_before_comments'); ?>
    <div class="comments">
        <div class="comments__header"><h3><i class="fa-solid fa-comments"></i> <?php $cc = count($comments); echo $cc !== 1 ? __('comments_count_plural', [':count' => $cc]) : __('comments_count', [':count' => $cc]); ?></h3></div>
        <?php if ($_cUser): ?>
        <form class="comment-form" action="<?php echo url('/album/' . $aid . '/comment'); ?>" method="POST" id="albCommentForm">
            <?php echo Router::csrfField(); ?>
            <?php echo SpamGuard::formFields(); ?>
            <div class="comment-form__avatar"><?php echo strtoupper(mb_substr($_cUser['username'] ?? 'U', 0, 1)); ?></div>
            <div class="comment-form__input">
                <textarea name="body" placeholder="<?php echo __('add_a_comment'); ?>" required rows="1" onfocus="this.closest('.comment-form').classList.add('focused')" oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'"></textarea>
                <?php echo Captcha::renderWidget('comment'); ?>
                <div class="comment-form__actions">
                    <button type="button" class="comment-form__cancel" onclick="var f=this.closest('.comment-form');f.classList.remove('focused');f.querySelector('textarea').value='';f.querySelector('textarea').style.height='auto'"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="comment-form__submit"><?php echo __('comment_btn'); ?></button>
                </div>
            </div>
        </form>
        <?php elseif (!$_cReg): ?>
        <form class="comment-form" action="<?php echo url('/album/' . $aid . '/comment'); ?>" method="POST">
            <?php echo Router::csrfField(); ?>
            <?php echo SpamGuard::formFields(); ?>
            <div class="comment-form__avatar"><i class="fa-solid fa-user"></i></div>
            <div class="comment-form__input">
                <input type="text" name="guest_name" placeholder="<?php echo __('your_name'); ?>" style="margin-bottom:8px;width:100%;max-width:250px;padding:6px 10px;border:1px solid var(--border,#333);border-radius:6px;background:var(--bg-surface,#1a1a2e);color:var(--text,#e0e0e0);font-size:13px;outline:none;">
                <textarea name="body" placeholder="<?php echo __('add_a_comment'); ?>" required rows="1" onfocus="this.closest('.comment-form').classList.add('focused')" oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'"></textarea>
                <?php echo Captcha::renderWidget('comment'); ?>
                <div class="comment-form__actions">
                    <button type="button" class="comment-form__cancel" onclick="var f=this.closest('.comment-form');f.classList.remove('focused');f.querySelector('textarea').value=''"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="comment-form__submit"><?php echo __('comment_btn'); ?></button>
                </div>
            </div>
        </form>
        <?php else: ?>
        <div class="comments__login"><i class="fa-solid fa-user"></i> <a href="#" onclick="authModal('login');return false;"><?php echo __('log_in'); ?></a> <?php echo __('log_in_to_comment'); ?></div>
        <?php endif; ?>
        <?php if (!empty($comments)): ?>
        <div class="comments__list" id="albCommentsList">
            <?php foreach ($comments as $i => $comment): ?>
            <div class="comment<?php echo $i >= 3 ? ' comment--hidden' : ''; ?>">
                <div class="comment__avatar"><?php echo strtoupper(mb_substr(htmlspecialchars($comment['username'] ?? 'A'), 0, 1)); ?></div>
                <div class="comment__body">
                    <div class="comment__header"><span class="comment__author"><?php echo htmlspecialchars($comment['username'] ?? __('anonymous')); ?></span><span class="comment__date"><?php echo Format::timeAgo($comment['created_at']); ?></span></div>
                    <p class="comment__text comment__text--clamped"><?php echo nl2br(htmlspecialchars($comment['body'])); ?></p>
                    <?php if (!empty($comment['replies'])): ?>
                    <div class="comment__replies">
                        <?php foreach ($comment['replies'] as $reply): ?>
                        <div class="comment comment--reply">
                            <div class="comment__avatar comment__avatar--sm"><?php echo strtoupper(mb_substr(htmlspecialchars($reply['username'] ?? 'A'), 0, 1)); ?></div>
                            <div class="comment__body"><div class="comment__header"><span class="comment__author"><?php echo htmlspecialchars($reply['username'] ?? __('anonymous')); ?></span><span class="comment__date"><?php echo Format::timeAgo($reply['created_at']); ?></span></div><p class="comment__text comment__text--clamped"><?php echo nl2br(htmlspecialchars($reply['body'])); ?></p></div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php if (count($comments) > 3): $moreCount = count($comments) - 3; ?>
        <button type="button" class="comments__view-more" id="albCommentsViewMore"><i class="fa-solid fa-chevron-down"></i> <?php echo $moreCount !== 1 ? __('view_more_comments_plural', [':count' => $moreCount]) : __('view_more_comments', [':count' => $moreCount]); ?></button>
        <?php endif; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>


<div class="alb-lb" id="albLb" aria-hidden="true">
    <button type="button" class="alb-lb__close" id="albLbClose" aria-label="Close" title="Close (Esc)"><i class="fa-solid fa-xmark"></i></button>
    <button type="button" class="alb-lb__nav alb-lb__nav--prev" id="albLbPrev" aria-label="Previous" title="Previous"><i class="fa-solid fa-chevron-left"></i></button>
    <div class="alb-lb__stage" id="albLbStage"><img id="albLbImg" src="" alt="" draggable="false"></div>
    <button type="button" class="alb-lb__nav alb-lb__nav--next" id="albLbNext" aria-label="Next" title="Next"><i class="fa-solid fa-chevron-right"></i></button>
    <div class="alb-lb__bar">
        <div class="alb-lb__counter"><span id="albLbCur">1</span> / <?php echo count($images); ?></div>
        <div class="alb-lb__group">
            <button type="button" class="alb-lb__btn" id="albLbZoomOut" title="Zoom out (-)"><i class="fa-solid fa-minus"></i></button>
            <span class="alb-lb__zoom" id="albLbZoom">100%</span>
            <button type="button" class="alb-lb__btn" id="albLbZoomIn" title="Zoom in (+)"><i class="fa-solid fa-plus"></i></button>
            <button type="button" class="alb-lb__btn" id="albLbZoomReset" title="Reset (0)"><i class="fa-solid fa-expand"></i></button>
        </div>
        <div class="alb-lb__group">
            <button type="button" class="alb-lb__btn" id="albLbPlay" title="Slideshow (Space)"><i class="fa-solid fa-play"></i></button>
            <select class="alb-lb__speed" id="albLbSpeed" title="Slideshow speed">
                <option value="2000">2s</option><option value="3000" selected>3s</option><option value="5000">5s</option><option value="8000">8s</option>
            </select>
            <?php if ($allowDownload): ?><a class="alb-lb__btn" id="albLbDl" href="#" download title="Download"><i class="fa-solid fa-download"></i></a><?php endif; ?>
        </div>
    </div>
</div>

<script>
(function(){
    var imgs = <?php echo json_encode(array_column($images, 'url'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
    var lb=document.getElementById('albLb'), img=document.getElementById('albLbImg'), stage=document.getElementById('albLbStage'),
        cur=document.getElementById('albLbCur'), zoomLbl=document.getElementById('albLbZoom'), dl=document.getElementById('albLbDl'),
        playBtn=document.getElementById('albLbPlay'), speedSel=document.getElementById('albLbSpeed');
    var idx=0, zoom=1, panX=0, panY=0, playing=false, timer=null;
    function applyT(){ img.style.transform='translate('+panX+'px,'+panY+'px) scale('+zoom+')'; img.classList.toggle('zoomed',zoom>1); if(zoomLbl)zoomLbl.textContent=Math.round(zoom*100)+'%'; }
    function resetZoom(){ zoom=1;panX=0;panY=0;applyT(); }
    function setZoom(z){ zoom=Math.min(5,Math.max(1,z)); if(zoom===1){panX=0;panY=0;} applyT(); }
    function show(i){ if(!imgs.length)return; idx=(i+imgs.length)%imgs.length; resetZoom(); img.src=imgs[idx]; cur.textContent=idx+1; if(dl)dl.href=imgs[idx]; }
    window.albLb={ open:function(i){ if(!imgs.length)return; show(i); lb.classList.add('open'); lb.setAttribute('aria-hidden','false'); document.body.style.overflow='hidden'; } };
    function stopPlay(){ playing=false; if(timer){clearInterval(timer);timer=null;} if(playBtn){playBtn.classList.remove('active');playBtn.innerHTML='<i class="fa-solid fa-play"></i>';} }
    function startPlay(){ playing=true; if(playBtn){playBtn.classList.add('active');playBtn.innerHTML='<i class="fa-solid fa-pause"></i>';} timer=setInterval(function(){ show(idx+1); }, parseInt(speedSel?speedSel.value:'3000',10)); }
    function close(){ stopPlay(); lb.classList.remove('open'); lb.setAttribute('aria-hidden','true'); document.body.style.overflow=''; img.src=''; resetZoom(); }
    document.getElementById('albLbClose').addEventListener('click', close);
    document.getElementById('albLbPrev').addEventListener('click', function(){ show(idx-1); });
    document.getElementById('albLbNext').addEventListener('click', function(){ show(idx+1); });
    document.getElementById('albLbZoomIn').addEventListener('click', function(){ setZoom(zoom+0.5); });
    document.getElementById('albLbZoomOut').addEventListener('click', function(){ setZoom(zoom-0.5); });
    document.getElementById('albLbZoomReset').addEventListener('click', resetZoom);
    if(playBtn)playBtn.addEventListener('click', function(){ playing?stopPlay():startPlay(); });
    if(speedSel)speedSel.addEventListener('change', function(){ if(playing){ stopPlay(); startPlay(); } });
    stage.addEventListener('wheel', function(e){ e.preventDefault(); setZoom(zoom+(e.deltaY<0?0.25:-0.25)); }, {passive:false});
    var dragging=false,sx=0,sy=0,ox=0,oy=0;
    img.addEventListener('mousedown', function(e){ if(zoom<=1)return; dragging=true;sx=e.clientX;sy=e.clientY;ox=panX;oy=panY;img.classList.add('grabbing');e.preventDefault(); });
    window.addEventListener('mousemove', function(e){ if(!dragging)return; panX=ox+(e.clientX-sx);panY=oy+(e.clientY-sy);applyT(); });
    window.addEventListener('mouseup', function(){ dragging=false;img.classList.remove('grabbing'); });
    lb.addEventListener('click', function(e){ if(e.target===lb||e.target===stage) close(); });
    document.addEventListener('keydown', function(e){
        if(!lb.classList.contains('open'))return;
        if(e.key==='Escape')close(); else if(e.key==='ArrowLeft')show(idx-1); else if(e.key==='ArrowRight')show(idx+1);
        else if(e.key==='+'||e.key==='=')setZoom(zoom+0.5); else if(e.key==='-')setZoom(zoom-0.5); else if(e.key==='0')resetZoom();
        else if(e.key===' '){ e.preventDefault(); playing?stopPlay():startPlay(); }
    });

    
    var fav = document.getElementById('albFavBtn');
    if(fav){ fav.addEventListener('click', function(){
        var id=fav.dataset.id, csrf=fav.dataset.csrf;
        fetch('/album/'+id+'/favorite',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:'{}'})
        .then(function(r){ if(r.status===401){ location.href='/login'; return null; } return r.json(); })
        .then(function(d){ if(!d)return; fav.dataset.fav=d.favorited?'1':'0';
            fav.querySelector('i').className=(d.favorited?'fa-solid':'fa-regular')+' fa-heart';
            document.getElementById('albFavCount').textContent=d.count; });
    }); }

    
    var cp = document.getElementById('albCopyBtn');
    if(cp){ cp.addEventListener('click', function(){
        navigator.clipboard && navigator.clipboard.writeText(location.href).then(function(){
            var ic=cp.querySelector('i'); var old=ic.className; ic.className='fa-solid fa-check'; setTimeout(function(){ic.className=old;},1200);
        });
    }); }

    
    document.querySelectorAll('.vote-btn[data-album-id]').forEach(function(btn){
        btn.addEventListener('click', function(){
            var id=btn.dataset.albumId, vote=btn.dataset.vote, csrf=btn.dataset.csrf;
            fetch('/album/'+id+'/'+vote,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:'{}'})
            .then(function(r){ if(r.status===401){ location.href='/login'; return null; } return r.json(); })
            .then(function(d){ if(!d||d.error)return;
                var counts=document.querySelectorAll('.vote-btn[data-album-id] .vote-count');
                if(counts[0])counts[0].textContent=d.likes; if(counts[1])counts[1].textContent=d.dislikes;
                var lk=document.querySelector('.vote-btn.like'), dk=document.querySelector('.vote-btn.dislike');
                if(lk)lk.classList.toggle('active', d.userVote==='like'); if(dk)dk.classList.toggle('active', d.userVote==='dislike');
            });
        });
    });

    
    var _cvm=document.getElementById('albCommentsViewMore');
    if(_cvm){ _cvm.addEventListener('click', function(){ document.querySelectorAll('#albCommentsList .comment--hidden').forEach(function(c){ c.classList.remove('comment--hidden'); }); _cvm.style.display='none'; }); }
})();
</script>


<div id="albReportModal" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.7);align-items:center;justify-content:center">
    <div style="background:var(--bg-surface, #1a1a2e);border:1px solid var(--border, #333);border-radius:12px;padding:24px;max-width:420px;width:calc(100% - 32px);position:relative">
        <button type="button" onclick="albCloseReport()" style="position:absolute;top:12px;right:12px;background:none;border:none;color:var(--text-muted, #888);cursor:pointer;padding:4px"><i class="fa-solid fa-xmark"></i></button>
        <h3 style="margin:0 0 4px;font-size:16px;color:var(--text, #e0e0e0)"><i class="fa-solid fa-flag" style="margin-right:6px"></i> <?php echo __('report_gallery'); ?></h3>
        <p style="margin:0 0 16px;font-size:13px;color:var(--text-muted, #888)"><?php echo __('report_gallery_desc'); ?></p>
        <select id="albRepReason" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:8px;background-color:var(--bg);color:var(--text);font-size:13px;outline:none;margin-bottom:12px;box-sizing:border-box">
            <option value="" disabled selected><?php echo __('report_select_reason'); ?></option>
            <?php foreach (['illegal'=>__('report_reason_illegal'),'copyright'=>__('report_reason_copyright'),'spam'=>__('report_reason_spam'),'broken'=>__('report_reason_broken'),'underage'=>__('report_reason_underage'),'other'=>__('report_reason_other')] as $rk=>$rl): ?>
            <option value="<?php echo $rk; ?>"><?php echo $rl; ?></option>
            <?php endforeach; ?>
        </select>
        <input type="email" id="albRepEmail" placeholder="<?php echo __('report_email_placeholder'); ?>" style="width:100%;padding:8px 12px;border:1px solid var(--border, #333);border-radius:8px;background:var(--bg, #0f0f23);color:var(--text, #e0e0e0);font-size:13px;outline:none;margin-bottom:12px;box-sizing:border-box">
        <textarea id="albRepDetails" rows="4" placeholder="<?php echo __('report_details_placeholder'); ?>" style="width:100%;padding:8px 12px;border:1px solid var(--border, #333);border-radius:8px;background:var(--bg, #0f0f23);color:var(--text, #e0e0e0);font-size:13px;resize:vertical;outline:none;margin-bottom:16px;box-sizing:border-box"></textarea>
        <?php echo SpamGuard::formFields(); ?>
        <div style="display:flex;justify-content:flex-end;gap:8px">
            <button type="button" onclick="albCloseReport()" style="padding:8px 16px;border:1px solid var(--border, #333);border-radius:8px;background:transparent;color:var(--text-muted, #888);font-size:13px;cursor:pointer"><?php echo __('cancel'); ?></button>
            <button type="button" id="albRepSubmit" onclick="albSubmitReport()" style="padding:8px 20px;border:none;border-radius:8px;background:var(--primary, #6366f1);color:#fff;font-size:13px;font-weight:600;cursor:pointer;opacity:.5;pointer-events:none" disabled><?php echo __('report_submit'); ?></button>
        </div>
        <div id="albRepMsg" style="display:none;margin-top:12px;padding:10px 14px;border-radius:8px;font-size:13px"></div>
    </div>
</div>
<script>
(function(){
    var modal=document.getElementById('albReportModal');
    var btn=document.getElementById('albReportBtn');
    var submitBtn=document.getElementById('albRepSubmit');
    var msgEl=document.getElementById('albRepMsg');
    var reasonSelect=document.getElementById('albRepReason');
    if(!btn||!modal)return;
    btn.addEventListener('click',function(){
        modal.style.display='flex'; msgEl.style.display='none';
        submitBtn.disabled=true; submitBtn.style.opacity='.5'; submitBtn.style.pointerEvents='none';
        reasonSelect.selectedIndex=0;
        document.getElementById('albRepEmail').value=''; document.getElementById('albRepDetails').value='';
    });
    modal.addEventListener('click',function(e){ if(e.target===modal) albCloseReport(); });
    reasonSelect.addEventListener('change',function(){ if(this.value){ submitBtn.disabled=false; submitBtn.style.opacity='1'; submitBtn.style.pointerEvents='auto'; } });
    window.albCloseReport=function(){ modal.style.display='none'; };
    window.albSubmitReport=function(){
        var reason=reasonSelect.value; if(!reason)return;
        submitBtn.disabled=true; submitBtn.textContent='...';
        var albumId=btn.getAttribute('data-album-id'); var csrf=btn.getAttribute('data-csrf');
        var details=document.getElementById('albRepDetails').value.trim();
        var email=document.getElementById('albRepEmail').value.trim();
        var payload={reason:reason,details:details,reporter_email:email,_csrf_token:csrf};
        var sgTs=modal.querySelector('input[name="_sg_ts"]'); var sgH=modal.querySelector('input[name="_sg_h"]'); var hp=modal.querySelector('input[name="website"]');
        if(sgTs)payload._sg_ts=sgTs.value; if(sgH)payload._sg_h=sgH.value; if(hp)payload.website=hp.value;
        fetch('/album/'+albumId+'/report',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify(payload)})
        .then(function(r){return r.json().then(function(d){return{ok:r.ok,data:d};});})
        .then(function(res){
            msgEl.style.display='block';
            if(res.ok){ msgEl.style.background='rgba(34,197,94,.15)'; msgEl.style.color='#22c55e'; msgEl.textContent=res.data.message||'Report submitted.'; setTimeout(albCloseReport,2000); }
            else{ msgEl.style.background='rgba(239,68,68,.15)'; msgEl.style.color='#ef4444'; msgEl.textContent=res.data.message||'An error occurred.'; submitBtn.disabled=false; submitBtn.textContent='<?php echo __('report_submit'); ?>'; submitBtn.style.opacity='1'; submitBtn.style.pointerEvents='auto'; }
        })
        .catch(function(){ msgEl.style.display='block'; msgEl.style.background='rgba(239,68,68,.15)'; msgEl.style.color='#ef4444'; msgEl.textContent='Network error. Please try again.'; submitBtn.disabled=false; submitBtn.textContent='<?php echo __('report_submit'); ?>'; submitBtn.style.opacity='1'; submitBtn.style.pointerEvents='auto'; });
    };
})();
</script>
