---
// 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
  allPosts?: any[];    // All posts for related content in fullscreen mode
  content?: string;    // Current post content for fullscreen view
}

// Extract props with defaults
const {
  slug,
  title,
  tags = [],
  category = "Uncategorized",
  allPosts = [],
  content = "" // Default to empty string if content is not passed
} = Astro.props;

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

// Prepare graph data for current post and its tags
const nodes = [
  // Current post node
  {
    id: slug,
    label: title,
    type: "post",
    category: category,
    tags: tags,
    content: content, // Use the content prop
    url: `/posts/${slug}`
  },
  // Tag nodes
  ...tags.map(tag => ({
    id: `tag-${tag}`,
    label: tag,
    type: "tag",
    url: `/tag/${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 };

// Generate predefined colors for categories (copied from KnowledgeGraph.astro)
const predefinedColors = {
  'Kubernetes': '#326CE5', 'Docker': '#2496ED', 'DevOps': '#FF6F61',
  'Homelab': '#06B6D4', 'Networking': '#9333EA', 'Infrastructure': '#10B981',
  'Automation': '#F59E0B', 'Security': '#EF4444', 'Monitoring': '#6366F1',
  'Storage': '#8B5CF6', 'Obsidian': '#7C3AED', 'Tutorial': '#3B82F6',
  'Uncategorized': '#A0AEC0'
};

// Generate colors based on node types
const nodeTypeColors = {
  'post': '#3B82F6', // Blue for posts
  'tag': '#10B981'   // Green for tags
};
---

<!-- Enhanced mini graph component with fullscreen capability -->
<div class="knowledge-graph-wrapper">
  <h4 class="graph-title">Post Connections</h4>
  <div id={graphId} class="mini-graph-container"></div>

  <!-- Fullscreen Toggle Button -->
  <button id={`${graphId}-fullscreen-toggle`} class="fullscreen-toggle" aria-label="Toggle fullscreen">
    <svg id={`${graphId}-fullscreen-enter-icon`} xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <polyline points="15 3 21 3 21 9"></polyline>
      <polyline points="9 21 3 21 3 15"></polyline>
      <line x1="21" y1="3" x2="14" y2="10"></line>
      <line x1="3" y1="21" x2="10" y2="14"></line>
    </svg>
    <svg id={`${graphId}-fullscreen-exit-icon`} class="hidden" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <polyline points="4 14 10 14 10 20"></polyline>
      <polyline points="20 10 14 10 14 4"></polyline>
      <line x1="14" y1="10" x2="21" y2="3"></line>
      <line x1="3" y1="21" x2="10" y2="14"></line>
    </svg>
  </button>

  <!-- Full Post Content Panel (for fullscreen mode) -->
  <div id={`${graphId}-full-post-content`} class="full-post-content">
    <div class="full-post-header">
      <h2 id={`${graphId}-full-post-title`} class="full-post-title">Post Title</h2>
      <button id={`${graphId}-close-full-post`} class="close-button" aria-label="Close post content">
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
      </button>
    </div>

    <div class="full-post-metadata">
      <div class="metadata-row">
        <span class="metadata-label">Category:</span>
        <div id={`${graphId}-full-post-category`} class="full-post-category"></div>
      </div>
      <div class="metadata-row">
        <span class="metadata-label">Tags:</span>
        <div id={`${graphId}-full-post-tags`} class="full-post-tags"></div>
      </div>
    </div>

    <div id={`${graphId}-full-post-container`} class="full-post-container">
      <div class="full-post-placeholder">
        <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
          <polyline points="14 2 14 8 20 8"></polyline>
          <line x1="16" y1="13" x2="8" y2="13"></line>
          <line x1="16" y1="17" x2="8" y2="17"></line>
          <polyline points="10 9 9 9 8 9"></polyline>
        </svg>
        <p>Select a post node to view its content</p>
      </div>
    </div>

    <div class="full-post-footer">
      <a href="#" id={`${graphId}-full-post-link`} class="full-post-link" target="_self" rel="noopener noreferrer">
        Read Full Article
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
          <polyline points="15 3 21 3 21 9"></polyline>
          <line x1="10" y1="14" x2="21" y2="3"></line>
        </svg>
      </a>
    </div>
  </div>
</div>

<!-- Enhanced CSS for MiniGraph with fullscreen support -->
<style>
  .knowledge-graph-wrapper {
    position: relative;
    width: 100%;
    margin-bottom: 1rem;
    transition: all 0.5s cubic-bezier(0.19, 1, 0.22, 1);
  }

  /* Fullscreen mode styles */
  .knowledge-graph-wrapper.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    max-height: 100vh;
    z-index: 9999;
    margin: 0;
    padding: 0;
    background: var(--bg-primary, #0f1219);
    backdrop-filter: blur(10px);
    display: flex;
    border-radius: 0;
    overflow: hidden;
  }

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

  .knowledge-graph-wrapper.fullscreen .graph-title {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 5;
    font-size: 1.2rem;
    margin: 0;
  }

  .mini-graph-container {
    width: 100%;
    height: 200px; /* Default height */
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid var(--card-border, rgba(56, 189, 248, 0.2));
    background: rgba(15, 23, 42, 0.2);
    transition: all 0.3s ease;
  }

  /* Adjust graph container in fullscreen mode */
  .knowledge-graph-wrapper.fullscreen .mini-graph-container {
    position: relative;
    width: 60%;
    height: 100%;
    border-radius: 0;
    margin: 0;
    border: none;
    border-right: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1));
  }

  /* Fullscreen Toggle Button */
  .fullscreen-toggle {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 24px;
    height: 24px;
    border-radius: 4px;
    background: rgba(30, 41, 59, 0.7);
    border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1));
    color: var(--text-primary, #e2e8f0);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 6;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    opacity: 0.5;
  }

  .mini-graph-container:hover .fullscreen-toggle,
  .fullscreen-toggle:hover {
    opacity: 1;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  .knowledge-graph-wrapper.fullscreen .fullscreen-toggle {
    top: 20px;
    right: 20px;
    width: 32px;
    height: 32px;
    opacity: 1;
  }

  /* Hide one of the fullscreen icons */
  .hidden {
    display: none;
  }

  /* Full Post Content Panel */
  .full-post-content {
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 100%;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.19, 1, 0.22, 1);
    background: var(--bg-secondary, #161a24);
    border-radius: 12px;
    opacity: 0;
    z-index: 4;
    border: 1px solid var(--card-border, rgba(56, 189, 248, 0.2));
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    visibility: hidden;
    display: none;
  }

  /* Full post panel in fullscreen mode */
  .knowledge-graph-wrapper.fullscreen .full-post-content {
    position: relative;
    width: 40%;
    height: 100%;
    background: rgba(15, 23, 42, 0.95);
    backdrop-filter: blur(10px);
    display: flex;
    flex-direction: column;
    opacity: 1;
    visibility: visible;
    border: none;
    border-radius: 0;
    box-shadow: none;
  }

  .knowledge-graph-wrapper.fullscreen .full-post-content.active {
    display: flex;
  }

  .full-post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(15, 23, 42, 0.8);
  }

  .full-post-title {
    font-size: 1.5rem;
    margin: 0;
    color: var(--text-primary, #e2e8f0);
    font-weight: 600;
    line-height: 1.3;
  }

  .close-button {
    background: none;
    border: none;
    color: var(--text-secondary, #a0aec0);
    cursor: pointer;
    padding: 5px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  .close-button:hover {
    color: var(--text-primary, #e2e8f0);
    background: rgba(255, 255, 255, 0.1);
  }

  .full-post-metadata {
    padding: 1rem 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    background: rgba(15, 23, 42, 0.6);
  }

  .metadata-row {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .metadata-label {
    color: var(--text-secondary, #a0aec0);
    font-size: 0.85rem;
  }

  .full-post-category {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 500;
  }

  .full-post-tags {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .post-tag {
    background: rgba(16, 185, 129, 0.1);
    color: #10B981;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
    transition: all 0.2s ease;
  }

  .post-tag:hover {
    background: rgba(16, 185, 129, 0.2);
    transform: translateY(-2px);
  }

  .full-post-container {
    flex: 1;
    padding: 1.5rem;
    overflow-y: auto;
    color: var(--text-primary, #e2e8f0);
    background: var(--bg-secondary, #161a24);
  }

  .full-post-container::-webkit-scrollbar {
    width: 8px;
  }

  .full-post-container::-webkit-scrollbar-track {
    background: rgba(30, 41, 59, 0.5);
    border-radius: 4px;
  }

  .full-post-container::-webkit-scrollbar-thumb {
    background: rgba(226, 232, 240, 0.1);
    border-radius: 4px;
  }

  .full-post-container::-webkit-scrollbar-thumb:hover {
    background: rgba(226, 232, 240, 0.2);
  }

  .full-post-placeholder {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--text-secondary, #a0aec0);
    text-align: center;
    padding: 2rem;
  }

  .full-post-placeholder svg {
    margin-bottom: 1rem;
    opacity: 0.5;
  }

  .full-post-footer {
    padding: 1rem;
    background: rgba(15, 23, 42, 0.7);
    border-top: 1px solid rgba(255, 255, 255, 0.05);
  }

  .full-post-link {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.75rem;
    background: linear-gradient(90deg, var(--accent-primary, #06b6d4), var(--accent-secondary, #3b82f6));
    color: var(--bg-primary, #0f1219);
    text-decoration: none;
    font-weight: 500;
    transition: all 0.3s ease;
    border-radius: 6px;
  }

  .full-post-link:hover {
    background: linear-gradient(90deg, var(--accent-secondary, #3b82f6), var(--accent-primary, #06b6d4));
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(6, 182, 212, 0.3);
  }

  /* Post content styles */
  .post-content {
    line-height: 1.7;
    font-size: 1rem;
  }

  .post-content h1, .post-content h2, .post-content h3,
  .post-content h4, .post-content h5, .post-content h6 {
    margin-top: 1.5rem;
    margin-bottom: 1rem;
    color: var(--text-primary, #e2e8f0);
    font-weight: 600;
  }

  .post-content p {
    margin-bottom: 1.25rem;
    color: var(--text-secondary, #a0aec0);
  }

  .post-content a {
    color: var(--accent-primary, #06b6d4);
    text-decoration: none;
    border-bottom: 1px dotted var(--accent-primary, #06b6d4);
    transition: all 0.2s ease;
  }

  .post-content a:hover {
    color: var(--accent-secondary, #3b82f6);
    border-bottom-style: solid;
  }

  .post-content pre {
    background: rgba(15, 23, 42, 0.6);
    padding: 1rem;
    border-radius: 6px;
    overflow-x: auto;
    margin: 1.5rem 0;
    border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1));
  }

  .post-content code {
    font-family: var(--font-mono, monospace);
    font-size: 0.9rem;
  }

  .post-content img {
    max-width: 100%;
    height: auto;
    margin: 1.5rem 0;
    border-radius: 6px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  }

  .post-content blockquote {
    border-left: 4px solid var(--accent-primary, #06b6d4);
    padding-left: 1rem;
    margin-left: 0;
    margin-right: 0;
    font-style: italic;
    color: var(--text-secondary, #a0aec0);
  }

  .post-content ul, .post-content ol {
    padding-left: 1.5rem;
    margin-bottom: 1.25rem;
  }

  .post-content li {
    margin-bottom: 0.5rem;
  }

  /* Media Queries for Fullscreen */
  @media screen and (max-width: 992px) {
    /* Adjust fullscreen layout for smaller screens */
    .knowledge-graph-wrapper.fullscreen {
      flex-direction: column;
    }

    .knowledge-graph-wrapper.fullscreen .mini-graph-container {
      width: 100%;
      height: 50%;
      margin-right: 0;
    }

    .knowledge-graph-wrapper.fullscreen .full-post-content {
      width: 100%;
      height: 50%;
    }
  }

  @media screen and (max-width: 768px) {
    .knowledge-graph-wrapper.fullscreen .mini-graph-container {
      height: 40%;
    }

    .knowledge-graph-wrapper.fullscreen .full-post-content {
      height: 60%;
    }

    .full-post-header {
      padding: 1rem;
    }

    .full-post-title {
      font-size: 1.25rem;
    }

    .full-post-metadata {
      padding: 0.75rem 1rem;
    }

    .full-post-container {
      padding: 1rem;
    }
  }

  @media screen and (max-width: 480px) {
    .knowledge-graph-wrapper.fullscreen .mini-graph-container {
      height: 35%;
    }

    .knowledge-graph-wrapper.fullscreen .full-post-content {
      height: 65%;
    }

    .full-post-title {
      font-size: 1.1rem;
    }
  }
</style>

<script define:vars={{ graphId, graphData, nodeTypeColors, predefinedColors }}>
  // 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);
      const graphWrapper = container.closest('.knowledge-graph-wrapper');
      if (!container || !graphWrapper) {
        console.error(`[MiniGraph] Container #${graphId} or wrapper not found.`);
        return;
      }

      // Get fullscreen elements
      const fullscreenToggle = document.getElementById(`${graphId}-fullscreen-toggle`);
      const fullscreenEnterIcon = document.getElementById(`${graphId}-fullscreen-enter-icon`);
      const fullscreenExitIcon = document.getElementById(`${graphId}-fullscreen-exit-icon`);
      const fullPostContent = document.getElementById(`${graphId}-full-post-content`);
      const closeFullPostBtn = document.getElementById(`${graphId}-close-full-post`);
      const fullPostTitle = document.getElementById(`${graphId}-full-post-title`);
      const fullPostContainer = document.getElementById(`${graphId}-full-post-container`);
      const fullPostCategory = document.getElementById(`${graphId}-full-post-category`);
      const fullPostTags = document.getElementById(`${graphId}-full-post-tags`);
      const fullPostLink = document.getElementById(`${graphId}-full-post-link`);

      // State variable for fullscreen mode
      let isFullscreen = false;

      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;
        }

        // Format data for Cytoscape
        const elements = [];

        // Add nodes with appropriate styling based on type
        graphData.nodes.forEach(node => {
          let nodeColor;

          if (node.type === 'post') {
            // Posts get category color if available
            nodeColor = node.category && predefinedColors[node.category]
              ? predefinedColors[node.category]
              : nodeTypeColors['post'];
          } else {
            // Tags get their type color
            nodeColor = nodeTypeColors[node.type];
          }

          elements.push({
            data: {
              id: node.id,
              label: node.label,
              type: node.type,
              category: node.category || '',
              tags: node.tags || [],
              color: nodeColor,
              url: node.url || '#',
              content: node.content || '' // Include content data for post nodes
            }
          });
        });

        // Add edges
        graphData.edges.forEach((edge, index) => {
          elements.push({
            data: {
              id: `e${index}`,
              source: edge.source,
              target: edge.target,
              type: edge.type
            }
          });
        });

        // Initialize Cytoscape
        const cy = cytoscape({
          container,
          elements: elements,
          style: [
            // Base node style
            {
              selector: 'node',
              style: {
                'background-color': 'data(color)',
                'label': 'data(label)',
                'width': node => node.data('type') === 'post' ? 25 : 18,
                'height': node => node.data('type') === 'post' ? 25 : 18,
                'font-size': '8px',
                'color': '#E2E8F0',
                'text-valign': 'bottom',
                'text-halign': 'center',
                'text-margin-y': 5,
                'text-wrap': 'ellipsis',
                'text-max-width': '60px',
                'text-background-opacity': 0.7,
                'text-background-color': '#0F1219',
                'text-background-padding': '3px',
                'text-background-shape': 'roundrectangle',
                'border-width': '2px',
                'border-color': '#0F1219',
                'border-opacity': 0.8
              }
            },
            // Post node style
            {
              selector: 'node[type="post"]',
              style: {
                'shape': 'ellipse',
                'font-size': '9px',
                'text-max-width': '80px'
              }
            },
            // Tag node style
            {
              selector: 'node[type="tag"]',
              style: {
                'shape': 'diamond',
                'border-width': '1px',
                'border-color': '#10B981',
                'border-opacity': 0.9
              }
            },
            // Edge style
            {
              selector: 'edge',
              style: {
                'width': 1,
                'line-color': 'rgba(16, 185, 129, 0.6)',
                'line-style': 'dashed',
                'curve-style': 'bezier',
                'opacity': 0.7
              }
            },
            // Selection and hover styles
            {
              selector: '.highlighted',
              style: {
                'background-color': 'data(color)',
                'border-color': '#FFFFFF',
                'border-width': '3px',
                'color': '#FFFFFF',
                'text-background-opacity': 0.9,
                'opacity': 1,
                'z-index': 20
              }
            },
            {
              selector: '.faded',
              style: {
                'opacity': 0.15,
                'text-opacity': 0.3,
                'background-opacity': 0.3,
                'z-index': 1
              }
            },
            {
              selector: 'node:selected',
              style: {
                'border-width': '4px',
                'border-color': '#FFFFFF',
                'border-opacity': 1,
                'background-color': 'data(color)',
                'text-opacity': 1,
                'color': '#FFFFFF',
                'z-index': 30
              }
            }
          ],
          // Use cose layout similar to KnowledgeGraph.astro
          layout: {
            name: 'cose',
            idealEdgeLength: 50,
            nodeOverlap: 10,
            refresh: 20,
            fit: true,
            padding: 20,
            randomize: false,
            componentSpacing: 50,
            nodeRepulsion: 450000,
            edgeElasticity: 100,
            nestingFactor: 5,
            gravity: 80,
            numIter: 1000,
            initialTemp: 200,
            coolingFactor: 0.95,
            minTemp: 1.0
          },
          zoom: 1,
          minZoom: 0.2,
          maxZoom: 3,
          zoomingEnabled: true,
          userZoomingEnabled: true,
          panningEnabled: true,
          userPanningEnabled: true,
          boxSelectionEnabled: false
        });

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

        // --- Fullscreen Toggle Functionality ---
        if (fullscreenToggle) {
          fullscreenToggle.addEventListener('click', toggleFullscreen);
        }

        // --- Node Interactions ---
        let hoverTimeout;
        cy.on('mouseover', 'node', function(e) {
          const node = e.target;
          clearTimeout(hoverTimeout);
          node.addClass('highlighted');
          node.connectedEdges().addClass('highlighted');
          container.style.cursor = 'pointer';
        });

        cy.on('mouseout', 'node', function(e) {
          const node = e.target;
          hoverTimeout = setTimeout(() => {
            if (!node.selected()) {
              node.removeClass('highlighted');
              node.connectedEdges().removeClass('highlighted');
            }
          }, 100);
          container.style.cursor = 'default';
        });

        // Node click handler - dispatches to appropriate function based on fullscreen mode
        cy.on('tap', 'node', function(e) {
          const node = e.target;

          if (isFullscreen) {
            handleNodeClickFullscreen(node);
          } else {
            handleNodeClickNormal(node);
          }

          // Common highlight functionality for both modes
          cy.elements().removeClass('highlighted').removeClass('faded');
          node.addClass('highlighted');
          node.neighborhood().addClass('highlighted');
          cy.elements().difference(node.neighborhood().union(node)).addClass('faded');
        });

        // Handle node click in normal mode - navigate to the URL
        function handleNodeClickNormal(node) {
          const nodeData = node.data();

          // In normal mode, just navigate to the URL (default browser behavior will take care of this)
          if (nodeData.url && nodeData.url !== '#') {
            window.location.href = nodeData.url;
          }
        }

        // Handle node click in fullscreen mode - shows content in side panel
        function handleNodeClickFullscreen(node) {
          const nodeData = node.data();

          // Only show content for post nodes
          if (nodeData.type === 'post') {
            if (fullPostContent) {
              // Set post title
              fullPostTitle.textContent = nodeData.label;

              // Set post category if available
              if (nodeData.category) {
                const catColor = predefinedColors[nodeData.category] || 'var(--accent-primary, #06b6d4)';
                fullPostCategory.textContent = nodeData.category;
                fullPostCategory.style.backgroundColor = `${catColor}33`;
                fullPostCategory.style.color = catColor;
                fullPostCategory.parentElement.style.display = 'flex';
              } else {
                fullPostCategory.parentElement.style.display = 'none';
              }

              // Set post tags if available
              if (nodeData.tags && nodeData.tags.length > 0) {
                fullPostTags.innerHTML = '';
                nodeData.tags.forEach(tag => {
                  const tagEl = document.createElement('span');
                  tagEl.className = 'post-tag';
                  tagEl.textContent = tag;
                  fullPostTags.appendChild(tagEl);
                });
                fullPostTags.parentElement.style.display = 'flex';
              } else {
                fullPostTags.parentElement.style.display = 'none';
              }

              // Display the content or a placeholder
              if (nodeData.content && nodeData.content.trim() !== '') { // Check if content exists and is not empty
                fullPostContainer.innerHTML = `
                  <article class="post-content">
                    ${nodeData.content}
                  </article>
                `;
              } else {
                // If we don't have content, show a placeholder
                fullPostContainer.innerHTML = `
                  <div class="full-post-placeholder">
                    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                      <polyline points="14 2 14 8 20 8"></polyline>
                      <line x1="16" y1="13" x2="8" y2="13"></line>
                      <line x1="16" y1="17" x2="8" y2="17"></line>
                      <polyline points="10 9 9 9 8 9"></polyline>
                    </svg>
                    <p>Content preview not available. Click 'Read Full Article' to view the post.</p>
                  </div>
                `;
              }

              // Set the article link
              fullPostLink.href = nodeData.url || '#';
              fullPostLink.textContent = 'Read Full Article';
              fullPostLink.setAttribute('target', '_blank'); // Ensure it opens in new tab

              // Make the content panel visible
              fullPostContent.classList.add('active');
              fullPostContent.style.display = 'flex';
            }
          } else if (nodeData.type === 'tag') {
            // For tag nodes in fullscreen mode, we'll show placeholder content
            if (fullPostContent) {
              fullPostTitle.textContent = `Tag: ${nodeData.label}`;

              fullPostCategory.parentElement.style.display = 'none';
              fullPostTags.parentElement.style.display = 'none';

              fullPostContainer.innerHTML = `
                <div class="full-post-placeholder">
                  <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#10B981" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path>
                    <line x1="7" y1="7" x2="7.01" y2="7"></line>
                  </svg>
                  <p>View all posts tagged with "${nodeData.label}"</p>
                </div>
              `;

              // Set link to tag page
              fullPostLink.href = nodeData.url || '#';
              fullPostLink.textContent = `Browse all "${nodeData.label}" posts`;
              fullPostLink.setAttribute('target', '_blank'); // Ensure it opens in new tab

              // Show the panel
              fullPostContent.classList.add('active');
              fullPostContent.style.display = 'flex';
            }
          }
        }

        // Background click handler
        cy.on('tap', function(e) {
          if (e.target === cy) {
            if (isFullscreen && fullPostContent) {
              fullPostContent.classList.remove('active');
            }
            cy.elements().removeClass('selected highlighted faded');
          }
        });

        // Close fullpost panel button
        if (closeFullPostBtn) {
          closeFullPostBtn.addEventListener('click', () => {
            if (fullPostContent) {
              fullPostContent.classList.remove('active');
            }
            cy.$(':selected').unselect();
            cy.elements().removeClass('highlighted faded');
          });
        }

        // Add event listener to ensure proper link behavior in fullscreen mode
        if (fullPostLink) {
          fullPostLink.setAttribute('target', '_blank'); // Ensure link always opens in new tab

          // This is the updated event listener
          fullPostLink.addEventListener('click', (e) => {
            // We're not preventing default behavior anymore
            // This allows the link to work naturally, even in fullscreen mode
            console.log('Full post link clicked:', fullPostLink.href);
          });
        }

        // Listen for ESC key to exit fullscreen
        document.addEventListener('keydown', (e) => {
          if (e.key === 'Escape' && isFullscreen) {
            toggleFullscreen();
          }
        });

        // Update window resize handler to preserve layout in fullscreen mode
        window.addEventListener('resize', () => {
          if (cy) {
            cy.resize();
            if (!isFullscreen) {
              cy.fit(null, 20);
            } else {
              // Optionally refit in fullscreen too, if needed
              cy.fit(null, 20);
            }
          }
        });

        // Toggle fullscreen function
        function toggleFullscreen() {
          isFullscreen = !isFullscreen;

          if (isFullscreen) {
            // Enable fullscreen mode
            graphWrapper.classList.add('fullscreen');
            fullscreenEnterIcon.classList.add('hidden');
            fullscreenExitIcon.classList.remove('hidden');

            // Hide any other visible panels if needed
            if (fullPostContent) fullPostContent.classList.remove('active');

            // In fullscreen, we adjust the cytoscape layout to fit
            setTimeout(() => {
              cy.resize();
              cy.fit(null, 20);
            }, 300); // Wait for transition to complete
          } else {
            // Disable fullscreen mode
            graphWrapper.classList.remove('fullscreen');
            fullscreenEnterIcon.classList.remove('hidden');
            fullscreenExitIcon.classList.add('hidden');

            // Hide the full post content panel
            if (fullPostContent) {
              fullPostContent.classList.remove('active');
            }

            // Reset the cytoscape layout
            setTimeout(() => {
              cy.resize();
              cy.fit(null, 20);
            }, 300); // Wait for transition to complete
          }
        }

      } 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>