---
// サービスロボット導入シミュレーション（/series8）の「3Dの場面」（2026-11-13・LOG503）
// 看護師と搬送ロボット「ハコブくん」のやり取りを、場面ごとに動画と説明のパネルで見せる。
// 中身は src/data/sim_scenes.json。動画は R2 の /media/。
// 黒い面に、上に大きな動画と説明、下に全場面の一覧（場所で絞れる）を置く。場面が増えても一覧が伸びるだけで形は崩れない（2026-11-15）。
// 場面を選ぶ → 動画と説明が切り替わる。角度（本番・横から・真上）を切り替えられる。
// 本番と真上の動画では、流れの行を押すとその時刻へ移り、再生中の行に印が付く。
import data from '../data/sim_scenes.json';
import { media } from '../lib/media';
// TOP にも置く（2026-11-15 エイイチの指示）。押された数を分けて数えるため、place で data-ev の頭を変える
const { place = 'series8' } = Astro.props as { place?: 'series8' | 'top' };
const ev = (t: string) => (place === 'top' ? `TOP:${t}` : t);
const first = data.scenes[0];
const fmt = (t: number) => `0:${String(Math.floor(t)).padStart(2, '0')}`;
---
<section class="s-3d" id="scenes" data-ev-area={place === 'top' ? 'top-scenes' : 'scenes'}><div class="sc-in">
  <h2 class="sec-h">3Dで見る現場の場面 | Scenes</h2>
  <p class="sc-lead">{data.title}</p>
  <p class="sc-note">{data.note}</p>

  <div class="sc-stage" id="sc-stage" role="tabpanel">
    <div class="sc-video">
      <div class="sc-frame">
        <video id="sc-v" src={media(first.angles[0].src)} poster={media(first.poster)} controls muted playsinline preload="metadata" aria-label={`${first.name}（${first.angles[0].label}）`}></video>
      </div>
      <div class="sc-angles" id="sc-angles" role="group" aria-label="カメラの角度">
        {first.angles.map((a, i) => (
          <button type="button" class="sc-angle" aria-pressed={i === 0 ? 'true' : 'false'} data-angle={a.id}>{a.label}<i>{a.sec}秒</i></button>
        ))}
      </div>
      <p class="sc-angle-note" id="sc-angle-note" hidden></p>
    </div>

    <div class="sc-info">
      <h3 class="sc-name" id="sc-name">{first.name}</h3>
      <dl class="sc-meta">
        <div><dt>場所</dt><dd id="sc-place">{first.place}</dd></div>
        <div><dt>登場</dt><dd id="sc-who">{first.who}</dd></div>
      </dl>
      <p class="sc-sit" id="sc-sit">{first.situation}</p>
      <p class="sc-h sc-h-steps">流れ<span id="sc-steps-hint">（押すとその場面へ）</span></p>
      <ol class="sc-steps" id="sc-steps">
        {first.steps.map((st) => (
          <li><button type="button" data-t={st.t}><time>{fmt(st.t)}</time><span>{st.text}</span></button></li>
        ))}
      </ol>
      <p class="sc-h sc-h-points">見どころ</p>
      <ul class="sc-points" id="sc-points">{first.points.map((p) => <li>{p}</li>)}</ul>
    </div>
  </div>
  {data.groups && data.groups.length > 1 && (
    <div class="sc-filter" role="group" aria-label="場所で絞る">
      <button type="button" aria-pressed="true" data-group="">すべて</button>
      {data.groups.map((g) => <button type="button" aria-pressed="false" data-group={g}>{g}</button>)}
    </div>
  )}
  <div class="sc-picks" role="tablist" aria-label="3Dの場面">
    {data.scenes.map((s, i) => (
      <button type="button" role="tab" class="sc-pick" data-group={s.group} id={`sctab-${s.id}`} aria-selected={i === 0 ? 'true' : 'false'} aria-controls="sc-stage" data-scene={s.id} data-ev={ev(`3Dの場面:${s.name}`)}>
        <img src={media(s.poster)} alt="" loading="lazy" />
        <b>{s.name}</b>
      </button>
    ))}
  </div>

  <a class="sc-log" href={data.log.href} data-ev={ev('3Dの場面の記録を開く')}>{data.log.label} →</a>
