"use client"; // PEP-179: «Погоня за задачей» above the team list. The pug (the product manager) drops a task, // agents at work chase it around the track, free ones wait on the bench. Live data comes from // the page (core `teamChaseView`) and is re-read by `LiveRefresh scope="team"`; motion is pure CSS // (TeamChase.module.css). A copy of the last data stays in localStorage for the offline app. import { useRouter } from "next/navigation"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react"; import type { ChaseAgent, TeamChaseView } from "@peppa/core"; import { intlLocale } from "@peppa/shared/i18n"; import { setTeamChaseHiddenAction } from "@/app/(app)/team/actions"; import { useT } from "@/components/I18n"; import { useWords } from "@/components/Words"; import s from "./TeamChase.module.css"; const CYCLE = 9; const TASK_LEAD = 3.6; const FIRST_GAP = 0.67; const GAP = 0.54; const HEIGHT = 410; const TOP = 150; const BOTTOM = 380; const STORE = "peppa.team-chase"; /** The rounded track for a stage `w` px wide, starting under the pug (top middle). */ export function trackPath(w: number): { d: string; left: number; right: number; r: number } { const m = Math.max(28, Math.round(w * 0.08)); const left = m; const right = w - m; const r = Math.max(30, Math.min(80, (right - left) / 5, (BOTTOM - TOP) / 2)); const cx = w / 2; const d = `M ${cx} ${TOP} H ${right - r} A ${r} ${r} 0 0 1 ${right} ${TOP + r} V ${BOTTOM - r} A ${r} ${r} 0 0 1 ${right - r} ${BOTTOM} H ${left + r} A ${r} ${r} 0 0 1 ${left} ${BOTTOM - r} V ${TOP + r} A ${r} ${r} 0 0 1 ${left + r} ${TOP} Z`; return { d, left, right, r }; } /** How far ahead (s) a runner in `slot` is: a line behind the task, around the loop. */ const lead = (slot: number) => (((TASK_LEAD - FIRST_GAP - slot * GAP) % CYCLE) + CYCLE) % CYCLE; /** Stable places on the track: an agent keeps its slot while it runs, so nobody jumps. */ function useSlots(ids: number[]): Map { const ref = useRef(new Map()); return useMemo(() => { const prev = ref.current; const next = new Map(); for (const id of ids) if (prev.has(id)) next.set(id, prev.get(id)!); for (const id of ids) { if (next.has(id)) continue; const used = new Set(next.values()); let slot = 0; while (used.has(slot)) slot++; next.set(id, slot); } ref.current = next; return next; }, [ids.join(",")]); // eslint-disable-line react-hooks/exhaustive-deps } // The pixel pug (12×11), coloured after the clay mascot (`PugMascot`). Asleep — eyes closed. const PUG_COLORS: Record = { D: "#4A3428", F: "#E8B98A", K: "#0B0B0B", W: "#FFFFFF", P: "#FF7DB8" }; const PUG_AWAKE = ["DD.FFFFFF.DD", "DDFFFFFFFFDD", "DFFFFFFFFFFD", "FFKKFFFFKKFF", "FFKWFFFFKWFF", "FFFFDDDDFFFF", "FFFDDDDDDFFF", "FFFDDKKDDFFF", ".FFDDDDDDFF.", ".FFFDPPDFFF.", "..FFFFFFFF.."]; const PUG_ASLEEP = [...PUG_AWAKE.slice(0, 3), "FFFFFFFFFFFF", "FKKKFFFFKKKF", ...PUG_AWAKE.slice(5)]; function PixelPug({ asleep, label }: { asleep: boolean; label: string }) { const rows = asleep ? PUG_ASLEEP : PUG_AWAKE; return ( {rows.flatMap((row, y) => [...row].map((c, x) => (c === "." ? null : )))} ); } /** The agent's sign: the first letter of the nickname in a circle of its colour. */ const initial = (name: string) => [...name.trim()][0]?.toUpperCase() ?? "?"; function readStore(): TeamChaseView | null { try { const v = JSON.parse(localStorage.getItem(STORE) ?? "null"); return v && Array.isArray(v.runners) && Array.isArray(v.bench) ? (v as TeamChaseView) : null; } catch { return null; } } export function TeamChase({ view, hidden: hiddenAtStart, awaitingKey }: { view: TeamChaseView; hidden: boolean; awaitingKey: string | null }) { const t = useT(); const w = useWords(); const router = useRouter(); const [hidden, setHidden] = useState(hiddenAtStart); const [data, setData] = useState(view); const [offline, setOffline] = useState(false); const [paused, setPaused] = useState(false); const [lowPower, setLowPower] = useState(false); const [open, setOpen] = useState(null); const [width, setWidth] = useState(720); const [plus, setPlus] = useState(0); const stage = useRef(null); const touch = useRef(false); const accepted = useRef(view.accepted); const seen = useRef | null>(null); // Fresh server data: keep it, remember it for the offline app, «+1» when the count grew. useEffect(() => { setData(view); try { localStorage.setItem(STORE, JSON.stringify(view)); } catch {} if (view.accepted > accepted.current) setPlus((k) => k + 1); accepted.current = view.accepted; }, [view]); // Offline: the newest known team (the cached page or the stored copy); back online — re-read. // «Offline» is also a network that is there while Peppa is not (the page came from the // service worker's cache): a small request to the server tells, repeated while it fails. useEffect(() => { let off = false; let timer: ReturnType | null = null; let stopped = false; const set = (next: boolean) => { if (next) { const stored = readStore(); if (stored && stored.at > view.at) setData(stored); } else if (off) router.refresh(); off = next; setOffline(next); }; const probe = async () => { if (timer) clearTimeout(timer); timer = null; if (stopped || document.visibilityState !== "visible") return; let ok = navigator.onLine; if (ok) ok = await fetch("/api/health", { cache: "no-store" }).then(() => true, () => false); if (stopped) return; set(!ok); if (!ok) timer = setTimeout(probe, 15_000); }; const onOffline = () => set(true); const onVisible = () => document.visibilityState === "visible" && void probe(); void probe(); window.addEventListener("online", probe); window.addEventListener("offline", onOffline); document.addEventListener("visibilitychange", onVisible); return () => { stopped = true; if (timer) clearTimeout(timer); window.removeEventListener("online", probe); window.removeEventListener("offline", onOffline); document.removeEventListener("visibilitychange", onVisible); }; }, [router, view.at]); // A hidden tab or a minimised app: the picture stands still. useEffect(() => { const onVis = () => setPaused(document.visibilityState !== "visible"); onVis(); document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, []); // Battery saver: a discharging battery under 20 % — no motion. useEffect(() => { const nav = navigator as Navigator & { getBattery?: () => Promise<{ charging: boolean; level: number; addEventListener: (e: string, f: () => void) => void }> }; nav .getBattery?.() .then((b) => { const check = () => setLowPower(!b.charging && b.level <= 0.2); check(); b.addEventListener("chargingchange", check); b.addEventListener("levelchange", check); }) .catch(() => {}); }, []); // The installed app works offline: shell files and this page are cached by /sw.js. useEffect(() => { navigator.serviceWorker?.register("/sw.js", { scope: "/" }).catch(() => {}); }, []); useLayoutEffect(() => { const el = stage.current; if (!el) return; const measure = () => el.clientWidth && setWidth(el.clientWidth); measure(); const ro = new ResizeObserver(measure); ro.observe(el); return () => ro.disconnect(); }, [hidden]); // Close an open hint on a tap elsewhere. useEffect(() => { if (!open) return; const close = (e: PointerEvent) => !(e.target as Element).closest?.("[data-chase-key]") && setOpen(null); document.addEventListener("pointerdown", close); return () => document.removeEventListener("pointerdown", close); }, [open]); const slots = useSlots(data.runners.map((a) => a.id)); // Who just came in (from the bench or new to the team) — they hop in, the rest keep running. const fresh = useMemo(() => { const keys = [...data.runners.map((a) => `r${a.id}`), ...data.bench.map((a) => `b${a.id}`)]; const before = seen.current; seen.current = new Set(keys); return before ? new Set(keys.filter((k) => !before.has(k))) : new Set(); }, [data]); const toggle = (next: boolean) => { setHidden(next); void setTeamChaseHiddenAction(next).catch(() => {}); }; /** Touch: the first tap shows the hint, the second acts. Mouse and keyboard act at once. */ const tap = (key: string, act: () => void) => { if (touch.current && open !== key) return setOpen(key); setOpen(null); act(); }; const showCard = (id: number) => { const card = document.getElementById(`agent-${id}`); if (!card) return; const still = matchMedia("(prefers-reduced-motion: reduce)").matches; card.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "center" }); card.setAttribute("data-highlight", ""); setTimeout(() => card.removeAttribute("data-highlight"), 2500); }; const hhmm = (iso: string) => new Date(iso).toLocaleTimeString(intlLocale(t.locale), { hour: "2-digit", minute: "2-digit" }); const working = data.runners.length + data.extra; const idle = working === 0; const { d, left, right, r } = trackPath(width); const cx = width / 2; const tasksWord = w.Task("genPl"); if (hidden) return (
{t("Работают: {n}", { n: working })} · {t("Свободны: {n}", { n: data.bench.length })}
); const runnerLabel = (a: ChaseAgent) => (a.task ? t("Агент {name}, задача {title}", { name: a.name, title: a.task.title }) : t("Агент {name}, работает", { name: a.name })); const goTask = (a: ChaseAgent) => a.task && router.push(`/t/${a.task.key}`); const runnerProps = (a: ChaseAgent, key: string) => ({ type: "button" as const, "aria-label": runnerLabel(a), "data-chase-key": key, "data-open": open === key ? "" : undefined, onPointerDown: (e: React.PointerEvent) => (touch.current = e.pointerType !== "mouse"), onKeyDown: () => (touch.current = false), onClick: () => tap(key, () => goTask(a)), }); const tip = (a: ChaseAgent) => ( {a.name} {" · "} {a.task ? `${a.task.key} ${a.task.title}` : t("работает")} ); return (
{t("Игрок")}: {t("вы")} Peppa FACTORY {tasksWord}: {String(data.accepted).padStart(6, "0")}
{offline &&

{t("Нет связи — данные на {time}", { time: hhmm(data.at) })}

}
{!idle &&
}
{idle && ( zz )}
{t("вы")} · {t("продакт")}
{idle ? (
) : ( <>
{t("Ловите {task}!", { task: w.task("acc") })}
)} {plus > 0 && ( +1 )} {data.runners.map((a) => { const key = `r${a.id}`; const ahead = lead(slots.get(a.id) ?? 0); return ( ); })} {data.extra > 0 && ( +{data.extra} )}
{idle ? (

{t("Агенты отдыхают")}

) : ( <>

{t("Работают: {n}", { n: working })}
{t("Гоняют {task} по кругу, пока не доведут до готового", { task: w.task("acc") })}

{data.runners.map((a) => ( ■ {a.name} ))}
)} {awaitingKey && ( {t("Жмите «Принять»")} )}
{data.runners.map((a) => { const key = `m${a.id}`; return ( ); })} {data.extra > 0 && +{data.extra}}
{data.bench.length > 0 && (

{t("Свободны: {n}", { n: data.bench.length })} · {t("наведите, чтобы узнать кличку")}

    {data.bench.map((a, i) => { const key = `b${a.id}`; return (
  • ); })}
)}
); }