<?php
$posts = $posts ?? [];
$pagination = $pagination ?? ['current' => 1, 'perPage' => 9, 'hasMore' => false, 'hasPrev' => false];

$currentPage = $pagination['current'];
$hasMore = $pagination['hasMore'] ?? false;
$hasPrev = $pagination['hasPrev'] ?? false;

function foryou_format_datetime($timestamp)
{
    if (empty($timestamp)) {
        return 'Unknown';
    }
    if ($timestamp > 1000000000000) {
        $timestamp = (int)round($timestamp / 1000);
    }
    return date('M j, Y g:i A', $timestamp);
}

function foryou_relative_time($timestamp)
{
    if (empty($timestamp)) {
        return '—';
    }
    if ($timestamp > 1000000000000) {
        $timestamp = (int)round($timestamp / 1000);
    }
    $now = time();
    $diff = max(0, $now - $timestamp);
    if ($diff < 60) {
        return $diff . 's ago';
    }
    if ($diff < 3600) {
        return floor($diff / 60) . 'm ago';
    }
    if ($diff < 86400) {
        return floor($diff / 3600) . 'h ago';
    }
    if ($diff < 604800) {
        return floor($diff / 86400) . 'd ago';
    }
    return date('M j, Y', $timestamp);
}
?>

<main class="main-wrapper">
  <div class="main-content foryou-feed">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between mb-4">
      <div>
        <h2 class="page-title mb-1">For You Feed</h2>
        <p class="text-muted mb-0">Curated posts from the community • Page <?php echo $currentPage; ?></p>
      </div>
      <div class="mt-3 mt-md-0 text-md-end d-none">
       
      </div>
    </div>

    <div id="foryou-feed" class="row g-4">
      <?php if (!empty($posts)): ?>
        <?php $this->load->view('foryou/_posts', ['posts' => $posts, 'context' => 'feed']); ?>
      <?php endif; ?>
    </div>

    <div id="foryou-loader" class="text-center py-4 <?php echo $hasMore ? '' : 'd-none'; ?>">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>

    <div id="foryou-empty" class="card border-0 shadow-sm <?php echo empty($posts) ? '' : 'd-none'; ?>">
      <div class="card-body text-center py-5">
        <img src="<?php echo base_url('assets/images/empty-state.svg'); ?>" alt="No posts" class="empty-illustration mb-3">
        <h5>No posts available yet</h5>
        <p class="text-muted">Once creators start uploading content, you will see their posts here.</p>
      </div>
    </div>
  </div>
</main>

