// Shared React context for live-feed state and tweaks.
// Pushes fake new jumps in whenever liveEvents is on.

const JYContext = React.createContext(null);

function useJY() { return React.useContext(JYContext); }

function JYProvider({ children, tweaks }) {
  const [recent, setRecent] = React.useState(RECENT_JUMPS);
  const [spotlight, setSpotlight] = React.useState(SPOTLIGHT);
  const [celebrate, setCelebrate] = React.useState(null); // pulse trigger id
  const [clock, setClock] = React.useState(() => new Date());
  const [leaderboard, setLeaderboard] = React.useState(LEADERBOARD);

  // Clock tick
  React.useEffect(() => {
    const id = setInterval(() => setClock(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  // Live events
  React.useEffect(() => {
    if (!tweaks.liveEvents) return;

    const tick = () => {
      // pick a random jumper
      const jumper = NICKNAMES[Math.floor(Math.random() * NICKNAMES.length)];
      const height = 60 + Math.floor(Math.random() * 150); // 60-210cm
      const isPR = Math.random() < 0.12;
      const pad = ["A1","A3","A7","B1","C2","B4"][Math.floor(Math.random()*6)];
      const evt = { ...jumper, height, ts: "just nu", isPR, pad };

      setRecent(prev => {
        // re-timestamp old ones
        const aged = prev.map((e,i) => ({ ...e, ts: `${2*(i+1)}s sedan` }));
        return [evt, ...aged].slice(0, 7);
      });

      // occasional PR → promote to spotlight
      if (isPR && height > 140) {
        setSpotlight({
          ...jumper,
          best: height,
          previousBest: height - (5 + Math.floor(Math.random()*20)),
          level: 8 + Math.floor(Math.random()*10),
          xp: 200 + Math.floor(Math.random()*700),
          xpGained: 20 + Math.floor(Math.random()*60),
          jumps: 50 + Math.floor(Math.random()*200),
          badge: "🔥 NYTT PERSONLIGT REKORD",
        });
        setCelebrate(Date.now());
      }

      // Update leaderboard — if jumper in top10 and height > their best, bump it
      setLeaderboard(prev => {
        const idx = prev.findIndex(p => p.name === jumper.name);
        if (idx === -1 || height <= prev[idx].best) {
          return prev.map(p => p.name === jumper.name ? { ...p, jumps: p.jumps + 1 } : p);
        }
        const updated = [...prev];
        updated[idx] = { ...updated[idx], best: height, jumps: updated[idx].jumps + 1, trend: "up" };
        updated.sort((a,b) => b.best - a.best);
        return updated.map((p,i) => ({ ...p, rank: i+1 }));
      });
    };

    const id = setInterval(tick, 2200 + Math.random() * 1200);
    return () => clearInterval(id);
  }, [tweaks.liveEvents]);

  const value = { recent, spotlight, celebrate, clock, leaderboard, tweaks };
  return <JYContext.Provider value={value}>{children}</JYContext.Provider>;
}

Object.assign(window, { JYContext, JYProvider, useJY });
