// Amili Kit: Sticky buy bar. https://amili.ai/kit#kit-buybar
// 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 { renderBuyBar, BUYBAR_CSS, BUYBAR_JS } from './kit/buybar.mjs';
//   html = `<style>${BUYBAR_CSS}</style>` + renderBuyBar(opts) + `<script>${BUYBAR_JS}</script>` // JS is optional
//
// opts = {
//   name: 'Sherpa Original Deluxe',  // required: what the button buys (short)
//   href: '/go/sherpa',              // required: your own link or affiliate gate
//   label: 'Check price',            // button text (never a price you cannot keep fresh)
//   note: 'Affiliate link',          // small line under the name; '' hides it (keep it if the link earns you money)
//   img: { src, width: 32, height: 32 }, // optional thumbnail (fixed size: no layout shift)
//   mode: 'sticky' | 'fixed',        // sticky: sits in the page flow at the end of your content (default)
//                                    // fixed: pinned to the screen from the first paint, page padded so nothing is covered
//   phoneOnly: true,                 // hide from 768px up (desktop has the in-page button in view)
//   sponsored: true,                 // rel="sponsored nofollow noopener"
//   from: 'sticky-bar',              // data-from, for a click beacon
//   hideWhen: '#buy',                // with BUYBAR_JS: fade out while this element is on screen (no duplicate buttons)
//   closable: true,                  // with BUYBAR_JS: a close button; closed stays closed for the visit
// }
// No brand mark: this is a buy area. Put it once per page, at the end of the main content (sticky mode needs that).


const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const PRICE = /[$\u20ac\u00a3\u00a5]\s?\d|\d\s?(usd|eur|gbp)\b/i;

export function validateBuyBar(o) {
  const errs = [];
  if (!o?.name) errs.push('name is required');
  if (!o?.href) errs.push('href is required');
  if (o?.label && PRICE.test(o.label)) errs.push('label must not carry a price (prices go stale; say "Check price")');
  if (o?.img && !(o.img.width && o.img.height)) errs.push('img needs width and height (no layout shift)');
  if (o?.mode && !['sticky', 'fixed'].includes(o.mode)) errs.push('mode must be sticky or fixed');
  return errs;
}

export function renderBuyBar(o) {
  const errs = validateBuyBar(o);
  if (errs.length) throw new Error(`Amili Kit buy bar: ${errs.join('; ')}`);
  const cls = ['ak-bb', o.mode === 'fixed' ? 'ak-bb-fixed' : '', o.phoneOnly === false ? '' : 'ak-bb-phone'].filter(Boolean).join(' ');
  const rel = o.sponsored === false ? 'noopener' : 'sponsored nofollow noopener';
  const img = o.img ? `<img src="${esc(o.img.src)}" width="${+o.img.width}" height="${+o.img.height}" alt="" loading="lazy" decoding="async">` : '';
  const note = o.note === '' ? '' : `<span class="ak-bb-d">${esc(o.note || 'Affiliate link')}</span>`;
  const close = o.closable === false ? '' : '<button type="button" class="ak-bb-x" aria-label="Close" hidden><span aria-hidden="true">&times;</span></button>';
  return `<aside class="${cls}" aria-label="Buy ${esc(o.name)}"${o.hideWhen ? ` data-hide-when="${esc(o.hideWhen)}"` : ''}><div class="ak-bb-in">${img}`
    + `<span class="ak-bb-t"><span class="ak-bb-n">${esc(o.name)}</span>${note}</span>`
    + `<a class="ak-bb-b" href="${esc(o.href)}" rel="${rel}"${o.from === '' ? '' : ` data-from="${esc(o.from || 'sticky-bar')}"`}>${esc(o.label || 'Check price')}<span class="ak-bb-vh"> for ${esc(o.name)}</span></a>`
    + `${close}</div></aside>`;
}

export const BUYBAR_CSS = `.ak-bb{position:sticky;bottom:0;z-index:40;margin:1.5rem 0 0;padding:0 1rem env(safe-area-inset-bottom,0px);background:var(--ak-bg,Canvas);color:var(--ak-fg,CanvasText);border-top:1px solid var(--ak-line,color-mix(in srgb,currentColor 14%,transparent));box-shadow:0 -6px 16px rgba(0,0,0,.08);transition:opacity .2s,visibility .2s}
.ak-bb-in{display:flex;align-items:center;gap:10px;min-height:56px;max-width:var(--ak-max,60rem);margin:0 auto;padding:6px 0}
.ak-bb img{width:32px;height:32px;flex:0 0 32px;object-fit:contain}
.ak-bb-t{flex:1 1 auto;min-width:0}
.ak-bb-n{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;font-size:.95rem;line-height:1.2}
.ak-bb-d{display:block;margin-top:1px;font-size:.7rem;line-height:1.3;opacity:.7}
.ak-bb-b{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;min-height:44px;min-width:44px;padding:0 16px;border-radius:10px;background:var(--ak-accent,#b45309);color:var(--ak-on-accent,#fff);font-weight:700;font-size:.9rem;text-decoration:none;white-space:nowrap}
.ak-bb-b:hover{filter:brightness(1.08)}
.ak-bb-b:focus-visible,.ak-bb-x:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.ak-bb-x{flex:0 0 auto;width:44px;height:44px;margin-right:-10px;border:0;background:none;color:inherit;font-size:22px;line-height:1;cursor:pointer;opacity:.6}
.ak-bb-vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.ak-bb.ak-bb-fixed{position:fixed;left:0;right:0;margin:0}
body:has(.ak-bb-fixed:not(.ak-bb-off)){padding-bottom:calc(64px + env(safe-area-inset-bottom,0px))}
.ak-bb.ak-bb-hide{opacity:0;visibility:hidden}
.ak-bb.ak-bb-off{display:none}
@media (min-width:48rem){.ak-bb.ak-bb-phone{display:none}body:has(.ak-bb-fixed.ak-bb-phone){padding-bottom:0}}
@media (prefers-reduced-motion:reduce){.ak-bb{transition:none}}
@media print{.ak-bb{display:none}}`;

// Optional. Fades the bar out while the hideWhen element is on screen (visibility, so nothing moves) and wires the
// close button; closed stays closed for the rest of the visit (sessionStorage, no cookie).
export const BUYBAR_JS = `(function(){"use strict";
var KEY="ak-bb-closed";function closed(){try{return sessionStorage.getItem(KEY)==="1"}catch(e){return false}}
document.querySelectorAll(".ak-bb").forEach(function(bar){
if(closed()){bar.classList.add("ak-bb-off");return}
var x=bar.querySelector(".ak-bb-x");if(x){x.hidden=false;x.addEventListener("click",function(){bar.classList.add("ak-bb-off");try{sessionStorage.setItem(KEY,"1")}catch(e){}})}
var sel=bar.getAttribute("data-hide-when"),t=sel&&document.querySelector(sel);
if(t&&"IntersectionObserver"in window){new IntersectionObserver(function(es){es.forEach(function(e){bar.classList.toggle("ak-bb-hide",e.isIntersecting)})}).observe(t)}
});})();`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
export default { name: 'buybar', title: 'Sticky buy bar', render: renderBuyBar, css: BUYBAR_CSS, js: BUYBAR_JS };
