/* Saints Calendar — Today's Saints ticker */

const TodayTicker = ({ onOpenSaint }) => {
  const _td = new Date();
  const today = window.getSaintsForDay(_td.getMonth() + 1, _td.getDate());
  const items = today.saints.length > 0 ? today.saints : (today.primary ? [today.primary] : []);
  const trackRef = React.useRef(null);
  const offsetRef = React.useRef(0);
  const pausedRef = React.useRef(false);
  const halfWidthRef = React.useRef(0);

  // Constant pixel speed — px/sec
  const PX_PER_SEC = 50;

  React.useEffect(() => {
    if (!trackRef.current || items.length === 0) return;
    const el = trackRef.current;

    const measure = () => {
      halfWidthRef.current = el.scrollWidth / 2;
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);

    let last = performance.now();
    let raf = 0;
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      if (!pausedRef.current && halfWidthRef.current > 0) {
        offsetRef.current += dt * PX_PER_SEC;
        if (offsetRef.current >= halfWidthRef.current) {
          offsetRef.current -= halfWidthRef.current;
        }
        el.style.transform = `translateX(${-offsetRef.current}px)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
    };
  }, [items.length]);

  if (items.length === 0) return null;

  const loop = [...items, ...items, ...items, ...items];

  return (
    <div className="ticker"
      onMouseEnter={() => { pausedRef.current = true; }}
      onMouseLeave={() => { pausedRef.current = false; }}
    >
      <div className="container ticker-inner">
        <div className="ticker-label">
          <span className="ticker-dot"></span>
          Today's Saints
          <span className="ticker-date">{_td.toLocaleDateString('en-US', { month: 'long', day: 'numeric' })}</span>
        </div>
        <div className="ticker-tunnel">
          <div className="ticker-fade ticker-fade-l"></div>
          <div className="ticker-track ticker-track-js" ref={trackRef}>
            {loop.map((s, i) => (
              <button
                key={`${s.id}-${i}`}
                className="ticker-item"
                onClick={() => onOpenSaint(s.id)}
                title={s.epithet}
              >
                <span className="ticker-cross">✠</span>
                <span className="ticker-name">{s.honorific} {s.name}</span>
                {s.epithet && <span className="ticker-epithet"> — {s.epithet}</span>}
              </button>
            ))}
          </div>
          <div className="ticker-fade ticker-fade-r"></div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { TodayTicker });
