---
// MiniGraph.astro - A standalone mini knowledge graph component
// This component is designed to work independently from the blog structure

// Define props interface
interface Props {
  slug: string;        // Current post slug
  title: string;       // Current post title
  tags?: string[];     // Current post tags
  category?: string;   // Current post category
}

// Extract props with defaults
const {
  slug,
  title,
  tags = [],
  category = "Uncategorized"
} = Astro.props;

// Generate unique ID for the graph container
const graphId = `graph-${Math.random().toString(36).substring(2, 8)}`;

// Prepare simple graph data for just the post and its tags
const nodes = [
  // Current post node
  {
    id: slug,
    label: title,
    type: "post"
  },
  // Tag nodes
  ...tags.map(tag => ({
    id: `tag-${tag}`,
    label: tag,
    type: "tag"
  }))
];

// Create edges connecting post to tags
const edges = tags.map(tag => ({
  source: slug,
  target: `tag-${tag}`,
  type: "post-tag"
}));

// Prepare graph data object
const graphData = { nodes, edges };
---

<!-- Super simple HTML structure -->
<div class="knowledge-graph-wrapper">
  <h4 class="graph-title">Post Connections</h4>
  <div id={graphId} class="mini-graph-container"></div>
</div>

<!-- Minimal CSS -->
<style>
  .knowledge-graph-wrapper {
    width: 100%;
    margin-bottom: 1rem;
  }

  .graph-title {
    font-size: 1rem;
    margin-bottom: 0.5rem;
    color: var(--text-primary, #e2e8f0);
  }

  .mini-graph-container {
    width: 100%;
    height: 200px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid var(--card-border, rgba(56, 189, 248, 0.2));
    background: rgba(15, 23, 42, 0.2);
  }
</style>

<!-- Standalone initialization script -->
<script define:vars={{ graphId, graphData }}>
  // Wait for page to fully load
  window.addEventListener('load', function() {
    // Retry initialization multiple times in case Cytoscape or the DOM isn't ready yet
    let retries = 0;
    const maxRetries = 5;
    const retryInterval = 500; // ms

    function initGraph() {
      // Ensure Cytoscape is loaded
      if (typeof cytoscape === 'undefined') {
        console.warn(`[MiniGraph] Cytoscape not loaded, retry ${retries+1}/${maxRetries}...`);
        if (retries < maxRetries) {
          retries++;
          setTimeout(initGraph, retryInterval);
        } else {
          console.error("[MiniGraph] Cytoscape library not available after multiple attempts.");
          const container = document.getElementById(graphId);
          if (container) {
            container.innerHTML = '<div style="padding:10px;color:#a0aec0;text-align:center;">Graph library not loaded</div>';
          }
        }
        return;
      }

      // Verify container exists
      const container = document.getElementById(graphId);
      if (!container) {
        console.error(`[MiniGraph] Container #${graphId} not found.`);
        return;
      }

      try {
        // Check if we have any nodes
        if (graphData.nodes.length === 0) {
          container.innerHTML = '<div style="padding:10px;color:#a0aec0;text-align:center;">No connections</div>';
          return;
        }

        // Initialize Cytoscape
        const cy = cytoscape({
          container,
          elements: [
            ...graphData.nodes.map(node => ({
              data: {
                id: node.id,
                label: node.label,
                type: node.type
              }
            })),
            ...graphData.edges.map((edge, index) => ({
              data: {
                id: `e${index}`,
                source: edge.source,
                target: edge.target,
                type: edge.type
              }
            }))
          ],
          style: [
            // Base node style
            {
              selector: 'node',
              style: {
                'background-color': '#3B82F6',
                'label': 'data(label)',
                'width': 20,
                'height': 20,
                'font-size': '8px',
                'color': '#E2E8F0',
                'text-valign': 'bottom',
                'text-halign': 'center',
                'text-margin-y': 5,
                'text-wrap': 'ellipsis',
                'text-max-width': '60px'
              }
            },
            // Post node style
            {
              selector: 'node[type="post"]',
              style: {
                'background-color': '#06B6D4',
                'width': 30,
                'height': 30,
                'font-size': '9px',
                'text-max-width': '80px'
              }
            },
            // Tag node style
            {
              selector: 'node[type="tag"]',
              style: {
                'background-color': '#10B981',
                'shape': 'diamond',
                'width': 18,
                'height': 18
              }
            },
            // Edge style
            {
              selector: 'edge',
              style: {
                'width': 1,
                'line-color': 'rgba(16, 185, 129, 0.6)',
                'line-style': 'dashed',
                'curve-style': 'bezier',
                'opacity': 0.7
              }
            }
          ],
          // Simple layout for small space
          layout: {
            name: 'concentric',
            concentric: function(node) {
              return node.data('type') === 'post' ? 10 : 1;
            },
            levelWidth: function() { return 1; },
            minNodeSpacing: 50,
            animate: false
          }
        });

        // Make nodes clickable
        cy.on('tap', 'node[type="tag"]', function(evt) {
          const node = evt.target;
          const tagName = node.data('label');
          window.location.href = `/tag/${tagName}`;
        });

        // Fit graph to container
        cy.fit(undefined, 20);

      } catch (error) {
        console.error('[MiniGraph] Error initializing graph:', error);
        container.innerHTML = '<div style="padding:10px;color:#a0aec0;text-align:center;">Error loading graph</div>';
      }
    }

    // Start initialization attempt
    initGraph();
  });
</script>