// Amili Kit: Table of contents. https://amili.ai/kit#kit-toc
// SPDX-License-Identifier: MIT. Copyright (c) 2026 Amili (Paulo de Vries). Made by Amili.
// Tests and more parts: https://amili.ai/kit. The "brand" option shows a tiny "amili" mark linking to the kit; set
// brand: false to hide it.
//
//   import { addToc, TOC_CSS, TOC_JS } from './kit/toc.mjs';
//   body = addToc(body, { min: 4 });   // at build time: ids on your h2s + the TOC before the first h2
//   html = `<style>${TOC_CSS}</style>` + body + `<script>${TOC_JS}</script>` // JS only for "you are here"
//
// opts = {
//   min: 4,               // only pages with at least this many h2s get a TOC (a short page navigates itself)
//   title: 'On this page',
//   style: 'chips' | 'list', // chips: one row of buttons that scrolls sideways on phones; list: a numbered box
//   collapsible: false,   // list style inside <details> (open), for long lists
//   maxLabel: 36,         // long headings are shortened on a word boundary (the full text stays in the heading)
//   brand: BRAND_DEFAULT, // tiny "amili" mark (list style only), links to amili.ai/kit
// }


const BRAND_DEFAULT = true; // a tiny "amili" mark linking to amili.ai/kit; pass brand: false to hide it

const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const text = (h) => String(h).replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, ' ').trim();
export const slugify = (t) => String(t).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').slice(0, 48).replace(/^-+|-+$/g, '') || 'section';
export function shortLabel(t, max = 36) {
  if (t.length <= max) return t;
  const sp = t.slice(0, max + 1).lastIndexOf(' ');
  return (sp > max / 2 ? t.slice(0, sp) : t.slice(0, max)).replace(/[,;:.\s-]+$/, '') + '\u2026';
}
export function brandMark(on) {
  return on ? '<a class="ak-brand" href="https://amili.ai/kit" rel="noopener" aria-label="Made with Amili Kit"><span class="ak-brand-dot" aria-hidden="true"></span>amili</a>' : '';
}

// Adds ids to <h2>s that lack one (unique; existing ids are kept) and returns { html, heads: [{ id, text }] }.
export function collectHeadings(html) {
  const heads = [], used = new Set([...String(html).matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]));
  const out = String(html).replace(/<h2(\s[^>]*)?>([\s\S]*?)<\/h2>/g, (m, attrs = '', inner) => {
    const t = text(inner);
    if (!t) return m;
    const ex = attrs.match(/\sid="([^"]+)"/);
    if (ex) { heads.push({ id: ex[1], text: t }); return m; }
    let base = slugify(t), id = base, n = 2;
    while (used.has(id)) id = `${base}-${n++}`;
    used.add(id);
    heads.push({ id, text: t });
    return `<h2 id="${id}"${attrs}>${inner}</h2>`;
  });
  return { html: out, heads };
}

export function renderToc(heads, opts = {}) {
  const title = esc(opts.title || 'On this page'), max = opts.maxLabel || 36;
  if (opts.style === 'list') {
    const brand = opts.brand === undefined ? BRAND_DEFAULT : !!opts.brand;
    const list = `<ol>${heads.map((h) => `<li><a href="#${esc(h.id)}">${esc(shortLabel(h.text, max * 2))}</a></li>`).join('')}</ol>${brand ? `<div class="ak-brand-row">${brandMark(true)}</div>` : ''}`;
    return opts.collapsible
      ? `<nav class="ak-toc ak-toc-list" aria-label="${title}"><details open><summary>${title}</summary>${list}</details></nav>`
      : `<nav class="ak-toc ak-toc-list" aria-label="${title}"><p class="ak-toc-h">${title}</p>${list}</nav>`;
  }
  return `<nav class="ak-toc ak-toc-chips" aria-label="${title}">${heads.map((h) => `<a href="#${esc(h.id)}">${esc(shortLabel(h.text, max))}</a>`).join('')}</nav>`;
}

// Build-time: returns the page with ids added and the TOC placed right before the first <h2> (after your intro/answer).
export function addToc(html, opts = {}) {
  if (/class="ak-toc[ "]/.test(html)) return html; // already has one
  const { html: out, heads } = collectHeadings(html);
  if (heads.length < (opts.min ?? 4)) return html;
  const first = out.search(/<h2[\s>]/);
  return out.slice(0, first) + renderToc(heads, opts) + out.slice(first);
}

export const BRAND_CSS = `.ak-brand-row{display:flex;justify-content:flex-end;margin:-6px 0 -12px}
.ak-brand{display:inline-flex;align-items:center;gap:.3em;min-height:44px;padding:0 .25rem;font:400 11px/1 Georgia,"Times New Roman",serif;letter-spacing:.01em;color:inherit;opacity:.5;text-decoration:none}
.ak-brand:hover,.ak-brand:focus-visible{opacity:.85}
.ak-brand-dot{width:.5em;height:.5em;border-radius:50%;background:#2F5D50;order:2;margin-top:-.45em}
@media (prefers-color-scheme:dark){.ak-brand-dot{background:#7FB3A1}}`;