</div></section>

<script define:vars={{ scenes: data.scenes.map((s) => ({ ...s, poster: media(s.poster), angles: s.angles.map((a) => ({ ...a, src: media(a.src) })) })) }}>
  const $ = (id) => document.getElementById(id);
  const v = $('sc-v');
  const picks = [...document.querySelectorAll('.sc-pick')];
  const fmt = (t) => `0:${String(Math.floor(t)).padStart(2, '0')}`;
  let scene = scenes[0], angle = scene.angles[0];

  const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
  const setAngle = (a, keepTime) => {
    const t = keepTime && a.timed && angle.timed ? v.currentTime : 0;
    const playing = !v.paused;
    angle = a;
    document.querySelectorAll('.sc-angle').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.angle === a.id)));
    v.src = a.src; v.poster = a.id === 'main' ? scene.poster : '';
    v.setAttribute('aria-label', `${scene.name}（${a.label}）`);
    if (t) v.addEventListener('loadedmetadata', () => { v.currentTime = t; }, { once: true });
    if (playing) v.play().catch(() => {});
    const note = $('sc-angle-note'); note.hidden = !a.note; note.textContent = a.note || '';
    // 流れの時刻は本番と真上の動画のもの。横からの動画（短い切り出し）では押せないようにする
    const steps = $('sc-steps'); steps.classList.toggle('off', !a.timed);
    $('sc-steps-hint').textContent = a.timed ? '（押すとその場面へ）' : '（本番のカメラの時刻）';
    mark();
  };
  const setScene = (s, push) => {
    scene = s;
    picks.forEach((b) => { const on = b.dataset.scene === s.id; b.setAttribute('aria-selected', String(on)); b.tabIndex = on ? 0 : -1; });
    $('sc-name').textContent = s.name;
    $('sc-place').textContent = s.place; $('sc-who').textContent = s.who; $('sc-sit').textContent = s.situation;
    $('sc-points').innerHTML = s.points.map((p) => `<li>${esc(p)}</li>`).join('');
    $('sc-steps').innerHTML = s.steps.map((st) => `<li><button type="button" data-t="${st.t}"><time>${fmt(st.t)}</time><span>${esc(st.text)}</span></button></li>`).join('');
    $('sc-angles').innerHTML = s.angles.map((a, i) => `<button type="button" class="sc-angle" aria-pressed="${i === 0}" data-angle="${a.id}">${esc(a.label)}<i>${a.sec}秒</i></button>`).join('');
    v.pause();
    angle = s.angles[0];
    setAngle(s.angles[0], false);
    if (push) history.replaceState(null, '', `#scene-${s.id}`);
  };
  // 再生中の行に印を付ける
  const mark = () => {
    const items = [...document.querySelectorAll('#sc-steps li')];
    let k = -1;
    if (angle.timed) scene.steps.forEach((st, i) => { if (v.currentTime + 0.05 >= st.t) k = i; });
    items.forEach((li, i) => li.classList.toggle('now', i === k));
  };
  v.addEventListener('timeupdate', mark);
  v.addEventListener('seeked', mark);
  $('sc-steps').addEventListener('click', (e) => {
    const b = e.target.closest('button[data-t]'); if (!b || !angle.timed) return;
    v.currentTime = Number(b.dataset.t); v.play().catch(() => {});
  });
  $('sc-angles').addEventListener('click', (e) => {
    const b = e.target.closest('.sc-angle'); if (!b) return;
    const a = scene.angles.find((x) => x.id === b.dataset.angle); if (a && a !== angle) setAngle(a, true);
  });
  picks.forEach((b, i) => {
    b.tabIndex = i === 0 ? 0 : -1;
    b.addEventListener('click', () => {
      setScene(scenes.find((s) => s.id === b.dataset.scene), true);
      // 一覧は動画の下にあるので、選んだら動画の位置へ戻す
      const st = $('sc-stage'); if (st.getBoundingClientRect().top < 0) st.scrollIntoView({ behavior: 'smooth' });
    });
    b.addEventListener('keydown', (e) => {
      const k = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0; if (!k) return;
      e.preventDefault();
      const vis = picks.filter((x) => !x.hidden); const j = vis.indexOf(b);
      const n = vis[(j + k + vis.length) % vis.length]; n.focus(); n.click();
    });
  });
  // 場所で絞る（一覧の表示だけを変える。再生中の場面はそのまま）
  document.querySelectorAll('.sc-filter button').forEach((f) => f.addEventListener('click', () => {
    const g = f.dataset.group;
    document.querySelectorAll('.sc-filter button').forEach((x) => x.setAttribute('aria-pressed', String(x === f)));
    picks.forEach((b) => { b.hidden = !!g && b.dataset.group !== g; });
  }));
  // /series8#scene-stumble のように開くと、その場面から始まる
  const start = scenes.find((s) => location.hash === `#scene-${s.id}`);
  if (start) { setScene(start, false); $('scenes').scrollIntoView(); }
