// Amili Kit: Comparison table. https://amili.ai/kit#kit-compare
// 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 { renderCompare, COMPARE_CSS, COMPARE_JS } from './kit/compare.mjs';
//   html = `<style>${COMPARE_CSS}</style>` + renderCompare(opts) + `<script>${COMPARE_JS}</script>` // JS only for sorting
//
// opts = {
//   caption: 'Five travel tripods compared',     // required: what the table compares (also the scroll region's name)
//   columns: [{ key: 'weight', label: 'Weight', unit: 'kg', best: 'min', sort: true }, ...],
//                                                 // best: 'min'|'max' marks the best value per column; sort: sortable
//   rows: [{ name: 'Tripod A', href: '/tripod-a/', cells: { weight: 1.2 }, cta: { href: '/go/a', label: 'Check price' } }],
//   rowHeader: 'Model',                           // label of the first column
//   pin: 'first' | 'last' | 'none',               // keep the name (or the buy column) visible while scrolling sideways
//   phone: 'scroll' | 'stack',                    // below 600px: scroll sideways (default) or one card per row
//   sponsored: true,                              // cta links get rel="sponsored nofollow noopener" (affiliate links)
//   from: 'spec-row',                             // data-from on every cta, for a click beacon
//   note: 'Prices change; checked 28 Sep 2026.',  // optional line under the table
// }
// No brand mark: a table with buy links is a buy area.


const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 't';

export function validateCompare(o) {
  const errs = [];
  if (!o?.caption) errs.push('caption is required (it names the table and its scroll region)');
  if (!o?.columns?.length) errs.push('columns: at least one');
  if (!o?.rows?.length || o.rows.length < 2) errs.push('rows: at least two things to compare');
  const keys = new Set((o?.columns || []).map((c) => c.key));
  for (const c of o?.columns || []) {
    if (!c.key || !c.label) errs.push(`column without key/label: ${JSON.stringify(c)}`);
    if (c.best && !['min', 'max'].includes(c.best)) errs.push(`column ${c.key}: best must be min or max`);
  }
  for (const r of o?.rows || []) {
    if (!r.name) errs.push('row without name');
    for (const k of Object.keys(r.cells || {})) if (!keys.has(k)) errs.push(`row ${r.name}: unknown column ${k}`);
    if (r.cta && !r.cta.href) errs.push(`row ${r.name}: cta without href`);
  }
  return errs;
}

// The best value per column (numbers only; ties all win). Returns { key: Set(rowIndex) }.
export function bestCells(columns, rows) {
  const out = {};
  for (const c of columns) {
    if (!c.best) continue;
    const vals = rows.map((r, i) => [typeof r.cells?.[c.key] === 'number' ? r.cells[c.key] : NaN, i]).filter(([v]) => Number.isFinite(v));
    if (vals.length < 2) continue;
    const target = c.best === 'min' ? Math.min(...vals.map(([v]) => v)) : Math.max(...vals.map(([v]) => v));
    out[c.key] = new Set(vals.filter(([v]) => v === target).map(([, i]) => i));
  }
  return out;
}

const fmt = (v, c) => (v == null || v === '' ? '<span class="ak-cmp-na">&ndash;<span class="ak-vh"> not listed</span></span>' : typeof v === 'boolean' ? (v ? 'Yes' : 'No') : esc(v) + (c.unit && typeof v === 'number' ? `&nbsp;${esc(c.unit)}` : ''));

