{% load spellbook_tags %}
<div class="toc-wrapper">
    {% if toc.children %}
        <ul class="toc-list">
            {% include "django_spellbook/recursive/_toc_sidebar.html" with items=toc.children %}
        </ul>
    {% endif %}
</div>
<style>
  .toc-wrapper {
    font-size: 0.95rem;
  }

  .toc-list,
  .toc-sublist {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .toc-sublist {
    margin-left: 1.5rem;
    border-left: 1px solid #00000044;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
  }

  .toc-sublist .toc-sublist {
    margin-left: 1rem; /* Slightly smaller indent for deeper levels */
    border-left-style: dashed; 
  }

  .toc-sublist .toc-sublist .toc-sublist {
    border-left-color: #15151575; 
  }
  .toc-item,
  .toc-subitem {
    margin: 0.5rem 0;
  }

  .toc-link {
    text-decoration: none;
    color: #555;
    display: block;
    padding: 0.25rem 0.5rem !important;
    width: 100%;
    border-radius: 4px;
    transition: all 0.2s ease;
  }

  .toc-link:hover {
    background-color: #f5f5f555;
    color: #000;
  }

  .toc-section {
    font-weight: 600;
    color: #333;
    display: block;
    padding: 0.25rem 0.5rem;
    margin-top: 1rem;
  }

  .toc-item.active div a,
  .toc-subitem.active div a {
    background-color: #b1b1b18f !important;
    color: #363636;
    font-weight: 500;
  }

  .toc-item.active div a:hover,
  .toc-subitem.active div a:hover {
    background-color: #bebebe9a !important;
    color: #242424;
  }

  @media (max-width: 767px) {
    .toc-wrapper {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #eee;
      border-radius: 4px;
      padding: 0.5rem;
    }
  }

  .toc-item-header {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    cursor: pointer;
    padding: 0.25rem;
  }

  /* Prevent the link from having its own click area */
  .toc-item-header .toc-link {
    pointer-events: auto;
    padding: 0;
  }
  .toc-toggle {
    background: none;
    border: none;
    padding: 0.25rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .toc-arrow {
    transition: transform 0.3s ease;
    fill: currentColor;
  }

  .toc-toggle.collapsed .toc-arrow {
    transform: rotate(-90deg);
  }

  .toc-sublist.collapsed {
    max-height: 0;
  }
</style>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const TOC_ACTIVE_PAGE_KEY = "spellbook_active_page";
    
    // Get current page info from the active TOC item
    function getCurrentPageInfo() {
      const activeItem = document.querySelector(".toc-item.active");
      if (!activeItem) return null;
      
      const tocId = activeItem.dataset.tocId;
      const parentPath = [];
      let current = activeItem;
      
      // Build the path from root to active item
      while (current && current.dataset.tocId) {
        parentPath.unshift(current.dataset.tocId);
        // Move up to parent toc item
        const parentSublist = current.parentElement.closest(".toc-sublist");
        if (parentSublist) {
          current = parentSublist.parentElement.closest(".toc-item");
        } else {
          break;
        }
      }
      
      return {
        activePageId: tocId,
        parentPath: parentPath,
        fullPath: parentPath.join(".")
      };
    }
    
    // Save current active page to localStorage
    function saveCurrentPage() {
      try {
        const pageInfo = getCurrentPageInfo();
        if (pageInfo) {
          localStorage.setItem(TOC_ACTIVE_PAGE_KEY, JSON.stringify(pageInfo));
        }
      } catch (e) {
        console.warn("Failed to save active page to localStorage:", e);
      }
    }
    
    // Get stored active page from localStorage
    function getStoredActivePage() {
      try {
        const stored = localStorage.getItem(TOC_ACTIVE_PAGE_KEY);
        return stored ? JSON.parse(stored) : null;
      } catch (e) {
        console.warn("Failed to parse active page from localStorage:", e);
        return null;
      }
    }
    
    // Initialize TOC state based on current active page
    function initializeTocState() {
      // First, collapse everything by default
      document.querySelectorAll(".toc-sublist").forEach((sublist) => {
        sublist.style.maxHeight = "0px";
        sublist.classList.add("collapsed");
      });

      document.querySelectorAll(".toc-toggle").forEach((toggle) => {
        toggle.classList.add("collapsed");
      });
      
      // Get current page info
      const currentPageInfo = getCurrentPageInfo();
      
      if (currentPageInfo) {
        // Save current page as the active page
        saveCurrentPage();
        
        // Expand path to current active item
        expandPathToActiveItem(currentPageInfo.parentPath);
      } else {
        // No active item found, check if we have a stored active page
        const storedPage = getStoredActivePage();
        if (storedPage) {
          // Try to restore the active state and expand its path
          restoreActiveItemFromStorage(storedPage);
        }
      }
    }
    
    // Expand the path to the active item
    function expandPathToActiveItem(parentPath) {
      if (parentPath.length <= 1) return; // No parents to expand
      
      // Expand each parent level
      for (let i = 0; i < parentPath.length - 1; i++) {
        const tocItem = document.querySelector(`[data-toc-id="${parentPath[i]}"]`);
        if (tocItem) {
          const sublist = tocItem.querySelector(".toc-sublist");
          const toggle = tocItem.querySelector(".toc-toggle");
          if (sublist) {
            expandTocItem(tocItem, sublist, toggle, false);
          }
        }
      }
    }
    
    // Try to restore active item from storage
    function restoreActiveItemFromStorage(storedPage) {
      // Find the stored active item
      const activeItem = document.querySelector(`[data-toc-id="${storedPage.activePageId}"]`);
      if (activeItem) {
        // Add active class if not already present
        if (!activeItem.classList.contains("active")) {
          activeItem.classList.add("active");
        }
        
        // Expand path to this item
        expandPathToActiveItem(storedPage.parentPath);
      }
    }
    
    // Expand a TOC item
    function expandTocItem(tocItem, sublist, toggle, saveState = false) {
      if (!sublist) return;
      
      const totalHeight = sublist.scrollHeight;
      sublist.style.maxHeight = totalHeight + "px";
      sublist.classList.remove("collapsed");
      
      if (toggle) {
        toggle.classList.remove("collapsed");
      }
      
      // Update parent heights if this item is nested
      let parent = sublist.parentElement.closest(".toc-sublist");
      while (parent) {
        parent.style.maxHeight = parent.scrollHeight + "px";
        parent = parent.parentElement.closest(".toc-sublist");
      }
    }
    
    // Collapse a TOC item
    function collapseTocItem(tocItem, sublist, toggle, saveState = false) {
      if (!sublist) return;
      
      // Collapse this sublist and all nested sublists
      sublist.style.maxHeight = "0px";
      sublist.classList.add("collapsed");
      
      if (toggle) {
        toggle.classList.add("collapsed");
      }
      
      // Collapse all nested items
      sublist.querySelectorAll(".toc-sublist").forEach((nested) => {
        nested.style.maxHeight = "0px";
        nested.classList.add("collapsed");
        const nestedToggle = nested.previousElementSibling?.querySelector(".toc-toggle");
        if (nestedToggle) {
          nestedToggle.classList.add("collapsed");
        }
      });
    }

    // Set up click event listeners
    document.querySelectorAll(".toc-item-header").forEach((header) => {
      header.addEventListener("click", (e) => {
        const tocItem = header.closest(".toc-item");
        const toggle = header.querySelector(".toc-toggle");
        const link = header.querySelector(".toc-link");
        const sublist = header.nextElementSibling;

        // If there's a sublist, toggle it
        if (sublist && sublist.classList.contains("toc-sublist")) {
          e.preventDefault();
          
          if (sublist.classList.contains("collapsed")) {
            expandTocItem(tocItem, sublist, toggle, false);
          } else {
            collapseTocItem(tocItem, sublist, toggle, false);
          }
        } else if (link && link.href) {
          // When clicking a link, save this as the new active page
          const linkTocId = tocItem.dataset.tocId;
          if (linkTocId) {
            // Remove active class from current item
            document.querySelectorAll(".toc-item.active").forEach(item => {
              item.classList.remove("active");
            });
            
            // Add active class to clicked item
            tocItem.classList.add("active");
            
            // Save the new active page
            saveCurrentPage();
          }
          
          window.location.href = link.href;
        }
      });
    });

    // Initialize everything
    initializeTocState();
  });
</script>
