// Amili Kit: footer. https://amili.ai/kit
// SPDX-License-Identifier: MIT. Copyright (c) 2026 Amili (Paulo de Vries). Made by Amili.
//
// One config object -> one <footer class="ak-footer"> + under 3 KB of CSS. No JS, no images, no fonts, no layout shift.
// Colours inherit your text colour, so light and dark follow your site; pin any of
// --ak-fg --ak-muted --ak-line --ak-bg --ak-link --ak-max to override.
//
//   import { renderFooter, FOOTER_CSS } from './footer.mjs';
//   html = `...<style>${FOOTER_CSS}</style>...` + renderFooter(cfg)
//
// cfg = {
//   site: 'Example Site',                        // required, display name
//   url: 'https://example.com',                  // required, your origin
//   purpose: 'What this site is for.',           // required, one line
//   links: [{ href, label }],                    // top sections, max 6 (throws above 6)
//   more: [{ href, label }],                     // every other link your old footer carried
//   notes: ['plain text'] | notesHtml: ['<a>'],  // short paragraphs (method, sources)
//   disclosure: 'exact text' | disclosureHtml,   // affiliate disclosure, your own wording, verbatim
//   amazon: true,                                // asserts a disclosure is present (throws if missing)
//   trust: { business, address, kvk, btw, email, contactHref, aboutHref },
//   legal: [{ href, label }],                    // privacy, terms
//   cookie: { attrs: 'data-cc="show"', label },  // only if you already have a consent script
//   updated: '2026-09-28',                       // data sites: "Data last updated"
//   languages: [{ href, label, hreflang, current }],
//   lang: 'en' | 'nl', labels: { ... }, year: 2026,
//   credit: true,                                // "Made with Amili Kit" link; false hides it
// }

const L = {
  en: { explore: 'Explore', more: 'More', legal: 'Legal', updated: 'Data last updated', credit: 'Made with Amili Kit · Join the Amili beta', madeBy: 'Website by', madeHook: 'Want one like this?', lang: 'Language', cookie: 'Cookie settings', kvk: 'KvK', btw: 'VAT' },
  nl: { explore: 'Ontdek', more: 'Meer', legal: 'Juridisch', updated: 'Gegevens bijgewerkt', credit: 'Gemaakt met Amili Kit', madeBy: 'Website door', madeHook: 'Ook zo’n site?', lang: 'Taal', cookie: 'Cookie-instellingen', kvk: 'KvK', btw: 'btw' },
};
const MONTHS = { en: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], nl: ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'] };
// Amazon Associates Dos and Don'ts > Amazon Trademarks (read 2026-10-02): this exact line belongs on the site.
export const AMAZON_TM = 'Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.';
const EMOJI = /\p{Extended_Pictographic}/u;

const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const a = (l, cls = '') => `<a href="${esc(l.href)}"${cls ? ` class="${cls}"` : ''}${l.rel ? ` rel="${esc(l.rel)}"` : ''}${l.hreflang ? ` hreflang="${esc(l.hreflang)}"` : ''}${l.current ? ' aria-current="true"' : ''}>${esc(l.label)}</a>`;
const li = (arr) => arr.map((l) => `<li>${a(l)}</li>`).join('');

