---
import Layout from '../layouts/Layout.astro';

const WIKIJS_BASE_URL = 'https://wiki.teletype.hu';
const WIKIJS_TOKEN = import.meta.env.WEBAPP_WIKIJS_TOKEN;

interface WikiPage {
  id: number;
  path: string;
  title: string;
  description: string;
  content: string;
  render?: string;
  updatedAt: string;
  createdAt: string;
  locale: string;
}

let blogPages: WikiPage[] = [];
let error: string | null = null;
let permissionWarning = false;

try {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  if (WIKIJS_TOKEN) {
    headers['Authorization'] = `Bearer ${WIKIJS_TOKEN}`;
  }

  // 1. Get the list of pages with the "blog" tag
  const LIST_QUERY = `
    {
      pages {
        list(orderBy: CREATED, orderByDirection: DESC, tags: ["blog"]) {
          id
          path
          title
          description
          updatedAt
          createdAt
          locale
        }
      }
    }
  `;

  const listResponse = await fetch(`${WIKIJS_BASE_URL}/graphql`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query: LIST_QUERY }),
  });

  const listJson = await listResponse.json();
  
  if (listJson.errors) {
    throw new Error(`GraphQL error: ${listJson.errors.map((e: any) => e.message).join(', ')}`);
  }
  
  const pages = listJson?.data?.pages?.list ?? [];

  // 2. Fetch content for each page (WikiJS list doesn't include content)
  // To keep it efficient, we only fetch the first few blog posts' content if needed, 
  // or we can fetch all if the list is short.
  const pagesWithContent = await Promise.all(pages.map(async (p: any) => {
    try {
      const CONTENT_QUERY = `
        {
          pages {
            single(id: ${p.id}) {
              content
            }
          }
        }
      `;
      const contentRes = await fetch(`${WIKIJS_BASE_URL}/graphql`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ query: CONTENT_QUERY }),
      });
      const contentJson = await contentRes.json();
      return {
        ...p,
        content: contentJson?.data?.pages?.single?.content ?? ''
      };
    } catch (e) {
      console.error(`Failed to fetch content for page ${p.id}`, e);
      return { ...p, content: '' };
    }
  }));

  blogPages = pagesWithContent.map((p: any) => ({
    id: p.id,
    path: p.path,
    title: p.title || p.path,
    description: p.description ?? '',
    content: p.content ?? '',
    updatedAt: p.updatedAt,
    createdAt: p.createdAt,
    locale: p.locale,
  }));

} catch (e: any) {
  console.error('Failed to fetch WikiJS data:', e);
  error = `Failed to fetch wiki data: ${e.message}`;
}

function timeAgo(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffMins < 1) return 'just now';
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  if (diffDays < 30) return `${diffDays}d ago`;
  return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}

function getPermalink(path: string): string {
  const slug = path.startsWith('blog/') ? path.replace('blog/', '') : path;
  return `/blog/${slug}`;
}

