import { Alpine } from "./alpine";

function toggleSidebar(): void {
  const sidebar = document.getElementById("docs-sidebar");
  const overlay = document.getElementById("docs-overlay");

  if (sidebar && overlay) {
    sidebar.classList.toggle("translate-x-0");
    sidebar.classList.toggle("-translate-x-full");
    overlay.classList.toggle("hidden");
  }
}

function toggleSection(el: HTMLElement): void {
  const items = el.nextElementSibling as HTMLElement;
  const arrow = el.querySelector(".section-arrow") as HTMLElement;
  if (!items || !arrow) return;
  
  const isCollapsed = items.getAttribute("data-collapsed") === "true";

  if (isCollapsed) {
    items.classList.remove("hidden");
    items.setAttribute("data-collapsed", "false");
    arrow.style.transform = "rotate(0deg)";
  } else {
    items.classList.add("hidden");
    items.setAttribute("data-collapsed", "true");
    arrow.style.transform = "rotate(-90deg)";
  }
}

function initializeDocsSearch(): void {
  const searchInput = document.getElementById(
    "docs-search",
  ) as HTMLInputElement;
  const searchResults = document.getElementById("docs-search-results");

  if (!searchInput || !searchResults) return;

  let docsSearchTimeout: ReturnType<typeof setTimeout> | null = null;

  searchInput.addEventListener("input", () => {
    const query = searchInput.value.trim();

    if (docsSearchTimeout) {
      clearTimeout(docsSearchTimeout);
    }

    if (query.length < 2) {
      searchResults.innerHTML = "";
      searchResults.classList.add("hidden");
      return;
    }

    docsSearchTimeout = setTimeout(() => {
      performDocsSearch(query);
    }, 300);
  });
}

function performDocsSearch(query: string): void {
  const searchResults = document.getElementById("docs-search-results");
  if (!searchResults) return;

  if (!(window as any).lunr) {
    console.warn("Lunr.js not loaded");
    return;
  }

  try {
    const idx = (window as any).lunrIndex;
    if (!idx) {
      searchResults.innerHTML =
        '<p class="p-2 text-sm" style="color: var(--text-secondary)">Search index not loaded</p>';
      searchResults.classList.remove("hidden");
      return;
    }

    const results = idx.search(query);

    if (results.length === 0) {
      searchResults.innerHTML =
        '<p class="p-2 text-sm" style="color: var(--text-secondary)">No results found</p>';
    } else {
      searchResults.innerHTML = results
        .slice(0, 10)
        .map((result: { ref: string }) => {
          const doc = (window as any).docsData?.[result.ref];
          if (!doc) return "";

          return `
                    <a href="${result.ref}" class="block p-2 hover:bg-opacity-50 transition-colors" style="background-color: var(--bg-secondary)">
                        <p class="font-medium text-sm" style="color: var(--text-primary)">${doc.title || result.ref}</p>
                        ${doc.section ? `<p class="text-xs" style="color: var(--text-secondary)">${doc.section}</p>` : ""}
                    </a>
                `;
        })
        .join("");
    }

    searchResults.classList.remove("hidden");
  } catch (error) {
    console.error("Search error:", error);
    searchResults.innerHTML =
      '<p class="p-2 text-sm" style="color: var(--text-secondary)">Search error</p>';
    searchResults.classList.remove("hidden");
  }
}

function highlightCurrentPage(): void {
  const currentPath = window.location.pathname;
  document.querySelectorAll(".nav-item").forEach((item) => {
    if (item.getAttribute("href") === currentPath) {
      item.classList.add("text-accent", "bg-accent/10", "border-r-2", "border-accent");
    }
  });
}

function initializeCodeCopyButtons(): void {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const hljs = (window as any).hljs;
  if (hljs) {
    hljs.highlightAll();

    document.querySelectorAll("pre code").forEach((block) => {
      const pre = block.parentElement;
      if (!pre) return;
      
      const wrapper = document.createElement("div");
      wrapper.className = "relative group";
      pre.parentNode.insertBefore(wrapper, pre);
      wrapper.appendChild(pre);

      const button = document.createElement("button");
      button.className = "absolute top-2 right-2 bg-background-secondary text-text-secondary px-2 py-1 rounded text-xs opacity-0 group-hover:opacity-100 transition-opacity border border-border hover:text-accent";
      button.textContent = "Copy";
      button.onclick = async () => {
        await navigator.clipboard.writeText(block.textContent || "");
        button.textContent = "Copied!";
        setTimeout(() => {
          button.textContent = "Copy";
        }, 2000);
      };
      wrapper.appendChild(button);
    });
  }
}

Alpine.data("docs", () => ({
  toggleSidebar,
  toggleSection,
  initializeSearch: initializeDocsSearch,
  highlightCurrentPage,
  initializeCodeCopyButtons,
}));

export { toggleSidebar, toggleSection, initializeDocsSearch, highlightCurrentPage, initializeCodeCopyButtons };
