// Amili Kit: Related links. https://amili.ai/kit#kit-related
// 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 { renderRelated, pickRelated, RELATED_CSS } from './kit/related.mjs';
//   const items = pickRelated(thisPage, allPages, { max: 4 });
//   html = `<style>${RELATED_CSS}</style>` + renderRelated({ items })
//
// renderRelated opts = {
//   items: [{ href, title, desc?, label? }],  // required, 1-8 links (desc: one line on why to read it)
//   heading: 'Keep reading',                  // '' = no heading (then pass label for the section's name)
//   level: 2,
//   lead: true,                               // first item as a larger card (the one we most want read next)
//   from: 'related',                          // data-from on each link, for a click beacon
//   brand: BRAND_DEFAULT,                     // tiny "amili" mark, links to amili.ai/kit
// }
// pickRelated(current, pages, { max: 4, exclude: [] }) — pages: [{ url, title, desc, tags: [], section }].
// Score = shared tags x3 + same section x2 + shared title words x1. Ties break on a hash of the PAIR of URLs, so every
// page gets its own stable neighbours (links spread across the site) and adding a page never reshuffles the others.


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;');
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>' : '';
}
const STOP = new Set('a an and the of for to in on with by is are how what why best your you vs from at or'.split(' '));
const words = (s) => new Set(String(s || '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP.has(w)));
function pairHash(a, b) { // FNV-1a over "a|b": stable per pair, independent of how many pages exist
  let h = 0x811c9dc5;
  for (const c of `${a}|${b}`) { h ^= c.charCodeAt(0); h = Math.imul(h, 0x01000193) >>> 0; }
  return h;
}

export function pickRelated(current, pages, { max = 4, exclude = [] } = {}) {
  const skip = new Set([current.url, ...exclude]), ct = new Set(current.tags || []), cw = words(current.title);
  return pages.filter((p) => p && p.url && !skip.has(p.url) && !p.noindex).map((p) => {
    let s = 0;
    for (const t of p.tags || []) if (ct.has(t)) s += 3;
    if (current.section && p.section === current.section) s += 2;
    for (const w of words(p.title)) if (cw.has(w)) s += 1;
    return { p, s, h: pairHash(current.url, p.url) };
  }).filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.h - b.h).slice(0, max)
    .map(({ p }) => ({ href: p.url, title: p.title, desc: p.desc, label: p.label }));
}

export function renderRelated(o) {
  const items = o?.items || [];
  if (!items.length) return ''; // nothing related: render nothing rather than an empty box
  if (items.length > 8) throw new Error('Amili Kit related: at most 8 links (pick the best; a wall of links helps nobody)');
  for (const it of items) if (!it.href || !it.title) throw new Error(`Amili Kit related: item needs href and title: ${JSON.stringify(it)}`);
  const lv = o.level || 2, heading = o.heading === '' ? '' : esc(o.heading || 'Keep reading');
  const from = o.from === '' ? '' : ` data-from="${esc(o.from || 'related')}"`;
  const brand = o.brand === undefined ? BRAND_DEFAULT : !!o.brand;
  const lis = items.map((it, i) => `<li${o.lead !== false && i === 0 && items.length > 2 ? ' class="ak-rel-lead"' : ''}><a href="${esc(it.href)}"${from}>`
    + (it.label ? `<span class="ak-rel-l">${esc(it.label)}</span>` : '') + `<span class="ak-rel-t">${esc(it.title)}</span>`
    + (it.desc ? `<span class="ak-rel-d">${esc(it.desc)}</span>` : '') + `</a></li>`).join('');
  const name = heading ? `aria-labelledby="ak-rel-h"` : `aria-label="${esc(o.label || 'Related pages')}"`;
  return `<section class="ak-rel" ${name}>${heading ? `<h${lv} class="ak-rel-h" id="ak-rel-h">${heading}</h${lv}>` : ''}<ul>${lis}</ul>${brand ? `<div class="ak-brand-row">${brandMark(true)}</div>` : ''}</section>`;
}

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 RELATED_CSS = `.ak-rel{margin:2.5rem 0;color:inherit}
.ak-rel-h{margin:0 0 .75rem}
.ak-rel ul{display:grid;grid-template-columns:1fr;gap:10px;margin:0;padding:0;list-style:none}
@media (min-width:40rem){.ak-rel ul{grid-template-columns:repeat(2,minmax(0,1fr))}.ak-rel-lead{grid-column:1/-1}}
@media (min-width:64rem){.ak-rel ul{grid-template-columns:repeat(3,minmax(0,1fr))}}
.ak-rel a{display:flex;flex-direction:column;gap:3px;height:100%;min-height:44px;padding:12px 14px;border:1px solid var(--ak-line,color-mix(in srgb,currentColor 16%,transparent));border-radius:var(--ak-radius,12px);color:inherit;text-decoration:none}
.ak-rel a:hover{border-color:color-mix(in srgb,currentColor 45%,transparent)}
.ak-rel a:hover .ak-rel-t{text-decoration:underline;text-underline-offset:.2em}
.ak-rel a:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.ak-rel-l{font-size:.75rem;font-weight:650;letter-spacing:.03em;text-transform:uppercase;opacity:.65}
.ak-rel-t{font-weight:650;line-height:1.3}
.ak-rel-d{font-size:.875rem;line-height:1.45;opacity:.75}
.ak-rel-lead a{padding:16px 18px;background:color-mix(in srgb,currentColor 4%,transparent)}
.ak-rel-lead .ak-rel-t{font-size:1.125rem}
${BRAND_CSS}`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
export default { name: 'related', title: 'Related links', render: renderRelated, css: RELATED_CSS, js: '' };
