class ApiBar extends HTMLElement {
  connectedCallback() {
    const func = this.getAttribute("func") ?? "Run function";
    const service = this.getAttribute("service") ?? "datastore";
    const method = this.getAttribute("method") ?? "get";
    const output = this.getAttribute("output") ?? "output";

    const nameAttr = this.getAttribute("name")?.trim();
    const names = nameAttr ? nameAttr.split(";").map((n) => n.trim()) : [];

    const nameChips = names.length
      ? names
          .map((n) => `<div class="chip">${n}${this.getDropdown()}</div>`)
          .join("")
      : "";

    this.innerHTML = `
      <div class="bar">
        <div class="chip dark">
          <span class="icon">${this.getIcon()}</span>
          ${func}
        </div>

        <div class="chip dark">${service}</div>

        <div class="chip">
          ${method}
          ${this.getDropdown()}
        </div>

        ${nameChips}

        <div class="plus">
          <svg viewBox="0 0 24 24">
            <line x1="12" y1="5" x2="12" y2="19" stroke="#9ec7cd" stroke-width="2" stroke-linecap="round"/>
            <line x1="5" y1="12" x2="19" y2="12" stroke="#9ec7cd" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </div>

        <span class="icon">
          <svg viewBox="0 0 24 24">
            <line x1="5" y1="12" x2="17" y2="12" stroke="#9ec7cd" stroke-width="3" stroke-linecap="round"/>
            <polyline points="12,7 17,12 12,17" fill="none" stroke="#9ec7cd" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </span>

        <div class="chip dark">l!${output}</div>
      </div>
    `;
  }

  getDropdown() {
    return `
      <span class="icon">
        <svg viewBox="0 0 24 24">
          <polyline points="6,9 12,15 18,9"
            fill="none"
            stroke="#9ec7cd"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"/>
        </svg>
      </span>
    `;
  }

  getIcon() {
    return `
      <svg style="color:#e74c3c" viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="3"
        stroke-linecap="round"
        stroke-linejoin="round">
        <path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
      </svg>
    `;
  }
}

customElements.define("api-bar", ApiBar);

const overlay = document.getElementById("overlay");
const overlayImage = document.getElementById("overlayImage");
const closeBtn = document.getElementById("closeBtn");

let scale = 1;

const zoomHint = document.getElementById("zoomHint");

document.querySelectorAll(".clickable").forEach((img) => {
  img.addEventListener("click", () => {
    overlay.style.display = "flex";
    overlayImage.src = img.src;
    scale = 1;
    overlayImage.style.transform = `scale(${scale})`;

    // hint
    zoomHint.style.opacity = "1";
    setTimeout(() => {
      zoomHint.style.opacity = "0";
    }, 3000);
  });
});

// close btn
closeBtn.addEventListener("click", () => {
  overlay.style.display = "none";
  overlayImage.src = "";
});

// close
overlay.addEventListener("click", (e) => {
  if (e.target === overlay) {
    overlay.style.display = "none";
    overlayImage.src = "";
  }
});

overlayImage.addEventListener("wheel", (e) => {
  e.preventDefault();
  if (e.deltaY < 0) {
    // in
    scale += 0.1;
    if (scale > 3) scale = 3;
  } else {
    // out
    scale -= 0.1;
    if (scale < 0.5) scale = 0.5;
  }

  overlayImage.style.transform = `scale(${scale})`;
});

// QOL
document.addEventListener("DOMContentLoaded", () => {
  const toc = document.getElementById("toc");
  if (!toc) return;

  const headings = Array.from(document.querySelectorAll("h2, h3"));
  const tocFrag = document.createDocumentFragment();

  function slugify(text) {
    return text
      .toString()
      .trim()
      .toLowerCase()
      .replace(/[^\w\s-]/g, "")
      .replace(/\s+/g, "-");
  }

  function showTooltip(el, text = "Copied") {
    const tip = document.createElement("span");
    tip.className = "copy-tip";
    tip.textContent = text;
    el.parentElement?.appendChild(tip);
    setTimeout(() => tip.remove(), 1300);
  }

  headings.forEach((h) => {
    const text = h.textContent.trim();
    if (!text) return;

    const id = h.id ? h.id : slugify(text);
    h.id = id;

    const anchor = document.createElement("a");
    anchor.href = `#${id}`;
    anchor.className = "heading-anchor";
    anchor.title = `Link to ${text}`;
    anchor.innerText = "#";
    anchor.addEventListener("click", (e) => {
      e.stopPropagation();
    });

    h.appendChild(anchor);

    const item = document.createElement("a");
    item.href = `#${id}`;
    item.className = "toc-item";
    item.textContent = text;
    tocFrag.appendChild(item);
  });

  toc.appendChild(tocFrag);

  if (location.hash) {
    const el = document.querySelector(location.hash);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
  }
});