</script>

<style is:global>
  /* 中身を JS で入れ替えるので、global にして .s-3d の中だけに効かせる */
  /* セクションを画面の横いっぱいの黒い面にする。上に動画と説明、下に全場面の一覧（2026-11-15） */
  .s-3d { margin: 40px 0; padding: 80px; background: #111; color: #f5f5f0; }
  /* 中身の左右は、ほかのセクションの白いカード（.panel）の中身とそろえる */
  .s-3d .sc-in { box-sizing: border-box; max-width: 1280px; margin: 0 auto; padding: 0 32px; }
  .s-3d .sec-h { color: #f5f5f0; }
  .s-3d .sc-lead { margin: -12px 0 8px; font: 600 18px/28px var(--sans); color: #f5f5f0; }
  .s-3d .sc-note { margin: 0 0 40px; font: 400 14px/24px var(--sans); color: #b8b8b0; max-width: 880px; }
  /* 動画（左）と説明（右） */
  .s-3d .sc-stage { display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 40px; align-items: start; scroll-margin-top: 96px; }
  .s-3d .sc-frame { background: #000; border-radius: 8px; overflow: hidden; }
  .s-3d .sc-frame video { display: block; width: 100%; aspect-ratio: 16 / 9; background: #000; }
  .s-3d .sc-angles { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0 0; }
  .s-3d .sc-angle { display: inline-flex; align-items: baseline; gap: 6px; padding: 8px 14px; border: 0; border-radius: 4px; background: #2a2a2a; color: #f5f5f0; font: 500 14px/20px var(--sans); cursor: pointer; }
  .s-3d .sc-angle:hover { background: #3a3a3a; }
  .s-3d .sc-angle i { font-style: normal; font-size: 12px; color: #888; font-variant-numeric: tabular-nums; }
  .s-3d .sc-angle[aria-pressed="true"] { background: #f5f5f0; color: #111; }
  .s-3d .sc-angle[aria-pressed="true"] i { color: #555; }
  .s-3d .sc-angle-note { margin: 8px 0 0; font: 400 13px/22px var(--sans); color: #b8b8b0; }
  .s-3d .sc-name { margin: 0 0 16px; font: 600 24px/36px var(--sans); color: #f5f5f0; }
  .s-3d .sc-meta { margin: 0 0 16px; display: grid; gap: 6px; }
  .s-3d .sc-meta div { display: grid; grid-template-columns: 3em minmax(0, 1fr); gap: 8px; }
  .s-3d .sc-meta dt { font: 500 12px/22px var(--sans); color: #888; }
  .s-3d .sc-meta dd { margin: 0; font: 400 13px/22px var(--sans); color: #f5f5f0; }
  .s-3d .sc-sit { margin: 0 0 24px; font: 400 14px/26px var(--sans); color: #d8d8d0; }
  .s-3d .sc-h { margin: 0 0 8px; font: 600 13px/20px var(--sans); color: #f5f5f0; }
  .s-3d .sc-h span { font-weight: 400; color: #888; }
  .s-3d .sc-steps { list-style: none; margin: 0 0 24px; padding: 0; display: grid; gap: 2px; }
  .s-3d .sc-steps button { display: grid; grid-template-columns: 3em minmax(0, 1fr); gap: 8px; width: 100%; padding: 6px 8px; border: 0; border-radius: 4px; background: transparent; text-align: left; cursor: pointer; font: inherit; color: #f5f5f0; }
  .s-3d .sc-steps button:hover { background: #2a2a2a; }
  .s-3d .sc-steps time { font: 500 12px/22px var(--sans); color: #888; font-variant-numeric: tabular-nums; }
  .s-3d .sc-steps span { font: 400 13px/22px var(--sans); }
  /* 再生中の行は、行ごと白く塗る（左の線は使わない） */
  .s-3d .sc-steps li.now button, .s-3d .sc-steps li.now button:hover { background: #f5f5f0; color: #111; }
  .s-3d .sc-steps li.now time { color: #555; }
  .s-3d .sc-steps.off button { cursor: default; }
  .s-3d .sc-steps.off button:hover { background: transparent; }
  .s-3d .sc-points { margin: 0; padding-left: 1.2em; font: 400 13px/24px var(--sans); color: #d8d8d0; }
  /* 場所で絞る（選んだものは面ごと白く塗る） */
  .s-3d .sc-filter { display: flex; flex-wrap: wrap; gap: 8px; margin: 56px 0 20px; }
  .s-3d .sc-filter button { padding: 10px 18px; border: 0; border-radius: 6px; background: #2a2a2a; color: #f5f5f0; font: 600 14px/20px var(--sans); cursor: pointer; }
  .s-3d .sc-filter button:hover { background: #3a3a3a; }
  .s-3d .sc-filter button[aria-pressed="true"] { background: #f5f5f0; color: #111; }
  /* 全場面の一覧（増えたら行が増える） */
  .s-3d .sc-picks { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; margin: 0; }
  .s-3d .sc-stage + .sc-picks, .s-3d .sc-stage + .sc-log { margin-top: 56px; }
  .s-3d .sc-pick { display: block; padding: 0; border: 0; border-radius: 6px; overflow: hidden; background: #2a2a2a; color: #f5f5f0; text-align: left; cursor: pointer; font: inherit; }
  .s-3d .sc-pick[hidden] { display: none; }
  .s-3d .sc-pick img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; opacity: .72; transition: opacity .2s; }
  .s-3d .sc-pick b { display: block; padding: 8px 10px 10px; font: 600 14px/20px var(--sans); }
  .s-3d .sc-pick:hover { background: #3a3a3a; }
  .s-3d .sc-pick:hover img, .s-3d .sc-pick[aria-selected="true"] img { opacity: 1; }
  .s-3d .sc-pick[aria-selected="true"] { background: #f5f5f0; color: #111; }
  .s-3d .sc-pick:focus-visible, .s-3d .sc-filter button:focus-visible { outline: 2px solid #f5f5f0; outline-offset: 2px; }
  .s-3d .sc-log { display: inline-block; margin-top: 40px; font: 500 14px/22px var(--sans); color: #f5f5f0; text-decoration: underline; text-underline-offset: 3px; }
  @media (max-width: 1023px) {
    .s-3d { padding: 56px 24px; }
    .s-3d .sc-stage { grid-template-columns: minmax(0, 1fr); gap: 28px; }
    .s-3d .sc-picks { grid-template-columns: repeat(3, minmax(0, 1fr)); }
  }
  @media (max-width: 599px) {
    .s-3d { margin: 32px 0; padding: 40px 12px; }
    .s-3d .sc-in { padding: 0 16px; }
    .s-3d .sc-name { font-size: 20px; line-height: 30px; }
    .s-3d .sc-filter { margin-top: 40px; }
    .s-3d .sc-picks { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
    .s-3d .sc-pick b { font-size: 13px; line-height: 18px; padding: 6px 8px 8px; }
  }
</style>