export function renderCompare(o) {
  const errs = validateCompare(o);
  if (errs.length) throw new Error(`Amili Kit compare: ${errs.join('; ')}`);
  const id = `ak-cmp-${slug(o.caption)}`, best = bestCells(o.columns, o.rows);
  const hasCta = o.rows.some((r) => r.cta);
  const rel = o.sponsored === false ? 'noopener' : 'sponsored nofollow noopener';
  const sortBtn = (c, label) => (c.sort ? `<button type="button" class="ak-cmp-sort" data-k="${esc(c.key)}">${label}<span aria-hidden="true" class="ak-cmp-arrow"></span></button>` : label);
  const head = `<tr><th scope="col">${esc(o.rowHeader || 'Name')}</th>${o.columns.map((c) => `<th scope="col"${c.sort ? ' aria-sort="none"' : ''}>${sortBtn(c, esc(c.label) + (c.unit ? ` <span class="ak-cmp-unit">(${esc(c.unit)})</span>` : ''))}</th>`).join('')}${hasCta ? '<th scope="col"><span class="ak-vh">Where to buy</span></th>' : ''}</tr>`;
  const body = o.rows.map((r, i) => {
    const name = r.href ? `<a href="${esc(r.href)}">${esc(r.name)}</a>` : esc(r.name);
    const cells = o.columns.map((c) => {
      const v = r.cells?.[c.key], isBest = best[c.key]?.has(i);
      const sv = typeof v === 'number' ? ` data-v="${v}"` : v == null ? '' : ` data-v="${esc(String(v).toLowerCase())}"`;
      return `<td data-label="${esc(c.label)}"${sv}${isBest ? ' class="ak-cmp-best"' : ''}>${fmt(v, c)}${isBest ? '<span class="ak-cmp-tag">Best</span>' : ''}</td>`;
    }).join('');
    const cta = hasCta ? `<td class="ak-cmp-cta">${r.cta ? `<a href="${esc(r.cta.href)}" rel="${rel}"${o.from ? ` data-from="${esc(o.from)}"` : ''}${r.cta.target ? ` target="${esc(r.cta.target)}"` : ''}>${esc(r.cta.label || 'Check price')}<span class="ak-vh"> for ${esc(r.name)}</span></a>` : ''}</td>` : '';
    return `<tr><th scope="row">${name}</th>${cells}${cta}</tr>`;
  }).join('');
  const pin = o.pin === 'none' ? '' : o.pin === 'last' && hasCta ? ' ak-pin-last' : ' ak-pin-first';
  const phone = o.phone === 'stack' ? ' ak-cmp-stack' : '';
  return `<figure class="ak-cmp${phone}"><div class="ak-cmp-wrap" role="region" aria-labelledby="${id}" tabindex="0">`
    + `<table class="ak-cmp-t${pin}"><caption id="${id}">${esc(o.caption)}</caption><thead>${head}</thead><tbody>${body}</tbody></table></div>`
    + (o.phone === 'stack' ? '' : '<p class="ak-cmp-hint" aria-hidden="true">Swipe the table sideways to see every column.</p>')
    + (o.note ? `<figcaption class="ak-cmp-note">${esc(o.note)}</figcaption>` : '') + `</figure>`;
}

