<?php
session_start();

// Example auth + age flags (replace with real logic)
$isLoggedIn = isset($_SESSION['user_id']);
$isOver18   = isset($_SESSION['is_over_18']) && $_SESSION['is_over_18'] == 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>NZ Infinite Art Gallery</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Tailwind CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    .filter-blur {
      filter: blur(18px);
    }
  </style>
</head>
<body class="bg-slate-50 text-slate-900">
  <!-- Header -->
  <header class="border-b border-slate-200 bg-white/80 backdrop-blur sticky top-0 z-20">
    <div class="max-w-6xl mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <div class="w-8 h-8 rounded-full bg-teal-500 flex items-center justify-center text-white font-bold">
          NZ
        </div>
        <div>
          <h1 class="text-lg font-semibold tracking-tight">Aotearoa Art Stream</h1>
          <p class="text-xs text-slate-500">Newest works from across New Zealand</p>
        </div>
      </div>
      <div class="flex items-center gap-4">
        <button id="nsfwToggle"
                class="hidden text-xs px-3 py-1 rounded-full border border-teal-500 text-teal-700 hover:bg-teal-50 transition">
          Hide NSFW
        </button>
        <?php if ($isLoggedIn): ?>
          <a href="upload.php"
             class="text-xs px-3 py-1 rounded-full bg-teal-500 text-white hover:bg-teal-600 transition">
            Upload
          </a>
          <a href="logout.php" class="text-xs text-slate-500 hover:text-slate-700">Logout</a>
        <?php else: ?>
          <a href="login.php" class="text-xs text-slate-500 hover:text-slate-700">Login</a>
          <a href="register.php"
             class="text-xs px-3 py-1 rounded-full bg-teal-500 text-white hover:bg-teal-600 transition">
            Join
          </a>
        <?php endif; ?>
      </div>
    </div>
  </header>

  <!-- Main -->
  <main class="max-w-6xl mx-auto px-4 pt-4 pb-16">
    <!-- Search + Filters -->
    <section class="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
      <div class="flex-1 flex items-center gap-2">
        <input id="searchInput"
               type="text"
               placeholder="Search by title or tags..."
               class="w-full md:w-80 px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm focus:outline-none focus:ring-2 focus:ring-teal-400 focus:border-teal-400">
        <button id="searchBtn"
                class="px-3 py-2 rounded-lg bg-teal-500 text-white text-sm hover:bg-teal-600 transition">
          Search
        </button>
      </div>
      <div class="text-xs text-slate-500">
        Showing newest works first · Scroll to travel back in time
      </div>
    </section>

    <!-- Gallery Grid -->
    <section id="gallery"
             class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
      <!-- Cards injected by JS -->
    </section>

    <!-- Loading / End -->
    <div id="loadingIndicator" class="flex justify-center mt-6 text-sm text-slate-500 hidden">
      Loading more works...
    </div>
    <div id="endIndicator" class="flex justify-center mt-6 text-sm text-slate-400 hidden">
      You’ve reached the beginning of the gallery.
    </div>
  </main>

  <script>
    const isOver18   = <?php echo $isOver18 ? 'true' : 'false'; ?>;
    const isLoggedIn = <?php echo $isLoggedIn ? 'true' : 'false'; ?>;

    let offset       = 0;
    const limit      = 24;
    let loading      = false;
    let reachedEnd   = false;
    let currentQuery = '';
    let showNSFW     = false;

    const gallery          = document.getElementById('gallery');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const endIndicator     = document.getElementById('endIndicator');
    const searchInput      = document.getElementById('searchInput');
    const searchBtn        = document.getElementById('searchBtn');
    const nsfwToggle       = document.getElementById('nsfwToggle');

    if (isOver18) {
      nsfwToggle.classList.remove('hidden');
      const stored = localStorage.getItem('nz_gallery_show_nsfw');
      showNSFW = stored === 'true';
      updateNSFWToggleLabel();
    }

    function updateNSFWToggleLabel() {
      if (!nsfwToggle) return;
      nsfwToggle.textContent = showNSFW ? 'Hide NSFW' : 'Show NSFW';
    }

    if (nsfwToggle) {
      nsfwToggle.addEventListener('click', () => {
        showNSFW = !showNSFW;
        localStorage.setItem('nz_gallery_show_nsfw', showNSFW ? 'true' : 'false');
        updateNSFWToggleLabel();
        applyNSFWBlur();
      });
    }

    function applyNSFWBlur() {
      const nsfwCards = document.querySelectorAll('[data-nsfw="1"]');
      nsfwCards.forEach(card => {
        const media = card.querySelector('img, video');
        if (!media) return;
        if (showNSFW) {
          media.classList.remove('filter-blur');
        } else {
          media.classList.add('filter-blur');
        }
      });
    }

    async function fetchPosts() {
      if (loading || reachedEnd) return;
      loading = true;
      loadingIndicator.classList.remove('hidden');

      try {
        const params = new URLSearchParams({
          offset: offset,
          limit: limit,
          q: currentQuery
        });
        const res = await fetch('api/feed.php?' + params.toString(), {
          credentials: 'include'
        });
        if (!res.ok) throw new Error('Failed to load feed');
        const data = await res.json();

        if (!Array.isArray(data) || data.length === 0) {
          if (offset === 0) {
            endIndicator.textContent = 'No works found yet.';
          }
          reachedEnd = true;
          endIndicator.classList.remove('hidden');
          return;
        }

        renderPosts(data);
        offset += data.length;
      } catch (e) {
        console.error(e);
      } finally {
        loading = false;
        loadingIndicator.classList.add('hidden');
      }
    }

    function renderPosts(posts) {
      posts.forEach(post => {
        const card = document.createElement('article');
        card.className = 'bg-white rounded-xl shadow-sm overflow-hidden border border-slate-100 flex flex-col';
        card.dataset.nsfw = post.nsfw ? '1' : '0';

        const mediaWrapper = document.createElement('a');
        mediaWrapper.href = 'post.php?id=' + encodeURIComponent(post.id);
        mediaWrapper.className = 'block relative group';

        let media;
        if (post.type === 'image') {
          media = document.createElement('img');
          media.src = post.file_url;
          media.alt = post.title || 'Artwork';
          media.className = 'w-full h-auto object-cover';
        } else {
          media = document.createElement('video');
          media.src = post.file_url;
          media.className = 'w-full h-auto object-cover';
          media.muted = true;
          media.loop = true;
          media.playsInline = true;
          media.addEventListener('mouseenter', () => media.play());
          media.addEventListener('mouseleave', () => media.pause());
        }

        if (post.nsfw && isOver18) {
          if (!showNSFW) media.classList.add('filter-blur');
        }

        if (post.nsfw && !isOver18) {
          // Should not be sent by backend, but just in case:
          return;
        }

        mediaWrapper.appendChild(media);

        if (post.nsfw && isOver18) {
          const badge = document.createElement('div');
          badge.className = 'absolute top-2 left-2 px-2 py-1 text-[10px] uppercase tracking-wide bg-red-600 text-white rounded-full';
          badge.textContent = 'NSFW / 18+';
          mediaWrapper.appendChild(badge);
        }

        const body = document.createElement('div');
        body.className = 'p-3 flex flex-col gap-2';

        const titleRow = document.createElement('div');
        titleRow.className = 'flex items-center justify-between gap-2';

        const title = document.createElement('h2');
        title.className = 'text-sm font-semibold text-slate-900 line-clamp-1';
        title.textContent = post.title || 'Untitled';

        const meta = document.createElement('div');
        meta.className = 'text-[11px] text-slate-500';
        meta.textContent = post.username ? `by ${post.username}` : '';

        titleRow.appendChild(title);
        titleRow.appendChild(meta);

        const tagsRow = document.createElement('div');
        tagsRow.className = 'flex flex-wrap gap-1';
        if (Array.isArray(post.tags)) {
          post.tags.slice(0, 5).forEach(tag => {
            const tagEl = document.createElement('span');
            tagEl.className = 'text-[10px] px-2 py-0.5 rounded-full bg-teal-50 text-teal-700 border border-teal-100';
            tagEl.textContent = '#' + tag;
            tagsRow.appendChild(tagEl);
          });
        }

        const footerRow = document.createElement('div');
        footerRow.className = 'flex items-center justify-between text-[11px] text-slate-400';

        const created = document.createElement('span');
        created.textContent = post.created_human || '';

        const stats = document.createElement('span');
        stats.textContent = (post.rating_count || 0) + ' votes · ' + (post.comment_count || 0) + ' comments';

        footerRow.appendChild(created);
        footerRow.appendChild(stats);

        body.appendChild(titleRow);
        if (tagsRow.childNodes.length > 0) body.appendChild(tagsRow);
        body.appendChild(footerRow);

        card.appendChild(mediaWrapper);
        card.appendChild(body);

        gallery.appendChild(card);
      });
    }

    function resetAndSearch() {
      offset = 0;
      reachedEnd = false;
      gallery.innerHTML = '';
      endIndicator.classList.add('hidden');
      fetchPosts();
    }

    searchBtn.addEventListener('click', () => {
      currentQuery = searchInput.value.trim();
      resetAndSearch();
    });

    searchInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        currentQuery = searchInput.value.trim();
        resetAndSearch();
      }
    });

    window.addEventListener('scroll', () => {
      if (loading || reachedEnd) return;
      const scrollPos = window.innerHeight + window.scrollY;
      const threshold = document.body.offsetHeight - 800;
      if (scrollPos >= threshold) {
        fetchPosts();
      }
    });

    // Initial load
    fetchPosts();
  </script>
</body>
</html>