// AmosReactionReader — long-form reader for a reaction-video article.
// Layout: sticky topbar, then a two-column stage:
//   Left  — the "video" (poster panel with play/scrub/time + current-pause banner)
//   Right — sticky rail of Amos' timed pauses, each jumping the scrubber
//
// Media is simulated with a timer (no real file). When a pause timestamp is
// reached, the video "pauses" and the active pause card slides into place.
// Clicking a pause in the rail jumps there and shows its comment.

function AmosReactionReader({ articleId, onBack, onOpenDoc, onOpenCollection }) {
  const I = window.useI18n();
  const meta = (window.AMOS_DATA.articles || []).find(a => a.id === articleId);
  const body = (window.AMOS_REACTION_BODIES || {})[articleId];

  // Hamburger so the sidebar is reachable from the reaction reader on mobile
  // (audit rank 9).
  const burger = React.createElement('button', {
    className:'amos-sidebar-toggle', type:'button',
    onClick: () => window.dispatchEvent(new CustomEvent('amos:toggle-sidebar')),
    title:'Open navigation  ([)', 'aria-label':'Open navigation'
  },
    React.createElement('svg',{width:16,height:16,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:'2',strokeLinecap:'round'},
      React.createElement('line',{x1:3,y1:6,x2:21,y2:6}),
      React.createElement('line',{x1:3,y1:12,x2:21,y2:12}),
      React.createElement('line',{x1:3,y1:18,x2:21,y2:18})
    )
  );

  const [time, setTime] = React.useState(0);         // seconds
  const [playing, setPlaying] = React.useState(false);
  const [atPause, setAtPause] = React.useState(null); // current pause object
  const [activeIdx, setActiveIdx] = React.useState(0);
  const lastPauseRef = React.useRef(-1);
  const rafRef = React.useRef(null);
  const tickRef = React.useRef(null);

  // Persist scrub position so reloads keep the pastor's place
  const STORE_KEY = 'amos.amos.reaction.' + articleId + '.t';
  React.useEffect(() => {
    const saved = parseInt(localStorage.getItem(STORE_KEY) || '0', 10);
    if (!isNaN(saved) && saved > 0) setTime(saved);
  }, [articleId]);
  React.useEffect(() => {
    try { localStorage.setItem(STORE_KEY, String(time)); } catch {}
  }, [time]);

  if (!meta || !body) {
    return React.createElement('div', { className:'amos-reader' },
      React.createElement('div', { className:'car-topbar' },
        burger,
        React.createElement('button', { className:'back', onClick: onBack },
          window.I.chevron(14), 'Back to Amos of Rome')
      ),
      React.createElement('div', {
        style:{ padding:48, fontFamily:'Iowan Old Style, serif', color:'#7d5a17' }
      }, 'This reaction is in preparation.')
    );
  }

  const total = body.source.duration;
  const pauses = body.timeline.filter(e => e.kind === 'pause');

  const fmtTime = (s) => {
    s = Math.max(0, Math.floor(s));
    const m = Math.floor(s / 60);
    const r = s % 60;
    return m + ':' + (r < 10 ? '0' : '') + r;
  };

  // Tick engine
  React.useEffect(() => {
    if (!playing) { if (tickRef.current) { clearInterval(tickRef.current); tickRef.current = null; } return; }
    tickRef.current = setInterval(() => {
      setTime(t => {
        const next = t + 1;
        if (next >= total) {
          setPlaying(false);
          return total;
        }
        // Trigger a pause if we've crossed its timestamp
        const hit = pauses.find(p => p.at > t && p.at <= next);
        if (hit && lastPauseRef.current !== hit.at) {
          lastPauseRef.current = hit.at;
          setAtPause(hit);
          setActiveIdx(pauses.indexOf(hit));
          setPlaying(false);
        }
        return next;
      });
    }, 250); // 1 simulated second per 250ms so the demo moves briskly
    return () => { if (tickRef.current) clearInterval(tickRef.current); };
  }, [playing, total, pauses]);

  const jumpTo = (p) => {
    lastPauseRef.current = p.at;
    setTime(p.at);
    setAtPause(p);
    setActiveIdx(pauses.indexOf(p));
    setPlaying(false);
  };

  const resume = () => {
    setAtPause(null);
    setPlaying(true);
  };
  const togglePlay = () => {
    if (atPause) { resume(); return; }
    setPlaying(p => !p);
  };

  // Track click → scrub
  const onTrackClick = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const pct = (e.clientX - rect.left) / rect.width;
    const t = Math.round(pct * total);
    // Find nearest pause we've crossed
    const passed = pauses.slice().reverse().find(p => p.at <= t);
    lastPauseRef.current = passed ? passed.at : -1;
    setTime(t);
    setAtPause(null);
    if (passed) setActiveIdx(pauses.indexOf(passed));
    setPlaying(false);
  };

  const refChipClick = (r) => {
    if (r.docKey) onOpenDoc && onOpenDoc({ id: r.docKey });
    else if (r.collectionKey) onOpenCollection && onOpenCollection(r.collectionKey);
  };

  return React.createElement('div', { className:'amos-reader amos-rx' },

    // Topbar (matches AmosArticleReader look)
    React.createElement('div', { className:'car-topbar' },
      burger,
      React.createElement('button', { className:'back', onClick: onBack },
        window.I.chevron(14), 'Back to Amos of Rome'),
      React.createElement('div', { className:'car-topbar-meta' },
        React.createElement('span', { className:'kind' }, 'Reaction video'),
        React.createElement('span', { className:'sep' }, '\u00b7'),
        React.createElement('span', null, body.source.preacher, ' \u00b7 ', body.source.congregation)
      )
    ),

    // Byline block
    React.createElement('header', { className:'rx-header' },
      React.createElement('div', { className:'rx-kicker' },
        React.createElement('span', { className:'rx-dot' }),
        'Amos watches ',
        React.createElement('span', null, body.source.preacher)
      ),
      React.createElement('h1', { className:'rx-title' }, meta.title),
      meta.subtitle && React.createElement('p', { className:'rx-sub' }, meta.subtitle),
      React.createElement('div', { className:'rx-stats' },
        React.createElement('span', null, fmtTime(total), ' sermon'),
        React.createElement('span', { className:'sep' }, '\u00b7'),
        React.createElement('span', null, pauses.length, ' pauses'),
        React.createElement('span', { className:'sep' }, '\u00b7'),
        React.createElement('span', null, fmtTime(meta.runtime || total), ' with commentary')
      )
    ),

    // Stage
    React.createElement('div', { className:'rx-stage' },

      // Left — video + controls + active pause banner
      React.createElement('div', { className:'rx-player-col' },

        React.createElement('div', { className:'rx-player' },
          // Poster background
          React.createElement('div', {
            className:'rx-poster',
            style:{
              '--hue': (meta.video && meta.video.posterHue) || 348
            }
          },
            React.createElement('div', { className:'rx-poster-grain' }),
            React.createElement('div', { className:'rx-poster-content' },
              React.createElement('div', { className:'rx-poster-church' }, body.source.congregation),
              React.createElement('div', { className:'rx-poster-title' }, body.source.posterLabel || body.source.title),
              React.createElement('div', { className:'rx-poster-preacher' }, body.source.preacher, ' \u00b7 ', body.source.year)
            )
          ),

          // Pause overlay — Amos interrupts
          atPause && React.createElement('div', { className:'rx-pause-overlay' },
            React.createElement('div', { className:'rx-pause-chip' },
              React.createElement('span', { className:'seal' }, 'C'),
              'Amos pauses at ', fmtTime(atPause.at)
            ),
            React.createElement('div', { className:'rx-pause-topic' }, atPause.topic),
            React.createElement('div', { className:'rx-pause-lead' }, atPause.amosLead),
            React.createElement('button', { className:'rx-pause-resume', onClick: resume },
              window.I.play ? window.I.play(14) : '\u25B6',
              ' Resume sermon'
            )
          ),

          // Center play button when not playing and no pause visible
          !playing && !atPause && React.createElement('button', {
            className:'rx-play-big',
            onClick: togglePlay,
            'aria-label': 'Play'
          }, '\u25B6')
        ),

        // Scrubber + controls
        React.createElement('div', { className:'rx-controls' },
          React.createElement('button', { className:'rx-play-btn', onClick: togglePlay },
            (playing ? '\u2759\u2759' : '\u25B6')
          ),
          React.createElement('div', { className:'rx-time' }, fmtTime(time)),
          React.createElement('div', { className:'rx-track', onClick: onTrackClick },
            React.createElement('div', { className:'rx-track-fill', style:{ width: (time/total*100) + '%' } }),
            // Pause markers
            pauses.map((p, i) => React.createElement('span', {
              key: i,
              className: 'rx-marker' + (activeIdx === i ? ' active' : '') + (time >= p.at ? ' passed' : ''),
              style: { left: (p.at/total*100) + '%' },
              onClick: (e) => { e.stopPropagation(); jumpTo(p); },
              title: p.topic
            }))
          ),
          React.createElement('div', { className:'rx-time end' }, fmtTime(total))
        ),

        // Refs for the active pause
        atPause && atPause.refs && atPause.refs.length > 0 && React.createElement('div', { className:'rx-active-refs' },
          React.createElement('div', { className:'rx-active-refs-label' }, 'Amos is citing'),
          atPause.refs.map((r, i) => React.createElement('button', {
            key: i,
            className:'rx-ref-chip',
            onClick: () => refChipClick(r)
          },
            React.createElement('span', { className:'rx-ref-label' }, r.label),
            r.scope && React.createElement('span', { className:'rx-ref-scope' }, r.scope)
          ))
        ),

        // Current-pause body (full commentary) below the player
        atPause && React.createElement('div', { className:'rx-pause-body' },
          React.createElement('div', { className:'rx-pause-body-head' },
            React.createElement('span', { className:'seal' }, 'C'),
            React.createElement('span', { className:'name' }, 'Amos of Rome'),
            React.createElement('span', { className:'sep' }, '\u00b7'),
            React.createElement('span', { className:'at' }, 'pausing at ', fmtTime(atPause.at))
          ),
          atPause.amosComment.map((para, i) =>
            React.createElement('p', { key: i, className:'rx-pause-para' }, para)
          )
        )
      ),

      // Right — sticky rail of pauses
      React.createElement('aside', { className:'rx-rail' },
        React.createElement('div', { className:'rx-rail-head' },
          React.createElement('span', null, 'Amos\u2019 pauses'),
          React.createElement('span', { className:'count' }, pauses.length)
        ),
        React.createElement('div', { className:'rx-rail-list' },
          pauses.map((p, i) => React.createElement('button', {
            key: i,
            className: 'rx-rail-item' + (activeIdx === i ? ' active' : '') + (time >= p.at ? ' passed' : ''),
            onClick: () => jumpTo(p)
          },
            React.createElement('div', { className:'rx-rail-num' }, String(i+1).padStart(2,'0')),
            React.createElement('div', { className:'rx-rail-body' },
              React.createElement('div', { className:'rx-rail-time' }, fmtTime(p.at)),
              React.createElement('div', { className:'rx-rail-topic' }, p.topic),
              React.createElement('div', { className:'rx-rail-lead' }, p.amosLead)
            )
          ))
        )
      )
    ),

    // Abstract + referenced collections at the bottom
    meta.abstract && React.createElement('section', { className:'rx-foot' },
      React.createElement('div', { className:'rx-foot-head' }, 'About this reaction'),
      React.createElement('p', { className:'rx-foot-abs' }, meta.abstract),
      meta.referenced && meta.referenced.length > 0 && React.createElement('div', { className:'rx-foot-refs' },
        React.createElement('div', { className:'rx-foot-refs-label' }, 'Draws on'),
        meta.referenced.map((r, i) => React.createElement('button', {
          key: i,
          className:'rx-ref-chip outline',
          onClick: () => refChipClick(r)
        },
          React.createElement('span', { className:'rx-ref-label' }, r.label),
          r.scope && React.createElement('span', { className:'rx-ref-scope' }, r.scope)
        ))
      )
    )
,
    React.createElement(window.Footer, null)
  )
}
Object.assign(window, { AmosReactionReader });
