// app.mjs: draws the three instruments on /strata/what-is-umami/. All arithmetic is in engine.mjs.
import { equivalent, multiplier, split, bestSplit, occupancy, crossover, LAWS, GAMMA_IMP } from './engine.mjs';

const NS = 'http://www.w3.org/2000/svg';
const $ = (id) => document.getElementById(id);
const el = (tag, attrs = {}, parent) => {
  const n = document.createElementNS(NS, tag);
  for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
  if (parent) parent.appendChild(n);
  return n;
};
const fmt = (x, d = 3) => (Math.abs(x) >= 100 ? x.toFixed(0) : Math.abs(x) >= 10 ? x.toFixed(1) : x.toFixed(d));
const g100 = (x) => `${fmt(x, 3)} g per 100 ml`;

// ------------------------------------------------------------------ 1. the mixing bench
const U_MAX = 0.1, V_MAX = 0.02; // a range we chose; the 1967 panel's own range is in the paywalled paper
function bench() {
  const u = (Number($('u').value) / 1000) * U_MAX;
  const v = (Number($('v').value) / 1000) * V_MAX;
  const y = equivalent(u, v);
  $('u-val').textContent = g100(u);
  $('v-val').textContent = g100(v);
  const svg = $('bench');
  svg.replaceChildren();
  const W = 640, H = 210, L = 170, R = 20, top = 20, row = 44;
  const scale = Math.max(0.05, y * 1.08);
  const x = (val) => L + (val / scale) * (W - L - R);
  const rows = [
    ['MSG alone', u, 'bar-u'],
    ['IMP alone (law: 0)', 0, 'bar-v'],
    ['simply added', u, 'bar-sum'],
    ['the 1967 law', y, 'bar-y'],
  ];
  rows.forEach(([name, val, cls], k) => {
    const yy = top + k * row;
    el('text', { x: L - 10, y: yy + 17, class: "lab big", "text-anchor": "end" }, svg).textContent = name;
    el('rect', { x: L, y: yy, width: Math.max(0, x(val) - L), height: 24, class: cls, rx: 3 }, svg);
    const inside = x(val) + 70 > W;
    el('text', { x: inside ? x(val) - 6 : x(val) + 6, y: yy + 17, class: inside ? 'lab onbar' : 'lab', 'text-anchor': inside ? 'end' : 'start' }, svg).textContent = fmt(val, 4);
  });
  el('text', { x: L, y: H - 6, class: 'tick' }, svg).textContent = 'MSG-equivalent strength, g per 100 ml';
  const times = u > 0 ? y / u : 1;
  $('bench-out').textContent =
    `y = u + ${GAMMA_IMP} u v = ${fmt(u, 4)} + ${GAMMA_IMP} × ${fmt(u, 4)} × ${fmt(v, 4)} = ${fmt(y, 4)}\n` +
    (u === 0 ? 'With no glutamate the formula gives nothing, however much IMP you add.'
      : `${fmt(times, 2)} times as strong as the MSG in it alone; ${fmt(multiplier(u, v), 2)} times the same total weight of plain MSG.`);
  const rowsL = Object.values(LAWS).map((L) => `<tr><td>${L.label}</td><td>${fmt(L.f(u, v), 4)}</td></tr>`);
  $('laws').innerHTML = rowsL.join('');
}

