// LiveLeaderboard — the rank-flip showpiece
// Periodically reorders rows by token spend, animates with FLIP + tick numbers

const LB_DATA = [
  { id: 'mc',  name: 'm.chen',    team: 'infra',    avatar: 'MC', tokens: 12.4, delta: 18, summary: 'Migrated billing svc to Postgres · Wrote 14 e2e tests · Drafted Q3 reliability RFC' },
  { id: 'devin', name: 'devin.agent',  team: 'autonomous', avatar: 'DV', tokens: 9.8, delta: 41, summary: 'Patched 23 Sentry exceptions overnight · Opened 6 PRs in checkout', isAgent: true },
  { id: 'ap',  name: 'a.park',    team: 'platform', avatar: 'AP', tokens: 8.91, delta: -4, summary: 'Refactored auth middleware · Patched 9 P2 bugs · Onboarded 2 new services' },
  { id: 'jo',  name: 'j.okafor',  team: 'growth',   avatar: 'JO', tokens: 6.10, delta: 6,  summary: 'Shipped checkout v2 experiment · Cut LCP by 320ms on /pricing' },
  { id: 'sk',  name: 's.kowalski', team: 'data',    avatar: 'SK', tokens: 5.42, delta: 12, summary: 'Rebuilt warehouse ETL · Doc generation for 31 dbt models' },
  { id: 'rt',  name: 'r.tanaka',  team: 'mobile',   avatar: 'RT', tokens: 4.18, delta: -8, summary: 'iOS push deeplink fix · Migrated 3 screens to new design system' },
];

function LiveLeaderboard({ rows = 5, autoShuffle = true, intervalMs = 3500 }) {
  const [data, setData] = React.useState(LB_DATA);
  const [tick, setTick] = React.useState(0);
  const containerRef = React.useRef(null);
  const positionsRef = React.useRef({});

  // FLIP animation: capture positions before sort, animate after
  React.useLayoutEffect(() => {
    if (!containerRef.current) return;
    const els = containerRef.current.querySelectorAll('[data-row-id]');
    els.forEach((el) => {
      const id = el.dataset.rowId;
      const newRect = el.getBoundingClientRect();
      const oldRect = positionsRef.current[id];
      if (oldRect && oldRect.top !== newRect.top) {
        const dy = oldRect.top - newRect.top;
        el.animate(
          [{ transform: `translateY(${dy}px)` }, { transform: 'translateY(0)' }],
          { duration: 380, easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)' }
        );
      }
      positionsRef.current[id] = newRect;
    });
  }, [data, tick]);

  React.useEffect(() => {
    if (!autoShuffle) return;
    const id = setInterval(() => {
      setData((prev) => {
        const next = prev.map((r) => ({
          ...r,
          tokens: Math.max(0.5, +(r.tokens + (Math.random() - 0.4) * 0.8).toFixed(2)),
          delta: Math.round((Math.random() - 0.4) * 60),
        }));
        next.sort((a, b) => b.tokens - a.tokens);
        return next;
      });
      setTick((t) => t + 1);
    }, intervalMs);
    return () => clearInterval(id);
  }, [autoShuffle, intervalMs]);

  const visible = data.slice(0, rows);

  return (
    <div style={{
      background: 'var(--bg-1)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--radius-md)',
      overflow: 'hidden',
    }}>
      {/* Window chrome / header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 16px',
        borderBottom: '1px dashed var(--fg-3)',
        background: 'var(--bg-1)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--bg-3)' }} />
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--bg-3)' }} />
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }} />
          </div>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-2)',
          }}>tokenmaxxer · org · this week</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>live</span>
        </div>
      </div>

      {/* Column heads */}
      <div style={{
        display: 'grid', gridTemplateColumns: '40px 200px 1fr 100px 70px',
        gap: 16, padding: '10px 16px',
        borderBottom: '1px solid var(--border)',
        background: 'var(--bg-0)',
      }}>
        <span className="t-overline">#</span>
        <span className="t-overline">who</span>
        <span className="t-overline">what shipped</span>
        <span className="t-overline" style={{ textAlign: 'right' }}>tokens</span>
        <span className="t-overline" style={{ textAlign: 'right' }}>wow</span>
      </div>

      {/* Rows */}
      <div ref={containerRef}>
        {visible.map((r, i) => (
          <div
            key={r.id}
            data-row-id={r.id}
            className={i === 0 ? 'lb-row lb-active' : 'lb-row'}
            style={{
              display: 'grid', gridTemplateColumns: '40px 200px 1fr 100px 70px',
              gap: 16, alignItems: 'center',
              padding: '14px 16px',
              borderBottom: i < visible.length - 1 ? '1px dashed var(--fg-4)' : 'none',
              background: i === 0 ? 'var(--accent-faint)' : 'transparent',
              borderLeft: i === 0 ? '2px solid var(--accent)' : '2px solid transparent',
              paddingLeft: 14,
              transition: 'background var(--dur-mid) var(--ease)',
            }}
          >
            <span className="t-num" style={{
              fontSize: 13,
              color: i === 0 ? 'var(--accent)' : 'var(--fg-3)',
              fontWeight: i === 0 ? 600 : 400,
            }}>
              {String(i + 1).padStart(2, '0')}
            </span>

            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
              <div style={{
                width: 28, height: 28, borderRadius: r.isAgent ? 'var(--radius-sm)' : '50%',
                background: r.isAgent ? 'var(--accent)' : 'var(--bg-3)',
                color: r.isAgent ? 'var(--accent-fg)' : 'var(--fg-1)',
                border: '1px solid var(--border)',
                display: 'grid', placeItems: 'center',
                fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
                flex: 'none',
              }}>{r.avatar}</div>
              <div style={{ minWidth: 0 }}>
                <div style={{
                  fontSize: 13, color: 'var(--fg-1)', fontWeight: 500,
                  fontFamily: 'var(--font-mono)',
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                }}>{r.name}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>
                  {r.isAgent ? 'agent · ' : ''}{r.team}
                </div>
              </div>
            </div>

            <div style={{
              fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.4,
              overflow: 'hidden', display: '-webkit-box',
              WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            }}>{r.summary}</div>

            <span style={{ textAlign: 'right' }}>
              <TickNum value={r.tokens} decimals={2} suffix="M" />
            </span>

            <span style={{
              textAlign: 'right',
              fontFamily: 'var(--font-mono)', fontSize: 12,
              color: r.delta > 0 ? 'var(--accent)' : r.delta < 0 ? 'var(--danger)' : 'var(--fg-3)',
            }}>
              {r.delta > 0 ? '↑' : r.delta < 0 ? '↓' : '·'} {Math.abs(r.delta)}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { LiveLeaderboard, LB_DATA });
