// Live Discoveries ticker. Items animate in from the bottom.
// Simulates new edges arriving from the Bright Data scraper.

window.DiscoveriesTicker = function DiscoveriesTicker() {
  const seed = window.FORGE_DISCOVERIES;
  const futures = window.FORGE_FUTURE_DISCOVERIES;
  const [items, setItems] = React.useState(seed.slice(0, 6).map((d, i) => ({ ...d, _id: i, _t: Date.now() + d.ts_offset * 1000 })));
  const idRef = React.useRef(seed.length);
  const futIdxRef = React.useRef(0);

  React.useEffect(() => {
    const interval = setInterval(() => {
      const next = futures[futIdxRef.current % futures.length];
      futIdxRef.current += 1;
      const item = { ...next, _id: idRef.current++, _t: Date.now() };
      setItems(prev => [item, ...prev].slice(0, 6));
    }, 5200);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="ticker">
      <div className="ticker-head">
        <span className="dot" />
        <span className="label">Live Discoveries</span>
        <span>— scraper · bright data SERP</span>
        <span className="feed">
          <span style={{ color: "var(--bone-3)" }}>{items.length}</span>
          <span>new this minute</span>
        </span>
      </div>
      <div className="ticker-list">
        {items.map((d) => (
          <div key={d._id} className={`disc-row r-${d.relation.toLowerCase()}`}>
            <span className="rel">{d.relation}</span>
            <span className="pair">
              <span className="a">{d.a}</span>
              <span className="arr">→</span>
              <span className="b">{d.b}</span>
            </span>
            <span className="src" title={d.source}>{d.source}</span>
            <span className={`tier-badge t${d.tier}`}>T{d.tier}</span>
            <span className="ts" style={{ gridColumn: "1 / -1", color: "var(--bone-4)", marginTop: -1 }}>
              {relativeTime(d._t)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

function relativeTime(t) {
  const dt = Math.floor((Date.now() - t) / 1000);
  if (dt < 5) return "just now";
  if (dt < 60) return `${dt}s ago`;
  if (dt < 3600) return `${Math.floor(dt/60)}m ago`;
  return `${Math.floor(dt/3600)}h ago`;
}
