---
import BaseLayout from '../layouts/BaseLayout.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
import MiniKnowledgeGraph from '../components/MiniKnowledgeGraph.astro';
import { getCollection } from 'astro:content';

// Get all posts
const allPosts = await getCollection('posts').catch(error => {
  console.error('Error fetching posts collection:', error);
  return [];
});

// Try blog collection if posts doesn't exist
const blogPosts = allPosts.length === 0 ? await getCollection('blog').catch(() => []) : [];
const combinedPosts = [...allPosts, ...blogPosts];

// Use the first post as a test post
const testPost = combinedPosts.length > 0 ? combinedPosts[0] : {
  slug: 'test-post',
  data: {
    title: 'Test Post',
    tags: ['test', 'graph'],
    category: 'Test'
  }
};

// Create related posts - use the next 3 posts in the collection or create test posts
const relatedPosts = combinedPosts.length > 1 
  ? combinedPosts.slice(1, 4) 
  : [
    {
      slug: 'related-1',
      data: {
        title: 'Related Post 1',
        tags: ['test', 'graph'],
        category: 'Test'
      }
    },
    {
      slug: 'related-2',
      data: {
        title: 'Related Post 2',
        tags: ['test'],
        category: 'Test'
      }
    }
  ];
---

<BaseLayout title="Test MiniKnowledgeGraph">
  <Header slot="header" />
  
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-6">MiniKnowledgeGraph Test Page</h1>
    
    <div class="bg-slate-800 rounded-lg p-6 mb-8">
      <p class="mb-4">This is a test page to ensure the MiniKnowledgeGraph component is working properly.</p>
      
      <div class="border border-slate-700 rounded-lg p-4 mb-6">
        <h2 class="text-xl font-bold mb-4">Test Post Details:</h2>
        <p><strong>Title:</strong> {testPost.data.title}</p>
        <p><strong>Slug:</strong> {testPost.slug}</p>
        <p><strong>Tags:</strong> {testPost.data.tags?.join(', ') || 'None'}</p>
        <p><strong>Category:</strong> {testPost.data.category || 'None'}</p>
        <p><strong>Related Posts:</strong> {relatedPosts.length}</p>
      </div>
      
      <div class="mini-knowledge-graph-area">
        <h2 class="text-xl font-bold mb-4">MiniKnowledgeGraph Component:</h2>
        
        <div class="mini-knowledge-graph-wrapper">
          <MiniKnowledgeGraph
            currentPost={testPost}
            relatedPosts={relatedPosts}
            height="300px"
            title="Test Graph"
          />
        </div>
        
        <!-- Debug Information Display -->
        <div class="debug-info mt-4 p-4 bg-gray-900 rounded-lg">
          <h3 class="text-lg font-bold mb-2">Debug Info</h3>
          <div id="debug-container">Loading debug info...</div>
        </div>
      </div>
    </div>
  </div>
  
  <Footer slot="footer" />
</BaseLayout>

<style>
  .mini-knowledge-graph-area {
    margin-top: 2rem;
  }
  
  .mini-knowledge-graph-wrapper {
    width: 100%;
    border-radius: 10px;
    overflow: hidden;
    display: block !important;
    position: relative;
    min-height: 300px;
    height: 300px;
    background: var(--card-bg, #1e293b);
    border: 1px solid var(--card-border, #334155);
    visibility: visible !important;
  }
  
  .debug-info {
    font-family: monospace;
    font-size: 0.8rem;
    line-height: 1.4;
  }
</style>

<script>
  // Debug utility for testing the knowledge graph
  document.addEventListener('DOMContentLoaded', function() {
    setTimeout(checkGraphStatus, 500);
    
    // Also check after window load
    window.addEventListener('load', function() {
      setTimeout(checkGraphStatus, 1000);
    });
  });
  
  function checkGraphStatus() {
    const debugContainer = document.getElementById('debug-container');
    if (!debugContainer) return;
    
    // Get container info
    const container = document.querySelector('.mini-knowledge-graph-wrapper');
    const cyContainer = document.getElementById('mini-cy');
    
    // Check for cytoscape instance
    const cyInstance = window.miniCy;
    
    let html = '<ul>';
    
    // Container dimensions
    if (container) {
      html += `<li>Container: ${container.offsetWidth}x${container.offsetHeight}px</li>`;
      html += `<li>Display: ${getComputedStyle(container).display}</li>`;
      html += `<li>Visibility: ${getComputedStyle(container).visibility}</li>`;
    } else {
      html += '<li>Container: Not found</li>';
    }
    
    // Cytoscape container
    if (cyContainer) {
      html += `<li>Cy Container: ${cyContainer.offsetWidth}x${cyContainer.offsetHeight}px</li>`;
    } else {
      html += '<li>Cy Container: Not found</li>';
    }
    
    // Cytoscape instance
    html += `<li>Cytoscape object: ${typeof cytoscape !== 'undefined' ? 'Available' : 'Not available'}</li>`;
    html += `<li>Cytoscape instance: ${cyInstance ? 'Initialized' : 'Not initialized'}</li>`;
    
    // If instance exists, get more details
    if (cyInstance) {
      html += `<li>Nodes: ${cyInstance.nodes().length}</li>`;
      html += `<li>Edges: ${cyInstance.edges().length}</li>`;
    }
    
    html += '</ul>';
    
    // Add refresh button
    html += '<button id="refresh-debug" class="mt-2 px-3 py-1 bg-blue-700 text-white rounded hover:bg-blue-600">' + 
            'Refresh Debug Info</button>';
    
    debugContainer.innerHTML = html;
    
    // Add event listener to refresh button
    document.getElementById('refresh-debug')?.addEventListener('click', checkGraphStatus);
  }
</script> 