function getCleanPreview(content: string): string {
  if (!content) return '';
  return content
    .replace(/[#*`_\[\]()]/g, '')
    .trim()
    .slice(0, 300) + '...';
}
---

<Layout>
  <div class="blog-container">
    <header class="blog-header">
      <div class="blog-header-decor">
        <div class="hero-decor-blob -top-24 -left-24 h-96 w-96 bg-purple-600"></div>
        <div class="hero-decor-blob -bottom-24 -right-24 h-96 w-96 bg-blue-600"></div>
      </div>
      
      <div class="hero-container">
        <div class="hero-badge">
          Community Stories
        </div>
        <h1 class="hero-title">
          Developer <span class="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-400">Blog</span>
        </h1>
        <p class="hero-subtitle mb-10">
          News, updates, and behind-the-scenes stories from the Teletype Games community.
        </p>
      </div>
    </header>

    <main class="blog-main">

      {error && (
        <div class="error-banner" role="alert">
          <span class="text-2xl">⚠️</span>
          <div>
            <h3 class="error-banner-title">Failed to connect to Wiki</h3>
            <p class="error-banner-desc">{error}</p>
          </div>
        </div>
      )}

      {!error && blogPages.length === 0 && (
        <div class="empty-state">
          <div class="empty-state-icon">📭</div>
          <h2 class="empty-state-title">No blog posts found</h2>
          <p class="empty-state-desc">We haven't published any blog posts yet. Check back soon!</p>
        </div>
      )}

      {!error && blogPages.length > 0 && (
        <div class="blog-posts-list">
          {blogPages.map((page) => {
            const isNew = (new Date().getTime() - new Date(page.createdAt).getTime()) < 7 * 24 * 60 * 60 * 1000;
            const permalink = getPermalink(page.path);

            return (
              <article class="blog-post-card">
                <div class="blog-post-content">
                  <div class="blog-post-meta">
                    <div class="flex items-center gap-4">
                      <div class="blog-post-timestamp">
                        {isNew && (
                          <span class="new-post-badge">
                            <span class="new-post-dot"></span>
                            New Post
                          </span>
                        )}
                        <span>{timeAgo(page.createdAt)}</span>
                      </div>
                    </div>
                  </div>

                  <h2 class="blog-post-title">
                    <a href={permalink} class="hover:text-indigo-600 transition-colors">
                      {page.title}
                    </a>
                  </h2>
                  
                  <div class="blog-post-preview">
                    {page.description && (
                      <p class="blog-post-description">
                        {page.description}
                      </p>
                    )}
                    
                    {page.content && (
                      <p class="blog-post-body">
                        {getCleanPreview(page.content)}
                      </p>
                    )}
                  </div>
                  
                  <div class="mt-6">
                    <a href={permalink} class="read-more-btn">
                      Read more
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z" clip-rule="evenodd" />
                      </svg>
                    </a>
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      )}
    </main>
  </div>
</Layout>

<style>
  .blog-container {
    @apply bg-gray-50 min-h-screen pb-20;
  }
  .blog-header {
    @apply relative overflow-hidden py-24 text-white text-center bg-indigo-900;
  }
  .blog-header-decor {
    @apply absolute inset-0 opacity-30;
  }
  .blog-main {
    @apply max-w-5xl mx-auto px-4 md:px-8 -mt-12 relative z-10;
  }
  
  /* Banners */
  .banner-base {
    @apply max-w-7xl mx-auto border-l-4 p-6 rounded-r-xl shadow-lg mb-12 flex items-start gap-4;
  }
  .error-banner { @apply banner-base bg-red-50 border-red-500; }
  .error-banner-title { @apply text-red-800 font-bold text-lg; }
  .error-banner-desc { @apply text-red-700 mt-1; }
  
  /* Empty State */
  .empty-state {
    @apply max-w-7xl mx-auto bg-white rounded-2xl shadow-xl p-12 text-center border border-gray-100;
  }
  .empty-state-icon { @apply text-6xl mb-4; }
  .empty-state-title { @apply text-2xl font-bold text-gray-900 mb-2; }
  .empty-state-desc { @apply text-gray-500 max-w-md mx-auto; }

  /* Posts */
  .blog-posts-list {
    @apply flex flex-col gap-12;
  }
  .blog-post-card {
    @apply bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden;
  }
  .blog-post-content {
    @apply p-6 md:p-10;
  }
  .blog-post-meta {
    @apply flex items-center justify-between mb-4;
  }
  .blog-post-timestamp {
    @apply flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-gray-400;
  }
  .new-post-badge {
    @apply flex items-center gap-1 text-green-600 bg-green-50 px-2 py-0.5 rounded-full border border-green-100;
  }
  .new-post-dot {
    @apply w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse;
  }
  .blog-post-title {
    @apply text-2xl md:text-3xl font-black text-gray-900 mb-4 leading-tight;
  }
  
  .blog-post-preview {
    @apply relative overflow-hidden;
    max-height: 8rem; /* kb 4-5 sor */
  }

  .blog-post-preview::after {
    content: "";
    @apply absolute bottom-0 left-0 w-full h-16 bg-gradient-to-b from-transparent to-white pointer-events-none;
  }

  .blog-post-description {
    @apply text-lg text-gray-800 font-bold mb-2 leading-relaxed;
  }

  .blog-post-body {
    @apply text-base text-gray-500 font-medium leading-relaxed;
  }
  
  .read-more-btn {
    @apply inline-flex items-center text-indigo-600 font-bold hover:text-indigo-800 transition-colors;
  }
</style>

<style is:global>
  .wiki-content h1 { @apply text-2xl font-bold mt-8 mb-4 text-gray-900; }
  .wiki-content h2 { @apply text-xl font-bold mt-6 mb-3 text-gray-800; }
  .wiki-content h3 { @apply text-lg font-bold mt-4 mb-2 text-gray-800; }
  .wiki-content p { @apply mb-4 text-gray-700 leading-relaxed; }
  .wiki-content ul { @apply list-disc ml-6 mb-4 text-gray-700; }
  .wiki-content ol { @apply list-decimal ml-6 mb-4 text-gray-700; }
  .wiki-content li { @apply mb-1; }
  .wiki-content a { @apply text-indigo-600 hover:underline; }
  .wiki-content img { @apply max-w-full h-auto rounded-lg my-6 shadow-md; }
  .wiki-content pre { @apply bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-6 font-mono text-sm; }
  .wiki-content code { @apply bg-gray-100 text-pink-600 px-1 rounded font-mono text-sm; }
  .wiki-content blockquote { @apply border-l-4 border-gray-300 pl-4 italic my-6 text-gray-600; }
  .wiki-content table { @apply w-full border-collapse my-6; }
  .wiki-content th, .wiki-content td { @apply border border-gray-200 p-3 text-left; }
  .wiki-content th { @apply bg-gray-50 font-bold; }
</style>
