// ---------------- 設定のパネル ----------------
const KIND_LABEL = E.KIND;
const cfgs = Object.fromEntries(E.SCENES.map((s) => [s.id, { ...s.defaults }]));
const SC = (id = sceneId) => E.SCENES.find((s) => s.id === id);
const splitOpt = (t) => { const m = t.match(/^(.*?)（(.*)）$/); return m ? [m[1], m[2]] : [t, '']; };
const label = (sc, k, v) => splitOpt(sc.groups.find((g) => g.k === k).opts.find((o) => o[0] === v)[1])[0];
// 設定のまとめ・自動再生の行に使う短い見出し
// 見出しは1行に収まる長さにする（2行に折り返さないように。9文字まで）
const SHORT = { yield: 'すれ違うときの動き', detect: '人に気づく距離', speed: '歩道での速さ', signal: '寄る側の合図', ratio: '1人が見る台数', order: '助けの順番', mrm: '待つ間のロボット', route: '踏切を通る道', voice: '動けないときの機体', push: '押して動かせるか', rescue: '駆け付ける人', pass: '追いついたとき', gap: '前の人との間', traffic: '車の多さ', time: '走らせる時間', stop: '人に近づく距離', waitpos: '止まる場所', stopAt: '止まる場所', sound: '近づく人への知らせ', wait: '受け取りを待つ', face: '顔の表示', resp: '囲まれたとき', body: '車体の重さ', sensor: 'センサー', approach: '人と動物が来たら', rear: '後ろの見張り', brake: '止まり方', bike: '自転車の走り方', map: '地図の見直し', way: '通れないとき', env: '天気と時間', launch: '出発のさせ方', cap: 'たまる台数', waitAt: '待たせる場所', cross: '車が来ているとき', insurance: '賠償責任保険', record: '記録を残す日数' };
function cfgSummary(sc, c, other) {
  return sc.groups.map((g) => `<div><span>${SHORT[g.k] || g.label.replace(/（.*$/, '')}</span><b class="${other && (typeof other === 'string' ? other === g.k : other[g.k] !== c[g.k]) ? 'chg' : ''}">${label(sc, g.k, c[g.k])}</b></div>`).join('');
}
let locked = false;
function drawScenes() {
  const btn = (s) => `<button class="sc ${s.id === sceneId ? 'on' : ''}" data-id="${s.id}"><b>${s.title}</b><span>${s.sub}</span></button>`;
  $('#scenes').innerHTML = '<div class="h">場面</div>' + E.SCENE_GROUPS.map(([g, nm]) => `<div class="gh">${nm}</div>` + E.SCENES.filter((s) => s.group === g).map(btn).join('')).join('');
  $('#ref').textContent = SC().ref;
}
function drawPanel() {
  const sc = SC(), cfg = cfgs[sceneId];
  $('#groups').innerHTML = sc.groups.map((g) => {
    const n = splitOpt(g.opts.find((o) => o[0] === cfg[g.k])[1])[1];
    return `<div class="grp"><span>${g.label}</span><div class="opts">${g.opts.map((o, i) => `<button data-k="${g.k}" data-i="${i}" class="${cfg[g.k] === o[0] ? 'on' : ''}" aria-pressed="${cfg[g.k] === o[0]}">${splitOpt(o[1])[0]}</button>`).join('')}</div>${n ? `<p class="optNote">${n}</p>` : ''}</div>`;
  }).join('');
  $('#panel').classList.toggle('locked', locked);
}
$('#scenes').addEventListener('click', (e) => { const b = e.target.closest('.sc'); if (!b || locked) return; sceneId = b.dataset.id; drawScenes(); drawPanel(); view.setScene(sceneId); showIdle(); });
$('#groups').addEventListener('click', (e) => {
  const b = e.target.closest('button[data-k]'); if (!b || locked) return;
  const g = SC().groups.find((x) => x.k === b.dataset.k); cfgs[sceneId][g.k] = g.opts[+b.dataset.i][0];
  drawPanel(); showIdle();
});