export function validateFooterConfig(cfg) {
  const errs = [];
  const cr = cfg?.credit;
  if (cr && typeof cr === 'object') {
    if (cr.mode !== 'client') errs.push(`credit.mode must be 'client', got ${cr.mode}`);
    if (cr.tone && !['light', 'dark'].includes(cr.tone)) errs.push(`credit.tone must be light|dark, got ${cr.tone}`);
    if (cr.style && !['standard', 'quiet', 'plain', 'invite'].includes(cr.style)) errs.push(`credit.style must be standard|quiet|plain|invite, got ${cr.style}`);
    if (cr.href && !/^https:\/\//.test(cr.href)) errs.push(`credit.href must be https, got ${cr.href}`);
  }
  for (const k of ['site', 'url', 'purpose']) if (!cfg?.[k]) errs.push(`missing ${k}`);
  if ((cfg?.links || []).length > 6) errs.push(`links: ${cfg.links.length} > 6 (move the rest to more[])`);
  if (cfg?.amazon && !cfg.disclosure && !cfg.disclosureHtml) errs.push('amazon: true but no disclosure');
  if (cfg?.trademark && !cfg.amazon) errs.push('trademark: true needs amazon: true');
  if (cfg?.updated && !/^\d{4}-\d{2}-\d{2}/.test(cfg.updated)) errs.push(`updated must be ISO yyyy-mm-dd, got ${cfg.updated}`);
  const texts = [cfg?.site, cfg?.purpose, ...(cfg?.links || []).map((l) => l.label), ...(cfg?.more || []).map((l) => l.label), ...(cfg?.legal || []).map((l) => l.label)];
  for (const t of texts) if (t && EMOJI.test(t)) errs.push(`emoji in footer text: ${t}`);
  for (const l of [...(cfg?.links || []), ...(cfg?.more || []), ...(cfg?.legal || [])]) if (!l?.href || !l?.label) errs.push(`link without href/label: ${JSON.stringify(l)}`);
  return errs;
}

// The fleet credit (Paulo mv2k1cipuh9d1z + BRAND-SPREAD.md rule 2): the page where a site is ordered, nofollow on every page of
// every site because the same link from dozens of owned sites to one domain reads as a link scheme. A followed credit, if any,
// is one contextual line on a site's about page, never this footer. Always the address as the anchor, so labels cannot change it.
export const CREDIT_URL = { en: 'https://amili.ai/pricing', nl: 'https://amili.ai/nl/prijzen' };
export function creditHref(url, lang = 'en') {
  const host = new URL(url).hostname.replace(/^www\./, '');
  return `${CREDIT_URL[lang] || CREDIT_URL.en}?utm_source=${encodeURIComponent(host)}&utm_medium=footer&utm_campaign=brand-spread`;
}

// ---- CLIENT CREDIT (Kit 1.14.0, Paulo 2026-10-13) ------------------------------------------------------------------
// One line under a client site's footer, one link (44px), in the footer's muted colour. Three styles (credit.style), chosen
// per client after a 20-owner panel (Paulo 2026-10-13: "Iedere klant moet dit ok vinden"; panel log kept
// in the private Amili state, not published):
//   standard (default) "Website door amili✱", the mint asterisk breathes very calmly (opacity only, 6.5 s): alive, never loud
//   quiet              same words, the asterisk static and in the text colour (no motion, no brand colour: lawyer,
//                      dentist, therapist, accountant, architect).
//   plain              "Website door Amili" as plain text in the site's own font, no mark, no link (notary, lawyer, a
//                      broker who wants no outgoing link). A client who wants no credit at all: credit: false.
//   invite             "Website door amili✱ · Ook zo’n site? →": the hook a step brighter + a livelier breath (4.6 s, scale
//                      + opacity); only for a client who said yes to it (it gets the most clicks, and the most refusals)
// Every animation is transform/opacity only and static under prefers-reduced-motion. Opens in a new tab (the client keeps their visitor). rel="nofollow": the same credit on many client sites is a
// "widely distributed footer link" in Google's link-spam policy, so it must not pass ranking; clicks are what it is for.
// data-amili-credit lets a client site's own analytics count the click without any tracker added for it.
// ONE place to change where it points (a "Gemaakt door Amili" landing page later): CLIENT_CREDIT_URL; a site may pass href.
export const CLIENT_CREDIT_URL = { en: 'https://amili.ai/', nl: 'https://amili.ai/nl/' };
export function clientCreditHref(url, lang = 'en', { href, campaign = 'client-credit' } = {}) {
  const host = new URL(url).hostname.replace(/^www\./, '');
  const u = new URL(href || CLIENT_CREDIT_URL[lang] || CLIENT_CREDIT_URL.en);
  u.searchParams.set('utm_source', host); u.searchParams.set('utm_medium', 'footer'); u.searchParams.set('utm_campaign', campaign);
  return u.href;
}
// The amili asterisk: the app icon's exact six-petal spark (favicon.svg group translate(426 122) scale(66)), as inline SVG so
// it needs no mask support and no CSS to keep its size. Class amili-mark-dot: the wordmark rule of amili-ui-gate (R) looks for it.
const STAR_SVG = '<svg class="amili-mark-dot" viewBox="-1 -1 2 2" width="10" height="10" aria-hidden="true" focusable="false"><g stroke="currentColor" stroke-width=".58" stroke-linecap="round"><path d="M0 0L.184-.686M0 0L.686-.184M0 0L.502.502M0 0L-.184.686M0 0L-.686.184M0 0L-.502-.502"/></g><circle r=".319" fill="currentColor"/></svg>';
const ARROW_SVG = '<svg class="ak-made-arrow" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false"><path d="M3 8h9M8.5 4.5 12 8l-3.5 3.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
function renderClientCredit(cfg, t) {
  const cr = cfg.credit;
  const href = clientCreditHref(cfg.url, cfg.lang, cr);
  const style = cr.style || 'standard';
  if (style === 'plain') return `<div class="ak-made ak-made--${cr.tone === 'dark' ? 'dark' : 'light'} ak-made--plain"><p class="ak-made-a">${esc(t.madeBy)} Amili</p></div>`;
  const hook = style === 'invite' ? ` <span class="ak-made-sep" aria-hidden="true">·</span> <span class="ak-made-hook">${esc(t.madeHook)}${ARROW_SVG}</span>` : '';
  return `<div class="ak-made ak-made--${cr.tone === 'dark' ? 'dark' : 'light'} ak-made--${style}"><a class="ak-made-a" href="${esc(href)}" target="_blank" rel="noopener nofollow" data-amili-credit="client-footer">`
    + `<span class="ak-made-by">${esc(t.madeBy)}</span> <span class="amili-mark" role="img" aria-label="Amili">amili${STAR_SVG}</span>${hook}</a></div>`;
}

export function renderFooter(cfg) {
  const errs = validateFooterConfig(cfg);
  if (errs.length) throw new Error(`Amili Kit footer config for ${cfg?.site || '?'}: ${errs.join('; ')}`);
  const t = { ...(L[cfg.lang] || L.en), ...(cfg.labels || {}) };
  const year = cfg.year || new Date().getFullYear();
  const parts = [];

  parts.push(`<div class="ak-top"><div class="ak-id"><p class="ak-name">${esc(cfg.site)}</p><p class="ak-purpose">${esc(cfg.purpose)}</p></div>`
    + (cfg.links?.length ? `<nav class="ak-nav" aria-label="${esc(t.explore)}"><ul>${li(cfg.links)}</ul></nav>` : '') + '</div>');

  if (cfg.more?.length) parts.push(`<nav class="ak-more" aria-label="${esc(t.more)}"><ul>${li(cfg.more)}</ul></nav>`);
  for (const n of cfg.notes || []) parts.push(`<p class="ak-note">${esc(n)}</p>`);
  for (const n of cfg.notesHtml || []) parts.push(`<p class="ak-note">${n}</p>`);
  if (cfg.disclosure || cfg.disclosureHtml) parts.push(`<p class="ak-disc">${cfg.disclosureHtml || esc(cfg.disclosure)}</p>`);
  if (cfg.trademark) parts.push(`<p class="ak-disc ak-tm">${AMAZON_TM}</p>`);

  const tr = cfg.trust;
  if (tr) {
    const bits = [];
    if (tr.business) bits.push(`<span>${esc(tr.business)}</span>`);
    if (tr.address) bits.push(`<span>${esc(tr.address)}</span>`);
    if (tr.kvk) bits.push(`<span>${esc(t.kvk)} ${esc(tr.kvk)}</span>`);
    if (tr.btw) bits.push(`<span>${esc(t.btw)} ${esc(tr.btw)}</span>`);
    if (tr.email) bits.push(`<a href="mailto:${esc(tr.email)}">${esc(tr.email)}</a>`);
    if (tr.aboutHref) bits.push(a({ href: tr.aboutHref, label: tr.aboutLabel || 'About' }));
    if (tr.contactHref) bits.push(a({ href: tr.contactHref, label: tr.contactLabel || 'Contact' }));
    if (bits.length) parts.push(`<p class="ak-trust">${bits.join('')}</p>`);
  }

  const bottom = [`<span>&copy; ${year} ${esc(cfg.site)}</span>`];
  if (cfg.updated) {
    const [y, m, d] = cfg.updated.slice(0, 10).split('-').map(Number);
    const mo = (MONTHS[cfg.lang] || MONTHS.en)[m - 1];
    bottom.push(`<span>${esc(t.updated)} <time datetime="${esc(cfg.updated.slice(0, 10))}">${d} ${mo} ${y}</time></span>`);
  }
  const legal = [...(cfg.legal || []).map((l) => `<li>${a(l)}</li>`)];
  if (cfg.cookie) legal.push(`<li><button type="button" class="ak-btn" ${cfg.cookie.attrs || ''}>${esc(cfg.cookie.label || t.cookie)}</button></li>`);
  if (legal.length) bottom.push(`<ul class="ak-legal" aria-label="${esc(t.legal)}">${legal.join('')}</ul>`);
  if (cfg.languages?.length) bottom.push(`<ul class="ak-lang" aria-label="${esc(t.lang)}">${li(cfg.languages)}</ul>`);
  const client = cfg.credit && typeof cfg.credit === 'object';
  if (cfg.credit !== false && !client) bottom.push(`<a class="ak-credit" href="${esc(creditHref(cfg.url, cfg.lang))}" rel="nofollow noopener">${esc((L[cfg.lang] || L.en).credit)}</a>`);
  parts.push(`<div class="ak-bottom">${bottom.join('')}</div>`);
  if (client) parts.push(renderClientCredit(cfg, t));

  return `<footer class="ak-footer"><div class="ak-in">${parts.join('')}</div></footer>`;
}

// Keep under 3 KB (footer.test.mjs asserts it). Inherits colour; 44px targets; one column at 375px, no JS, no layout shift.
export const FOOTER_CSS = `.ak-footer{margin-top:3rem;padding:2rem 1rem 1.25rem;border-top:1px solid;border-color:var(--ak-line,color-mix(in srgb,currentColor 16%,transparent));background:var(--ak-bg,transparent);color:var(--ak-fg,inherit);font-size:.9375rem;line-height:1.55;text-align:left}
.ak-footer *{box-sizing:border-box}
.ak-footer nav{display:block;margin:0;padding:0;overflow:visible;font-size:inherit}
.ak-footer nav a{padding:0;margin:0;border-radius:0;white-space:normal;min-height:44px}
.ak-footer li{margin:0;max-width:none}
.ak-footer ul{margin:0;padding:0;list-style:none}
.ak-in{max-width:var(--ak-max,72rem);margin:0 auto;display:grid;gap:1rem}
.ak-footer p{margin:0}
.ak-footer a,.ak-btn{color:var(--ak-link,inherit);text-decoration:underline;text-decoration-color:var(--ak-line,color-mix(in srgb,currentColor 35%,transparent));text-underline-offset:.2em}
.ak-footer li>a,.ak-trust>a,.ak-credit,.ak-btn{display:inline-flex;align-items:center;min-height:44px}
.ak-footer a:hover,.ak-btn:hover{text-decoration-color:currentColor}
.ak-footer a:focus-visible,.ak-btn:focus-visible{outline:2px solid currentColor;outline-offset:2px;border-radius:2px}
.ak-top{display:grid;gap:.75rem}
.ak-name{font-weight:650;font-size:1.0625rem}
.ak-purpose,.ak-note,.ak-disc,.ak-trust,.ak-bottom{color:var(--ak-muted,color-mix(in srgb,currentColor 74%,transparent))}
.ak-nav ul{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:1rem}
.ak-more ul,.ak-legal,.ak-lang{display:flex;flex-wrap:wrap;column-gap:1.25rem}
.ak-legal li{display:flex}
.ak-note,.ak-disc{font-size:.875rem;max-width:62ch}
.ak-note a{display:inline-block;padding:14px 0;margin:-14px 0}
.ak-trust{font-size:.875rem;display:flex;flex-wrap:wrap;column-gap:1rem;align-items:center}
.ak-trust>span{min-height:44px;display:inline-flex;align-items:center}
.ak-bottom{font-size:.8125rem;display:flex;flex-wrap:wrap;align-items:center;column-gap:1.25rem;border-top:1px solid;border-color:var(--ak-line,color-mix(in srgb,currentColor 12%,transparent));padding-top:.5rem}
.ak-btn{background:none;border:0;padding:0;font:inherit;cursor:pointer}
.ak-lang [aria-current]{font-weight:650;text-decoration:none}
.ak-credit{margin-left:auto}
@media (min-width:48rem){.ak-top{grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);gap:2rem}.ak-nav ul{grid-template-columns:repeat(3,minmax(0,1fr))}}`;

// The client credit's CSS: only on sites that use credit: { mode: 'client' }. No url(), < 1.5 KB (footer.test.mjs).
// The asterisk breathes by transform + opacity (compositor only, no layout shift); --ak-mark overrides its colour
// (tone light = #34936F, 3.5:1 on white; tone dark = #ABE7CE, the app's mint).
export const CLIENT_CREDIT_CSS = `.ak-made{max-width:var(--ak-max,72rem);margin:0 auto;padding:0 1rem calc(1rem + env(safe-area-inset-bottom));display:flex;--ak-mk:var(--ak-mark,#34936F)}
.ak-made--dark{--ak-mk:var(--ak-mark,#ABE7CE)}
.ak-footer .ak-made{margin:-.5rem 0 0;padding:0}
.ak-made-a{display:inline-flex;flex-wrap:wrap;align-items:center;gap:.25rem .5rem;min-height:44px;padding:.375rem 0;color:var(--ak-muted,color-mix(in srgb,currentColor 74%,transparent));text-decoration:none;font-size:.75rem;line-height:1.3;letter-spacing:.01em}
.ak-footer .ak-made-a{text-decoration:none;color:color-mix(in srgb,var(--ak-muted,currentColor) 82%,transparent)}
.ak-made .amili-mark{display:inline-flex;align-items:flex-start;gap:.06em;color:var(--ak-fg,currentColor);font:700 .9375rem/1 "Iowan Old Style",Charter,Georgia,"Times New Roman",serif;letter-spacing:-.005em;white-space:nowrap}
.ak-made .amili-mark-dot{display:block;flex:0 0 auto;width:.56em;height:.56em;margin-top:-.02em;color:var(--ak-mk);background:none;border-radius:0;transform-origin:50% 50%;animation:ak-breathe 4.6s ease-in-out infinite}
@keyframes ak-breathe{0%,100%{transform:scale(.9);opacity:.75}50%{transform:scale(1.05);opacity:1}}
.ak-made--standard .amili-mark-dot{animation:ak-breathe-calm 6.5s ease-in-out infinite}
@keyframes ak-breathe-calm{0%,100%{opacity:.6}50%{opacity:1}}
.ak-made--quiet .amili-mark-dot{animation:none;color:inherit}
.ak-made--standard .amili-mark,.ak-made--quiet .amili-mark{color:inherit}
.ak-made-a:hover .amili-mark{color:var(--ak-fg,currentColor)}
.ak-made-sep{opacity:.6}
.ak-made--plain .ak-made-a{margin:0}
.ak-made-hook{display:inline-flex;align-items:center;gap:.25rem;color:var(--ak-fg,currentColor);border-bottom:1px solid var(--ak-line,color-mix(in srgb,currentColor 30%,transparent));padding-bottom:1px}
.ak-made-arrow{transition:transform .15s}
.ak-made-a:hover .ak-made-hook{border-bottom-color:var(--ak-mk)}
.ak-made-a:hover .ak-made-arrow{transform:translateX(3px)}
.ak-made-a:focus-visible{outline:2px solid currentColor;outline-offset:2px;border-radius:2px}
@media (min-width:48rem){.ak-made{justify-content:flex-end}}
@media (prefers-reduced-motion:reduce){.ak-made .amili-mark-dot{animation:none;transform:none;opacity:1}.ak-made-arrow{transition:none}}`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
export default { name: 'footer', title: 'Footer', render: renderFooter, css: FOOTER_CSS, js: '' };