// ------------------------------------------------------------------ 2. how many times stronger?
const C_MIN = 0.005, C_MAX = 0.1;
const cFrom = (s) => C_MIN * Math.pow(C_MAX / C_MIN, Number(s) / 1000);
function curve() {
  const c = cFrom($('c').value);
  $('c-val').textContent = g100(c);
  const svg = $('curve');
  svg.replaceChildren();
  const W = 640, H = 300, L = 54, R = 16, T = 16, B = 44;
  const top = Math.max(2, bestSplit(C_MAX).times * 1.05);
  const X = (f) => L + f * (W - L - R);
  const Y = (m) => T + (1 - m / top) * (H - T - B);
  for (let m = 0; m <= top; m += top > 20 ? 5 : top > 8 ? 2 : 1) {
    el('line', { x1: L, x2: W - R, y1: Y(m), y2: Y(m), class: 'grid' }, svg);
    el('text', { x: L - 8, y: Y(m) + 4, class: 'tick', 'text-anchor': 'end' }, svg).textContent = `${m}×`;
  }
  for (let f = 0; f <= 1.0001; f += 0.25) {
    el('text', { x: X(f), y: H - B + 18, class: 'tick', 'text-anchor': 'middle' }, svg).textContent = `${Math.round(f * 100)}%`;
  }
  el('text', { x: (L + W - R) / 2, y: H - 6, class: 'tick', 'text-anchor': 'middle' }, svg).textContent = 'share of the spoonful that is IMP (the rest is MSG)';
  el('line', { x1: L, x2: W - R, y1: Y(1), y2: Y(1), class: 'axis' }, svg);
  let d = '';
  for (let k = 0; k <= 400; k++) {
    const f = k / 400;
    d += `${k ? 'L' : 'M'}${X(f).toFixed(1)},${Y(split(c, f).times).toFixed(1)}`;
  }
  el('path', { d, class: 'curveline' }, svg);
  const b = bestSplit(c);
  el('line', { x1: X(b.f), x2: X(b.f), y1: Y(0), y2: Y(b.times), class: 'cursor' }, svg);
  el('circle', { cx: X(b.f), cy: Y(b.times), r: 5, class: 'dot' }, svg);
  $('curve-out').textContent =
    `Best split: ${fmt(b.f * 100, 1)}% IMP, ${fmt(b.times, 3)} times the strength of the same weight of plain MSG.\n` +
    `Halve the spoonful (${fmt(c / 2, 4)}) and the best is ${fmt(bestSplit(c / 2).times, 3)} times; double it (${fmt(2 * c, 4)}) and it is ${fmt(bestSplit(2 * c).times, 3)} times` + '.';
}

// ------------------------------------------------------------------ 3. where the product comes from
function receptor() {
  const alpha = Number($('alpha').value);
  $('alpha-val').textContent = `${alpha}×`;
  const svg = $('receptor');
  svg.replaceChildren();
  const W = 640, H = 260, L = 54, R = 16, T = 14, B = 40;
  const gMin = 0.01, gMax = 100;
  const X = (g) => L + (Math.log10(g / gMin) / Math.log10(gMax / gMin)) * (W - L - R);
  const Y = (o) => T + (1 - o) * (H - T - B);
  for (const g of [0.01, 0.1, 1, 10, 100]) {
    el('line', { x1: X(g), x2: X(g), y1: T, y2: H - B, class: 'grid' }, svg);
    el('text', { x: X(g), y: H - B + 16, class: 'tick', 'text-anchor': 'middle' }, svg).textContent = String(g);
  }
  for (const o of [0, 0.5, 1]) {
    el('text', { x: L - 8, y: Y(o) + 4, class: 'tick', 'text-anchor': 'end' }, svg).textContent = String(o);
  }
  el('text', { x: (L + W - R) / 2, y: H - 4, class: 'tick', 'text-anchor': 'middle' }, svg).textContent = 'glutamate, in units of its own binding constant (log scale)';
  [[0, 'curve-g'], [1, 'curve-gi']].forEach(([i, cls]) => {
    let d = '';
    for (let k = 0; k <= 300; k++) {
      const g = gMin * Math.pow(gMax / gMin, k / 300);
      d += `${k ? 'L' : 'M'}${X(g).toFixed(1)},${Y(occupancy(g, i, alpha)).toFixed(1)}`;
    }
    el('path', { d, class: cls }, svg);
  });
  const low = occupancy(0.01, 1, alpha) / occupancy(0.01, 0, alpha);
  $('receptor-out').textContent =
    `Glutamate alone (grey) and with the nucleotide at its own binding constant (gold).\n` +
    `At low glutamate the nucleotide multiplies the signal by ${fmt(low, 2)}; at high glutamate both curves reach 1, and the multiplying stops.`;
}