export const COMPARE_CSS = `.ak-cmp{margin:1.5rem 0;max-width:100%;--ak-cmp-bg:var(--ak-bg,Canvas);--ak-cmp-line:var(--ak-line,color-mix(in srgb,currentColor 14%,transparent))}
.ak-cmp-wrap{position:relative;overflow-x:auto;-webkit-overflow-scrolling:touch;border:1px solid var(--ak-cmp-line);border-radius:var(--ak-radius,12px);background:var(--ak-cmp-bg);color:var(--ak-fg,inherit)}
.ak-cmp-wrap:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.ak-cmp-t{border-collapse:separate;border-spacing:0;width:100%;min-width:34rem;font-size:.9375rem;line-height:1.4}
.ak-cmp-t caption{caption-side:top;text-align:left;padding:.75rem 1rem .25rem;font-weight:600}
.ak-cmp-t th,.ak-cmp-t td{padding:.7rem 1rem;text-align:left;vertical-align:top;border-bottom:1px solid var(--ak-cmp-line)}
.ak-cmp-t thead th{font-size:.8125rem;font-weight:650;letter-spacing:.01em;background:color-mix(in srgb,currentColor 5%,var(--ak-cmp-bg));white-space:nowrap}
.ak-cmp-t tbody tr:last-child>*{border-bottom:0}
.ak-cmp-t tbody th{font-weight:650}
.ak-cmp-t td[data-v]{font-variant-numeric:tabular-nums}
.ak-cmp-t a{color:inherit;text-underline-offset:.2em}
.ak-cmp-t tbody th a{display:inline-flex;align-items:center;min-height:44px;margin:-.7rem 0}
.ak-pin-first tr>:first-child{position:sticky;left:0;z-index:1;background:var(--ak-cmp-bg);box-shadow:8px 0 8px -8px color-mix(in srgb,currentColor 30%,transparent)}
.ak-pin-first thead tr>:first-child{background:color-mix(in srgb,currentColor 5%,var(--ak-cmp-bg))}
.ak-pin-last tr>:last-child{position:sticky;right:0;z-index:1;background:var(--ak-cmp-bg);box-shadow:-8px 0 8px -8px color-mix(in srgb,currentColor 30%,transparent)}
.ak-cmp-best{font-weight:650}
.ak-cmp-tag{display:inline-block;margin-left:.4em;padding:0 .4em;border-radius:4px;font-size:.6875rem;font-weight:650;line-height:1.5;vertical-align:.1em;background:color-mix(in srgb,var(--ak-good,#2f7d4f) 16%,transparent);color:inherit}
.ak-cmp-na{opacity:.5}
.ak-cmp-unit{font-weight:400;opacity:.7}
.ak-cmp-cta a{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0 1rem;margin:-.35rem 0;border-radius:10px;background:var(--ak-accent,#b45309);color:var(--ak-on-accent,#fff);font-weight:650;text-decoration:none;white-space:nowrap}
.ak-cmp-cta a:hover{filter:brightness(1.08)}
.ak-cmp-cta a:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.ak-cmp-sort{display:inline-flex;align-items:center;gap:.35em;min-height:44px;margin:-.7rem 0;padding:0;border:0;background:none;color:inherit;font:inherit;cursor:pointer}
.ak-cmp-arrow{width:0;height:0;border:4px solid transparent;border-top-color:currentColor;margin-top:4px;opacity:.35}
[aria-sort=ascending] .ak-cmp-arrow{border-top-color:transparent;border-bottom-color:currentColor;margin:-4px 0 0;opacity:1}
[aria-sort=descending] .ak-cmp-arrow{opacity:1}
.ak-cmp-hint,.ak-cmp-note{margin:.5rem 0 0;font-size:.8125rem;opacity:.7}
.ak-vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
@media (min-width:48rem){.ak-cmp-hint{display:none}}
@media (max-width:37.5rem){.ak-cmp-stack .ak-cmp-t{min-width:0}.ak-cmp-stack thead{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
.ak-cmp-stack .ak-cmp-t,.ak-cmp-stack tbody,.ak-cmp-stack tr,.ak-cmp-stack th,.ak-cmp-stack td{display:block}
.ak-cmp-stack tr{border-bottom:1px solid var(--ak-cmp-line);padding:.5rem 0}.ak-cmp-stack tbody tr:last-child{border-bottom:0}
.ak-cmp-stack td,.ak-cmp-stack tbody th{border:0;padding:.3rem 1rem;position:static;box-shadow:none}
.ak-cmp-stack td[data-label]::before{content:attr(data-label) ": ";font-weight:600;opacity:.7}
.ak-cmp-stack .ak-cmp-cta{padding-top:.5rem}}
@media print{.ak-cmp-wrap{overflow:visible}.ak-cmp-hint,.ak-cmp-cta{display:none}}`;

// Optional: click a sortable header to sort (numbers numerically, text alphabetically; empty cells last). Without this
// script the table is complete and readable; sorting is the only thing it adds.
export const COMPARE_JS = `(function(){"use strict";
function sort(btn){var th=btn.closest("th"),tr=th.parentNode,table=th.closest("table"),col=Array.prototype.indexOf.call(tr.children,th),
dir=th.getAttribute("aria-sort")==="ascending"?"descending":"ascending",tb=table.tBodies[0],rows=Array.prototype.slice.call(tb.rows);
Array.prototype.forEach.call(tr.children,function(h){if(h.hasAttribute("aria-sort"))h.setAttribute("aria-sort","none")});
th.setAttribute("aria-sort",dir);
rows.sort(function(a,b){var x=a.cells[col].getAttribute("data-v"),y=b.cells[col].getAttribute("data-v");
if(x===null&&y===null)return 0;if(x===null)return 1;if(y===null)return -1;
var nx=parseFloat(x),ny=parseFloat(y),c=(!isNaN(nx)&&!isNaN(ny))?nx-ny:x.localeCompare(y);return dir==="ascending"?c:-c});
rows.forEach(function(r){tb.appendChild(r)})}
document.addEventListener("click",function(e){var b=e.target.closest&&e.target.closest(".ak-cmp-sort");if(b)sort(b)});
})();`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
export default { name: 'compare', title: 'Comparison table', render: renderCompare, css: COMPARE_CSS, js: COMPARE_JS };