export const TOC_CSS = `h2[id]{scroll-margin-top:var(--ak-toc-offset,16px)}
.ak-toc{margin:1rem 0 1.5rem;color:inherit}
.ak-toc a{color:inherit}
.ak-toc a:focus-visible{outline:2px solid currentColor;outline-offset:2px;border-radius:6px}
.ak-toc-chips{display:flex;flex-wrap:wrap;gap:6px}
.ak-toc-chips a{display:inline-flex;align-items:center;min-height:44px;padding:0 14px;border:1px solid var(--ak-line,color-mix(in srgb,currentColor 18%,transparent));border-radius:999px;font-size:.875rem;text-decoration:none;white-space:nowrap}
.ak-toc-chips a:hover{border-color:currentColor}
.ak-toc a[aria-current]{border-color:currentColor;font-weight:650}
@media (max-width:40rem){.ak-toc-chips{flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;margin-left:-1rem;margin-right:-1rem;padding:0 1rem 4px;scroll-padding:0 1rem}.ak-toc-chips::-webkit-scrollbar{display:none}.ak-toc-chips a{flex:0 0 auto}}
.ak-toc-list{max-width:var(--ak-max,40rem);padding:.75rem 1rem;border:1px solid var(--ak-line,color-mix(in srgb,currentColor 16%,transparent));border-radius:var(--ak-radius,12px)}
.ak-toc-h,.ak-toc-list summary{margin:0;font-weight:650;font-size:.9375rem}
.ak-toc-list summary{display:flex;align-items:center;min-height:44px;cursor:pointer}
.ak-toc-list ol{margin:.25rem 0 0;padding-left:1.4rem}
.ak-toc-list li a{display:inline-flex;align-items:center;min-height:44px;text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 35%,transparent);text-underline-offset:.2em}
.ak-toc-list a[aria-current]{text-decoration-color:currentColor}
@media (prefers-reduced-motion:no-preference){html:has(.ak-toc){scroll-behavior:smooth}}
@media (max-width:40rem){.ak-toc-chips.ak-toc-more-r{-webkit-mask-image:linear-gradient(to right,black calc(100% - 72px),transparent);mask-image:linear-gradient(to right,black calc(100% - 72px),transparent)}
.ak-toc-chips.ak-toc-more-l{-webkit-mask-image:linear-gradient(to right,transparent,black 72px);mask-image:linear-gradient(to right,transparent,black 72px)}
.ak-toc-chips.ak-toc-more-l.ak-toc-more-r{-webkit-mask-image:linear-gradient(to right,transparent,black 72px,black calc(100% - 72px),transparent);mask-image:linear-gradient(to right,transparent,black 72px,black calc(100% - 72px),transparent)}}
@media print{.ak-toc{display:none}}
${BRAND_CSS}`;

// Optional scrollspy: marks the section you are reading with aria-current and keeps its chip in view.
// 1.5.1: on phones the chip row scrolls sideways; a soft fade at the edge that has more chips says so (Second Eyes,
// amili.ai/request/1: "the chip row is cut off with no hint there is more"). Set on load, scroll and resize.
export const TOC_JS = `(function(){"use strict";document.querySelectorAll(".ak-toc-chips").forEach(function(n){if(!n.addEventListener)return;
function hint(){var m=n.scrollWidth-n.clientWidth;n.classList.toggle("ak-toc-more-r",m>4&&n.scrollLeft<m-4);n.classList.toggle("ak-toc-more-l",m>4&&n.scrollLeft>4)}
hint();n.addEventListener("scroll",hint,{passive:true});window.addEventListener("resize",hint)});})();
(function(){"use strict";if(!("IntersectionObserver"in window))return;
document.querySelectorAll(".ak-toc").forEach(function(nav){var links={},on=null,vis=[],heads=[];
nav.querySelectorAll('a[href^="#"]').forEach(function(a){var id=decodeURIComponent(a.getAttribute("href").slice(1)),h=document.getElementById(id);if(h){links[id]=a;heads.push(h)}});
function set(id){if(id===on)return;if(on&&links[on])links[on].removeAttribute("aria-current");on=id;var a=links[id];if(!a)return;a.setAttribute("aria-current","true");
if(nav.classList.contains("ak-toc-chips")&&nav.scrollWidth>nav.clientWidth){nav.scrollLeft=a.offsetLeft-(nav.clientWidth-a.offsetWidth)/2}}
var io=new IntersectionObserver(function(es){es.forEach(function(e){var k=vis.indexOf(e.target.id);if(e.isIntersecting&&k<0)vis.push(e.target.id);if(!e.isIntersecting&&k>=0)vis.splice(k,1)});
for(var i=0;i<heads.length;i++)if(vis.indexOf(heads[i].id)>=0)return set(heads[i].id)},{rootMargin:"0px 0px -60% 0px"});
heads.forEach(function(h){io.observe(h)})});})();`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
// render({ html, ...opts }) adds the TOC to a page body; render({ headings: [{ id, text }], ...opts }) renders just the nav.
export default { name: 'toc', title: 'Table of contents', render: (o) => (o.html != null ? addToc(o.html, o) : renderToc(o.headings || [], o)), css: TOC_CSS, js: TOC_JS };