// ------------------------------------------------------------------ 4. the century, in books
let SERIES = null, VIEW = 'tastes';
function books() {
  if (!SERIES) return;
  const svg = $('books');
  svg.replaceChildren();
  const W = 640, H = 300, L = 54, R = 16, T = 16, B = 40;
  const y0 = SERIES.yearStart, n = SERIES.four.length;
  const lines = VIEW === 'tastes'
    ? [['four', '“four basic/primary tastes”', 'line-four'], ['five', '“five basic/primary tastes”', 'line-five']]
    : [['umami', '“umami”', 'line-five'], ['msg', '“monosodium glutamate”', 'line-four'], ['ajinomoto', '“Ajinomoto”', 'line-ctl']];
  const top = Math.max(...lines.flatMap(([k]) => SERIES[k])) * 1.05;
  const X = (i) => L + (i / (n - 1)) * (W - L - R);
  const Y = (v) => T + (1 - v / top) * (H - T - B);
  el('rect', { x: X(0), y: T, width: X(8) - X(0), height: H - T - B, class: 'before' }, svg);
  for (let yr = 1900; yr <= 2020; yr += 20) {
    el('line', { x1: X(yr - y0), x2: X(yr - y0), y1: T, y2: H - B, class: 'grid' }, svg);
    el('text', { x: X(yr - y0), y: H - B + 16, class: 'tick', 'text-anchor': 'middle' }, svg).textContent = String(yr);
  }
  const step = top > 200 ? 100 : top > 40 ? 20 : top > 10 ? 5 : 2;
  for (let v = 0; v <= top; v += step) {
    el('text', { x: L - 8, y: Y(v) + 4, class: 'tick', 'text-anchor': 'end' }, svg).textContent = String(v);
  }
  lines.forEach(([k, name, cls], j) => {
    let d = '';
    SERIES[k].forEach((v, i) => { d += `${i ? 'L' : 'M'}${X(i).toFixed(1)},${Y(v).toFixed(1)}`; });
    el('path', { d, class: cls }, svg);
    el('text', { x: L + 10, y: T + 16 + j * 16, class: `key ${cls}` }, svg).textContent = name;
  });
  const base = 'Occurrences per billion words (for a phrase, per billion phrases of its length). The shaded band is 1900 to 1907, before Ikeda\'s discovery.';
  if (VIEW === 'tastes') {
    const cross = crossover(SERIES.four, SERIES.five, y0);
    el('line', { x1: X(cross - y0), x2: X(cross - y0), y1: T, y2: H - B, class: 'cursor' }, svg);
    $('books-out').textContent = `${base}\nDashed line: ${cross}, from which "five" leads in every year.`;
  } else {
    const at = (k, yr) => fmt(SERIES[k][yr - y0], 2);
    $('books-out').textContent = `${base}\nIn 1900, before either could exist, "monosodium glutamate" reads ${at('msg', 1900)} and "Ajinomoto" ${at('ajinomoto', 1900)} per billion: misdated books, the chart's floor.\nDashed line: ${crossover(SERIES.msg, SERIES.umami, y0)}, from which "umami" leads "monosodium glutamate" in every year.`;
    const c2 = crossover(SERIES.msg, SERIES.umami, y0);
    el('line', { x1: X(c2 - y0), x2: X(c2 - y0), y1: T, y2: H - B, class: 'cursor' }, svg);
  }
}

function init() {
  for (const id of ['u', 'v']) $(id).addEventListener('input', bench);
  $('c').addEventListener('input', curve);
  $('alpha').addEventListener('input', receptor);
  for (const b of document.querySelectorAll('[data-view]')) {
    b.addEventListener('click', () => {
      VIEW = b.dataset.view;
      for (const o of document.querySelectorAll('[data-view]')) o.setAttribute('aria-pressed', String(o === b));
      books();
    });
  }
  bench(); curve(); receptor();
  fetch('series.json').then((r) => r.json()).then((s) => { SERIES = s; books(); })
    .catch(() => { $('books-out').textContent = 'The series did not load; series.json sits beside this page.'; });
}
if (typeof document !== 'undefined') init();
