<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>事故が起きたら誰の責任？（試作）</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Noto+Sans+JP:wght@400;500;700&display=swap">
<style>
/* VOICE: サイトと同じ、静かで道具らしい画面
   IDEA: 交差点を上から見る運行の管理画面
   PICTURE: three.js の T字路。バス（白）・歩行者（黄）・誘導員（青）
   COLOUR and TYPE: 白地・黒の面、赤は事故だけ。Noto Sans JP ＋ Inter
   LAYOUT: 左に交差点、右に仕組みのパネル。結果からは1枚ずつの画面 */
:root{color-scheme:light;--ink:#111;--sub:#555;--face:#f7f7f7;--line:#e5e5e5;--red:#d93a3a}
*{box-sizing:border-box;min-width:0}
body{margin:0;background:#fff;color:var(--ink);font:15px/1.6 Inter,'Noto Sans JP',sans-serif;overflow-x:clip}
button{font:inherit;color:inherit}
.view{display:none}.view.on{display:flex}
#play{height:100vh;min-height:620px}
#stage{position:relative;flex:1;background:#eceef1;overflow:hidden}
#stage canvas{position:absolute;inset:0;width:100%;height:100%}
.card{position:absolute;background:#fff;border-radius:12px;padding:14px 18px}
#top{left:16px;top:16px;max-width:430px}
#top h1{margin:0;font-size:13px;font-weight:700}.tag{font-size:11px;font-weight:400;background:#f0f0f0;border-radius:4px;padding:2px 6px;margin-left:8px}
#intro p{margin:6px 0 0}#intro .lead{font-size:20px;font-weight:700;line-height:1.45}
#clock{display:none}#clock .d{font-size:28px;font-weight:600}#clock .d small{font-size:13px;font-weight:400;margin-left:8px}
.seg{display:flex;gap:4px;background:#f0f0f0;border-radius:8px;padding:3px;margin-top:8px}
.seg button{border:0;border-radius:6px;background:transparent;padding:6px 10px;font-size:12px;cursor:pointer}
.seg button.on{background:#111;color:#fff}
#stats{left:16px;right:16px;bottom:16px;display:none;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.st span{display:block;font-size:12px;color:var(--sub)}.st b{font-size:26px;font-weight:600}.st i{font-style:normal;font-size:13px;margin-left:3px}
#views{right:16px;top:16px;padding:8px;display:flex;flex-direction:column;gap:6px;align-items:flex-end}
#views .seg{margin:0;flex-wrap:wrap;justify-content:flex-end}
#views .hint{font-size:11px;color:var(--sub);padding:0 4px;align-self:flex-start;text-align:left}
#stage canvas,#acR canvas{touch-action:none;cursor:grab}
#callout{display:none;max-width:250px;padding:10px 12px;font-size:12px;line-height:1.6;pointer-events:none}
#callout b{display:block;font-size:13px}
#panel{width:360px;flex:none;background:#fff;padding:20px;display:flex;flex-direction:column;gap:14px;overflow:auto}
#panel h2{margin:0;font-size:15px}
#groups{display:flex;flex-direction:column;gap:14px}
#modeTabs{margin:0}#modeTabs button{flex:1;white-space:nowrap;font-size:12.5px;padding:7px 8px}
#scenes{display:flex;flex-direction:column;gap:6px}#scenes .h{font-size:13px;color:#333;margin-bottom:2px}
#scenes .sc{all:unset;box-sizing:border-box;cursor:pointer;display:block;border:1px solid #e3e3e0;border-radius:10px;padding:8px 10px}
#scenes .sc b{display:block;font-size:12.5px}#scenes .sc span{display:block;font-size:11.5px;color:#777;line-height:1.5;margin-top:2px}
#scenes .sc.on{border-color:#111;box-shadow:0 0 0 1px #111}
.inc.safe{border-color:#2f7d4f}.inc.safe .tag{background:#2f7d4f}
.sbtns{display:flex;flex-direction:column;gap:8px;margin-top:14px}.sbtns .link{align-self:flex-start;font-size:13px}
#panel .cta{height:44px;font-size:14px;white-space:nowrap;padding:0 16px}#panel .cta.sub{background:#fff;color:#111;border:1px solid #111}
#panel .note,#panelNote{font-size:11.5px;line-height:1.6;margin:0}#panel .link{font-size:13px}
#sceneCmp .cols{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px}
#sceneCmp .col h3{margin:0 0 8px;font-size:14px;color:#666}
#sceneCmp .cfg{display:grid;grid-template-columns:auto 1fr;gap:3px 12px;font-size:12px;color:#666;background:#f5f5f3;border-radius:10px;padding:10px 12px;margin-bottom:10px}#sceneCmp .cfg b{color:#111}#sceneCmp .cfg .chg{background:#fff1b8;border-radius:4px;padding:0 4px}
table.auto{width:100%;border-collapse:collapse;margin-top:14px;font-size:13px}table.auto th{text-align:left;font-size:11.5px;color:#777;font-weight:600;padding:8px 10px;border-bottom:1px solid #e3e3e0}
table.auto td{padding:10px;border-bottom:1px solid #eee;vertical-align:top;line-height:1.6}table.auto i{font-style:normal;display:inline-block;background:#f0f0ee;border-radius:999px;padding:1px 9px;margin:0 4px 4px 0;font-size:12px}table.auto i.me{background:#111;color:#fff}
table.auto tr.arow{cursor:pointer}table.auto tr.arow:hover td{background:#fafaf8}table.auto .tg{color:#999;margin-right:6px}table.auto tr.adet td{padding:14px 10px;background:#fafaf8}table.auto tr.adet .inc{max-width:none;width:100%;box-sizing:border-box;background:#fff}
table.auto .sub{color:#666;font-size:12px}.rk{display:inline-block;font-size:12px;font-weight:700;color:#fff;border-radius:6px;padding:2px 8px;white-space:nowrap}.rk.hit{background:#d93a3a}.rk.near{background:#111}.rk.safe{background:#2f7d4f}
.ahist{margin-top:14px;border-top:1px solid #eee;padding-top:10px}.ahist h4{margin:0 0 6px;font-size:11.5px;color:#777;font-weight:600}
.ahist details{border-bottom:1px solid #f0f0ee;padding:6px 0}.ahist summary{cursor:pointer;display:flex;align-items:center;gap:8px;font-size:12.5px;list-style:none}.ahist summary::-webkit-details-marker{display:none}
.ahist summary b{width:18px;color:#999;font-weight:600}.ahist summary span:last-child{flex:1}.ahist details .inc{margin-top:8px}
#cfgLine b.chg{background:#fff1b8;border-radius:4px;padding:0 4px}
#sceneCmp .sum{background:#111;color:#fff;border-radius:14px;padding:14px 16px;font-size:14px;line-height:1.7;margin-top:12px}
@media(max-width:900px){#sceneCmp .cols{grid-template-columns:1fr}}
.optNote{margin:6px 0 0;font-size:11.5px;line-height:1.6;color:#777}
#runInfo{display:flex;flex-direction:column;gap:14px}
#cfgLine{margin:0;font-size:12px;line-height:1.6;color:#666;background:#f5f5f3;border-radius:10px;padding:10px 12px;display:grid;grid-template-columns:auto 1fr;gap:3px 12px}#cfgLine b{color:#111;font-weight:600}
.inc{border:1px solid #e3e3e0;border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:6px}
.inc.hit{border-color:#d93a3a}
.inc .hd{display:flex;align-items:center;gap:8px;font-size:12px;color:#666}
.inc .tag{font-size:12px;font-weight:700;color:#fff;background:#111;border-radius:6px;padding:2px 8px;margin-left:0}
.inc.hit .tag{background:#d93a3a}
.inc .what{margin:0 0 2px;font-size:13.5px;font-weight:700;line-height:1.55}
.inc h4{margin:6px 0 0;font-size:11.5px;color:#777;font-weight:600}
.inc ul{margin:0;padding-left:18px;font-size:13px;line-height:1.7}
.inc ul.who3{list-style:none;padding:0;display:flex;flex-direction:column;gap:5px}.inc ul.who3 li{line-height:1.55;font-size:12.5px}
.inc ul.who3 b{display:inline-block;font-size:11px;font-weight:600;background:#f0f0ee;border-radius:999px;padding:0 8px;margin-right:6px}.inc ul.who3 b.me{background:#111;color:#fff}
.inc .open{background:#fff6e5;border-radius:8px;padding:8px 10px;font-size:12.5px;line-height:1.55;margin-top:6px}.inc .open span{display:block;font-size:11px;font-weight:700;color:#8a5a00}
.inc .who{display:flex;flex-wrap:wrap;gap:6px}
.inc .who span{font-size:12px;background:#f0f0ee;border-radius:999px;padding:3px 10px}
.inc .who span.me{background:#111;color:#fff}
#incLog{display:flex;flex-direction:column;gap:6px}
#incLog .li{box-sizing:border-box;display:block;width:100%;cursor:pointer;font-size:12px;color:#555;line-height:1.6;border-top:1px solid #eee;padding:6px 0}
#incLog .li:hover .row1{color:#111}#incLog .li .row1::after{content:' ＋';color:#999}#incLog .li[aria-expanded=true] .row1::after{content:' －'}
#incLog .li .more{display:none;margin-top:8px;white-space:normal;cursor:default;color:#111;font-size:13px}#incLog .li[aria-expanded=true] .more{display:block}
#incLog .more .w{display:block;font-weight:700;color:#111;font-size:12.5px}#incLog .more .h{display:block;margin-top:6px;color:#777;font-size:11px}
#incLog .more .ul span{display:block}#incLog .more .who{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}#incLog .more .who i{font-style:normal;background:#ecece9;border-radius:999px;padding:1px 8px}#incLog .more .who i.me{background:#111;color:#fff}
#incLog .li b{color:#111;margin-right:6px}#incLog .li b.hit{color:#d93a3a}
.grp span{display:block;font-size:13px;color:#333;margin-bottom:6px}
.opts{display:flex;gap:5px;flex-wrap:wrap}
.opts button{border:0;border-radius:7px;background:#f0f0f0;padding:5px 10px;font-size:12px;cursor:pointer;min-height:30px}
.opts button.on{background:#111;color:#fff}.opts button:disabled{opacity:.35;cursor:not-allowed}
#panel.locked .opts button{cursor:default;color:#9a9a9a;background:#f5f5f5}#panel.locked .opts button.on{color:#fff;background:#111}
.cta{display:flex;align-items:center;justify-content:center;gap:8px;height:48px;padding:0 22px;border:0;border-radius:8px;background:#111;color:#fff;font-size:15px;font-weight:500;cursor:pointer;text-decoration:none}
.link{background:none;border:0;padding:0;font-size:14px;text-decoration:underline;cursor:pointer}
.note{font-size:12px;color:var(--sub);margin:0}
.sheet{min-height:100vh;flex-direction:column;gap:20px;padding:32px clamp(16px,4vw,40px);max-width:1280px;margin:0 auto}
.sheet h2{margin:0;font-size:26px;line-height:1.35}
.eyebrow{margin:0;font-size:13px;color:var(--sub)}
.chg{display:flex;gap:8px;flex-wrap:wrap;align-items:center;font-size:14px}.chg span{background:#f0f0f0;border-radius:8px;padding:5px 10px}.chg span.now{background:#111;color:#fff}
.two{display:grid;grid-template-columns:minmax(0,1fr) 360px;gap:28px}
.row{background:var(--face);border-radius:12px;padding:14px 20px;display:grid;grid-template-columns:180px repeat(2,minmax(0,1fr));gap:12px;align-items:baseline}
.row .k{font-weight:700}.row .p{font-size:28px;font-weight:600;color:#8a8a8a}.row .n{font-size:28px;font-weight:600}.row small{font-size:13px;font-weight:400;margin-left:3px}.row em{font-style:normal;font-size:13px;margin-left:8px;color:#333}
.acc{display:block;text-align:left;width:100%;border:0;background:var(--face);border-radius:12px;padding:14px 16px;cursor:pointer;margin-bottom:10px}
.acc .w{font-size:13px;color:var(--sub)}.acc .t{display:block;margin:2px 0 4px;line-height:1.5}.acc .go{font-size:13px;font-weight:500}
#accident{height:100vh;min-height:620px}
#acL{width:min(560px,48%);flex:none;padding:28px 28px 20px;display:flex;flex-direction:column;gap:14px;overflow:auto}
#facts{display:flex;gap:10px;flex-wrap:wrap}.fact{background:var(--face);border-radius:12px;padding:10px 14px}.fact span{display:block;font-size:12px;color:var(--sub)}.fact b{font-size:24px;font-weight:600}.fact i{font-style:normal;font-size:13px;margin-left:3px}
.ev{display:flex;gap:12px;align-items:baseline;width:100%;text-align:left;border:0;border-radius:10px;background:var(--face);padding:12px 14px;cursor:pointer}
.ev b{min-width:58px;font-weight:600}.ev.on{background:#111;color:#fff}
#acR{flex:1;position:relative;background:#eceef1}
.party{background:var(--face);border-radius:12px;padding:14px 20px;display:grid;grid-template-columns:170px minmax(0,1fr) 300px 64px;gap:18px;align-items:center}
.party.me{background:#ececec}.party .nm{font-weight:700}.party .cl{font-size:13px;color:#333;line-height:1.6}.party .v{font-size:24px;font-weight:600;text-align:right}
input[type=range]{width:100%;accent-color:#111;height:28px}
.bars{display:flex;flex-direction:column;gap:6px}.bar{height:12px;border-radius:6px;background:#111}.bar.all{background:#b9b9b9}
.foot{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap}
@media(max-width:900px){#play,#accident{height:auto;flex-direction:column}#stage,#acR{height:62vh;flex:none}#panel{width:100%}#acL{width:100%}.two{grid-template-columns:1fr}.party{grid-template-columns:1fr 64px}.party .cl{grid-column:1/-1}.party input{grid-column:1/-1}.row{grid-template-columns:1fr 1fr 1fr}#stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
</style>
</head>
<body>
<div id="play" class="view on">
  <div id="stage">
    <div id="top" class="card">
      <h1>事故が起きたら誰の責任？<span class="tag">試作 v0</span></h1>
      <div id="intro">
        <p class="lead">あなたは、この交差点を走る自動運転バスの運行を決める担当者です</p>
        <p id="introText">右で場面と設定を選んで、その1回を見てください。設定を1つ変えてもう一度見ると、問題が誰に移るかを比べられます。</p>
      </div>
      <div class="seg" id="sceneSpeeds" style="display:none;margin-top:10px"><button data-r="1" class="on">実際の速さ</button><button data-r="2">2倍</button><button data-r="4">4倍</button></div>
      <div id="clock">
        <div class="d" id="date">4月1日<small>1年のうち 1日目</small></div>
        <div class="seg" id="speeds">
          <button data-s="real">実際の速さ</button><button data-s="day" class="on">早送り</button><button data-s="skip">結果まで飛ばす</button>
        </div>
      </div>
    </div>
    <div id="views" class="card">
      <div class="seg" id="viewBtns">
        <button data-v="iso" class="on">斜め上</button><button data-v="opp">反対側</button><button data-v="top">真上</button><button data-v="follow">バスの後ろ</button>
      </div>
      <span class="hint">ドラッグで回す・ホイールや2本指で寄る</span>
    </div>
    <div id="callout" class="card"></div>
    <div id="stats" class="card">
      <div class="st"><span>事故</span><b id="sAcc" style="color:var(--red)">0</b><i>件</i></div>
      <div class="st"><span>ひやり（1m以内）</span><b id="sNear">0</b><i>回</i></div>
      <div class="st"><span>1便の遅れ（平均）</span><b id="sDelay">0.0</b><i>分</i></div>
      <div class="st"><span>運行の費用（いちばん安い仕組みを100）</span><b id="sCost">100</b></div>
    </div>
  </div>
  <aside id="panel">
    <h2 id="panelTitle" style="display:none"></h2>
    <div id="modeTabs" class="seg"><button data-m="scene" class="on">場面を選んで確かめる</button><button data-m="year">1年回す</button></div>
    <div id="scenes"></div>
    <div id="groups"></div>
    <div id="runInfo" style="display:none">
      <p id="cfgLine"></p>
      <div id="incident"><p class="note">ひやりや事故が起きると、ここに「何が起きたか・原因・かかわる人」が出ます</p></div>
      <div id="incLog"></div>
    </div>
    <div style="margin-top:auto;display:flex;flex-direction:column;gap:8px">
      <button class="cta" id="run">この仕組みで1年を回す <span aria-hidden="true">→</span></button>
      <button class="cta sub" id="autoRun" style="display:none">自動再生（設定を1つずつ変えて見る）</button>
      <p class="note" id="panelNote">数字は試作の仮の決まりで出しています。予測ではありません</p>
      <button class="link" id="stopRun" style="display:none;align-self:flex-start">止めて仕組みを変える</button>
    </div>
  </aside>
</div>

<div id="result" class="view sheet"></div>

<div id="accident" class="view">
  <div id="acL"></div>
  <div id="acR"></div>
</div>

<div id="assign" class="view sheet"></div>
<div id="compare" class="view sheet"></div>
<div id="sceneCmp" class="view sheet"></div>

<script type="text/plain" id="three-src">%%THREE%%</script>
<script type="text/plain" id="engine-src">%%ENGINE%%</script>
<script type="module">
{
const modURL = (id) => URL.createObjectURL(new Blob([document.getElementById(id).textContent], { type: 'text/javascript' }));
const THREE = await import(modURL('three-src'));
const E = await import(modURL('engine-src'));
const $ = (s) => document.querySelector(s);

// ---- 仕組みの項目 ----
const GROUPS = [
  { k: 'dir', scene: true, label: 'バスの来る向き', opts: [['wl', '西から来て左折'], ['er', '東から来て右折（対向車線を横切る）'], ['nl', '脇道から出て左折'], ['nr', '脇道から出て右折（対向車線を横切る）']] },
  { k: 'mode', label: '運行の形', opts: [['l2', 'レベル2・運転士（バスが走り、運転士が見張る。止まったあとの発進は運転士）'], ['l4in', 'レベル4・車内に主任者（バスが判断して走る。車内の主任者が見て、危ないときに止める）'], ['l4r1', 'レベル4・遠隔監視1台（車内は無人。遠隔監視者1人が1台を映像で見る）'], ['l4r3', 'レベル4・遠隔監視3台（車内は無人。遠隔監視者1人が3台を映像で見る）']] },
  { k: 'sensor', label: 'センサー', opts: [['normal', 'ふつう'], ['wide', '死角の少ないもの']] },
  { k: 'speed', label: '交差点での速さ', opts: [[6, '6 km/時'], [10, '10 km/時'], [15, '15 km/時']] },
  { k: 'guide', label: '交差点に誘導員', opts: [[true, '置く'], [false, '置かない']] },
  { k: 'route', label: '交差点の植え込み', opts: [['short', 'そのまま（見通しが悪い）'], ['long', '低く刈ってもらう（道の管理者に頼む）']] },
  { k: 'rest', label: (c) => `${WATCHER(c)}の休憩`, opts: [[true, 'こまめに入れる（見落としが減る・費用が上がる）'], [false, 'なしで回す（費用が下がる・見落としが増える）']] }
];
const NOUN = { dir: 'バスの向きを', mode: '運行の形を', sensor: 'センサーを', speed: '交差点の速さを', guide: '誘導員を', route: '植え込みを', rest: '休憩を' };
// 仕組みを変えたことを、文で言う（「〜したら、事故は減った」）
const changePhrase = (k, v) => ({ dir: `バスの来る向きを「${label('dir', v)}」にした`, mode: `運行の形を「${label('mode', v)}」にした`, sensor: `センサーを${v === 'wide' ? '死角の少ないもの' : 'ふつうのもの'}にした`, speed: `交差点の速さを時速${v}kmにした`,
  guide: v ? '誘導員を置いた' : '誘導員をなくした', route: v === 'long' ? '植え込みを低く刈ってもらった' : '植え込みをそのままにした', rest: v ? '休憩をこまめに入れた' : '休憩なしで回した' })[k];
// 選択肢の言葉は「本文（注釈）」の形。ボタンには本文だけ、注釈はボタンの下に小さく出す
const glabel = (g) => (typeof g.label === 'function' ? g.label(cfg) : g.label); // 見出しが、ほかの選択で変わるもの（休憩の対象など）
const splitOpt = (t) => { const m = t.match(/^(.*?)（(.*)）$/); return m ? [m[1], m[2]] : [t, '']; };
const label = (k, v) => splitOpt(GROUPS.find((g) => g.k === k).opts.find((o) => o[0] === v)[1])[0];
let cfg = { ...E.DEFAULTS, dir: E.SCENES[0].route };
const G = () => GROUPS.filter((g) => !g.scene || playKind === 'scene'); // バスの向きは場面のときだけ選ぶ（1年回すときは毎回ばらばら）
let locked = false;
// 場面によっては、前提として決まっている設定がある（例：誘導員の合図の場面は、誘導員がいることが前提）
const sceneReq = () => (playKind === 'scene' ? (E.SCENES.find((x) => x.id === sceneId) || {}).requires || {} : {});
// この場面で選べるバスの向き（場面のもとの向き＋ずらし方を決めてある向き）
const sceneDirs = () => { const sc = E.SCENES.find((x) => x.id === sceneId); return sc ? [sc.route, ...Object.keys(E.SCENE_DIRS[sc.id] || {})] : []; };
function drawPanel() {
  const req = sceneReq(); Object.assign(cfg, req);
  $('#groups').innerHTML = G().map((g) => { const fixed = g.k in req; return `<div class="grp"><span>${glabel(g)}</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]}" ${(fixed && cfg[g.k] !== o[0]) || (g.k === 'dir' && !sceneDirs().includes(o[0])) ? 'disabled' : ''}>${splitOpt(o[1])[0]}</button>`).join('')}</div>${fixed ? '<p class="optNote">この場面の前提なので、変えられません</p>' : g.k === 'dir' && sceneDirs().length < 4 ? '<p class="optNote">この場面の人は、脇道から出るバスとは交わりません</p>' : (() => { const n = splitOpt(g.opts.find((o) => o[0] === cfg[g.k])[1])[1]; return n ? `<p class="optNote">${n}</p>` : ''; })()}</div>`; }).join('');
  $('#panel').classList.toggle('locked', locked);
  $('#sCost').textContent = E.cost(cfg);
}
$('#groups').addEventListener('click', (e) => {
  const b = e.target.closest('button[data-k]'); if (!b || locked) return;
  const g = GROUPS.find((x) => x.k === b.dataset.k); cfg[g.k] = g.opts[+b.dataset.i][0];
  drawPanel(); scene.setCfg({ ...cfg });
});

// ---- 3D ----
const scene = (() => {
  const host = $('#stage');
  const r = new THREE.WebGLRenderer({ antialias: true });
  r.setPixelRatio(Math.min(devicePixelRatio, 2)); r.shadowMap.enabled = true; r.shadowMap.type = THREE.PCFSoftShadowMap;
  host.prepend(r.domElement);
  const s = new THREE.Scene(); s.background = new THREE.Color('#eceef1');
  const cam = new THREE.PerspectiveCamera(34, 1, 0.8, 400);
  const target = new THREE.Vector3(-1, 0, -4);
  const home = { az: Math.atan2(21, 32), el: Math.atan2(30, Math.hypot(21, 32)), dist: Math.hypot(21, 30, 32) };
  let az = home.az, el = home.el, dist = home.dist, mode = 'orbit';
  function placeCam() {
    if (mode === 'follow') return;
    cam.position.set(target.x + dist * Math.cos(el) * Math.sin(az), target.y + dist * Math.sin(el), target.z + dist * Math.cos(el) * Math.cos(az));
    cam.lookAt(target);
  }
  placeCam();
  s.add(new THREE.HemisphereLight('#ffffff', '#b9b4a8', 1.6));
  const d = new THREE.DirectionalLight('#ffffff', 1.5); d.position.set(-20, 40, 25); d.castShadow = true;
  d.shadow.mapSize.set(2048, 2048); Object.assign(d.shadow.camera, { left: -40, right: 40, top: 40, bottom: -40, near: 1, far: 120 }); s.add(d);
  const M = (c) => new THREE.MeshLambertMaterial({ color: c });
  const box = (w, h, dp, c, x, y, z, cast = false) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, dp), M(c)); m.position.set(x, y + h / 2, z); m.castShadow = cast; m.receiveShadow = true; s.add(m); return m; };
  box(260, 0.1, 260, '#e3e0d8', 0, -0.1, 0);
  box(200, 0.15, 14, '#efe7d4', 0, 0, 0);
  box(12, 0.15, 90, '#efe7d4', 0, 0, -51);
  box(200, 0.16, 7, '#7a7f87', 0, 0, 0);
  box(6, 0.16, 90, '#7a7f87', 0, 0, -48.5);
  for (let x = -96; x < 96; x += 4) if (Math.abs(x) > 5) box(2, 0.17, 0.15, '#f2f2f2', x, 0, 0);
  for (let x = -2.7; x <= 2.8; x += 0.9) box(0.45, 0.18, 2.8, '#ffffff', x, 0, -5.0);
  box(16, 2.6, 9, '#9aa0a8', -15, 0, -13, true); box(13, 2.2, 10, '#a3a8af', 15, 0, -14, true);
  box(16, 1.2, 6, '#b3b7bd', -15, 0, 12, true); box(16, 1.2, 6, '#b3b7bd', 15, 0, 12, true);
  const hedge = new THREE.Group(); for (const h of E.HEDGES) { const m = new THREE.Mesh(new THREE.BoxGeometry(h[1] - h[0], 1.3, h[3] - h[2]), M('#6f9a5a')); m.position.set((h[0] + h[1]) / 2, 0.8, (h[2] + h[3]) / 2); m.castShadow = true; hedge.add(m); } s.add(hedge);
  // バス
  const bus = new THREE.Group();
  const add = (g, w, h, dp, c, x, y, z) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, dp), M(c)); m.position.set(x, y, z); m.castShadow = true; g.add(m); return m; };
  {
    // バスの形（アーチ屋根）。真横から見た輪郭を幅方向に押し出す。前後は同じ形で、端のガラスは屋根の上まで続く
    const Lb = 5.2, Wb = 2.2, yb = 0.06, yt = 2.62, Rt = 1.35, Rb = 0.18, bv = 0.14, white = '#f6f6f4', glass = '#1d242c';
    const prof = (L2, y0, y1, rt, rbm) => { const x = L2 / 2, sh = new THREE.Shape();
      sh.moveTo(-x + rbm, y0); sh.lineTo(x - rbm, y0); sh.quadraticCurveTo(x, y0, x, y0 + rbm); sh.lineTo(x, y1 - rt);
      sh.absarc(x - rt, y1 - rt, rt, 0, Math.PI / 2, false); sh.lineTo(-x + rt, y1); sh.absarc(-x + rt, y1 - rt, rt, Math.PI / 2, Math.PI, false);
      sh.lineTo(-x, y0 + rbm); sh.quadraticCurveTo(-x, y0, -x + rbm, y0); return sh; };
    const ext = (sh, depth, bev, mat, seg = 24) => { const g = new THREE.ExtrudeGeometry(sh, { depth, curveSegments: seg, bevelEnabled: bev > 0, bevelSize: bev, bevelThickness: bev, bevelSegments: 5 }); g.translate(0, 0, -depth / 2); const m = new THREE.Mesh(g, mat); m.castShadow = true; bus.add(m); return m; };
    ext(prof(Lb - 2 * bv, yb + bv, yt - bv, Rt - bv, Rb), Wb - 2 * bv, bv, M(white));
    // 端のガラス：輪郭の端の部分だけを、車体の外へ少し出して作る。幅は車体より狭く、左右の面へは回り込まない
    const glassMat = new THREE.MeshPhongMaterial({ color: glass, specular: '#9aa6b2', shininess: 70 });
    const xe = Lb / 2 + 0.008, cy = yt - Rt, rr2 = Rt + 0.008, xg = 1.45, yw = 0.62, cx = Lb / 2 - Rt;
    for (const sg of [1, -1]) {
      // 縦の面は細かく区切って点を置く（角を丸めるときに、輪郭がなめらかになるように）
      const sh = new THREE.Shape(); sh.moveTo(xg, yw); sh.lineTo(xe, yw); for (let i = 1; i <= 24; i++) sh.lineTo(xe, yw + (cy - yw) * i / 24);
      const aEnd = Math.acos((xg - cx) / rr2); sh.absarc(cx, cy, rr2, 0, aEnd, false); sh.lineTo(xg, yw);
      const gwid = Wb - 2 * bv - 0.02, m = ext(sh, gwid, 0, glassMat, 40); if (sg < 0) m.scale.x = -1;
      // 端から見たガラスの四隅を丸める：ガラスの面に沿った長さ u で、両端に近い点ほど幅を狭める
      const uMax = (cy - yw) + rr2 * aEnd, hw = gwid / 2, rc = 0.32, pos = m.geometry.attributes.position;
      for (let i = 0; i < pos.count; i++) {
        const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i);
        const u = y <= cy + 1e-6 ? y - yw : (cy - yw) + rr2 * Math.atan2(y - cy, x - cx);
        const dEnd = Math.max(0, Math.min(u, uMax - u)); if (dEnd >= rc) continue;
        const lim = hw - rc + Math.sqrt(Math.max(0, rc * rc - (rc - dEnd) ** 2));
        if (Math.abs(z) > lim) pos.setZ(i, Math.sign(z) * lim);
      }
      pos.needsUpdate = true;
      add(bus, 0.02, 0.05, Wb * 0.62, '#e9f4ff', sg * (xe + 0.002), yw - 0.12, 0);
      for (const z of [0.5, -0.5]) add(bus, 0.02, 0.07, 0.22, sg > 0 ? '#ffffff' : '#d9534f', sg * (xe + 0.002), 0.34, z);
    }
    // 側面：外側の上の角を大きく丸めた窓、真ん中の2枚引き戸、足元のネイビーの帯
    // 側面に貼る部品は、層ごとに外へ少しずつ離す（同じ面に重ねるとチラつくため）。layer 0=窓とドア枠、1=ドアの板
    const flat = (sh, c, x, y, z, mx = 1, layer = 0) => { const g = new THREE.ExtrudeGeometry(sh, { depth: 0.02, bevelEnabled: false, curveSegments: 8 }); g.translate(0, 0, -0.01); const mat = M(c); mat.polygonOffset = true; mat.polygonOffsetFactor = -1 - layer * 2; mat.polygonOffsetUnits = -4 - layer * 4; const m = new THREE.Mesh(g, mat); m.position.set(x, y, z + Math.sign(z) * (0.012 + layer * 0.03)); m.scale.x = mx; bus.add(m); return m; };
    const rect = (w, h, q) => { const sh = new THREE.Shape(); sh.moveTo(-w / 2 + q, -h / 2); sh.lineTo(w / 2 - q, -h / 2); sh.quadraticCurveTo(w / 2, -h / 2, w / 2, -h / 2 + q); sh.lineTo(w / 2, h / 2 - q); sh.quadraticCurveTo(w / 2, h / 2, w / 2 - q, h / 2); sh.lineTo(-w / 2 + q, h / 2); sh.quadraticCurveTo(-w / 2, h / 2, -w / 2, h / 2 - q); sh.lineTo(-w / 2, -h / 2 + q); sh.quadraticCurveTo(-w / 2, -h / 2, -w / 2 + q, -h / 2); return sh; };
    const win = (() => { const w = 0.98, h = 1.5, q = 0.12, qo = 0.55, sh = new THREE.Shape(); sh.moveTo(0, 0); sh.lineTo(w - q, 0); sh.quadraticCurveTo(w, 0, w, q); sh.lineTo(w, h - qo); sh.quadraticCurveTo(w, h, w - qo, h); sh.lineTo(q, h); sh.quadraticCurveTo(0, h, 0, h - q); sh.lineTo(0, q); sh.quadraticCurveTo(0, 0, q, 0); return sh; })();
    for (const z of [1, -1]) {
      const zz = z * (Wb / 2 + 0.004);
      flat(win, glass, 0.74, 0.82, zz); flat(win, glass, -0.74, 0.82, zz, -1);
      flat(rect(1.36, 2.1, 0.08), '#dfe2e6', 0, 1.29, zz);
      for (const x of [-0.335, 0.335]) flat(rect(0.62, 2.0, 0.05), '#1f252d', x, 1.3, zz, 1, 1);
      add(bus, Lb - 0.9, 0.16, 0.03, '#1f3a5f', 0, 0.2, z * (Wb / 2 + 0.02));
    }
    for (const [x, z] of [[1.85, 1.0], [1.85, -1.0], [-1.85, 1.0], [-1.85, -1.0]]) { const w = new THREE.Mesh(new THREE.CylinderGeometry(0.32, 0.32, 0.28, 20), M('#262626')); w.rotation.x = Math.PI / 2; w.position.set(x, 0.32, z); bus.add(w); const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.18, 0.18, 0.3, 16), M('#cfd2d6')); hub.rotation.x = Math.PI / 2; hub.position.set(x, 0.32, z); bus.add(hub); }
    // 屋根の LiDAR は真ん中に1つ、小さく
    add(bus, 0.12, 0.05, 0.12, '#8d939b', 0, yt + 0.02, 0); const ld = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.06, 0.08, 16), M('#2b2f36')); ld.position.set(0, yt + 0.08, 0); bus.add(ld);
  }
  const blinkOn = new THREE.MeshBasicMaterial({ color: '#ffb020' }), blinkOff = new THREE.MeshLambertMaterial({ color: '#b08a40' });
  // ウインカー：前後の端の角（低い位置）と、側面の前後。左右どちらにも付け、曲がる側だけ光らせる
  const blinkers = [-1, 1].flatMap((side) => [[2.611, 0.5, side * 0.8, 0.02, 0.1, 0.16], [-2.611, 0.5, side * 0.8, 0.02, 0.1, 0.16], [2.25, 0.62, side * 1.106, 0.22, 0.08, 0.012], [-2.25, 0.62, side * 1.106, 0.22, 0.08, 0.012]].map(([x, y, z, w, h, d]) => { const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), blinkOff); m.position.set(x, y, z); m.userData.left = side < 0; bus.add(m); return m; }));
  s.add(bus);
  const person = (c) => { const g = new THREE.Group(); const b = new THREE.Mesh(new THREE.CylinderGeometry(0.26, 0.28, 1.22, 14), M(c)); b.position.y = 0.61; b.castShadow = true; g.add(b); const h = new THREE.Mesh(new THREE.SphereGeometry(0.2, 14, 10), M(c)); h.position.y = 1.46; h.castShadow = true; g.add(h); return g; };
  let vc = cfg; // 描いている回の設定（自動再生では回ごとに変わる）
  const setRoute = (rt) => { hedge.scale.y = rt === 'short' ? 1 : 0.35; hedge.position.y = rt === 'short' ? 0 : -0.25; };
  const guide = person('#1f5fd6'); guide.position.set(-4.6, 0.15, -6.7); s.add(guide);
  const arm = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.9), M('#1f5fd6')); arm.position.set(-4.6, 1.35, -6.2); s.add(arm);
  const pool = [];
  const ring = (c) => { const g = new THREE.Group(); const mat = new THREE.MeshBasicMaterial({ color: c }); const m = new THREE.Mesh(new THREE.TorusGeometry(1.4, 0.08, 8, 48), mat); m.rotation.x = -Math.PI / 2; g.add(m); const pin = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 2.2, 8), mat); pin.position.y = 2.6; g.add(pin); const head = new THREE.Mesh(new THREE.SphereGeometry(0.32, 16, 12), mat); head.position.y = 3.8; g.add(head); g.visible = false; s.add(g); return g; };
  const red = ring('#d93a3a'), black = ring('#111111');
  let cur = host;
  function resize() { const w = cur.clientWidth, h = cur.clientHeight; if (!w || !h) return; r.setSize(w, h, false); cam.aspect = w / h; cam.updateProjectionMatrix(); }
  const ro = new ResizeObserver(resize); ro.observe(host); resize();
  function setFrame(f, opts = {}) {
    const jump = Math.hypot(bus.position.x - f.bus.x, bus.position.z - f.bus.z) > 6;
    bus.position.set(f.bus.x, 0.16, f.bus.z); bus.rotation.y = f.bus.h;
    if (jump && mode === 'follow') snapFollow = true;
    // 左折の合図：交差点の手前から曲がり終わるまで点滅
    // 曲がる合図：曲がる側（左折なら左、右折なら右）だけを、交差点の手前から曲がり終わるまで点滅
    const lit = !!f.bus.blink && (performance.now() % 700) < 380;
    blinkers.forEach((m) => { m.material = lit && (f.bus.blink === 'L') === m.userData.left ? blinkOn : blinkOff; });
    // 人は id ごとに色と背の高さを少しずつ変える（誘導員の青は使わない）。通り過ぎるだけの人は淡い色
    while (pool.length < f.peds.length) { const p = person('#e8b923'); s.add(p); pool.push(p); }
    pool.forEach((p, i) => { const q = f.peds[i]; p.visible = !!q; if (!q) return; p.position.set(q.x, 0.15, q.z);
      const c = q.type === 'ambient' ? '#c4c1ba' : '#e8b923'; // 渡る人は黄色、通り過ぎるだけの人は淡い灰色、誘導員は青 if (p.userData.c !== c) { p.userData.c = c; p.children.forEach((m) => m.material.color.set(c)); }
      const sc = 0.9 + ((q.id * 37) % 5) * 0.05; p.scale.set(1, sc, 1); });
    arm.visible = !!f.guide && vc.guide; guide.visible = vc.guide;
    red.visible = !!opts.red; if (opts.red) red.position.set(opts.red.x, 0.3, opts.red.z);
    black.visible = !!opts.black; if (opts.black) black.position.set(opts.black.x, 0.3, opts.black.z);
  }
  function screenOf(x, z) { const v = new THREE.Vector3(x, 1.5, z).project(cam); return { x: (v.x + 1) / 2 * host.clientWidth, y: (1 - v.y) / 2 * host.clientHeight }; }
  let lastT = performance.now(), followH = 0, snapFollow = true; const lookAt = new THREE.Vector3();
  function loop() {
    const now = performance.now(), dtR = Math.min(0.1, (now - lastT) / 1000); lastT = now;
    if (mode === 'follow') {
      // 向きをなめらかに追い、斜め後ろの少し上から見る
      let dh = bus.rotation.y - followH; dh = Math.atan2(Math.sin(dh), Math.cos(dh));
      const k = snapFollow ? 1 : 1 - Math.exp(-dtR * 3);
      followH += dh * k;
      const dx = Math.cos(followH), dz = -Math.sin(followH);
      const want = new THREE.Vector3(bus.position.x - dx * 14, 8.5, bus.position.z - dz * 14);
      if (snapFollow) cam.position.copy(want); else cam.position.lerp(want, k);
      lookAt.lerp(new THREE.Vector3(bus.position.x + dx * 6, 0.5, bus.position.z + dz * 6), snapFollow ? 1 : k);
      cam.lookAt(lookAt); snapFollow = false;
    }
    r.render(s, cam); requestAnimationFrame(loop);
  }
  loop();
  // 動かす：ドラッグで回す、ホイール・2本指で寄る
  const ptrs = new Map(); let pinch0 = 0;
  const cv = r.domElement;
  cv.addEventListener('pointerdown', (e) => { cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); } });
  cv.addEventListener('pointermove', (e) => {
    const p = ptrs.get(e.pointerId); if (!p) return;
    if (ptrs.size === 1) {
      if (mode === 'follow') setView('custom');
      az -= (e.clientX - p.x) * 0.006; el = Math.min(1.55, Math.max(0.12, el + (e.clientY - p.y) * 0.005)); placeCam();
    } else if (ptrs.size === 2) {
      p.x = e.clientX; p.y = e.clientY; const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y);
      if (pinch0) { dist = Math.min(90, Math.max(8, dist * pinch0 / d)); pinch0 = d; placeCam(); } return;
    }
    p.x = e.clientX; p.y = e.clientY;
  });
  const up = (e) => { ptrs.delete(e.pointerId); pinch0 = 0; };
  cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
  cv.addEventListener('wheel', (e) => { e.preventDefault(); if (mode === 'follow') setView('custom'); dist = Math.min(90, Math.max(8, dist * Math.exp(e.deltaY * 0.0012))); placeCam(); }, { passive: false });
  function setView(v) {
    mode = v === 'follow' ? 'follow' : 'orbit'; if (mode === 'follow') { snapFollow = true; followH = bus.rotation.y; }
    if (v === 'iso') { az = home.az; el = home.el; dist = home.dist; }
    if (v === 'opp') { az = home.az + Math.PI; el = home.el; dist = home.dist; }
    if (v === 'top') { el = 1.55; dist = 52; }
    placeCam();
    document.querySelectorAll('#viewBtns button').forEach((b) => b.classList.toggle('on', b.dataset.v === v));
  }
  return { setView, setFrame, setRoute, setCfg: (c) => { vc = c; setRoute(c.route); }, screenOf, moveTo: (el) => { el.prepend(r.domElement); el.appendChild(document.getElementById('views')); ro.disconnect(); cur = el; ro.observe(el); requestAnimationFrame(resize); }, host };
})();
scene.setFrame({ bus: { ...E.busPose(49), v: 0 }, peds: [], guide: false });
$('#viewBtns').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) scene.setView(b.dataset.v); });

// ---- 1年を回す ----
const runs = []; let year = null, speed = 'day', timer = null, replay = null;
const dateOf = (d) => { const t = new Date(2027, 3, 1 + Math.floor(d * 365 / E.PARAMS.daysPerYear)); return `${t.getMonth() + 1}月${t.getDate()}日`; };
const timeOf = (i) => { const m = 7 * 60 + i * 18; return `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}`; };
$('#speeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; speed = b.dataset.s; [...$('#speeds').children].forEach((x) => x.classList.toggle('on', x === b)); if (speed === 'skip') finishFast(); });
$('#run').addEventListener('click', () => (playKind === 'scene' ? startScene() : startYear()));
$('#autoRun').addEventListener('click', startAuto);
$('#incLog').addEventListener('click', (e) => { const b = e.target.closest('.li'); if (!b) return; const open = b.getAttribute('aria-expanded') !== 'true'; b.setAttribute('aria-expanded', String(open)); if (incLog[+b.dataset.i]) incLog[+b.dataset.i].open = open; /* 新しいできごとが来ても、ひらいたものはひらいたまま */ });
$('#stopRun').addEventListener('click', () => { auto = null; stopTimers(); setPlayMode('setup'); });
function setPlayMode(m) {
  const running = m === 'run' || m === 'scene';
  if (m === 'setup') { stopTimers(); scene.setCfg({ ...cfg }); }
  locked = running; drawPanel();
  $('#groups').style.display = running ? 'none' : ''; $('#runInfo').style.display = running ? '' : 'none';
  $('#modeTabs').style.display = running ? 'none' : ''; $('#scenes').style.display = running ? 'none' : '';
  if (running) { $('#cfgLine').innerHTML = G().map((g) => `<span>${glabel(g)}</span><b>${label(g.k, cfg[g.k])}</b>`).join(''); $('#incident').innerHTML = '<p class="note">ひやりや事故が起きると、ここに「何が起きたか・原因・かかわる人」が出ます</p>'; $('#incLog').innerHTML = ''; incLog = []; }
  $('#sceneSpeeds').style.display = m === 'scene' ? 'flex' : 'none';
  $('#intro').style.display = m === 'setup' ? '' : 'none'; $('#clock').style.display = m === 'run' ? 'block' : 'none';
  $('#stats').style.display = m === 'run' ? 'grid' : 'none'; $('#callout').style.display = 'none';
  $('#run').style.display = m === 'setup' ? '' : 'none'; $('#autoRun').style.display = m === 'setup' && playKind === 'scene' ? '' : 'none'; $('#stopRun').style.display = running ? '' : 'none';
  $('#stopRun').textContent = m === 'scene' ? '設定に戻る' : '止めて仕組みを変える'; $('#incLog').style.display = m === 'scene' ? 'none' : '';
  $('#panelTitle').textContent = running ? 'シミュレーション設定' : ''; $('#panelTitle').style.display = running ? '' : 'none'; // 決める画面では、左上の説明が同じことを言っているので出さない
  $('#panelNote').textContent = m === 'run' ? '数字は試作の仮の決まり。予測ではありません' : '数字は試作の仮の決まり。予測ではありません';
}
function stopTimers() { clearTimeout(timer); timer = null; replay = null; }
// ---- 場面を選んで確かめる ----
let playKind = 'scene', sceneId = E.SCENES[0].id, sceneRuns = [], runCounter = 0, sceneRate = 1;
$('#sceneSpeeds').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; sceneRate = +b.dataset.r; [...$('#sceneSpeeds').children].forEach((x) => x.classList.toggle('on', x === b)); if (replay && replay.scene) replay.rate = sceneRate; });
function drawScenes() {
  $('#scenes').innerHTML = playKind === 'scene' ? '<div class="h">場面</div>' + E.SCENES.map((sc) => `<button class="sc ${sc.id === sceneId ? 'on' : ''}" data-id="${sc.id}"><b>${sc.title}</b><span>${sc.note}</span></button>`).join('') : '';
}
function setPlayKind(k) {
  playKind = k; [...$('#modeTabs').children].forEach((b) => b.classList.toggle('on', b.dataset.m === k));
  drawScenes(); drawPanel(); $('#autoRun').style.display = k === 'scene' ? '' : 'none';
  $('#run').innerHTML = k === 'scene' ? 'この場面を見る <span aria-hidden="true">→</span>' : 'この仕組みで1年を回す <span aria-hidden="true">→</span>';
  $('#introText').textContent = k === 'scene' ? '右で場面と設定を選んで、その1回を見てください。設定を1つ変えてもう一度見ると、問題が誰に移るかを比べられます。' : '右で仕組みを決めて、1年を回してください。いろいろな場面が混ざって起きます。起きた事故で誰にどれだけ責任があるかを、最後にあなたが考えます。';
}
$('#modeTabs').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) setPlayKind(b.dataset.m); });
$('#scenes').addEventListener('click', (e) => { const b = e.target.closest('.sc'); if (!b) return; sceneId = b.dataset.id; cfg.dir = E.SCENES.find((x) => x.id === sceneId).route; drawScenes(); drawPanel(); });
function startScene() {
  auto = null;
  const sc = E.SCENES.find((x) => x.id === sceneId); show('play'); setPlayMode('scene');
  $('#panelTitle').textContent = sc.title;
  $('#incident').innerHTML = '<p class="note">この場面を再生しています</p>';
  const p = { seed: 42, scene: E.sceneFor(sc, cfg.dir, cfg), cfg: { ...cfg }, kind: 'scene', runId: ++runCounter, rate: sceneRate };
  playPass(p, 1, (r) => sceneDone(p, r), -1);
}
// ---- 自動再生：選んだ場面を、設定を1つずつ変えながら次々に再生し、最後に一覧で並べる ----
let auto = null;
function autoVariants() {
  const req = sceneReq(), list = [{ label: 'いまの設定', cfg: { ...cfg }, k: null }];
  for (const g of G()) { if (g.k in req) continue; for (const o of g.opts) if (o[0] !== cfg[g.k] && (g.k !== 'dir' || sceneDirs().includes(o[0]))) list.push({ label: `${glabel(g)}を「${splitOpt(o[1])[0]}」に`, cfg: { ...cfg, [g.k]: o[0] }, k: g.k }); }
  return list;
}
function startAuto() {
  const sc = E.SCENES.find((x) => x.id === sceneId);
  auto = { sc, list: autoVariants(), i: 0, res: [] };
  show('play'); setPlayMode('scene'); $('#panelTitle').textContent = `${sc.title}（自動再生）`;
  autoNext();
}
function autoNext() {
  const a = auto; if (!a) return;
  if (a.i >= a.list.length) { const done = a; auto = null; openAutoSummary(done); return; }
  const v = a.list[a.i];
  $('#cfgLine').innerHTML = G().map((g) => `<span>${glabel(g)}</span><b class="${g.k === v.k ? 'chg' : ''}">${label(g.k, v.cfg[g.k])}</b>`).join('');
  $('#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)}`;
  const p = { seed: 42, scene: E.sceneFor(a.sc, v.cfg.dir, v.cfg), cfg: v.cfg, kind: 'scene', runId: ++runCounter, rate: sceneRate };
  playPass(p, 1, (r) => {
    if (auto !== a) return;
    const kind = r.hit ? 'hit' : r.near ? 'near' : 'safe';
    const ex = kind === 'hit' ? explain(r.facts, v.cfg, 'hit') : kind === 'near' ? explain(r.nearFacts, v.cfg, 'near') : null;
    a.res.push({ ...v, kind, ex, reasons: kind === 'safe' ? safeReasons(r, v.cfg) : null });
    // いまの回の結果を出し、その下にこれまでの回の履歴を並べる
    const cur = kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span></div><ul>${safeReasons(r, v.cfg).map((x) => `<li>${x}</li>`).join('')}</ul></div>` : incCard(kind, ex, v.label, '');
    $('#incident').innerHTML = `<p class="note" style="font-size:13px;color:#111"><b>${a.i + 1} / ${a.list.length}</b>　${v.label}</p>${cur}${autoHistory(a, true)}`;
    a.i++; timer = setTimeout(autoNext, 1500 / sceneRate);
  }, -1);
}
// 自動再生の履歴：これまでの回を新しい順に。押すと、その回の説明がひらく
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 '';
  const badge = (x) => (x.kind === 'hit' ? '<span class="rk hit">事故</span>' : x.kind === 'near' ? '<span class="rk near">ひやり</span>' : '<span class="rk safe">何も起きなかった</span>');
  return `<div class="ahist"><h4>これまでの回</h4>${list.map(({ x, n }) => `<details><summary><b>${n}</b>${badge(x)}<span>${x.label}</span></summary>${x.kind === 'safe' ? `<div class="inc safe"><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, x.label, '')}</details>`).join('')}</div>`;
}
function openAutoSummary(a) {
  const res = (x) => (x.kind === 'hit' ? '<span class="rk hit">事故</span>' : x.kind === 'near' ? '<span class="rk near">ひやり</span>' : '<span class="rk safe">何も起きなかった</span>');
  // 行を押すと、その回の詳しい説明（場面を1回見たときと同じカード）が下にひらく
  const detail = (x) => (x.kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span>${x.label}</div><h4>止まれた理由</h4><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, x.label, ''));
  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>${res(x)}</td><td>${x.ex ? x.ex.who.map((w) => `<i class="${w.includes('あなた') ? 'me' : ''}">${w}</i>`).join('') : `<span class="sub">${x.reasons[0]}</span>`}</td><td>${x.ex && x.ex.open ? `<span class="sub">${x.ex.open}</span>` : ''}</td></tr><tr class="adet" data-i="${i}" hidden><td colspan="4">${detail(x)}</td></tr>`).join('');
  $('#sceneCmp').innerHTML = `<p class="eyebrow">場面：${a.sc.title}（自動再生）</p><h2>設定を1つずつ変えると、結果と問題はどう変わる？</h2>
    <p class="note">いまの設定から1つだけ変えて、同じ場面を${a.res.length}回見た結果です。歩く人の動きは毎回同じです。行を押すと、その回の詳しい説明がひらきます</p>
    <table class="auto"><thead><tr><th>変えたこと</th><th>結果</th><th>かかわる人（何も起きなければ止まれた理由）</th><th>まだ決まっていないこと</th></tr></thead><tbody>${rows}</tbody></table>
    <div class="foot"><button class="link" id="autoBack">← 設定に戻る</button><button class="cta" id="autoAgain">別の場面で自動再生 <span aria-hidden="true">→</span></button></div>`;
  scene.moveTo($('#stage')); show('sceneCmp');
  $('#sceneCmp').querySelector('tbody').addEventListener('click', (e) => { 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 ? '＋' : '－'; });
  $('#autoBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#autoAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}
function safeReasons(r, c) {
  const k = new Set(r.events.map((e) => e.k)), out = [];
  if (k.has('sensed')) out.push('バスのセンサーが人に気づき、自動ブレーキで止まった');
  if (k.has('opbrake')) out.push(`${WATCHER(c)}が人に気づいて止めた`);
  if (k.has('remote')) out.push('遠隔監視者が映像で気づき、止める指示を出した');
  if (!out.length) out.push('人が渡り終えるまでバスが待ったか、人がバスに気づいて待った');
  return out;
}
function sceneDone(p, r) {
  const sc = p.scene, c = p.cfg;
  const kind = r.hit ? 'hit' : r.near ? 'near' : 'safe';
  const ex = kind === 'hit' ? explain(r.facts, c, 'hit') : kind === 'near' ? explain(r.nearFacts, c, 'near') : null;
  if (kind === 'safe') $('#incident').innerHTML = `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span>${sc.title}</div><h4>止まれた理由</h4><ul>${safeReasons(r, c).map((x) => `<li>${x}</li>`).join('')}</ul></div>`;
  const prev = sceneRuns.filter((x) => x.sceneId === sc.id).at(-1);
  sceneRuns.push({ sceneId: sc.id, cfg: c, kind, ex, reasons: kind === 'safe' ? safeReasons(r, c) : null });
  const btns = `<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></div>`;
  $('#incident').insertAdjacentHTML('beforeend', btns);
  $('#sAgain').addEventListener('click', () => { setPlayMode('setup'); });
  $('#sReplay').addEventListener('click', () => startScene());
  if (prev) $('#sCmp').addEventListener('click', () => openSceneCompare(prev, sceneRuns.at(-1)));
}
function openSceneCompare(a, b) {
  const sc = E.SCENES.find((x) => x.id === b.sceneId);
  const res = (x) => (x.kind === 'hit' ? '事故' : x.kind === 'near' ? 'ひやり' : '何も起きなかった');
  const changed = G().filter((g) => a.cfg[g.k] !== b.cfg[g.k]);
  const col = (x, other, title) => `<div class="col"><h3>${title}</h3>
    <div class="cfg">${G().map((g) => `<span>${g.label instanceof Function ? g.label(x.cfg) : g.label}</span><b class="${x.cfg[g.k] !== other.cfg[g.k] ? 'chg' : ''}">${label(g.k, x.cfg[g.k])}</b>`).join('')}</div>
    ${x.kind === 'safe' ? `<div class="inc safe"><div class="hd"><span class="tag">何も起きなかった</span></div><h4>止まれた理由</h4><ul>${x.reasons.map((t) => `<li>${t}</li>`).join('')}</ul></div>` : incCard(x.kind, x.ex, sc.title, '')}</div>`;
  const wa = new Set(a.ex ? a.ex.who : []), wb = new Set(b.ex ? 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) => `${g.label instanceof Function ? g.label(b.cfg) : g.label}を「${label(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>かかわる人は変わらなかった' : '');
  $('#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="foot"><button class="link" id="cmpBack">← 設定に戻る</button><button class="cta" id="cmpAgain">続けて、もう1つ変える <span aria-hidden="true">→</span></button></div>`;
  scene.moveTo($('#stage')); show('sceneCmp');
  $('#cmpBack').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
  $('#cmpAgain').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}
function startYear() {
  show('play'); setPlayMode('run');
  year = { cfg: { ...cfg }, seed: (runs.length + 1) * 7919, day: 0, pass: 0, accidents: [], near: 0, waitSum: 0, passes: 0 };
  updateStats(); tick();
}
function simDay() {
  const P = E.PARAMS, y = year; const shows = []; y.today = { day: y.day, acc: 0, near: 0 };
  for (let i = 0; i < P.passesPerDay; i++) {
    const seed = (y.seed * 1000003 + y.day * P.passesPerDay + i) >>> 0, evening = i >= 34 && i < 37;
    const r = E.simulatePass(y.cfg, E.rng(seed), { evening });
    y.passes++; y.waitSum += r.wait + (y.cfg.route === 'long' ? P.detourSec : 0);
    if (r.hit) { y.today.acc++; const a = { day: y.day, pass: i, seed, evening, facts: r.facts }; y.accidents.push(a); shows.push({ ...a, kind: 'hit' }); }
    else if (r.near) { y.near++; y.today.near++; if (shows.length < 1) shows.push({ day: y.day, pass: i, seed, evening, kind: 'near' }); }
  }
  y.day++; return shows;
}
function updateStats() {
  $('#sAcc').textContent = year.accidents.length; $('#sNear').textContent = year.near;
  $('#sDelay').textContent = (year.passes ? year.waitSum / year.passes / 60 : 0).toFixed(2); $('#sCost').textContent = E.cost(year.cfg);
  const d = Math.min(year.day, E.PARAMS.daysPerYear - 1);
  $('#date').innerHTML = `${dateOf(d)}<small>1年のうち ${d + 1}日目</small>`;
}
function playPass(p, rate, done, fromT = 0) {
  scene.setCfg(p.cfg || year.cfg); // 誘導員・植え込みを、この回の設定どおりに描く
  const r = E.simulatePass(p.cfg || year.cfg, E.rng(p.seed), { evening: p.evening, record: true, scene: p.scene });
  const hitE = r.events.find((e) => e.k === 'hit'); const fr = r.frames;
  let mark = null;
  if (p.kind === 'near' || (p.scene && r.near)) { let best = null; for (const f of fr) { if (f.bus.v <= 1.0) continue; for (const q of f.peds) { if (q.type === 'ambient' || (r.nearFacts && q.id !== r.nearFacts.id)) continue; const dd = Math.hypot(q.x - f.bus.x, q.z - f.bus.z); if (!best || dd < best.d) best = { d: dd, x: q.x, z: q.z, t: f.t }; } } mark = best; }
  const tEnd = hitE ? hitE.t + 1.5 : Math.min(E.PARAMS.passTime, (fr.at(-1) || { t: 0 }).t);
  // fromT < 0：交差点の手前16mあたりから見せる（長い直線は飛ばす）
  if (fromT < 0) { const f0 = fr.find((f) => Math.hypot(f.bus.x, f.bus.z + 4) < 16); fromT = f0 ? f0.t : 0; }
  // 速さは再生の途中でも変えられる（p.rate）。経過時間を毎回足していく
  p.rate = p.rate || rate; let t = fromT, last = performance.now(); replay = p; let lastF = null;
  $('#callout').style.display = 'none'; // 前の回の印を消してから始める
  const step = () => {
    if (replay !== p) return;
    const now = performance.now(); t += (now - last) / 1000 * p.rate; last = now; const f = frameAt(fr, t, r.route); lastF = f || lastF;
    if (f) {
      const opts = {};
      if (hitE && t >= hitE.t) { const q = f.peds.reduce((a, b) => (Math.hypot(b.x - f.bus.x, b.z - f.bus.z) < Math.hypot(a.x - f.bus.x, a.z - f.bus.z) ? b : a), f.peds[0] || f.bus); opts.red = q; callout(q, p.scene ? '事故' : `事故　${dateOf(p.day)} ${timeOf(p.pass)}`, '右のパネルに原因'); showIncident('hit', r.facts, p); }
      // ひやりの印は、近づいた瞬間から少しのあいだだけ出す
      if (mark && t >= mark.t && t < mark.t + 2.5) { opts.black = mark; callout(mark, 'ひやり', '右のパネルに原因'); if (r.nearFacts) showIncident('near', r.nearFacts, p); }
      else if (mark && t >= mark.t + 2.5 && !opts.red) $('#callout').style.display = 'none';
      scene.setFrame(f, opts);
    }
    if (t < tEnd) requestAnimationFrame(step);
    else { if (!hitE) { $('#callout').style.display = 'none'; if (lastF) scene.setFrame(lastF, {}); } if (replay === p) replay = null; done && done(r); }
  };
  requestAnimationFrame(step);
}
// 0.5秒ごとの記録の間をつないで、なめらかに動かす
function frameAt(fr, t, route) {
  if (!fr.length) return null;
  const i = Math.max(0, Math.min(fr.length - 1, Math.floor(t / 0.5))), a = fr[i], b = fr[i + 1] || a;
  const k = b === a ? 0 : Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t)));
  const L = (x, y) => x + (y - x) * k;
  let dh = b.bus.h - a.bus.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh));
  const peds = a.peds.map((p) => { const q = b.peds.find((x) => x.id === p.id) || p; return { ...p, x: L(p.x, q.x), z: L(p.z, q.z) }; });
  // バスは、道のりと速さから3次の補間でなめらかにつなぎ、道の形に沿って置く（直線でつなぐと速さが段になって見える）
  if (route && a.bus.s !== undefined && b !== a) {
    const T = b.t - a.t, u = k, h00 = 2 * u ** 3 - 3 * u ** 2 + 1, h10 = u ** 3 - 2 * u ** 2 + u, h01 = -2 * u ** 3 + 3 * u ** 2, h11 = u ** 3 - u ** 2;
    let sv = h00 * a.bus.s + h10 * T * a.bus.v + h01 * b.bus.s + h11 * T * b.bus.v; sv = Math.min(Math.max(sv, Math.min(a.bus.s, b.bus.s)), Math.max(a.bus.s, b.bus.s));
    const ps = E.ROUTES[route].pose(sv);
    return { t, bus: { x: ps.x, z: ps.z, h: ps.h, v: L(a.bus.v, b.bus.v), blink: a.bus.blink }, peds, guide: a.guide || b.guide };
  }
  return { t, bus: { x: L(a.bus.x, b.bus.x), z: L(a.bus.z, b.bus.z), h: a.bus.h + dh * k, v: L(a.bus.v, b.bus.v), blink: a.bus.blink }, peds, guide: a.guide || b.guide };
}
// 走っている間のパネル：起きたことの説明
let incLog = [], incShown = null;
// ひやり・事故の説明カード（いま起きたものも、一覧でひらいたものも同じ見た目）
function incCard(kind, ex, when, note) {
  const sec = (title, arr) => (arr.length ? `<h4>${title}</h4><ul class="who3">${arr.map((x) => `<li><b class="${x.who.includes('あなた') ? 'me' : ''}">${x.who}</b>${x.text}</li>`).join('')}</ul>` : '');
  return `<div class="inc ${kind}"><div class="hd"><span class="tag">${kind === 'hit' ? '事故' : 'ひやり'}</span>${when}</div>
    <p class="what">${ex.what}</p>
    ${sec('人の問題', ex.people)}${sec('企業の問題', ex.company)}${sec('決まり・行政', ex.rules)}
    ${ex.open ? `<div class="open"><span>まだ決まっていないこと</span>${ex.open}</div>` : ''}
    ${note ? `<p class="note" style="margin:0">${note}</p>` : ''}</div>`;
}
function collapseIncident() {
  if (!year || !year.today) return;
  const d = year.today, txt = d.acc || d.near ? `${dateOf(d.day)}：事故${d.acc}件・ひやり${d.near}回` : `${dateOf(d.day)}：ひやりも事故もなし`;
  $('#incident').innerHTML = `<p class="note" style="margin:0">${txt}</p>`;
  if (incOpen) { incOpen = false; drawIncLog(); }
}
function showIncident(kind, f, p) {
  const key = p.seed + ':' + kind + ':' + (p.runId || ''); if (incShown === key) return; incShown = key;
  const ex = explain(f, p.cfg || year.cfg, kind);
  if (p.scene) { $('#incident').innerHTML = incCard(kind, ex, p.scene.title, ''); return; }
  $('#incident').innerHTML = incCard(kind, ex, `${dateOf(p.day)} ${timeOf(p.pass)}`, kind === 'hit' ? '1年が終わったら、この事故で誰にどれだけ責任があるかを考えます' : '');
  incLog.unshift({ kind, t: `${dateOf(p.day)} ${timeOf(p.pass)}`, s: ex.causes[0], ex }); incLog = incLog.slice(0, 8); incOpen = true;
  drawIncLog();
}
// 1日が終わり、そのできごとの再生も終わったら、説明のカードをたたんで「これまで」の一覧に移し、今日のまとめを出す
let incOpen = false;
function drawIncLog() {
  // 一覧の1行を押すと、その場で詳しい説明（何が起きたか・なぜ・かかわる人）をひらく
  $('#incLog').innerHTML = (incOpen ? incLog.slice(1) : incLog).map((x, i) => `<div class="li" role="button" tabindex="0" data-i="${incOpen ? i + 1 : i}" aria-expanded="${!!x.open}"><span class="row1"><b class="${x.kind}">${x.kind === 'hit' ? '事故' : 'ひやり'}</b>${x.t}　${x.s}</span><div class="more">${incCard(x.kind, x.ex, x.t, '')}</div></div>`).join('');
}
function callout(pt, title, text) { const c = $('#callout'); const s = scene.screenOf(pt.x, pt.z); c.style.display = 'block'; c.style.left = Math.min(s.x + 30, scene.host.clientWidth - 270) + 'px'; c.style.top = Math.max(s.y - 80, 90) + 'px'; c.innerHTML = `<b>${title}</b>${text}`; }
function tick() {
  if (!year) return;
  if (year.day >= E.PARAMS.daysPerYear) return endYear();
  const shows = simDay(); updateStats();
  if (!replay || !incOpen) collapseIncident(); // 説明のカードは、そのできごとの再生が終わった次の日にたたむ
  const hit = shows.find((x) => x.kind === 'hit');
  if (!replay) $('#callout').style.display = 'none';
  if (speed === 'skip') { timer = setTimeout(tick, 0); return; }
  if (hit) { playPass(hit, 1, () => { timer = setTimeout(tick, 1200); }); return; }
  if (speed === 'real') { const p = shows[0] || { day: year.day - 1, pass: 0, seed: (year.seed * 1000003 + (year.day - 1) * 40) >>> 0, kind: 'plain' }; playPass(p, 1, () => { timer = setTimeout(tick, 200); }); return; }
  // 1日を1秒：日は進めつづけ、再生はそれとは別に、1回の通過を交差点の先まで最後まで見せる
  if (!replay) {
    const p = shows[0] || { day: year.day - 1, pass: 0, seed: (year.seed * 1000003 + (year.day - 1) * E.PARAMS.passesPerDay) >>> 0, kind: 'plain' };
    playPass(p, 2.5, () => {}, -1);
  }
  timer = setTimeout(tick, 1000);
}
// 結果まで飛ばす：画面が固まらないよう、数日ずつ区切って計算し、そのあいだも日付と数字を進める
function finishFast() {
  if (!year) return; stopTimers(); const y = year;
  const chunk = () => { if (year !== y) return; for (let i = 0; i < 6 && y.day < E.PARAMS.daysPerYear; i++) simDay(); updateStats(); if (y.day < E.PARAMS.daysPerYear) timer = setTimeout(chunk, 0); else endYear(); };
  chunk();
}
function endYear() { stopTimers(); year.delay = year.waitSum / year.passes / 60; year.cost = E.cost(year.cfg); runs.push(year); showResult(); }

// ---- ③ 結果 ----
const views = ['play', 'result', 'accident', 'assign', 'compare', 'sceneCmp'];
function show(v) { views.forEach((x) => $('#' + x).classList.toggle('on', x === v)); window.scrollTo(0, 0); }
function accText(a) {
  const f = a.facts; const who = f.startedBy === 'bus' ? 'バスが自分で発進した直後' : '運転士が発進させた直後';
  const ped = f.fromBehindHedge && year.cfg.route === 'short' ? '植え込みの陰から来た歩行者' : (E.PED_LABEL[f.pedType] || '横断歩道に向かってきた歩行者');
  return `${E.ROUTES[f.route].label}。${who}、${ped}と接触`;
}
function showResult() {
  const y = runs.at(-1), prev = runs.at(-2);
  const diffs = prev ? G().filter((g) => prev.cfg[g.k] !== y.cfg[g.k]) : [];
  const head = !prev ? `この仕組みで、1年に事故が${y.accidents.length}件、ひやりが${y.near}回起きた`
    : (diffs.length ? diffs.map((g) => changePhrase(g.k, y.cfg[g.k])).join('、') + 'ら、' : '同じ仕組みのままで、') + `事故は${y.accidents.length < prev.accidents.length ? '減った' : y.accidents.length > prev.accidents.length ? '増えた' : '変わらなかった'}`;
  const rows = [['事故', 'accidents', '件', (r) => r.accidents.length, true], ['ひやり（1m以内）', 'near', '回', (r) => r.near], ['1便の遅れ（平均）', 'delay', '分', (r) => r.delay.toFixed(2)], ['運行の費用（いちばん安い仕組みを100）', 'cost', '', (r) => r.cost]];
  const dif = (a, b) => { const d = +a - +b; return d === 0 ? '同じ' : `${Math.abs(+d.toFixed(2))}${d > 0 ? '増' : '減'}`; };
  $('#result').innerHTML = `
    <p class="eyebrow">1年（営業日300日・1日40便）を回した結果</p>
    <h2>${head}</h2>
    ${prev ? `<div class="chg"><span style="background:none;padding:0;color:var(--sub)">変えたところ</span>${diffs.map((g) => `<span>${glabel(g)}　${label(g.k, prev.cfg[g.k])}</span><span aria-hidden="true" style="background:none;padding:0">→</span><span class="now">${label(g.k, y.cfg[g.k])}</span>`).join('') || '<span>なし（乱数だけが違う）</span>'}</div>` : ''}
    <div class="two">
      <div style="display:flex;flex-direction:column;gap:10px">
        <div class="row" style="background:none;padding:0 20px;font-size:13px;color:var(--sub)"><span></span><span>${prev ? '前の1年' : ''}</span><span>${prev ? '今の1年' : 'この1年'}</span></div>
        ${rows.map(([k, , u, f, red]) => `<div class="row"><span class="k">${k}</span><span class="p">${prev ? f(prev) : ''}<small>${prev ? u : ''}</small></span><span class="n" style="${red ? 'color:var(--red)' : ''}">${f(y)}<small style="color:var(--ink)">${u}</small>${prev ? `<em>${dif(f(y), f(prev))}</em>` : ''}</span></div>`).join('')}
        <p class="note">運行の費用は、安全のためにかけたお金の大きさです。車内に乗る人や遠隔監視者の人件費、死角の少ないセンサー、誘導員、植え込みの手入れの依頼、休憩の交代要員が上乗せされます。安全とお金のどちらを取るかも、仕組みを決める人の判断です。<br>数字は試作の仮の決まりで出しています。同じ仕組みでも、歩行者の動きは毎年少しずつ違います</p>
      </div>
      <div>
        <p style="margin:0 0 10px;font-weight:700">この1年の事故　${y.accidents.length}件</p>
        ${y.accidents.slice(0, 4).map((a, i) => `<button class="acc" data-i="${i}"><span class="w">${dateOf(a.day)} ${timeOf(a.pass)}${a.evening ? '（夕方の逆光）' : ''}</span><span class="t">${accText(a)}</span><span class="go">くわしく見て、責任の割合を考える →</span></button>`).join('') || '<p class="note">この1年は事故が起きませんでした。ひやりは起きています</p>'}
        ${y.accidents.length > 4 ? `<p class="note">ほか ${y.accidents.length - 4}件</p>` : ''}
      </div>
    </div>
    <div class="foot"><span></span><button class="cta" id="again">仕組みを変えて、もう1年回す <span aria-hidden="true">→</span></button></div>`;
  show('result');
  $('#result').querySelectorAll('.acc').forEach((b) => b.addEventListener('click', () => openAccident(y.accidents[+b.dataset.i])));
  $('#again').addEventListener('click', () => { show('play'); setPlayMode('setup'); });
}

// ---- ④ 事故をひらく ----
let current = null;
let acStageReady = false;
function openAccident(a) {
  const y = runs.at(-1);
  const r = E.simulatePass(y.cfg, E.rng(a.seed), { evening: a.evening, record: true });
  const hit = r.events.find((e) => e.k === 'hit'); const t0 = hit.t;
  const st = r.events.find((e) => e.k === 'start'); const sensed = r.events.filter((e) => (e.k === 'sensed' || e.k === 'opbrake') && (!st || e.t >= st.t)).at(-1); // 発進したあとに気づいた時刻
  current = { a, r, y };
  const ev = r.events.filter((e) => e.t >= t0 - 30);
  $('#acL').innerHTML = `
    <p class="eyebrow">${dateOf(a.day)} ${timeOf(a.pass)}　T字路の横断歩道</p>
    <h2 style="margin:0;font-size:26px">事故の30秒</h2>
    <div id="facts">
      <div class="fact"><span>ぶつかったときの速さ</span><b>${hit.kmh}</b><i>km/時</i></div>
      <div class="fact"><span>危ないと気づいたのは</span>${sensed ? `<b>${(t0 - sensed.t).toFixed(1)}</b><i>秒前</i>` : '<b style="font-size:18px">気づけなかった</b>'}</div>
      <div class="fact"><span>歩行者</span><b style="font-size:18px">${(E.PED_LABEL[a.facts.pedType] || '').replace('人', '')}${a.facts.phone ? '・スマホを見ていた' : ''}</b></div>
    </div>
    <div style="display:flex;flex-direction:column;gap:8px" id="evs">
      ${ev.map((e, i) => `<button class="ev" data-t="${e.t}"><b>${e.t - t0 === 0 ? '0秒' : `−${(t0 - e.t).toFixed(1)}秒`}</b><span>${e.text}</span></button>`).join('')}
    </div>
    <p class="note">記録を押すと、その時刻の交差点に切り替わります。実際の事故の流れを参考にした、架空の事故です</p>
    <div class="foot"><button class="link" id="backRes">← 結果に戻る</button><button class="cta" id="toAssign">責任の割合を考える <span aria-hidden="true">→</span></button></div>`;
  show('accident');
  if (!acStageReady) { scene.moveTo($('#acR')); acStageReady = true; } else scene.moveTo($('#acR'));
  const seek = (t) => { const f = r.frames[Math.min(r.frames.length - 1, Math.ceil(t / 0.5))]; scene.setFrame(f, t >= t0 ? { red: { x: hit.x, z: hit.z } } : {}); };
  $('#evs').addEventListener('click', (e) => { const b = e.target.closest('.ev'); if (!b) return; $('#evs').querySelectorAll('.ev').forEach((x) => x.classList.toggle('on', x === b)); seek(+b.dataset.t); });
  const last = $('#evs').lastElementChild; last && last.click();
  $('#backRes').addEventListener('click', () => { scene.moveTo($('#stage')); show('result'); });
  $('#toAssign').addEventListener('click', openAssign);
}

// ---- ⑤ 責任の割合を考える ----
let alloc = null;
// ひやり・事故の原因と、かかわる人を、記録から組み立てる（走っている間のパネルと、責任を配る画面で同じものを使う）
// 運行の形ごとの、見ている人の呼び名
const WATCHER = (c) => ({ l2: '運転士', l4in: '車内の主任者', l4r1: '遠隔監視者', l4r3: '遠隔監視者' })[c.mode] || '運転士';
const IS_L4 = (c) => c.mode !== 'l2';
// ひやり・事故の説明を、人／企業／決まり・行政の3段と「まだ決まっていないこと」に組み立てる
// 決まりは「関係しそうな決まり」の名前だけを示し、法律上の答えは出さない
function explain(f, c, kind) {
  const people = [], company = [], rules = [], opens = [];
  const add = (arr, who, text) => { if (!arr.some((x) => x.text === text)) arr.push({ who, text }); };
  const ped = E.PED_LABEL[f.pedType] || '歩行者', W = WATCHER(c), me = '運行会社（あなた）';
  if (f.state === 'approach') add(people, '歩行者', `交差点に近づくバスの前に、${ped}が車道へ入ってきた`);
  else if (f.startedBy === 'human') {
    if (f.missed) add(people, W, 'この人を見落としたまま、発進させた');
    else if (c.guide && f.trustGuide) { add(people, W, '「誘導員が歩行者を止めてくれる」と読んで、早めに発進させた'); opens.push('誘導員の合図に、運転する側がどこまで頼ってよいか（決まりがない）'); }
    else add(people, W, '発進させたあとに、この人が横断歩道へ入ってきた。発進の判断そのものが問われる');
  } else {
    if (f.hedge && c.route === 'short' && c.sensor === 'normal') add(company, 'メーカー', '植え込みの陰が、バスのセンサーの死角になっていた');
    else if (c.sensor === 'normal') add(company, 'メーカー', 'バスは、横断歩道に向かってくる人を先読みしないまま、自分で発進した');
    else add(people, ped, 'バスが発進したあとに、この人が横断歩道へ入ってきた');
    if (f.missed) add(people, W, c.mode === 'l4in' ? '車内で見ていたが、この人を見落とした' : '映像でこの人を見落とした');
    if (c.mode === 'l4r1' || c.mode === 'l4r3') add(people, W, `映像で気づいて止める指示を出すまでに、時間がかかった${c.mode === 'l4r3' ? '（1人で3台を見ていた）' : ''}`);
  }
  if (f.state !== 'approach' && c.guide && f.guideRaised && !f.guideClear) add(people, '誘導員', '合図が、バスと歩行者のどちらに向けたものか、あいまいだった');
  if (f.phone) add(people, ped, 'スマホを見ていて、バスに気づくのが遅れた');
  if (f.pedType === 'hurry') add(people, ped, '急いでいて、バスのすぐそばに来るまで止まらなかった');
  if (f.pedType === 'diagonal') add(people, ped, '横断歩道の外を斜めに渡っていた');
  if (f.pedType === 'hesitate') add(people, ped, '端で迷ったあと、急に渡りはじめた');
  if (f.evening) add(company, 'メーカー', '夕方の逆光で、センサーの見える距離が短くなっていた');
  // 運行会社（見る人）の判断
  if (!c.rest && f.missed) add(company, me, `${W}を休憩なしで働かせていて、見落としやすくなっていた`);
  if (c.mode === 'l4r3') add(company, me, '遠隔監視者1人に3台を見させていた');
  if (c.speed >= 15) add(company, me, '交差点の速さを時速15kmにしていて、止まりきるまでの距離が長かった');
  if (!c.guide && f.state !== 'approach') add(company, me, '交差点に誘導員を置いていなかった');
  if (c.sensor === 'normal' && IS_L4(c) && f.state !== 'approach') add(company, me, '死角の少ないセンサーを入れていなかった');
  if (f.hedge && c.route === 'short') { add(company, '道の管理者', '高い植え込みが、交差点の見通しを悪くしていた'); add(company, me, '植え込みを刈るよう、道の管理者に頼んでいなかった'); }
  // 決まり・行政（関係しそうな決まりの名前だけ）
  if (c.mode === 'l2') { add(rules, '道路交通法', 'レベル2では運転の主体は運転士。運転士の安全確認の義務が中心になる'); opens.push('システムに任せて見ているだけの運転士に、どこまでの注意を求めるか'); }
  else { add(rules, '道路交通法（特定自動運行）', 'レベル4は公安委員会の許可を受けた運行。運行する会社と主任者に、決められた義務がある'); opens.push('レベル4の事故で、誰が刑事責任を負うか'); }
  add(rules, '自動車損害賠償保障法', 'けがをした人への賠償は、運送する会社（運行供用者）が負う、という整理が進んでいる');
  if (company.some((x) => x.who === 'メーカー')) { add(rules, '製造物責任法', 'センサーやソフトの作りに欠陥があればメーカーが問われ得る'); opens.push('ソフトウェアの欠陥を、製造物の欠陥として問えるか（日本では未整理）'); }
  if (company.some((x) => x.who === '道の管理者')) add(rules, '国家賠償法', '道の管理に問題があれば、道を管理する役所が問われ得る');
  if (c.mode === 'l4r3' || (c.mode === 'l4r1' && f.missed)) opens.unshift('遠隔監視者1人が何台まで見てよいか（基準なし）');
  if (people.some((x) => x.who === ped)) add(rules, '民事の過失', '歩行者の不注意は、賠償の割合を減らす事情として見られることがある');
  if (kind === 'hit') add(rules, '事故の報告', '運行する会社は、事故を警察に報告する。事故を調べる国の仕組みは、権限を強める方向で検討中');
  const R = E.ROUTES[f.route];
  const what = kind === 'hit' ? `${R.label}するバスが、${ped}と接触した（時速${f.kmh ?? '?'}km）` : `${R.label}するバスに、${ped}が${f.dist < 0.1 ? 'ほとんど触れるほど' : f.dist.toFixed(1) + 'm まで'}近づいた（バスは時速${f.kmh}km）`;
  const who = [...new Set([...people, ...company].map((x) => x.who))];
  return { what, people, company, rules, open: opens[0] || '', who, causes: [...people, ...company].map((x) => x.text) };
}
function clues() {
  // 責任の割合を考える相手と、その手がかり（説明の3段と同じ記録から作る）
  const { a, y } = current, f = a.facts, c = y.cfg, ex = explain(f, c, 'hit'), W = WATCHER(c);
  const of = (nm, fallback) => { const t = [...ex.people, ...ex.company].filter((x) => x.who === nm || (nm === '歩行者' && x.who === (E.PED_LABEL[f.pedType] || '歩行者'))).map((x) => x.text); return t.length ? t.join('。') : fallback; };
  return [
    { k: 'maker', nm: 'メーカー', cl: of('メーカー', c.sensor === 'wide' ? '死角の少ないセンサーを入れていた' : '目立った問題は記録に残っていない') },
    { k: 'op', nm: '運行会社（あなた）', me: true, cl: of('運行会社（あなた）', '') + '（あなたが決めた：' + [label('mode', c.mode), `時速${c.speed}km`, c.guide ? '誘導員あり' : '誘導員なし', c.route === 'short' ? '植え込みはそのまま' : '植え込みを刈ってもらう', c.rest ? 'こまめに休憩' : '休憩なし'].join('・') + '）' },
    { k: 'driver', nm: W, cl: of(W, c.mode === 'l2' ? '発進させ、運転を見ていた' : '見ていたが、記録に残る見落としはない') },
    { k: 'guide', nm: '誘導員', cl: c.guide ? of('誘導員', '「止まれ」の合図ははっきり出ていた') : 'この1年は置いていない', off: !c.guide },
    { k: 'road', nm: '道の管理者', cl: c.route === 'short' ? of('道の管理者', '交差点の植え込みが高く、見通しを悪くしていた') + '（運行会社から刈るよう頼まれてはいない）' : '頼まれて、植え込みを低く刈っていた' },
    { k: 'ped', nm: '歩行者', cl: of('歩行者', '前を見て歩いていた') },
  ];
}
function openAssign() {
  const ps = clues(); const n = ps.filter((p) => !p.off).length;
  alloc = Object.fromEntries(ps.map((p) => [p.k, p.off ? 0 : Math.round(100 / n)])); fix(ps[0].k);
  const draw = () => ps.map((p) => `<div class="party ${p.me ? 'me' : ''}"><span class="nm">${p.nm}</span><span class="cl">${p.cl}</span><input type="range" min="0" max="100" step="1" value="${alloc[p.k]}" data-k="${p.k}" aria-label="${p.nm}の責任" ${p.off ? 'disabled' : ''}><span class="v"><span id="v-${p.k}">${alloc[p.k]}</span><small style="font-size:13px;font-weight:400">%</small></span></div>`).join('');
  $('#assign').innerHTML = `<p class="eyebrow">${dateOf(current.a.day)} ${timeOf(current.a.pass)}　T字路の横断歩道</p><h2>この事故、誰にどれだけ責任がある？</h2><p class="note">合計がいつも100%になるよう、ほかが自動で動きます</p><div style="display:flex;flex-direction:column;gap:10px" id="parties">${draw()}</div>
  <div class="foot"><button class="link" id="backAc">← 事故の30秒に戻る</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]; }); });
  $('#backAc').addEventListener('click', () => show('accident'));
  $('#toCompare').addEventListener('click', () => openCompare(ps));
  function fix(k) {
    const others = ps.filter((p) => p.k !== k && !p.off).map((p) => p.k); const rest = 100 - alloc[k]; const sum = others.reduce((s, x) => s + alloc[x], 0);
    others.forEach((x) => { alloc[x] = sum ? Math.round(alloc[x] / sum * rest) : Math.round(rest / others.length); });
    const drift = 100 - Object.values(alloc).reduce((s, v) => s + v, 0); if (others[0]) alloc[others[0]] += drift;
  }
}

// ---- ⑥ 比べる ----
function openCompare(ps) {
  const top = ps.reduce((m, p) => (alloc[p.k] > alloc[m.k] ? p : m), ps[0]);
  $('#compare').innerHTML = `<p class="eyebrow">あなたの考えた割合</p><h2>あなたは「${top.nm}」の責任を一番重く見た</h2>
  <div style="display:flex;flex-direction:column;gap:10px">${ps.map((p) => `<div class="row" style="grid-template-columns:180px minmax(0,1fr) 90px"><span class="k">${p.nm}</span><div class="bars"><div class="bar" style="width:${alloc[p.k]}%"></div></div><span class="n" style="font-size:24px;text-align:right">${alloc[p.k]}<small>%</small></span></div>`).join('')}</div>
  <p class="note">ほかの人の割合と並べる部分は、答えを集める仕組みができてから入ります（試作 v0 では答えを送りません）。法律上の正解を示すものではありません</p>
  <div class="foot"><button class="link" id="otherAc">ほかの事故をひらく</button><button class="cta" id="again2">仕組みを変えて、もう1年回す <span aria-hidden="true">→</span></button></div>`;
  show('compare');
  $('#otherAc').addEventListener('click', () => { scene.moveTo($('#stage')); show('result'); });
  $('#again2').addEventListener('click', () => { scene.moveTo($('#stage')); show('play'); setPlayMode('setup'); });
}
drawPanel(); setPlayMode('setup'); setPlayKind('scene');
window.__ready = true;
}
</script>
</body>
</html>