<style>
  .foryou-feed {
    padding: 1.5rem;
  }
  .page-title {
    font-weight: 600;
  }
  .empty-illustration {
    max-width: 160px;
    opacity: 0.8;
  }
  .post-card {
    border-radius: 18px;
    overflow: hidden;
    background: #ffffff;
  }
  .post-media {
    position: relative;
    background: #111827;
  }
  .post-video {
    width: 100%;
    max-height: 320px;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    object-fit: cover;
  }
  .badge-overlay {
    position: absolute;
    top: 12px;
    left: 12px;
    border-radius: 999px;
    padding: 0.35rem 0.75rem;
    backdrop-filter: blur(6px);
  }
  .author-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid rgba(79, 70, 229, 0.2);
  }
  .author-avatar.placeholder {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: rgba(79, 70, 229, 0.1);
    color: #4f46e5;
    font-size: 1.25rem;
  }
  .song-chip {
    display: inline-flex;
    align-items: center;
    padding: 0.35rem 0.75rem;
    border-radius: 999px;
    background: rgba(79, 70, 229, 0.08);
    color: #4f46e5;
    font-size: 0.85rem;
  }
  .post-description {
    font-size: 0.95rem;
    line-height: 1.5;
  }
  .hashtags .badge {
    font-weight: 500;
    margin-right: 0.35rem;
  }
  .meta-grid {
    border: 1px solid rgba(0,0,0,0.05);
    border-radius: 12px;
    padding: 0.75rem;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.5rem 1rem;
    background: #f9fafb;
  }
  .meta-label {
    display: block;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: #6b7280;
  }
  .meta-value {
    font-weight: 500;
    color: #111827;
  }
  .foryou-post-card.fade-out {
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  .bg-primary-soft { background: rgba(79, 70, 229, 0.12) !important; }
  .bg-success-soft { background: rgba(16, 185, 129, 0.12) !important; }
  .bg-warning-soft { background: rgba(251, 191, 36, 0.20) !important; }
  .bg-danger-soft { background: rgba(239, 68, 68, 0.15) !important; }
  .bg-secondary-soft { background: rgba(107, 114, 128, 0.15) !important; }
</style>

<script>
  (function() {
    const feedEl = document.getElementById('foryou-feed');
    const loaderEl = document.getElementById('foryou-loader');
    const emptyEl = document.getElementById('foryou-empty');
    if (!feedEl || !loaderEl || !emptyEl) return;

    let currentPage = <?php echo (int)$currentPage; ?>;
    const perPage = <?php echo (int)$pagination['perPage']; ?>;
    let hasMore = <?php echo $hasMore ? 'true' : 'false'; ?>;
    let isLoading = false;

    const toggleEmptyState = () => {
      const hasCards = !!feedEl.querySelector('.foryou-post-card');
      if (hasCards) {
        emptyEl.classList.add('d-none');
      } else {
        emptyEl.classList.remove('d-none');
      }
    };

    const loadMore = () => {
      if (isLoading || !hasMore) return;
      isLoading = true;
      loaderEl.classList.remove('d-none');

      fetch('<?php echo base_url('foryou/loadMore'); ?>?page=' + (currentPage + 1), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
        .then(res => res.json())
        .then(data => {
          if (data && data.success) {
            if (data.html) {
              const temp = document.createElement('div');
              temp.innerHTML = data.html;
              const cards = temp.querySelectorAll('.foryou-post-card');
              cards.forEach(card => feedEl.appendChild(card));
              attachFeedHandlers();
              currentPage = data.page;
              hasMore = data.hasMore;
              toggleEmptyState();
            } else {
              hasMore = false;
            }
          } else {
            hasMore = false;
          }
        })
        .catch(() => { hasMore = false; })
        .finally(() => {
          loaderEl.classList.toggle('d-none', !hasMore);
          isLoading = false;
        });
    };

    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          loadMore();
        }
      });
    }, { rootMargin: '200px' });

    observer.observe(loaderEl);

    const attachFeedHandlers = () => {
      document.querySelectorAll('.btn-appropriate-post').forEach(btn => {
        if (btn.dataset.bound === 'true') return;
        btn.dataset.bound = 'true';
        btn.addEventListener('click', () => {
          const postId = btn.getAttribute('data-post-id');
          if (!postId || btn.disabled) return;

          btn.disabled = true;
          btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Updating...';

          fetch('<?php echo base_url('foryou/markAppropriate'); ?>', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              'X-Requested-With': 'XMLHttpRequest'
            },
            body: 'postId=' + encodeURIComponent(postId)
          })
            .then(res => res.json())
            .then(data => {
              if (!data || !data.success) {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Remove from For You page';
                return;
              }

              btn.classList.remove('btn-outline-primary');
              btn.classList.add('btn-success');
              btn.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Removed from For You page';
            })
            .catch(() => {
              btn.disabled = false;
              btn.innerHTML = '<i class="bi bi-check-circle me-1"></i>Remove from For You page';
            });
        });
      });
    };

    attachFeedHandlers();
    toggleEmptyState();

    const mutationObserver = new MutationObserver(() => {
      attachFeedHandlers();
      toggleEmptyState();
    });
    mutationObserver.observe(feedEl, { childList: true });
  })();
</script>