/*VIEW3D*/

// ---------------- 画面の切り替え ----------------
const views = ['play', 'sceneCmp', 'assign', 'compare'];
function show(v) { views.forEach((x) => $('#' + x).classList.toggle('on', x === v)); window.scrollTo(0, 0); }
function setPlayMode(m) {
  if (m !== 'scene') { $('#bubble').style.display = 'none'; }
  const running = m === 'scene';
  if (m === 'setup') { stopPlay(); showIdle(); }
  locked = running; drawPanel();
  $('#groups').style.display = running ? 'none' : ''; $('#runInfo').style.display = running ? '' : 'none';
  $('#scenes').style.display = running ? 'none' : ''; $('#ref').style.display = running ? 'none' : '';
  $('#intro').style.display = running ? 'none' : ''; $('#timebar').style.display = running ? 'flex' : 'none';
  $('#run').style.display = running ? 'none' : ''; $('#autoRun').style.display = running ? 'none' : ''; $('#stopRun').style.display = running ? '' : 'none';
  $('#panelTitle').style.display = running ? '' : 'none';
}

// ---------------- 再生 ----------------
let shown = null, idleRes = null, T = 0, rate = 1, playing = false, onDone = null, timer = null;
function showIdle() {
  idleRes = E.run(sceneId, cfgs[sceneId]); shown = idleRes; T = 0;
  view.setCur(idleRes); view.setFrame(0);
  $('#caption').style.display = 'none'; $('#op').style.display = 'none'; $('#labels').innerHTML = '';
}
function play(res, done) { shown = res; view.setCur(res); T = 0; playing = true; onDone = done; }
function stopPlay() { playing = false; onDone = null; clearTimeout(timer); timer = null; auto = null; }
$('#sceneSpeeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; rate = +b.dataset.r; [...$('#sceneSpeeds').children].forEach((x) => x.classList.toggle('on', x === b)); });
view.onTick((dt) => {
  const r0 = shown; if (!r0) return;
  if (playing) {
    T += dt * rate; const end = r0.frames[r0.frames.length - 1].t;
    if (T >= end) { T = end; view.setFrame(T); drawOverlay(r0, T); playing = false; const f = onDone; onDone = null; if (f) f(r0); return; }
  }
  view.setFrame(T);
  if (r0 !== idleRes) drawOverlay(r0, T);
});
function drawOverlay(r0, T) {
  $('#clockS').innerHTML = `${T.toFixed(0)}<small>秒</small>`;
  const evs = r0.events.filter((e) => e.t <= T), e = evs[evs.length - 1], cap = $('#caption');
  if (e && $('#bubble').style.display !== 'block') { cap.style.display = 'block'; cap.querySelector('.w').textContent = `${e.t.toFixed(0)}秒　${e.who === '—' ? '' : e.who}`; cap.querySelector('.t').textContent = e.text; cap.classList.toggle('hit', e.kind === 'hit'); }
  else cap.style.display = 'none';
  const fr = r0.frames[Math.min(r0.frames.length - 1, Math.floor(T / r0.dt))], op = $('#op');
  if (fr.queue) {
    op.style.display = 'block';
    op.querySelector('h3').textContent = r0.cfg.ratio === 1 ? '遠隔の担当（台ごとに1人）' : `遠隔の担当（1人で${r0.cfg.ratio}台）`;
    op.querySelector('.q').innerHTML = fr.queue.length ? fr.queue.map((q) => `<div class="r ${q.active ? 'act' : ''}"><b>${q.name}</b><i>${q.active ? (q.rushed ? '対応中・確認を短く' : '対応中') : `待ち ${Math.round(q.wait)}秒`}</i></div>`).join('') : '<div class="none">助けを求めている台はありません</div>';
  } else op.style.display = 'none';
  const L = [];
  const add = (x, y, z, text, cls = '') => { const p = view.screenOf(x, y, z); if (p.vis) L.push(`<div class="lbl ${cls}" style="left:${p.x}px;top:${p.y}px">${esc(text)}</div>`); };
  if (r0.scene === 'remote') for (const rb of fr.robots) add(rb.x, 2.1, rb.z, rb.id === 'A' ? '横断歩道の台' : '工事の前の台');
  for (const c of fr.cars || []) if (c.av) add(c.x, 2.4, c.z, '自動運転の車');
  if (r0.scene === 'cane') { const c = fr.peds.find((p) => p.kind === 'cane'); if (c) add(c.x, 2.0, c.z, '白い杖の人'); if (r0.cfg.sound === 'sound') { const ev2 = r0.events.find((x) => x.text.startsWith('近づく人に、音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, 'ロボットが止まっています。車道側を通れます', 'say'); } }
  if (r0.scene === 'sidebyside' && r0.cfg.pass === 'ask') { const ev2 = r0.events.find((x) => x.text.startsWith('音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 4) add(fr.robots[0].x, 2.0, fr.robots[0].z, '後ろから通ります', 'say'); }
  if (r0.scene === 'kids' && r0.cfg.face === 'face' && r0.cfg.resp === 'voice') { const ev2 = r0.events.find((x) => x.text.startsWith('音声で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, '通ります、離れてください', 'say'); }
  if (r0.scene === 'crossing' && r0.cfg.voice === 'ask' && fr.robots[0].light === 'ask') add(fr.robots[0].x, 2.3, fr.robots[0].z, r0.cfg.push === 'free' ? '動けません。押して外へ出してください' : '動けません。踏切の非常ボタンを押してください', 'say');
  if (r0.scene === 'wheelchair' && r0.cfg.signal) { const ev2 = r0.events.find((x) => x.text.startsWith('光と音で')); if (ev2 && T >= ev2.t && T < ev2.t + 5) add(fr.robots[0].x, 2.0, fr.robots[0].z, (ev2.text.match(/「(.*?)」/) || [])[1] || '', 'say'); }
  $('#labels').innerHTML = L.join('');
}

// ---------------- 説明のカード（バスの版と同じ形） ----------------
const whoOf = (ex) => [...new Set([...ex.people, ...ex.company].map((p) => p[0]))];
function incCard(kind, ex, when, facts) {
  const sec = (title, arr) => (arr.length ? `<h4>${title}</h4><ul class="who3">${arr.map(([w, t]) => `<li><b class="${w.includes('あなた') ? 'me' : ''}">${esc(w)}</b>${esc(t)}</li>`).join('')}</ul>` : '');
  const iss = [...ex.issues].sort((p, q) => E.ISSUES[p][0] - E.ISSUES[q][0]);
  return `<div class="inc ${kind}"><div class="hd"><span class="tag">${KIND_LABEL[kind]}</span>${esc(when)}</div>
    <p class="what">${esc(ex.what)}</p>
    ${facts ? `<div class="facts ${facts.length === 4 ? 'f4' : ''}">${facts.map((f) => `<div class="fact"><span>${f.k}</span><b>${f.v}</b><i>${f.u}</i></div>`).join('')}</div>` : ''}
    ${sec('人の問題', ex.people)}${sec('企業の問題', ex.company)}${sec('決まり・行政', ex.rules)}
    ${ex.open ? `<div class="open"><span>まだ決まっていないこと</span>${esc(ex.open)}</div>` : ''}
    ${iss.length ? `<div class="iss"><span>課題地図の関連する課題</span>${iss.map((s) => `<a href="https://pixelstomotors.com/issues/${s}" target="_blank" rel="noopener">#${E.ISSUES[s][0]} ${E.ISSUES[s][1]}</a>`).join('')}</div>` : ''}</div>`;
}
const MSG_URL = 'https://pixelstomotors.com/message';
const ctaPanel = () => `<div class="ctaP"><div><p class="who">配送ロボットや移動ロボットの導入を進めている方へ</p><h3>あなたの街や現場で、同じことを確かめませんか</h3><p class="b">歩道の幅や道順、遠隔の担当の体制、止まり方の作りを、あなたの現場に合わせて作り直せます。設定を変えると、人・企業・決まりのどこに問題が移るかを、走らせる前に確かめられます。</p></div><a href="${MSG_URL}" target="_blank" rel="noopener">相談する <span aria-hidden="true">→</span></a></div>`;
let bubbleShown = false;
function maybeBubble(kind) {
  if (bubbleShown || (kind !== 'hit' && kind !== 'issue')) return;
  bubbleShown = true; $('#caption').style.display = 'none'; $('#bubble').style.display = 'block'; // 1回の訪問で1度だけ
}
$('#bubble .x').addEventListener('click', () => { $('#bubble').style.display = 'none'; });

// ---------------- 場面を選んで確かめる ----------------
const sceneRuns = [];
const toRun = (r) => ({ sceneId: r.scene, cfg: r.cfg, kind: r.outcome.kind, ex: { ...r.explain, who: whoOf(r.explain) }, facts: r.facts, events: r.events });
function startScene() {
  const sc = SC(); show('play'); setPlayMode('scene');
  $('#panelTitle').textContent = sc.title; $('#cfgLine').innerHTML = cfgSummary(sc, cfgs[sceneId]);
  $('#incident').innerHTML = '<p class="note">この場面を再生しています</p>';
  play(E.run(sceneId, cfgs[sceneId]), sceneDone);
}
function sceneDone(r) {
  const sc = SC(r.scene), x = toRun(r);
  const prev = sceneRuns.filter((y) => y.sceneId === sc.id).at(-1);
  sceneRuns.push(x);
  $('#incident').innerHTML = incCard(x.kind, x.ex, sc.title, x.facts) + `<div class="sbtns"><button class="cta" id="sAgain">設定を変えて見直す <span aria-hidden="true">→</span></button>${prev ? '<button class="cta sub" id="sCmp">前の回と比べる</button>' : ''}<button class="link" id="sReplay">同じ設定でもう一度</button>${x.kind === 'hit' ? '<button class="cta sub" id="sAssign">誰にどれだけ責任があるかを考える</button>' : ''}<button class="cta sub" id="sRep">この回のレポートを見る</button></div>`;
  maybeBubble(x.kind);
  $('#sAgain').addEventListener('click', () => setPlayMode('setup'));
  $('#sReplay').addEventListener('click', () => startScene());
  $('#sRep').addEventListener('click', () => saveReport(sc.title, 'あなたが決めた設定で、この場面を1回見た結果です。', [runBlock(x, 'この回')]));
  if (prev) $('#sCmp').addEventListener('click', () => openSceneCompare(prev, x));
  if (x.kind === 'hit') $('#sAssign').addEventListener('click', () => openAssign(x, 'play'));
}
function openSceneCompare(a, b) {
  const sc = SC(b.sceneId), res = (x) => KIND_LABEL[x.kind];
  const changed = sc.groups.filter((g) => a.cfg[g.k] !== b.cfg[g.k]);
  const col = (x, other, title) => `<div class="col"><h3>${title}</h3><div class="cfgs" style="margin-bottom:10px">${cfgSummary(sc, x.cfg, other.cfg)}</div>${incCard(x.kind, x.ex, sc.title, x.facts)}</div>`;
  const wa = new Set(a.ex.who), wb = new Set(b.ex.who);
  const gone = [...wa].filter((w) => !wb.has(w)), added = [...wb].filter((w) => !wa.has(w));
  const sum = `変えたこと：${changed.length ? changed.map((g) => `${SHORT[g.k]}を「${label(sc, g.k, b.cfg[g.k])}」に`).join('、') : 'なし'}。<br>結果：${res(a)} → ${res(b)}。` +
    (gone.length ? `<br>問題から外れた：${gone.join('・')}` : '') + (added.length ? `<br>新しく問題になった：${added.join('・')}` : '') + (!gone.length && !added.length ? '<br>かかわる人は変わらなかった' : '') +
    (a.ex.open !== b.ex.open ? `<br>まだ決まっていないこと：${b.ex.open}` : '');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${sc.title}</p><h2>設定を変えると、問題はどこへ移る？</h2><div class="sum">${sum}</div><div class="cols">${col(a, b, 'まえ')}${col(b, a, 'あと')}</div>
    <div class="xbtn"><button class="cta sub" id="cmpRep">この比べた結果のレポートを見る</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="cmpBack">← 設定に戻る</button><button class="cta" id="cmpAgain">続けて、もう1つ変える <span aria-hidden="true">→</span></button></div>`;
  show('sceneCmp');
  $('#cmpRep').addEventListener('click', () => saveReport(`${sc.title}：設定を変えると、問題はどこへ移る？`, '', [`<div class="sum">${sum}</div>`, runBlock(a, 'まえ'), runBlock(b, 'あと')]));
  $('#cmpBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#cmpAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 自動再生：設定を1つずつ変えながら次々に再生し、最後に一覧で並べる ----------------
let auto = null;
function autoVariants() {
  const sc = SC(), cfg = cfgs[sceneId], list = [{ label: 'もとの設定のまま（下の設定）', cfg: { ...cfg }, k: null }];
  for (const g of sc.groups) for (const o of g.opts) if (o[0] !== cfg[g.k]) list.push({ label: `${SHORT[g.k]}：${label(sc, g.k, cfg[g.k])} → ${splitOpt(o[1])[0]}`, cfg: { ...cfg, [g.k]: o[0] }, k: g.k });
  return list;
}
function startAuto() {
  const sc = SC(); show('play'); setPlayMode('scene');
  auto = { sc, list: autoVariants(), i: 0, res: [] };
  $('#panelTitle').textContent = `${sc.title}（自動再生）`;
  autoNext();
}
function autoNext() {
  const a = auto; if (!a) return;
  if (a.i >= a.list.length) { auto = null; openAutoSummary(a); return; }
  const v = a.list[a.i];
  $('#cfgLine').innerHTML = cfgSummary(a.sc, v.cfg, v.k || undefined);
  $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p><div id="autoNow"></div>${autoHistory(a)}`;
  play(E.run(a.sc.id, v.cfg), (r) => {
    if (auto !== a) return;
    const x = { ...toRun(r), label: v.label, k: v.k };
    a.res.push(x);
    $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p>${incCard(x.kind, x.ex, v.label, x.facts)}${autoHistory(a, true)}`;
    a.i++; timer = setTimeout(autoNext, 1500 / rate);
  });
}
function autoHistory(a, skipLast) {
  const list = (skipLast ? a.res.slice(0, -1) : a.res).map((x, i) => ({ x, n: i + 1 })).reverse();
  if (!list.length) return '';
  return `<div class="ahist"><h4>これまでの回</h4>${list.map(({ x, n }) => `<details><summary><b>${n}</b><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span><span>${x.label}</span></summary>${incCard(x.kind, x.ex, x.label, x.facts)}</details>`).join('')}</div>`;
}
function openAutoSummary(a) {
  const rows = a.res.map((x, i) => `<tr class="arow" data-i="${i}"><td><span class="tg">＋</span>${i === 0 ? '<b>もとの設定のまま</b>' : x.label}</td><td><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span></td><td>${x.ex.who.map((w) => `<i class="${w.includes('あなた') ? 'me' : ''}">${w}</i>`).join('')}</td><td><span class="sub">${x.ex.open}</span></td></tr><tr class="adet" data-i="${i}" hidden><td colspan="4">${incCard(x.kind, x.ex, x.label, x.facts)}${x.kind === 'hit' ? `<div class="xbtn"><button class="cta sub" data-assign="${i}">この事故、誰にどれだけ責任があるかを考える</button></div>` : ''}</td></tr>`).join('');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${a.sc.title}（自動再生）</p><h2>設定を1つずつ変えると、結果と問題はどう変わる？</h2>
    <p class="note">下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。まわりの人や車の動き方の決まりは毎回同じです。行を押すと、その回の詳しい説明がひらきます</p>
    <h4 style="margin:14px 0 6px;font-size:12px;color:#777">もとの設定</h4><div class="cfgs">${cfgSummary(a.sc, a.res[0].cfg)}</div>
    <table class="auto"><thead><tr><th>変えたこと</th><th>結果</th><th>かかわる人</th><th>まだ決まっていないこと</th></tr></thead><tbody>${rows}</tbody></table>
    <div class="xbtn"><button class="cta sub" id="autoRep">この結果のレポートを見る</button></div>
    ${ctaPanel()}
    <div class="foot"><button class="link" id="autoBack">← 設定に戻る</button><button class="cta" id="autoAgain">別の場面で自動再生 <span aria-hidden="true">→</span></button></div>`;
  show('sceneCmp');
  $('#sceneCmp').querySelector('tbody').addEventListener('click', (e) => { const ab = e.target.closest('[data-assign]'); if (ab) { openAssign(a.res[+ab.dataset.assign], 'sceneCmp'); return; } const r = e.target.closest('.arow'); if (!r) return; const d = $('#sceneCmp').querySelector(`.adet[data-i="${r.dataset.i}"]`); d.hidden = !d.hidden; r.querySelector('.tg').textContent = d.hidden ? '＋' : '－'; });
  $('#autoRep').addEventListener('click', () => saveReport(`${a.sc.title}：設定を1つずつ変えた結果`, `下のもとの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。まわりの人や車の動き方の決まりは毎回同じです。`, [`<section><h2>もとの設定</h2><div class="cfgs">${cfgSummary(a.sc, a.res[0].cfg)}</div></section>`, summaryTable(a.res.map((x, i) => ({ ...x, label: i === 0 ? 'もとの設定のまま' : x.label }))), ...a.res.map((x, i) => runBlock(x, i === 0 ? 'もとの設定のまま' : x.label, i > 0))]));
  $('#autoBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#autoAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 責任の振り分け（自動運転バスの版と同じ形） ----------------
// 相手と手がかりは、その回の説明のカード（人の問題・企業の問題）から作る。「A・B」のように2者が並ぶものは、両方の手がかりにする
function clues(x) {
  const m = new Map();
  for (const [w, t] of [...x.ex.people, ...x.ex.company]) for (const nm of w.split('・')) { if (!m.has(nm)) m.set(nm, []); m.get(nm).push(t); }
  return [...m.entries()].map(([nm, ts], i) => ({ k: 'p' + i, nm, me: nm.includes('あなた'), cl: ts.join('。') }));
}
function openAssign(x, from) {
  const sc = SC(x.sceneId), ps = clues(x), n = ps.length;
  const alloc = x.alloc ? { ...x.alloc } : Object.fromEntries(ps.map((p) => [p.k, Math.round(100 / n)])); fix(ps[0].k);
  $('#assign').innerHTML = `<p class="eyebrow">${esc(sc.title)}</p><h2>この事故、誰にどれだけ責任がある？</h2><p class="what" style="margin:0;font-weight:700">${esc(x.ex.what)}</p><p class="note">合計がいつも100%になるよう、ほかが自動で動きます。手がかりは、この回の説明に出たことです</p><div style="display:flex;flex-direction:column;gap:10px" id="parties">${ps.map((p) => `<div class="party ${p.me ? 'me' : ''}"><span class="nm">${esc(p.nm)}</span><span class="cl">${esc(p.cl)}</span><input type="range" min="0" max="100" step="1" value="${alloc[p.k]}" data-k="${p.k}" aria-label="${esc(p.nm)}の責任"><span class="v"><span id="v-${p.k}">${alloc[p.k]}</span><small style="font-size:13px;font-weight:400">%</small></span></div>`).join('')}</div>
  <div class="foot"><button class="link" id="backRes">← 結果に戻る</button><button class="cta" id="toCompare">決めて、比べる <span aria-hidden="true">→</span></button></div>`;
  show('assign');
  $('#parties').addEventListener('input', (e) => { const k = e.target.dataset.k; alloc[k] = +e.target.value; fix(k); ps.forEach((p) => { $('#v-' + p.k).textContent = alloc[p.k]; $('#parties').querySelector(`input[data-k="${p.k}"]`).value = alloc[p.k]; }); });
  $('#backRes').addEventListener('click', () => show(from));
  $('#toCompare').addEventListener('click', () => { x.alloc = { ...alloc }; x.parties = ps; openAllocResult(x, from); });
  function fix(k) {
    const others = ps.filter((p) => p.k !== k).map((p) => p.k); const rest = 100 - alloc[k]; const sum = others.reduce((t, y) => t + alloc[y], 0);
    others.forEach((y) => { alloc[y] = sum ? Math.round(alloc[y] / sum * rest) : Math.round(rest / others.length); });
    const drift = 100 - Object.values(alloc).reduce((t, v) => t + v, 0); if (others[0]) alloc[others[0]] += drift;
  }
}
const allocRows = (x) => x.parties.map((p) => `<div class="row" style="grid-template-columns:180px minmax(0,1fr) 90px"><span class="k">${esc(p.nm)}</span><div class="bars"><div class="bar" style="width:${x.alloc[p.k]}%"></div></div><span class="n" style="font-size:24px;text-align:right">${x.alloc[p.k]}<small>%</small></span></div>`).join('');
function openAllocResult(x, from) {
  const top = x.parties.reduce((m, p) => (x.alloc[p.k] > x.alloc[m.k] ? p : m), x.parties[0]);
  $('#compare').innerHTML = `<p class="eyebrow">あなたの考えた割合</p><h2>あなたは「${esc(top.nm)}」の責任を一番重く見た</h2>
  <div style="display:flex;flex-direction:column;gap:10px">${allocRows(x)}</div>
  <p class="note">ほかの人の割合と並べる部分は、答えを集める仕組みができてから入ります（試作 v0 では答えを送りません）。法律上の正解を示すものではありません</p>
  <div class="xbtn"><button class="cta sub" id="alRep">割合を入れたレポートを見る</button></div>
  <div class="foot"><button class="link" id="alBack">← 割合を決め直す</button><button class="cta" id="alAgain">設定を変えて見直す <span aria-hidden="true">→</span></button></div>`;
  show('compare');
  $('#alRep').addEventListener('click', () => saveReport(`${SC(x.sceneId).title}：この事故、誰にどれだけ責任がある？`, 'この場面を見て、あなたが考えた責任の割合です。', [runBlock(x, x.label || 'この回')]));
  $('#alBack').addEventListener('click', () => openAssign(x, from));
  $('#alAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---------------- 見る人が持ち帰るレポート（1つのHTML。ブラウザで開き、印刷すればPDFにもなる） ----------------
function timeline(events) {
  if (!events || !events.length) return '';
  return `<h4>できごとの記録（場面の始まりからの秒数）</h4><table class="tl">${events.map((e) => `<tr><td>${e.t.toFixed(1)}秒</td><td>${e.who === '—' ? '' : esc(e.who) + '：'}${esc(e.text)}</td></tr>`).join('')}</table>`;
}
function runBlock(x, title, showChange) {
  const sc = SC(x.sceneId);
  return `<section><h2>${esc(title)}</h2><h4>選んだ設定</h4><div class="cfgs">${cfgSummary(sc, x.cfg, showChange ? x.k : undefined)}</div>${incCard(x.kind, x.ex, '', x.facts)}${x.alloc ? `<h4>あなたが考えた責任の割合</h4><table class="sumt">${x.parties.map((p) => `<tr><td>${esc(p.nm)}</td><td style="width:60%"><div style="height:10px;border-radius:5px;background:#111;width:${x.alloc[p.k]}%"></div></td><td style="text-align:right;white-space:nowrap">${x.alloc[p.k]}%</td></tr>`).join('')}</table>` : ''}${timeline(x.events)}</section>`;
}
function summaryTable(list) {
  return `<section><h2>結果の一覧</h2><table class="sumt"><tr><th>変えたこと</th><th>結果</th><th>かかわる人</th><th>まだ決まっていないこと</th></tr>${list.map((x) => `<tr><td>${esc(x.label)}</td><td><span class="rk ${x.kind}">${KIND_LABEL[x.kind]}</span></td><td>${esc(x.ex.who.join('・'))}</td><td>${esc(x.ex.open)}</td></tr>`).join('')}</table></section>`;
}
/*REPORTCSS*/
function saveReport(title, lead, blocks) {
  const now = new Date(), d = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
  const html = `<!DOCTYPE html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}｜事故が起きたら誰の責任？ 歩道の配送ロボット</title><style>${REPORT_CSS}</style></head><body><main>
<p class="eyebrow">事故が起きたら誰の責任？ 歩道の配送ロボット（試作）のレポート　${d}</p><h1>${esc(title)}</h1>${lead ? `<p>${esc(lead)}</p>` : ''}
${blocks.join('\n')}
<section class="rcta"><h2>あなたの街や現場で、同じことを確かめませんか</h2><p>このレポートは、架空の街で設定を変えたときに、人・企業・決まりのどこに問題が出るかを確かめたものです。配送ロボットや移動ロボットの導入を進めている方は、あなたの街や現場の歩道の幅や道順、遠隔の担当の体制、止まり方の作りに合わせて作り直し、走らせる前に同じことを確かめられます。</p><p><a href="${MSG_URL}">相談する</a>　${MSG_URL}</p></section>
<footer>実際の事故やトラブルの流れを参考にした、架空の場面です。動きと数字は試作の仮の決まり（版 ${E.VERSION}）で出したもので、予測ではありません。法律上の答えではなく、関係しそうな決まりと、まだ決まっていないことを示しています。<br>Pixels to Motors　pixelstomotors.com</footer></main></body></html>`;
  openReport(html);
}
// レポートは、まず画面の上で見せる。保存は見た人が「PDFで保存」を押したときだけ
function openReport(html) {
  let v = $('#repV');
  if (!v) {
    v = document.createElement('div'); v.id = 'repV';
    v.innerHTML = `<div class="rvBar"><b>レポート</b><span class="note">保存の画面で、送り先を「PDFに保存」にしてください</span><button class="cta" id="rvPdf">PDFで保存</button><button class="link" id="rvClose">閉じる</button></div><iframe title="レポート"></iframe>`;
    document.body.appendChild(v);
    const close = () => { v.style.display = 'none'; document.body.style.overflow = ''; };
    $('#rvClose').addEventListener('click', close);
    v.addEventListener('click', (e) => { if (e.target === v) close(); });
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && v.style.display === 'flex') close(); });
    $('#rvPdf').addEventListener('click', () => {
      const page = v.dataset.html.replace('<main>', `<div class="pbar"><button onclick="print()">PDFで保存</button><span>保存の画面で、送り先を「PDFに保存」にしてください。開かないときは、ブラウザのメニューの「印刷」から保存できます。</span></div><main>`).replace('</body>', '<script>addEventListener("load",()=>setTimeout(()=>print(),300))<\/script></body>');
      const url = URL.createObjectURL(new Blob([page], { type: 'text/html;charset=utf-8' }));
      const w = window.open(url, '_blank');
      if (!w) v.querySelector('.note').textContent = '新しいタブを開けませんでした。ポップアップを許可してから、もう一度押してください';
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    });
  }
  v.dataset.html = html;
  v.querySelector('iframe').srcdoc = html.replace('<head>', '<head><base target="_blank">');
  v.style.display = 'flex'; document.body.style.overflow = 'hidden';
}

$('#run').addEventListener('click', startScene);
$('#autoRun').addEventListener('click', startAuto);
$('#stopRun').addEventListener('click', () => setPlayMode('setup'));
drawScenes(); drawPanel(); view.setScene(sceneId); showIdle();
window.__dr = { E, state: () => ({ T, playing, auto: !!auto }) };
}
</script>
</body>
</html>
