From 18686cbceb824e538bc727b5c4947048af75817a Mon Sep 17 00:00:00 2001 From: Suriyakumarvijayanayagam Date: Fri, 4 Sep 2026 16:46:23 +0530 Subject: [PATCH] Live view at head office, relayed through the agent's outbound connection I got this wrong first time. "Head office cannot show live video cheaply" conflated TRUE VIDEO with SEEING THE CAMERA NOW, and only the first needs WebRTC and a TURN server. The shop PC is behind a router with no inbound route, so head office cannot pull the engine's MJPEG. It can answer the agent's outbound requests, which is the shape of everything else here: the server holds a poll open, the agent asks "is anyone watching?", and pushes JPEGs up for exactly as long as somebody is. Measured on the office camera: 98 KB full frame, 20.8 KB re-encoded at 640/q60, so one watcher costs ~83 KB/s. 47 frames arrived in 12 seconds - 4 fps, as configured. The UI says "about 4 frames a second" rather than letting anyone conclude the camera stutters. Nothing is uploaded when nobody is looking, which is the whole cost argument: Publish returns false once the last viewer goes, interest lapses on a timer each viewer refreshes as it reads (so a closed tab stops the upload within seconds), one push is capped at five minutes, and the UI streams one camera at a time. LiveHub is deliberately the opposite of the arrivals Hub. There a doorbell pushes nothing because nothing may be lost; here a dropped frame is the correct outcome, so each viewer has a one-slot buffer that is overwritten - the only frame worth having is the newest, and a queue would show an ever-growing delay behind the shop instead of dropping back to live. Ownership is proved once, before anything streams: the relay is keyed on a camera id, a hub does not know whose camera it holds, and a camera id is not a secret. Verified: another tenant gets 404, no session gets 401, and an agent cannot push into another site's camera. Also fixes a bug I introduced with it - the Live button was gated on `connected`, which is head office's last report and up to two minutes stale, so it hid itself during every reconnect. "Is that camera really down?" is exactly when somebody wants to look, and a hidden control says "you cannot" where the honest answer is "here is why". Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn --- CLAUDE.md | 89 +++++-- agent/main.go | 3 + agent/pkg/cameras/cameras.go | 3 + agent/pkg/cameras/clients.go | 26 +- agent/pkg/cameras/live.go | 225 ++++++++++++++++++ behavision/api.py | 44 +++- desktop/app.go | 3 + server/internal/api/api.go | 16 ++ server/internal/api/fake_test.go | 51 ++++ server/internal/api/handlers_live.go | 173 ++++++++++++++ server/internal/api/live.go | 184 ++++++++++++++ server/internal/api/live_test.go | 131 ++++++++++ server/internal/api/types.go | 5 + server/internal/store/api_cameras.go | 4 +- server/internal/store/api_snapshots.go | 48 ++++ .../web/dist/assets/index-B_gTsA07.js | 43 ---- ...{index-pUqVBCLm.css => index-CtuyPF09.css} | 2 +- .../web/dist/assets/index-D6UMLnOQ.js | 46 ++++ server/internal/web/dist/index.html | 4 +- web/src/api.js | 67 ++++++ web/src/styles.css | 39 +++ web/src/views/CameraLive.jsx | 85 +++++++ web/src/views/Cameras.jsx | 26 +- 23 files changed, 1250 insertions(+), 67 deletions(-) create mode 100644 agent/pkg/cameras/live.go create mode 100644 server/internal/api/handlers_live.go create mode 100644 server/internal/api/live.go create mode 100644 server/internal/api/live_test.go delete mode 100644 server/internal/web/dist/assets/index-B_gTsA07.js rename server/internal/web/dist/assets/{index-pUqVBCLm.css => index-CtuyPF09.css} (95%) create mode 100644 server/internal/web/dist/assets/index-D6UMLnOQ.js create mode 100644 web/src/views/CameraLive.jsx diff --git a/CLAUDE.md b/CLAUDE.md index cb84b78..879fd40 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2173,7 +2173,7 @@ Two bugs, both found by running it after a reboot rather than by reading it. stay up. A failure there means the server cannot authenticate to its own broker, which is exactly what this script exists to surface early. -## Where the live feed is, and why head office gets a picture instead +## Live view at head office, and what it honestly is Live video exists and always has — on the shop PC, where the camera is: @@ -2181,20 +2181,81 @@ Live video exists and always has — on the shop PC, where the camera is: on the office camera: 1280×720, ~850 KB/s. - The desktop app's Live screen and the engine's own dashboard both render it. -**Head office does not, and cannot cheaply.** The engine serves that stream on -`127.0.0.1` on a PC behind a shop's router with no inbound route. Putting live -video on `platform.loyaly.ai` needs a relay — WebRTC with TURN, or the agent -pushing a continuous stream up — which is infrastructure and bandwidth this does -not have. Nor can the browser be pointed straight at the shop PC even on one -LAN: the engine's API is Basic-authenticated with a credential it generates -locally and never sends anywhere, and shipping that credential to the cloud so a -web page could use it would put the key to the biometric API and the live face -feed in the server's database. That is a far worse trade than not having live -video at head office. +Head office has it too, and this is the part that was got wrong first: the +original answer here was "cannot cheaply", which conflated **true video** with +**seeing the camera now**. Only the first needs infrastructure this does not +have. -So head office shows the camera's **latest frame**, refreshed every 60 s. The -agent already holds it in memory for its own stream, so it costs a memory copy -rather than a camera round trip. +The shop PC is behind a router with no inbound route, so head office cannot +pull that stream. What it CAN do is answer the agent's outbound requests, which +is the shape of everything else in this system — so `LiveHub` + `cameras.Live` +relay frames the other way: head office holds a poll open, the agent asks "is +anyone watching?", and pushes JPEGs up for exactly as long as somebody is. + +**It is ~4 frames a second of 640 px JPEG, and the UI says so.** Measured on the +office camera: the full frame is 98 KB, re-encoded at 640/q60 it is 20.8 KB, so +one watcher costs ~83 KB/s. True 25 fps video would need WebRTC and a TURN +server; for *"what does that camera see right now"* — which is the question +somebody at head office is actually asking — a few frames a second is what the +question requires, and a label saying "about 4 frames a second" is better than +letting somebody conclude the camera stutters. + +The browser cannot be pointed straight at the shop PC even on one LAN: the +engine's API is Basic-authenticated with a credential it generates locally and +never sends anywhere, and shipping that to the cloud so a web page could use it +would put the key to the biometric API and the live face feed in the server's +database. + +**Nothing is uploaded when nobody is looking**, and that is the entire cost +argument: + +- `Publish` returns false once the last viewer has gone, which is what tells the + agent to stop pushing. If it were ever optimistic every shop PC in an estate + would upload continuously. +- Interest lapses on a timer refreshed by each viewer as it reads, so a browser + that vanishes without saying so — the normal way a tab closes — stops the + upload within seconds. +- One push is capped at five minutes. A tab left open for a week must not leave + a shop uploading for a week; a viewer who is still there simply reconnects. +- Only one camera streams at a time in the UI. A grid that went live all at once + would put an estate's worth of cameras on the wire because somebody opened a + page. + +**`LiveHub` is the exact opposite of the arrivals `Hub`, deliberately.** There a +doorbell pushes nothing because nothing may be lost. Here a dropped frame is the +*correct* outcome: each viewer has a one-slot buffer and a full slot is +overwritten, because the only frame worth having is the newest one and a queue +would show an ever-growing delay behind the shop instead of dropping back to +live. + +Other decisions worth keeping: + +- **Ownership is proved once, before anything streams.** Everything after that + point is keyed on a camera id and a hub does not know whose camera it holds — + and a camera id is not a secret. An agent pushing is checked against its own + site for the same reason. +- **The agent's poll is held open by the server** rather than answered at once. + Polling every few seconds puts a floor under how quickly a view can start; + polling slowly puts a ceiling on it. Holding it means pressing Live reaches + the shop PC immediately and an idle site costs about two requests a minute. +- **One request carries many frames**, each prefixed with its length. At a few + frames a second, per-request overhead and TLS handshakes would cost more than + the pictures. +- **The engine does the re-encode** (`frame.jpg?width=&quality=`). It already + has OpenCV open and the frame decoded; a scaler in the agent would be the same + work twice. On demand only — a camera nobody watches must not pay for a second + encode it will never use. +- **The Live button is offered even when the card says the camera is down.** + `connected` is head office's last report and can be two minutes stale, so + gating on it hid the button during every reconnect — and "is that camera + really down?" is exactly when somebody wants to look. A hidden control says + *"you cannot"* where the honest answer is *"here is why"*, which the live view + gives: it distinguishes a camera that is not connecting from a shop PC that is + not answering. + +Head office also still shows the camera's **latest frame** on the cards, +refreshed every 60 s, which is what a page of cameras should cost when nobody +has asked to watch one. ### The picture only worked if you had an S3 bucket diff --git a/agent/main.go b/agent/main.go index 928e1c7..aab0d3c 100644 --- a/agent/main.go +++ b/agent/main.go @@ -274,6 +274,9 @@ func cmdRun() error { cloud.Upload = uploader.UploadBytes eng := cameras.NewEngineClient(cfg.APIBase, cfg.APIUser, cfg.APIPassword) go cameras.New(eng, cloud, logger).Run(ctx) + // The live relay, which uploads nothing until somebody at head office is + // actually watching a camera. + go cameras.NewLive(eng, cloud, logger).Run(ctx) // Before the engine starts, so the engine can be launched already knowing // where to post its detections. diff --git a/agent/pkg/cameras/cameras.go b/agent/pkg/cameras/cameras.go index d8585f0..15e9bea 100644 --- a/agent/pkg/cameras/cameras.go +++ b/agent/pkg/cameras/cameras.go @@ -55,6 +55,9 @@ type Local struct { // Desired is a camera as head office holds it. type Desired struct { + // ID is head office's uuid for this camera; CameraID is the name the + // engine on this PC knows it by. The live relay translates between them. + ID string `json:"id"` CameraID string `json:"camera_id"` Label string `json:"label"` Host string `json:"host"` diff --git a/agent/pkg/cameras/clients.go b/agent/pkg/cameras/clients.go index 3a473e9..f1854d7 100644 --- a/agent/pkg/cameras/clients.go +++ b/agent/pkg/cameras/clients.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "net/url" + "strconv" "strings" "time" @@ -98,8 +99,29 @@ func (e *EngineClient) Remove(ctx context.Context, id string) error { // trip. A camera that has not produced a frame yet answers 503, which is a // normal state on a just-added camera and not an error worth logging loudly. func (e *EngineClient) Snapshot(ctx context.Context, id string) ([]byte, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, - e.Base+"/api/cameras/"+url.PathEscape(id)+"/frame.jpg", nil) + return e.Frame(ctx, id, 0, 0) +} + +// Frame fetches the latest frame, optionally re-encoded smaller. +// +// The live relay asks for ~640 px at quality 60 - about a third the bytes of +// the full frame - because it sends several a second up a shop's uplink, where +// the snapshot sends one a minute and can afford the detail. The engine does +// the re-encode: it already has OpenCV open and the frame in memory, and +// shipping a scaler into the agent to redo that would be the same work twice. +func (e *EngineClient) Frame(ctx context.Context, id string, width, quality int) ([]byte, error) { + q := url.Values{} + if width > 0 { + q.Set("width", strconv.Itoa(width)) + } + if quality > 0 { + q.Set("quality", strconv.Itoa(quality)) + } + target := e.Base + "/api/cameras/" + url.PathEscape(id) + "/frame.jpg" + if len(q) > 0 { + target += "?" + q.Encode() + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) if err != nil { return nil, err } diff --git a/agent/pkg/cameras/live.go b/agent/pkg/cameras/live.go new file mode 100644 index 0000000..6a38799 --- /dev/null +++ b/agent/pkg/cameras/live.go @@ -0,0 +1,225 @@ +package cameras + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "time" +) + +// Live relays camera frames to head office, but only while somebody is +// watching. +// +// The engine serves MJPEG on this PC's loopback and this PC sits behind a +// router with no inbound route, so head office cannot pull it. It can answer +// our outbound requests, which is the shape of everything else here: we ask +// "is anyone watching?", and push frames for as long as the answer is yes. +// +// It is a few frames a second of re-encoded JPEG, not 25 fps video. True video +// needs WebRTC and a TURN server; this needs neither, and answers the question +// somebody at head office is actually asking - what does that camera see right +// now - at a cost a shop's uplink can carry. +// +// **Nothing is uploaded when nobody is looking.** That is the entire cost +// argument, and it is why the wanted-check comes first and the push stops the +// moment the server says the last viewer has gone. +type Live struct { + Engine *EngineClient + Cloud *CloudClient + Log *log.Logger + FPS float64 + Width int + Quality int + pollDelay time.Duration +} + +// Defaults chosen to be honest about a shop's uplink rather than impressive: +// 640 px at quality 60 is ~25-35 KB, so 4 fps is ~120 KB/s per watcher, and a +// camera nobody is watching costs nothing at all. +const ( + DefaultLiveFPS = 4.0 + DefaultLiveWidth = 640 + DefaultLiveQuality = 60 +) + +func NewLive(eng *EngineClient, cloud *CloudClient, logger *log.Logger) *Live { + return &Live{Engine: eng, Cloud: cloud, Log: logger, + FPS: DefaultLiveFPS, Width: DefaultLiveWidth, Quality: DefaultLiveQuality} +} + +// Run waits for viewers and serves them until the context ends. +func (l *Live) Run(ctx context.Context) { + if l.Engine == nil || l.Cloud == nil { + return + } + for { + if ctx.Err() != nil { + return + } + wanted, err := l.Cloud.LiveWanted(ctx) + if err != nil { + // Unclaimed, offline, or head office is down. All three mean the + // same thing here - nobody can be watching - so back off rather + // than hammering, and keep the shop's own recognition untouched. + if ctx.Err() != nil { + return + } + l.sleep(ctx, 15*time.Second) + continue + } + if len(wanted) == 0 { + // The poll is held open by the server, so an empty answer already + // means ~25 s passed. No extra delay. + continue + } + for _, id := range wanted { + if ctx.Err() != nil { + return + } + l.serve(ctx, id) + } + } +} + +// serve pushes frames for one camera until the server says stop. +func (l *Live) serve(ctx context.Context, cameraID string) { + engineID, err := l.Cloud.LiveEngineID(ctx, cameraID) + if err != nil { + l.logf("live %s: %v", cameraID, err) + l.sleep(ctx, 2*time.Second) + return + } + interval := time.Duration(float64(time.Second) / l.fps()) + + // A pipe so frames can be written as they are grabbed while one request + // carries all of them. A request per frame would spend more on handshakes + // and headers than on pictures. + pr, pw := io.Pipe() + done := make(chan error, 1) + go func() { done <- l.Cloud.PushLive(ctx, cameraID, pr) }() + + tick := time.NewTicker(interval) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + _ = pw.CloseWithError(context.Canceled) + <-done + return + case err := <-done: + // The server closed the request: the last viewer went away, or the + // session cap was reached. Either way stop grabbing frames. + _ = pw.Close() + if err != nil { + l.logf("live %s ended: %v", cameraID, err) + } + return + case <-tick.C: + } + jpeg, err := l.Engine.Frame(ctx, engineID, l.Width, l.Quality) + if err != nil || len(jpeg) == 0 { + // A camera that is reconnecting has no frame. Keep the request + // open - the viewer sees the last frame rather than a dropped + // stream, and the next tick may well have one. + continue + } + var hdr [4]byte + binary.BigEndian.PutUint32(hdr[:], uint32(len(jpeg))) + if _, err := pw.Write(hdr[:]); err != nil { + <-done + return + } + if _, err := pw.Write(jpeg); err != nil { + <-done + return + } + } +} + +func (l *Live) fps() float64 { + if l.FPS <= 0 || l.FPS > 15 { + // Above this the relay stops being cheap and stops being honest about + // what an outbound HTTP push can carry. + return DefaultLiveFPS + } + return l.FPS +} + +func (l *Live) sleep(ctx context.Context, d time.Duration) { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C: + } +} + +func (l *Live) logf(format string, args ...any) { + if l.Log != nil { + l.Log.Printf(format, args...) + } +} + +// ------------------------------------------------------------------ wire -- + +// LiveWanted asks head office which of this site's cameras are being watched. +// The server holds the request open, so this returns promptly when somebody +// presses Live and after ~25 s when nobody has. +func (c *CloudClient) LiveWanted(ctx context.Context) ([]string, error) { + var body struct { + Cameras []string `json:"cameras"` + } + // Longer than the server's own wait, so a held request is not cut off by + // our own client timeout and reported as a failure. + ctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + if err := c.do(ctx, http.MethodGet, "/api/agent/live", nil, &body); err != nil { + return nil, err + } + return body.Cameras, nil +} + +// LiveEngineID maps head office's camera uuid to the name the engine knows, +// which is the only name this PC can ask for a frame with. +func (c *CloudClient) LiveEngineID(ctx context.Context, cameraID string) (string, error) { + desired, err := c.Desired(ctx) + if err != nil { + return "", err + } + for _, d := range desired { + if d.ID == cameraID { + return d.CameraID, nil + } + } + return "", fmt.Errorf("camera %s is not one of this site's", cameraID) +} + +// PushLive streams frames until the server stops reading. +func (c *CloudClient) PushLive(ctx context.Context, cameraID string, body io.Reader) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + c.Base+"/api/agent/cameras/"+cameraID+"/live", body) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+c.Token) + req.Header.Set("Content-Type", "application/octet-stream") + resp, err := c.Client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + blob, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("head office: %s: %s", resp.Status, bytes.TrimSpace(blob)) + } + var out struct { + Frames int `json:"frames"` + } + _ = json.Unmarshal(blob, &out) + return nil +} diff --git a/behavision/api.py b/behavision/api.py index 1a4c2ea..1617cc1 100644 --- a/behavision/api.py +++ b/behavision/api.py @@ -111,6 +111,35 @@ def _auth_dependencies(api_cfg: ApiSection) -> list: return [Depends(check)] +def _reencode(jpeg: bytes, width: int, quality: int) -> "bytes | None": + """Decode, scale and re-encode one frame. None on any failure. + + None rather than an exception on purpose: the caller falls back to the + original frame, so a re-encode that fails costs bandwidth rather than the + picture. A live view that goes blank because a resize failed is a worse + outcome than one that is briefly larger than asked for. + """ + try: + import cv2 + import numpy as np + + img = cv2.imdecode(np.frombuffer(jpeg, np.uint8), cv2.IMREAD_COLOR) + if img is None: + return None + if 0 < width < img.shape[1]: + # Only ever DOWN. Upscaling a frame to a requested width would send + # more bytes than the original for no more detail. + scale = width / img.shape[1] + img = cv2.resize(img, (width, max(1, int(img.shape[0] * scale))), + interpolation=cv2.INTER_AREA) + q = quality if 1 <= quality <= 100 else 75 + ok, buf = cv2.imencode(".jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), q]) + return buf.tobytes() if ok else None + except Exception: + log.debug("frame re-encode failed", exc_info=True) + return None + + def create_app(engine: Engine) -> FastAPI: app = FastAPI(title="Behavision", version="1.0.0", dependencies=_auth_dependencies(engine.cfg.api)) @@ -313,10 +342,23 @@ def create_app(engine: Engine) -> FastAPI: return probe_source(source, cam.max_width) @app.get("/api/cameras/{camera_id}/frame.jpg") - def frame(camera_id: str) -> Response: + def frame(camera_id: str, width: int = 0, quality: int = 0) -> Response: + """The latest frame, optionally re-encoded smaller. + + `width`/`quality` exist for the live relay, which sends several frames + a second up a shop's uplink and cannot afford the full-size picture the + dashboard uses. The re-encode happens here rather than in the agent + because this process already has OpenCV open and the frame decoded; + shipping a scaler into the agent would be the same work done twice. + + Done on demand, not on every frame: a camera nobody is watching must + not pay for a second encode it will never use. + """ jpeg = worker_or_404(camera_id).latest_jpeg() if jpeg is None: raise HTTPException(503, "no frame yet") + if width > 0 or quality > 0: + jpeg = _reencode(jpeg, width, quality) or jpeg return Response(jpeg, media_type="image/jpeg") @app.get("/api/cameras/{camera_id}/stream.mjpeg") diff --git a/desktop/app.go b/desktop/app.go index d44e6e9..a46cb53 100644 --- a/desktop/app.go +++ b/desktop/app.go @@ -229,6 +229,9 @@ func (a *App) startLocalCameras(ctx context.Context, logger *log.Logger) { // this app - and the headless agent - both ended up wiring configuration // and forgetting the check runner, so "Test connection" at head office // never completed on any shop PC. + // The live relay runs alongside the reconciler and uploads nothing until + // somebody at head office is actually watching a camera. + go agentcameras.NewLive(camEngine, camCloud, logger).Run(ctx) agentcameras.New(camEngine, camCloud, logger).Run(ctx) } diff --git a/server/internal/api/api.go b/server/internal/api/api.go index 536f6ab..b369da9 100644 --- a/server/internal/api/api.go +++ b/server/internal/api/api.go @@ -65,6 +65,14 @@ type Store interface { // reachable only with that site's own agent token. AgentCameras(ctx context.Context, siteID string) ([]AgentCamera, error) ApplyAgentReport(ctx context.Context, clientID, siteID string, rep AgentCameraReport) error + // CameraRef resolves one of a TENANT's cameras to its site and the name the + // engine knows it by. Used to prove ownership before anything is streamed. + CameraRef(ctx context.Context, clientID, cameraID string) (siteID, engineID string, err error) + // CameraRefBySite is the same question asked by an agent, which is + // authenticated for a site rather than a tenant. + CameraRefBySite(ctx context.Context, siteID, cameraID string) (site, engineID string, err error) + // SiteCameraIDs lists a site's camera uuids, for the agent's live poll. + SiteCameraIDs(ctx context.Context, siteID string) ([]string, error) // Camera pictures held by this server, for deployments with no object // storage. Where a bucket is configured neither of these is called. PutCameraSnapshot(ctx context.Context, clientID, siteID, cameraID string, jpeg []byte) error @@ -118,6 +126,10 @@ type Server struct { // business questions the screens ask. Nil means this deployment has no // API key, which is supported: the UI hides the panel. Assistant Assistant + // Live relays camera frames from a shop PC to whoever is watching, on + // demand. Created on first use. + Live *LiveHub + liveOnce sync.Once // Hub wakes live arrival streams when the MQTT consumer records a visit. // Nil is supported and means the streams fall back to their slow tick - // a server assembled without one is slower, not broken. @@ -197,6 +209,7 @@ func (s *Server) Routes() *http.ServeMux { mux.HandleFunc("PATCH /api/cameras/{id}", s.authed(s.handleUpdateCamera)) mux.HandleFunc("DELETE /api/cameras/{id}", s.authed(s.handleDeleteCamera)) mux.HandleFunc("GET /api/cameras/{id}/snapshot.jpg", s.authed(s.handleGetSnapshot)) + mux.HandleFunc("GET /api/cameras/{id}/live", s.authed(s.handleWatchLive)) // Prove a camera works: "connection" asks whether the shop PC can open the // stream, "placement" asks whether somebody walking past produces a view // good enough to recognise. Two questions, because a camera passes the @@ -242,6 +255,9 @@ func (s *Server) Routes() *http.ServeMux { mux.HandleFunc("POST /api/agent/cameras", s.agentAuthed(s.handleAgentCameraReport)) mux.HandleFunc("PUT /api/agent/cameras/{camera}/snapshot", s.agentAuthed(s.handlePutSnapshot)) + mux.HandleFunc("GET /api/agent/live", s.agentAuthed(s.handleAgentLiveWanted)) + mux.HandleFunc("POST /api/agent/cameras/{camera}/live", + s.agentAuthed(s.handleAgentPushLive)) mux.HandleFunc("GET /api/agent/checks", s.agentAuthed(s.handleAgentChecks)) mux.HandleFunc("POST /api/agent/checks", s.agentAuthed(s.handleAgentCheckResult)) diff --git a/server/internal/api/fake_test.go b/server/internal/api/fake_test.go index 15517b4..f7951d2 100644 --- a/server/internal/api/fake_test.go +++ b/server/internal/api/fake_test.go @@ -19,6 +19,11 @@ import ( // live - which tenant, which message on failure, what is echoed back - and // those are exactly what a real database would make slow and awkward to test. type fakeStore struct { + // Which tenant and site each camera belongs to. The live relay is keyed on + // a camera id and a hub does not know whose camera it holds, so ownership + // is proved before anything streams - and that is what these tests check. + cameraRefs map[string]cameraRef + // Camera pictures held by the server, for a deployment with no bucket. // Keyed as written by PutCameraSnapshot (by camera_id) and as read by // CameraSnapshot ("client/camera"), so a test has to say which it means. @@ -622,3 +627,49 @@ func (f *fakeStore) CameraSnapshot(_ context.Context, clientID, cameraID string) } return img, time.Unix(1756900000, 0).UTC(), nil } + +// ------------------------------------------------------------ live relay -- + +func (f *fakeStore) CameraRef(_ context.Context, clientID, cameraID string) (string, string, error) { + f.mu.Lock() + defer f.mu.Unlock() + ref, ok := f.cameraRefs[cameraID] + if !ok || ref.client != clientID { + return "", "", ErrNoSnapshot + } + return ref.site, ref.engineID, nil +} + +func (f *fakeStore) CameraRefBySite(_ context.Context, siteID, cameraID string) (string, string, error) { + f.mu.Lock() + defer f.mu.Unlock() + ref, ok := f.cameraRefs[cameraID] + if !ok || ref.site != siteID { + return "", "", ErrNoSnapshot + } + return ref.site, ref.engineID, nil +} + +func (f *fakeStore) SiteCameraIDs(_ context.Context, siteID string) ([]string, error) { + f.mu.Lock() + defer f.mu.Unlock() + var out []string + for id, ref := range f.cameraRefs { + if ref.site == siteID { + out = append(out, id) + } + } + return out, nil +} + +// addCameraRef registers a camera so ownership checks have something to check. +func (f *fakeStore) addCameraRef(id, client, site, engineID string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.cameraRefs == nil { + f.cameraRefs = map[string]cameraRef{} + } + f.cameraRefs[id] = cameraRef{client: client, site: site, engineID: engineID} +} + +type cameraRef struct{ client, site, engineID string } diff --git a/server/internal/api/handlers_live.go b/server/internal/api/handlers_live.go new file mode 100644 index 0000000..d0e5ce9 --- /dev/null +++ b/server/internal/api/handlers_live.go @@ -0,0 +1,173 @@ +package api + +import ( + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "io" + "net/http" + "time" +) + +const ( + // liveMaxFrame bounds one frame. The agent re-encodes to ~640 px before + // sending, so a frame is tens of KB; 1 MB is a ceiling, not a target. + liveMaxFrame = 1 << 20 + // liveSession caps one push. A browser tab left open for a week must not + // leave a shop uploading for a week; the agent simply asks again while + // anyone is still watching, so the cap costs a reconnect, not the stream. + liveSession = 5 * time.Minute + // liveWaitForWork is how long the agent's poll is held open. Long enough + // that an idle site makes ~2 requests a minute; short enough to sit well + // inside any proxy's idle timeout. + liveWaitForWork = 25 * time.Second +) + +// handleWatchLive streams one camera's frames to a signed-in user over SSE. +// +// SSE rather than serving MJPEG directly, for the same reason the snapshot is +// not a signed link: an cannot send an Authorization header, and minting +// a URL that works without a session - for LIVE video of a shop floor, no less +// - would be a much worse trade than the 33% base64 costs. +func (s *Server) handleWatchLive(w http.ResponseWriter, r *http.Request) { + p := PrincipalFrom(r.Context()) + id := r.PathValue("id") + if !looksLikeUUID(id) { + writeErr(w, http.StatusNotFound, "not_found", "No such camera.") + return + } + // Ownership is checked HERE, once, before anything is streamed. Everything + // after this point is keyed on a camera id, and a hub does not know whose + // camera it is holding. + if _, _, err := s.Store.CameraRef(r.Context(), p.ClientID, id); err != nil { + writeErr(w, http.StatusNotFound, "not_found", "No such camera.") + return + } + flusher, ok := w.(http.Flusher) + if !ok { + s.serverError(w, "live", errors.New("this server cannot stream")) + return + } + + frames, release := s.live().Watch(id) + defer release() + + h := w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-store") + h.Set("Connection", "keep-alive") + // Without this a proxy buffers the stream into one response that arrives + // when the connection closes - which for live video means never. + h.Set("X-Accel-Buffering", "no") + w.WriteHeader(http.StatusOK) + // Told up front, so a viewer can say "waiting for the shop PC" rather than + // showing an empty box while the agent is still being asked. + fmt.Fprint(w, "event: waiting\ndata: {}\n\n") + flusher.Flush() + + ctx := r.Context() + // Refreshed as we go rather than once at the start: this is what tells the + // agent somebody is still there, and a viewer that has gone away stops a + // shop uploading within seconds without having to announce anything. + keep := time.NewTicker(liveIdle / 3) + defer keep.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-keep.C: + s.live().Keep(id) + case frame, ok := <-frames: + if !ok { + return + } + s.live().Keep(id) + if _, err := fmt.Fprintf(w, "event: frame\ndata: %s\n\n", + base64.StdEncoding.EncodeToString(frame)); err != nil { + return + } + flusher.Flush() + } + } +} + +// handleAgentLiveWanted is the shop PC asking whether anyone is watching. +// +// Held open rather than answered immediately: an agent polling every few +// seconds would put a floor under how quickly a live view can start, and one +// polling slowly would put a ceiling on it. Holding the request means pressing +// "Live" reaches the shop PC at once, and an idle site costs about two requests +// a minute. +func (s *Server) handleAgentLiveWanted(w http.ResponseWriter, r *http.Request, ap AgentPrincipal) { + ids, err := s.Store.SiteCameraIDs(r.Context(), ap.SiteID) + if err != nil { + s.serverError(w, "live wanted", err) + return + } + if wanted := s.live().WantedAmong(ids); len(wanted) > 0 { + writeJSON(w, http.StatusOK, map[string]any{"cameras": wanted}) + return + } + select { + case <-r.Context().Done(): + return + case <-s.live().Bell(ids): + case <-time.After(liveWaitForWork): + } + writeJSON(w, http.StatusOK, map[string]any{ + "cameras": s.live().WantedAmong(ids)}) +} + +// handleAgentPushLive receives frames for as long as somebody is watching. +// +// One request carrying many frames, each prefixed with its length, rather than +// a request per frame: at a few frames a second the per-request overhead and +// the TLS handshakes would cost more than the pictures. +func (s *Server) handleAgentPushLive(w http.ResponseWriter, r *http.Request, ap AgentPrincipal) { + id := r.PathValue("camera") + if !looksLikeUUID(id) { + writeErr(w, http.StatusNotFound, "not_found", "No such camera.") + return + } + // The camera must belong to the AGENT's own site. Without this an agent + // could push its own pictures into another site's live view - a camera id + // is not a secret, and the agent supplies this one. + siteID, _, err := s.Store.CameraRefBySite(r.Context(), ap.SiteID, id) + if err != nil || siteID != ap.SiteID { + writeErr(w, http.StatusNotFound, "not_found", "No such camera.") + return + } + + deadline := time.Now().Add(liveSession) + body := r.Body + var header [4]byte + frames := 0 + for { + if time.Now().After(deadline) { + break + } + if _, err := io.ReadFull(body, header[:]); err != nil { + break + } + n := binary.BigEndian.Uint32(header[:]) + if n == 0 || n > liveMaxFrame { + // A length this side cannot trust ends the stream rather than + // allocating what it was told to. + writeErr(w, http.StatusBadRequest, "bad_frame", "Frame size out of range.") + return + } + frame := make([]byte, n) + if _, err := io.ReadFull(body, frame); err != nil { + break + } + frames++ + if !s.live().Publish(id, frame) { + // Nobody is watching any more. Saying so in the response is what + // stops the shop uploading; the agent goes back to waiting. + break + } + } + writeJSON(w, http.StatusOK, map[string]any{"frames": frames}) +} diff --git a/server/internal/api/live.go b/server/internal/api/live.go new file mode 100644 index 0000000..cd6ece2 --- /dev/null +++ b/server/internal/api/live.go @@ -0,0 +1,184 @@ +package api + +import ( + "sync" + "time" +) + +// LiveHub carries camera frames from a shop PC to whoever is watching. +// +// The shop PC's engine serves MJPEG on its own loopback, behind a router with +// no inbound route, so head office cannot pull it. What head office CAN do is +// answer the agent's outbound requests - which is the whole shape of this +// product already - so the agent asks "is anyone watching?", and pushes frames +// up for as long as somebody is. +// +// This is NOT true video. It is a few frames a second of re-encoded JPEG, which +// is what an outbound HTTP relay can carry honestly. Real 25 fps video needs +// WebRTC and a TURN server; this needs neither, and for "is that camera pointed +// at the right place, and is someone in the shop" a few frames a second is what +// the question actually requires. +// +// It is deliberately the OPPOSITE of the arrivals Hub, which is a doorbell that +// pushes nothing because nothing may be lost. Here a dropped frame is the +// correct outcome: a slow viewer must never stall the pump or accumulate a +// backlog of stale pictures, because the only frame worth having is the newest +// one. So each viewer gets a one-slot buffer and a full slot is overwritten. +type LiveHub struct { + mu sync.Mutex + cameras map[string]*liveCamera +} + +type liveCamera struct { + viewers map[chan []byte]struct{} + // wanted is refreshed by every watching viewer. The agent stops pushing + // when it lapses, which is what keeps a shop's uplink idle when nobody is + // looking - the entire cost argument for this feature. + wanted time.Time + // bell fires when the first viewer arrives, so an agent long-polling for + // work is answered immediately instead of on its next tick. + bell chan struct{} +} + +// liveIdle is how long a camera stays "wanted" after the last viewer refreshed +// it. Longer than the viewer's refresh interval so an ordinary pause between +// refreshes does not stop the stream, short enough that a browser that +// vanished stops a shop uploading within seconds. +const liveIdle = 12 * time.Second + +func NewLiveHub() *LiveHub { + return &LiveHub{cameras: map[string]*liveCamera{}} +} + +// Watch registers a viewer and returns its frame channel plus a release func. +func (h *LiveHub) Watch(cameraID string) (<-chan []byte, func()) { + h.mu.Lock() + defer h.mu.Unlock() + c := h.cameras[cameraID] + if c == nil { + c = &liveCamera{viewers: map[chan []byte]struct{}{}, bell: make(chan struct{}, 1)} + h.cameras[cameraID] = c + } + ch := make(chan []byte, 1) + c.viewers[ch] = struct{}{} + c.wanted = time.Now().Add(liveIdle) + select { + case c.bell <- struct{}{}: + default: + } + return ch, func() { + h.mu.Lock() + defer h.mu.Unlock() + if cam := h.cameras[cameraID]; cam != nil { + delete(cam.viewers, ch) + if len(cam.viewers) == 0 { + // Dropped entirely rather than left empty: an estate's worth of + // cameras nobody is watching would otherwise accumulate here + // for the life of the process. + delete(h.cameras, cameraID) + } + } + close(ch) + } +} + +// Keep extends a camera's interest window. Called by each viewer as it reads, +// so interest expires on its own when a browser goes away without saying so - +// which is the normal way a tab closes. +func (h *LiveHub) Keep(cameraID string) { + h.mu.Lock() + defer h.mu.Unlock() + if c := h.cameras[cameraID]; c != nil { + c.wanted = time.Now().Add(liveIdle) + } +} + +// Wanted reports whether anyone is watching this camera right now. +func (h *LiveHub) Wanted(cameraID string) bool { + h.mu.Lock() + defer h.mu.Unlock() + c := h.cameras[cameraID] + return c != nil && len(c.viewers) > 0 && time.Now().Before(c.wanted) +} + +// WantedAmong filters a site's cameras down to the ones being watched. The +// agent asks with the cameras it has, so this never has to know a site's +// inventory. +func (h *LiveHub) WantedAmong(ids []string) []string { + var out []string + for _, id := range ids { + if h.Wanted(id) { + out = append(out, id) + } + } + return out +} + +// Bell returns a channel that fires when a viewer starts watching one of these +// cameras, so an agent waiting for work wakes at once rather than on a tick. +// A nil channel blocks forever, which is the right behaviour for the caller's +// select when none of the cameras is known here yet. +func (h *LiveHub) Bell(ids []string) <-chan struct{} { + h.mu.Lock() + defer h.mu.Unlock() + for _, id := range ids { + if c := h.cameras[id]; c != nil { + return c.bell + } + } + // Register a placeholder for the first camera so a later Watch can ring + // something. Cheap: one struct per camera an agent asked about. + if len(ids) == 0 { + return nil + } + c := &liveCamera{viewers: map[chan []byte]struct{}{}, bell: make(chan struct{}, 1)} + h.cameras[ids[0]] = c + return c.bell +} + +// Publish hands one frame to every viewer of a camera and reports whether any +// remain. The agent uses that answer to stop pushing. +// +// A viewer whose slot is full has its pending frame REPLACED, never queued. The +// newest frame is the only one worth having, and a queue here would show a +// viewer an ever-growing delay behind the shop rather than dropping back to +// live. +func (h *LiveHub) Publish(cameraID string, frame []byte) bool { + h.mu.Lock() + defer h.mu.Unlock() + c := h.cameras[cameraID] + if c == nil || len(c.viewers) == 0 { + return false + } + for ch := range c.viewers { + select { + case ch <- frame: + default: + select { + case <-ch: + default: + } + select { + case ch <- frame: + default: + } + } + } + return time.Now().Before(c.wanted) +} + + +// live returns the hub, creating it on first use. +// +// Lazily, and stored on the Server, so a server built without one still works: +// unlike the arrivals doorbell there is no degraded mode to fall back to here, +// and a nil map panic on an endpoint somebody forgot to wire is the worst way +// to find out. +func (s *Server) live() *LiveHub { + s.liveOnce.Do(func() { + if s.Live == nil { + s.Live = NewLiveHub() + } + }) + return s.Live +} diff --git a/server/internal/api/live_test.go b/server/internal/api/live_test.go new file mode 100644 index 0000000..09960fb --- /dev/null +++ b/server/internal/api/live_test.go @@ -0,0 +1,131 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/loyaly/behavision-server/internal/auth" +) + +const liveCam = "22222222-3333-4444-5555-666666666666" + +// The whole cost argument for this feature: a camera nobody is watching must +// cost a shop nothing at all. If Wanted were ever optimistic, every shop PC in +// an estate would upload continuously. +func TestNobodyWatchingMeansNothingIsWanted(t *testing.T) { + h := NewLiveHub() + if h.Wanted(liveCam) { + t.Fatal("a camera nobody has asked for was reported as wanted") + } + if got := h.WantedAmong([]string{liveCam, "other"}); len(got) != 0 { + t.Fatalf("wanted %v with no viewers", got) + } +} + +func TestAViewerMakesACameraWantedAndReleasingStopsIt(t *testing.T) { + h := NewLiveHub() + _, release := h.Watch(liveCam) + if !h.Wanted(liveCam) { + t.Fatal("a watched camera was not wanted") + } + release() + if h.Wanted(liveCam) { + t.Fatal("the camera stayed wanted after the last viewer left") + } +} + +// The opposite policy to the arrivals Hub, and deliberately so. There nothing +// may be lost; here the only frame worth having is the newest one, and a queue +// would show a viewer an ever-growing delay behind the shop instead of dropping +// back to live. +func TestASlowViewerGetsTheNewestFrameNotTheOldest(t *testing.T) { + h := NewLiveHub() + frames, release := h.Watch(liveCam) + defer release() + + for _, f := range []string{"one", "two", "three"} { + h.Publish(liveCam, []byte(f)) + } + select { + case got := <-frames: + if string(got) != "three" { + t.Fatalf("a slow viewer was served %q, want the newest frame", got) + } + default: + t.Fatal("nothing was delivered") + } +} + +// Publish reporting false is what stops the shop PC uploading. If it kept +// saying true the agent would push into an empty room until the session cap. +func TestPublishReportsWhenTheLastViewerHasGone(t *testing.T) { + h := NewLiveHub() + _, release := h.Watch(liveCam) + if !h.Publish(liveCam, []byte("frame")) { + t.Fatal("publish said to stop while somebody was watching") + } + release() + if h.Publish(liveCam, []byte("frame")) { + t.Fatal("publish did not say to stop after the last viewer left") + } +} + +// A browser that vanishes without saying so - the normal way a tab closes - +// must stop the upload on its own. +func TestInterestExpiresWithoutBeingRefreshed(t *testing.T) { + h := NewLiveHub() + frames, release := h.Watch(liveCam) + defer release() + _ = frames + + h.mu.Lock() + h.cameras[liveCam].wanted = time.Now().Add(-time.Second) + h.mu.Unlock() + + if h.Wanted(liveCam) { + t.Fatal("interest did not lapse") + } + if h.Publish(liveCam, []byte("frame")) { + t.Fatal("publish kept the shop uploading for a viewer that had gone") + } +} + +// The relay is keyed on a camera id and a hub does not know whose camera it is +// holding, so ownership has to be proved before anything streams. Otherwise a +// camera id - which is not a secret - would be enough to watch another +// company's shop floor. +func TestAnotherTenantCannotWatchYourCamera(t *testing.T) { + srv, fs := newServer(t) + fs.addCameraRef(liveCam, "client-1", "site-1", "cam1") + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/cameras/"+liveCam+"/live", nil) + req = req.WithContext(context.WithValue(req.Context(), principalKey, + auth.Principal{ClientID: "someone-else", Role: "owner"})) + srv.handleWatchLive(rr, req) + + if rr.Code != http.StatusNotFound { + t.Fatalf("status %d, want 404", rr.Code) + } +} + +// An agent may only push into its OWN site's camera. The agent supplies this +// id, and a camera id is not a secret. +func TestAnAgentCannotPushIntoAnotherSitesCamera(t *testing.T) { + srv, fs := newServer(t) + fs.addCameraRef(liveCam, "client-1", "site-1", "cam1") + fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-1", SiteID: "site-2"}) + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, + "/api/agent/cameras/"+liveCam+"/live", nil) + req.Header.Set("Authorization", "Bearer agent-token") + srv.Routes().ServeHTTP(rr, req) + + if rr.Code != http.StatusNotFound { + t.Fatalf("status %d, want 404", rr.Code) + } +} diff --git a/server/internal/api/types.go b/server/internal/api/types.go index b0bbfdb..05e3ad2 100644 --- a/server/internal/api/types.go +++ b/server/internal/api/types.go @@ -440,6 +440,11 @@ type CameraInput struct { // thing stopping a tenant response carrying camera passwords would be // remembering to blank a field, on every path, forever. type AgentCamera struct { + // ID is head office's uuid. Carried alongside CameraID because the two + // name the same camera to different halves of the system: head office + // addresses it by uuid, the engine on the shop PC only knows the name in + // CameraID, and the live relay has to translate between them. + ID string `json:"id"` CameraID string `json:"camera_id"` Label string `json:"label"` Host string `json:"host"` diff --git a/server/internal/store/api_cameras.go b/server/internal/store/api_cameras.go index 92374fa..14caeef 100644 --- a/server/internal/store/api_cameras.go +++ b/server/internal/store/api_cameras.go @@ -199,7 +199,7 @@ func (s *Store) DeleteCamera(ctx context.Context, clientID, id string) (api.Came // yet" by absence, and would re-adopt what was just deleted. func (s *Store) AgentCameras(ctx context.Context, siteID string) ([]api.AgentCamera, error) { rows, err := s.pool.Query(ctx, ` - SELECT camera_id, label, host, port, path, username, password_enc, + SELECT id::text, camera_id, label, host, port, path, username, password_enc, max_width, tuning, enabled, revision, (deleted_at IS NOT NULL) FROM site_cameras WHERE site_id = $1::uuid @@ -213,7 +213,7 @@ func (s *Store) AgentCameras(ctx context.Context, siteID string) ([]api.AgentCam for rows.Next() { var c api.AgentCamera var sealed []byte - if err := rows.Scan(&c.CameraID, &c.Label, &c.Host, &c.Port, &c.Path, + if err := rows.Scan(&c.ID, &c.CameraID, &c.Label, &c.Host, &c.Port, &c.Path, &c.Username, &sealed, &c.MaxWidth, &c.Tuning, &c.Enabled, &c.Revision, &c.Deleted); err != nil { return nil, err diff --git a/server/internal/store/api_snapshots.go b/server/internal/store/api_snapshots.go index 81eba96..f504ad3 100644 --- a/server/internal/store/api_snapshots.go +++ b/server/internal/store/api_snapshots.go @@ -82,3 +82,51 @@ func (s *Store) CameraSnapshot(ctx context.Context, clientID, cameraID string) ( } return img, at, err } + +// CameraRef resolves one of a tenant's cameras to its site and the name the +// engine knows it by. +// +// Its job is to prove ownership before a live stream starts. Everything after +// that point is keyed on a camera id, and a hub relaying frames does not know +// whose camera it is holding — so this is the only place that can decide. +func (s *Store) CameraRef(ctx context.Context, clientID, cameraID string) (string, string, error) { + return s.cameraRef(ctx, `client_id = $2::uuid`, cameraID, clientID) +} + +// CameraRefBySite is the same question asked by an agent, which is +// authenticated for a site rather than a tenant. +func (s *Store) CameraRefBySite(ctx context.Context, siteID, cameraID string) (string, string, error) { + return s.cameraRef(ctx, `site_id = $2::uuid`, cameraID, siteID) +} + +func (s *Store) cameraRef(ctx context.Context, scope, cameraID, owner string) (string, string, error) { + var siteID, engineID string + err := s.pool.QueryRow(ctx, ` + SELECT site_id::text, camera_id FROM site_cameras + WHERE id = $1::uuid AND `+scope+` AND deleted_at IS NULL`, + cameraID, owner).Scan(&siteID, &engineID) + if errors.Is(err, pgx.ErrNoRows) { + return "", "", ErrNoSnapshot + } + return siteID, engineID, err +} + +// SiteCameraIDs lists a site's camera uuids, for the agent's live poll. +func (s *Store) SiteCameraIDs(ctx context.Context, siteID string) ([]string, error) { + rows, err := s.pool.Query(ctx, ` + SELECT id::text FROM site_cameras + WHERE site_id = $1::uuid AND deleted_at IS NULL AND enabled`, siteID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} diff --git a/server/internal/web/dist/assets/index-B_gTsA07.js b/server/internal/web/dist/assets/index-B_gTsA07.js deleted file mode 100644 index 838ad89..0000000 --- a/server/internal/web/dist/assets/index-B_gTsA07.js +++ /dev/null @@ -1,43 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var au={exports:{}},al={},cu={exports:{}},L={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var tr=Symbol.for("react.element"),Ec=Symbol.for("react.portal"),_c=Symbol.for("react.fragment"),Pc=Symbol.for("react.strict_mode"),Tc=Symbol.for("react.profiler"),zc=Symbol.for("react.provider"),Lc=Symbol.for("react.context"),Rc=Symbol.for("react.forward_ref"),Oc=Symbol.for("react.suspense"),Ic=Symbol.for("react.memo"),Fc=Symbol.for("react.lazy"),Zs=Symbol.iterator;function Dc(e){return e===null||typeof e!="object"?null:(e=Zs&&e[Zs]||e["@@iterator"],typeof e=="function"?e:null)}var du={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},fu=Object.assign,pu={};function an(e,t,n){this.props=e,this.context=t,this.refs=pu,this.updater=n||du}an.prototype.isReactComponent={};an.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};an.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function hu(){}hu.prototype=an.prototype;function qi(e,t,n){this.props=e,this.context=t,this.refs=pu,this.updater=n||du}var bi=qi.prototype=new hu;bi.constructor=qi;fu(bi,an.prototype);bi.isPureReactComponent=!0;var Js=Array.isArray,mu=Object.prototype.hasOwnProperty,es={current:null},vu={key:!0,ref:!0,__self:!0,__source:!0};function yu(e,t,n){var r,l={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)mu.call(t,r)&&!vu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1>>1,q=C[Q];if(0>>1;Ql(zl,z))wtl(ur,zl)?(C[Q]=ur,C[wt]=z,Q=wt):(C[Q]=zl,C[gt]=z,Q=gt);else if(wtl(ur,z))C[Q]=ur,C[wt]=z,Q=wt;else break e}}return T}function l(C,T){var z=C.sortIndex-T.sortIndex;return z!==0?z:C.id-T.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,u=s.now();e.unstable_now=function(){return s.now()-u}}var a=[],c=[],m=1,y=null,h=3,v=!1,w=!1,x=!1,R=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function f(C){for(var T=n(c);T!==null;){if(T.callback===null)r(c);else if(T.startTime<=C)r(c),T.sortIndex=T.expirationTime,t(a,T);else break;T=n(c)}}function g(C){if(x=!1,f(C),!w)if(n(a)!==null)w=!0,Pl(S);else{var T=n(c);T!==null&&Tl(g,T.startTime-C)}}function S(C,T){w=!1,x&&(x=!1,p(P),P=-1),v=!0;var z=h;try{for(f(T),y=n(a);y!==null&&(!(y.expirationTime>T)||C&&!Te());){var Q=y.callback;if(typeof Q=="function"){y.callback=null,h=y.priorityLevel;var q=Q(y.expirationTime<=T);T=e.unstable_now(),typeof q=="function"?y.callback=q:y===n(a)&&r(a),f(T)}else r(a);y=n(a)}if(y!==null)var or=!0;else{var gt=n(c);gt!==null&&Tl(g,gt.startTime-T),or=!1}return or}finally{y=null,h=z,v=!1}}var E=!1,_=null,P=-1,H=5,O=-1;function Te(){return!(e.unstable_now()-OC||125Q?(C.sortIndex=z,t(c,C),n(a)===null&&C===n(c)&&(x?(p(P),P=-1):x=!0,Tl(g,z-Q))):(C.sortIndex=q,t(a,C),w||v||(w=!0,Pl(S))),C},e.unstable_shouldYield=Te,e.unstable_wrapCallback=function(C){var T=h;return function(){var z=h;h=T;try{return C.apply(this,arguments)}finally{h=z}}}})(Su);xu.exports=Su;var Gc=xu.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Yc=N,ke=Gc;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),li=Object.prototype.hasOwnProperty,Xc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,bs={},eo={};function Zc(e){return li.call(eo,e)?!0:li.call(bs,e)?!1:Xc.test(e)?eo[e]=!0:(bs[e]=!0,!1)}function Jc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function qc(e,t,n,r){if(t===null||typeof t>"u"||Jc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function de(e,t,n,r,l,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var re={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){re[e]=new de(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];re[t]=new de(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){re[e]=new de(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){re[e]=new de(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){re[e]=new de(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){re[e]=new de(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){re[e]=new de(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){re[e]=new de(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){re[e]=new de(e,5,!1,e.toLowerCase(),null,!1,!1)});var ns=/[\-:]([a-z])/g;function rs(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ns,rs);re[t]=new de(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ns,rs);re[t]=new de(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ns,rs);re[t]=new de(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){re[e]=new de(e,1,!1,e.toLowerCase(),null,!1,!1)});re.xlinkHref=new de("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){re[e]=new de(e,1,!1,e.toLowerCase(),null,!0,!0)});function ls(e,t,n,r){var l=re.hasOwnProperty(t)?re[t]:null;(l!==null?l.type!==0:r||!(2u||l[s]!==i[u]){var a=` -`+l[s].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=s&&0<=u);break}}}finally{Ol=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?jn(e):""}function bc(e){switch(e.tag){case 5:return jn(e.type);case 16:return jn("Lazy");case 13:return jn("Suspense");case 19:return jn("SuspenseList");case 0:case 2:case 15:return e=Il(e.type,!1),e;case 11:return e=Il(e.type.render,!1),e;case 1:return e=Il(e.type,!0),e;default:return""}}function ui(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Mt:return"Fragment";case Dt:return"Portal";case ii:return"Profiler";case is:return"StrictMode";case si:return"Suspense";case oi:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Nu:return(e.displayName||"Context")+".Consumer";case Cu:return(e._context.displayName||"Context")+".Provider";case ss:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case os:return t=e.displayName||null,t!==null?t:ui(e.type)||"Memo";case be:t=e._payload,e=e._init;try{return ui(e(t))}catch{}}return null}function ed(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ui(t);case 8:return t===is?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function pt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function _u(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function td(e){var t=_u(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function dr(e){e._valueTracker||(e._valueTracker=td(e))}function Pu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=_u(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function $r(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function ai(e,t){var n=t.checked;return V({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function no(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=pt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Tu(e,t){t=t.checked,t!=null&&ls(e,"checked",t,!1)}function ci(e,t){Tu(e,t);var n=pt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?di(e,t.type,n):t.hasOwnProperty("defaultValue")&&di(e,t.type,pt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ro(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function di(e,t,n){(t!=="number"||$r(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Cn=Array.isArray;function Yt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=fr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Mn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var _n={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nd=["Webkit","ms","Moz","O"];Object.keys(_n).forEach(function(e){nd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),_n[t]=_n[e]})});function Ou(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||_n.hasOwnProperty(e)&&_n[e]?(""+t).trim():t+"px"}function Iu(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Ou(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var rd=V({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function hi(e,t){if(t){if(rd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function mi(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var vi=null;function us(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var yi=null,Xt=null,Zt=null;function so(e){if(e=lr(e)){if(typeof yi!="function")throw Error(k(280));var t=e.stateNode;t&&(t=hl(t),yi(e.stateNode,e.type,t))}}function Fu(e){Xt?Zt?Zt.push(e):Zt=[e]:Xt=e}function Du(){if(Xt){var e=Xt,t=Zt;if(Zt=Xt=null,so(e),t)for(e=0;e>>=0,e===0?32:31-(hd(e)/md|0)|0}var pr=64,hr=4194304;function Nn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Wr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var u=s&~l;u!==0?r=Nn(u):(i&=s,i!==0&&(r=Nn(i)))}else s=n&~l,s!==0?r=Nn(s):i!==0&&(r=Nn(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function nr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ie(t),e[t]=n}function wd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Tn),vo=" ",yo=!1;function na(e,t){switch(e){case"keyup":return Gd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ra(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ut=!1;function Xd(e,t){switch(e){case"compositionend":return ra(t);case"keypress":return t.which!==32?null:(yo=!0,vo);case"textInput":return e=t.data,e===vo&&yo?null:e;default:return null}}function Zd(e,t){if(Ut)return e==="compositionend"||!vs&&na(e,t)?(e=ea(),Tr=ps=rt=null,Ut=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xo(n)}}function oa(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?oa(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ua(){for(var e=window,t=$r();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=$r(e.document)}return t}function ys(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sf(e){var t=ua(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&oa(n.ownerDocument.documentElement,n)){if(r!==null&&ys(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=So(n,i);var s=So(n,r);l&&s&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,$t=null,ji=null,Ln=null,Ci=!1;function jo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ci||$t==null||$t!==$r(r)||(r=$t,"selectionStart"in r&&ys(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ln&&Wn(Ln,r)||(Ln=r,r=Kr(ji,"onSelect"),0Vt||(e.current=zi[Vt],zi[Vt]=null,Vt--)}function D(e,t){Vt++,zi[Vt]=e.current,e.current=t}var ht={},oe=vt(ht),he=vt(!1),_t=ht;function tn(e,t){var n=e.type.contextTypes;if(!n)return ht;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function me(e){return e=e.childContextTypes,e!=null}function Yr(){U(he),U(oe)}function zo(e,t,n){if(oe.current!==ht)throw Error(k(168));D(oe,t),D(he,n)}function ya(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(k(108,ed(e)||"Unknown",l));return V({},n,r)}function Xr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ht,_t=oe.current,D(oe,e),D(he,he.current),!0}function Lo(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=ya(e,t,_t),r.__reactInternalMemoizedMergedChildContext=e,U(he),U(oe),D(oe,e)):U(he),D(he,n)}var We=null,ml=!1,Yl=!1;function ga(e){We===null?We=[e]:We.push(e)}function gf(e){ml=!0,ga(e)}function yt(){if(!Yl&&We!==null){Yl=!0;var e=0,t=F;try{var n=We;for(F=1;e>=s,l-=s,He=1<<32-Ie(t)+l|n<P?(H=_,_=null):H=_.sibling;var O=h(p,_,f[P],g);if(O===null){_===null&&(_=H);break}e&&_&&O.alternate===null&&t(p,_),d=i(O,d,P),E===null?S=O:E.sibling=O,E=O,_=H}if(P===f.length)return n(p,_),$&&kt(p,P),S;if(_===null){for(;PP?(H=_,_=null):H=_.sibling;var Te=h(p,_,O.value,g);if(Te===null){_===null&&(_=H);break}e&&_&&Te.alternate===null&&t(p,_),d=i(Te,d,P),E===null?S=Te:E.sibling=Te,E=Te,_=H}if(O.done)return n(p,_),$&&kt(p,P),S;if(_===null){for(;!O.done;P++,O=f.next())O=y(p,O.value,g),O!==null&&(d=i(O,d,P),E===null?S=O:E.sibling=O,E=O);return $&&kt(p,P),S}for(_=r(p,_);!O.done;P++,O=f.next())O=v(_,p,P,O.value,g),O!==null&&(e&&O.alternate!==null&&_.delete(O.key===null?P:O.key),d=i(O,d,P),E===null?S=O:E.sibling=O,E=O);return e&&_.forEach(function(fn){return t(p,fn)}),$&&kt(p,P),S}function R(p,d,f,g){if(typeof f=="object"&&f!==null&&f.type===Mt&&f.key===null&&(f=f.props.children),typeof f=="object"&&f!==null){switch(f.$$typeof){case cr:e:{for(var S=f.key,E=d;E!==null;){if(E.key===S){if(S=f.type,S===Mt){if(E.tag===7){n(p,E.sibling),d=l(E,f.props.children),d.return=p,p=d;break e}}else if(E.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===be&&Io(S)===E.type){n(p,E.sibling),d=l(E,f.props),d.ref=wn(p,E,f),d.return=p,p=d;break e}n(p,E);break}else t(p,E);E=E.sibling}f.type===Mt?(d=Et(f.props.children,p.mode,g,f.key),d.return=p,p=d):(g=Mr(f.type,f.key,f.props,null,p.mode,g),g.ref=wn(p,d,f),g.return=p,p=g)}return s(p);case Dt:e:{for(E=f.key;d!==null;){if(d.key===E)if(d.tag===4&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){n(p,d.sibling),d=l(d,f.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=ni(f,p.mode,g),d.return=p,p=d}return s(p);case be:return E=f._init,R(p,d,E(f._payload),g)}if(Cn(f))return w(p,d,f,g);if(hn(f))return x(p,d,f,g);xr(p,f)}return typeof f=="string"&&f!==""||typeof f=="number"?(f=""+f,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,f),d.return=p,p=d):(n(p,d),d=ti(f,p.mode,g),d.return=p,p=d),s(p)):n(p,d)}return R}var rn=Sa(!0),ja=Sa(!1),qr=vt(null),br=null,Qt=null,xs=null;function Ss(){xs=Qt=br=null}function js(e){var t=qr.current;U(qr),e._currentValue=t}function Oi(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function qt(e,t){br=e,xs=Qt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pe=!0),e.firstContext=null)}function _e(e){var t=e._currentValue;if(xs!==e)if(e={context:e,memoizedValue:t,next:null},Qt===null){if(br===null)throw Error(k(308));Qt=e,br.dependencies={lanes:0,firstContext:e}}else Qt=Qt.next=e;return t}var jt=null;function Cs(e){jt===null?jt=[e]:jt.push(e)}function Ca(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Cs(t)):(n.next=l.next,l.next=n),t.interleaved=n,Xe(e,r)}function Xe(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var et=!1;function Ns(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Na(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ke(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function at(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,I&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Xe(e,n)}return l=r.interleaved,l===null?(t.next=t,Cs(r)):(t.next=l.next,l.next=t),r.interleaved=t,Xe(e,n)}function Lr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,cs(e,n)}}function Fo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var s={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=s:i=i.next=s,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function el(e,t,n,r){var l=e.updateQueue;et=!1;var i=l.firstBaseUpdate,s=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var a=u,c=a.next;a.next=null,s===null?i=c:s.next=c,s=a;var m=e.alternate;m!==null&&(m=m.updateQueue,u=m.lastBaseUpdate,u!==s&&(u===null?m.firstBaseUpdate=c:u.next=c,m.lastBaseUpdate=a))}if(i!==null){var y=l.baseState;s=0,m=c=a=null,u=i;do{var h=u.lane,v=u.eventTime;if((r&h)===h){m!==null&&(m=m.next={eventTime:v,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var w=e,x=u;switch(h=t,v=n,x.tag){case 1:if(w=x.payload,typeof w=="function"){y=w.call(v,y,h);break e}y=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=x.payload,h=typeof w=="function"?w.call(v,y,h):w,h==null)break e;y=V({},y,h);break e;case 2:et=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[u]:h.push(u))}else v={eventTime:v,lane:h,tag:u.tag,payload:u.payload,callback:u.callback,next:null},m===null?(c=m=v,a=y):m=m.next=v,s|=h;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;h=u,u=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(m===null&&(a=y),l.baseState=a,l.firstBaseUpdate=c,l.lastBaseUpdate=m,t=l.shared.interleaved,t!==null){l=t;do s|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);zt|=s,e.lanes=s,e.memoizedState=y}}function Do(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Zl.transition;Zl.transition={};try{e(!1),t()}finally{F=n,Zl.transition=r}}function Va(){return Pe().memoizedState}function Sf(e,t,n){var r=dt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Wa(e))Ha(t,n);else if(n=Ca(e,t,n,r),n!==null){var l=ae();Fe(n,e,r,l),Qa(n,t,r)}}function jf(e,t,n){var r=dt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Wa(e))Ha(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,u=i(s,n);if(l.hasEagerState=!0,l.eagerState=u,De(u,s)){var a=t.interleaved;a===null?(l.next=l,Cs(t)):(l.next=a.next,a.next=l),t.interleaved=l;return}}catch{}finally{}n=Ca(e,t,l,r),n!==null&&(l=ae(),Fe(n,e,r,l),Qa(n,t,r))}}function Wa(e){var t=e.alternate;return e===B||t!==null&&t===B}function Ha(e,t){Rn=nl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Qa(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,cs(e,n)}}var rl={readContext:_e,useCallback:le,useContext:le,useEffect:le,useImperativeHandle:le,useInsertionEffect:le,useLayoutEffect:le,useMemo:le,useReducer:le,useRef:le,useState:le,useDebugValue:le,useDeferredValue:le,useTransition:le,useMutableSource:le,useSyncExternalStore:le,useId:le,unstable_isNewReconciler:!1},Cf={readContext:_e,useCallback:function(e,t){return Ue().memoizedState=[e,t===void 0?null:t],e},useContext:_e,useEffect:Uo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Or(4194308,4,Ma.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Or(4194308,4,e,t)},useInsertionEffect:function(e,t){return Or(4,2,e,t)},useMemo:function(e,t){var n=Ue();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ue();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Sf.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=Ue();return e={current:e},t.memoizedState=e},useState:Mo,useDebugValue:Os,useDeferredValue:function(e){return Ue().memoizedState=e},useTransition:function(){var e=Mo(!1),t=e[0];return e=xf.bind(null,e[1]),Ue().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=B,l=Ue();if($){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),ee===null)throw Error(k(349));Tt&30||Ta(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Uo(La.bind(null,r,i,e),[e]),r.flags|=2048,Jn(9,za.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ue(),t=ee.identifierPrefix;if($){var n=Qe,r=He;n=(r&~(1<<32-Ie(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Xn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[$e]=t,e[Kn]=r,tc(e,t,!1,!1),t.stateNode=e;e:{switch(s=mi(n,r),n){case"dialog":M("cancel",e),M("close",e),l=r;break;case"iframe":case"object":case"embed":M("load",e),l=r;break;case"video":case"audio":for(l=0;lon&&(t.flags|=128,r=!0,kn(i,!1),t.lanes=4194304)}else{if(!r)if(e=tl(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),kn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!$)return ie(t),null}else 2*K()-i.renderingStartTime>on&&n!==1073741824&&(t.flags|=128,r=!0,kn(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=K(),t.sibling=null,n=A.current,D(A,r?n&1|2:n&1),t):(ie(t),null);case 22:case 23:return $s(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ye&1073741824&&(ie(t),t.subtreeFlags&6&&(t.flags|=8192)):ie(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function Rf(e,t){switch(ws(t),t.tag){case 1:return me(t.type)&&Yr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ln(),U(he),U(oe),Ps(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return _s(t),null;case 13:if(U(A),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));nn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return U(A),null;case 4:return ln(),null;case 10:return js(t.type._context),null;case 22:case 23:return $s(),null;case 24:return null;default:return null}}var jr=!1,se=!1,Of=typeof WeakSet=="function"?WeakSet:Set,j=null;function Kt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){W(e,t,r)}else n.current=null}function Vi(e,t,n){try{n()}catch(r){W(e,t,r)}}var Xo=!1;function If(e,t){if(Ni=Hr,e=ua(),ys(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,u=-1,a=-1,c=0,m=0,y=e,h=null;t:for(;;){for(var v;y!==n||l!==0&&y.nodeType!==3||(u=s+l),y!==i||r!==0&&y.nodeType!==3||(a=s+r),y.nodeType===3&&(s+=y.nodeValue.length),(v=y.firstChild)!==null;)h=y,y=v;for(;;){if(y===e)break t;if(h===n&&++c===l&&(u=s),h===i&&++m===r&&(a=s),(v=y.nextSibling)!==null)break;y=h,h=y.parentNode}y=v}n=u===-1||a===-1?null:{start:u,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ei={focusedElem:e,selectionRange:n},Hr=!1,j=t;j!==null;)if(t=j,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,j=e;else for(;j!==null;){t=j;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var x=w.memoizedProps,R=w.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?x:Le(t.type,x),R);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var f=t.stateNode.containerInfo;f.nodeType===1?f.textContent="":f.nodeType===9&&f.documentElement&&f.removeChild(f.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(g){W(t,t.return,g)}if(e=t.sibling,e!==null){e.return=t.return,j=e;break}j=t.return}return w=Xo,Xo=!1,w}function On(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Vi(t,n,i)}l=l.next}while(l!==r)}}function gl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Wi(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function lc(e){var t=e.alternate;t!==null&&(e.alternate=null,lc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[$e],delete t[Kn],delete t[Ti],delete t[vf],delete t[yf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ic(e){return e.tag===5||e.tag===3||e.tag===4}function Zo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ic(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Hi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Gr));else if(r!==4&&(e=e.child,e!==null))for(Hi(e,t,n),e=e.sibling;e!==null;)Hi(e,t,n),e=e.sibling}function Qi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Qi(e,t,n),e=e.sibling;e!==null;)Qi(e,t,n),e=e.sibling}var te=null,Re=!1;function qe(e,t,n){for(n=n.child;n!==null;)sc(e,t,n),n=n.sibling}function sc(e,t,n){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(cl,n)}catch{}switch(n.tag){case 5:se||Kt(n,t);case 6:var r=te,l=Re;te=null,qe(e,t,n),te=r,Re=l,te!==null&&(Re?(e=te,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):te.removeChild(n.stateNode));break;case 18:te!==null&&(Re?(e=te,n=n.stateNode,e.nodeType===8?Gl(e.parentNode,n):e.nodeType===1&&Gl(e,n),Bn(e)):Gl(te,n.stateNode));break;case 4:r=te,l=Re,te=n.stateNode.containerInfo,Re=!0,qe(e,t,n),te=r,Re=l;break;case 0:case 11:case 14:case 15:if(!se&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,s=i.destroy;i=i.tag,s!==void 0&&(i&2||i&4)&&Vi(n,t,s),l=l.next}while(l!==r)}qe(e,t,n);break;case 1:if(!se&&(Kt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){W(n,t,u)}qe(e,t,n);break;case 21:qe(e,t,n);break;case 22:n.mode&1?(se=(r=se)||n.memoizedState!==null,qe(e,t,n),se=r):qe(e,t,n);break;default:qe(e,t,n)}}function Jo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Of),t.forEach(function(r){var l=Wf.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function ze(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=s),r&=~i}if(r=l,r=K()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Df(r/1960))-r,10e?16:e,lt===null)var r=!1;else{if(e=lt,lt=null,sl=0,I&6)throw Error(k(331));var l=I;for(I|=4,j=e.current;j!==null;){var i=j,s=i.child;if(j.flags&16){var u=i.deletions;if(u!==null){for(var a=0;aK()-Ms?Nt(e,0):Ds|=n),ve(e,t)}function hc(e,t){t===0&&(e.mode&1?(t=hr,hr<<=1,!(hr&130023424)&&(hr=4194304)):t=1);var n=ae();e=Xe(e,t),e!==null&&(nr(e,t,n),ve(e,n))}function Vf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),hc(e,n)}function Wf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),hc(e,n)}var mc;mc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||he.current)pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pe=!1,zf(e,t,n);pe=!!(e.flags&131072)}else pe=!1,$&&t.flags&1048576&&wa(t,Jr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ir(e,t),e=t.pendingProps;var l=tn(t,oe.current);qt(t,n),l=zs(null,t,r,e,l,n);var i=Ls();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,me(r)?(i=!0,Xr(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ns(t),l.updater=yl,t.stateNode=l,l._reactInternals=t,Fi(t,r,e,n),t=Ui(null,t,r,!0,i,n)):(t.tag=0,$&&i&&gs(t),ue(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ir(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Qf(r),e=Le(r,e),l){case 0:t=Mi(null,t,r,e,n);break e;case 1:t=Ko(null,t,r,e,n);break e;case 11:t=Ho(null,t,r,e,n);break e;case 14:t=Qo(null,t,r,Le(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Mi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ko(e,t,r,l,n);case 3:e:{if(qa(t),e===null)throw Error(k(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Na(e,t),el(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=sn(Error(k(423)),t),t=Go(e,t,r,n,l);break e}else if(r!==l){l=sn(Error(k(424)),t),t=Go(e,t,r,n,l);break e}else for(ge=ut(t.stateNode.containerInfo.firstChild),we=t,$=!0,Oe=null,n=ja(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(nn(),r===l){t=Ze(e,t,n);break e}ue(e,t,r,n)}t=t.child}return t;case 5:return Ea(t),e===null&&Ri(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,s=l.children,_i(r,l)?s=null:i!==null&&_i(r,i)&&(t.flags|=32),Ja(e,t),ue(e,t,s,n),t.child;case 6:return e===null&&Ri(t),null;case 13:return ba(e,t,n);case 4:return Es(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=rn(t,null,r,n):ue(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ho(e,t,r,l,n);case 7:return ue(e,t,t.pendingProps,n),t.child;case 8:return ue(e,t,t.pendingProps.children,n),t.child;case 12:return ue(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,s=l.value,D(qr,r._currentValue),r._currentValue=s,i!==null)if(De(i.value,s)){if(i.children===l.children&&!he.current){t=Ze(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var u=i.dependencies;if(u!==null){s=i.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(i.tag===1){a=Ke(-1,n&-n),a.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var m=c.pending;m===null?a.next=a:(a.next=m.next,m.next=a),c.pending=a}}i.lanes|=n,a=i.alternate,a!==null&&(a.lanes|=n),Oi(i.return,n,t),u.lanes|=n;break}a=a.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(k(341));s.lanes|=n,u=s.alternate,u!==null&&(u.lanes|=n),Oi(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}ue(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,qt(t,n),l=_e(l),r=r(l),t.flags|=1,ue(e,t,r,n),t.child;case 14:return r=t.type,l=Le(r,t.pendingProps),l=Le(r.type,l),Qo(e,t,r,l,n);case 15:return Xa(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ir(e,t),t.tag=1,me(r)?(e=!0,Xr(t)):e=!1,qt(t,n),Ka(t,r,l),Fi(t,r,l,n),Ui(null,t,r,!0,e,n);case 19:return ec(e,t,n);case 22:return Za(e,t,n)}throw Error(k(156,t.tag))};function vc(e,t){return Wu(e,t)}function Hf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ne(e,t,n,r){return new Hf(e,t,n,r)}function Bs(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Qf(e){if(typeof e=="function")return Bs(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ss)return 11;if(e===os)return 14}return 2}function ft(e,t){var n=e.alternate;return n===null?(n=Ne(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Mr(e,t,n,r,l,i){var s=2;if(r=e,typeof e=="function")Bs(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case Mt:return Et(n.children,l,i,t);case is:s=8,l|=8;break;case ii:return e=Ne(12,n,t,l|2),e.elementType=ii,e.lanes=i,e;case si:return e=Ne(13,n,t,l),e.elementType=si,e.lanes=i,e;case oi:return e=Ne(19,n,t,l),e.elementType=oi,e.lanes=i,e;case Eu:return kl(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Cu:s=10;break e;case Nu:s=9;break e;case ss:s=11;break e;case os:s=14;break e;case be:s=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=Ne(s,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function Et(e,t,n,r){return e=Ne(7,e,r,t),e.lanes=n,e}function kl(e,t,n,r){return e=Ne(22,e,r,t),e.elementType=Eu,e.lanes=n,e.stateNode={isHidden:!1},e}function ti(e,t,n){return e=Ne(6,e,null,t),e.lanes=n,e}function ni(e,t,n){return t=Ne(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Kf(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Dl(0),this.expirationTimes=Dl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Dl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Vs(e,t,n,r,l,i,s,u,a){return e=new Kf(e,t,n,u,a),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ne(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ns(i),e}function Gf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(kc)}catch(e){console.error(e)}}kc(),ku.exports=xe;var qf=ku.exports,xc,iu=qf;xc=iu.createRoot,iu.hydrateRoot;const Sc="bv.access",Ks="bv.refresh";function Zi(e){try{return localStorage.getItem(e)||""}catch{return""}}function su(e,t){try{t?localStorage.setItem(e,t):localStorage.removeItem(e)}catch{}}function Nl(){return{access:Zi(Sc),refresh:Zi(Ks)}}function Gs(e,t){su(Sc,e),su(Ks,t)}function sr(){Gs("","")}function bf(){return!!Zi(Ks)}class bn extends Error{constructor(t,n,r){super(r),this.status=t,this.code=n}}let Sn=null;async function Ys(){return Sn||(Sn=(async()=>{const{refresh:e}=Nl();if(!e)throw new bn(401,"unauthorized","Signed out.");const t=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e})});if(!t.ok)throw sr(),new bn(t.status,"unauthorized","Your session has ended. Sign in again.");const n=await t.json();return Gs(n.access_token,n.refresh_token),n})().finally(()=>{Sn=null}),Sn)}async function G(e,t,n,r=!0){const{access:l}=Nl(),i={};l&&(i.Authorization="Bearer "+l),n!==void 0&&(i["Content-Type"]="application/json");const s=await fetch(t,{method:e,headers:i,body:n===void 0?void 0:JSON.stringify(n)});if(s.status===204)return null;const u=await s.text();let a=null;try{a=u?JSON.parse(u):null}catch{}if(s.ok)return a;const c=(a==null?void 0:a.error)||"";if(c==="token_expired"&&r)return await Ys(),G(e,t,n,!1);throw s.status===401&&sr(),new bn(s.status,c,(a==null?void 0:a.message)||`Something went wrong (${s.status}).`)}async function jc(e,t=!0){const{access:n}=Nl(),r=await fetch(e,{headers:n?{Authorization:"Bearer "+n}:{}});if(r.ok)return URL.createObjectURL(await r.blob());let l=null;try{l=await r.json()}catch{}const i=(l==null?void 0:l.error)||"";if(i==="token_expired"&&t)return await Ys(),jc(e,!1);throw r.status===401&&sr(),new bn(r.status,i,(l==null?void 0:l.message)||`That picture could not be loaded (${r.status}).`)}const Ft=e=>{const t=new URLSearchParams;for(const[r,l]of Object.entries(e||{}))l!=null&&l!==""&&t.set(r,l);const n=t.toString();return n?"?"+n:""},J={async login(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:t})}),r=await n.json().catch(()=>null);if(!n.ok)throw new bn(n.status,(r==null?void 0:r.error)||"",(r==null?void 0:r.message)||"Could not sign in.");return Gs(r.access_token,r.refresh_token),r.user},async logout(){try{await G("POST","/api/auth/logout")}catch{}sr()},me:()=>G("GET","/api/auth/me"),sites:()=>G("GET","/api/sites"),arrivals:e=>G("GET","/api/visits"+Ft(e)),visitors:(e,t=50)=>G("GET","/api/visitors"+Ft({q:e,limit:t})),visitorHistory:(e,t=50)=>G("GET",`/api/visitors/${encodeURIComponent(e)}/history`+Ft({limit:t})),saveProfile:(e,t)=>G("PUT",`/api/visitors/${encodeURIComponent(e)}/profile`,t),footfall:e=>G("GET","/api/reports/footfall"+Ft(e)),conversion:e=>G("GET","/api/reports/conversion"+Ft(e)),cameras:()=>G("GET","/api/cameras"),cameraSnapshot:e=>jc(e),createCamera:(e,t)=>G("POST",`/api/sites/${encodeURIComponent(e)}/cameras`,t),updateCamera:(e,t)=>G("PATCH",`/api/cameras/${encodeURIComponent(e)}`,t),deleteCamera:e=>G("DELETE",`/api/cameras/${encodeURIComponent(e)}`),checkCamera:(e,t,n)=>G("POST",`/api/cameras/${encodeURIComponent(e)}/check`,{kind:t,...n?{seconds:n}:{}}),siteCheck:e=>G("GET",`/api/sites/${encodeURIComponent(e)}/check`),enrolmentCode:(e,t)=>G("POST",`/api/sites/${encodeURIComponent(e)}/enrolment-code`,t||{}),ask:e=>G("POST","/api/assistant",{history:e}),clients:()=>G("GET","/api/admin/clients"),createClient:e=>G("POST","/api/admin/clients",e)};function ep({cursor:e,siteId:t,onPage:n,onError:r,signal:l}){let i=!1,s=e||"";return(async()=>{for(;!i;){try{const{access:a}=Nl(),c=await fetch("/api/visits/stream"+Ft({cursor:s,site_id:t}),{headers:{Authorization:"Bearer "+a,Accept:"text/event-stream"},signal:l});if(c.status===401){await Ys();continue}if(!c.ok||!c.body)throw new Error("stream unavailable");const m=c.body.getReader(),y=new TextDecoder;let h="";for(;!i;){const{value:v,done:w}=await m.read();if(w)break;h+=y.decode(v,{stream:!0});let x;for(;(x=h.indexOf(` - -`))!==-1;){const R=h.slice(0,x);h=h.slice(x+2);for(const p of R.split(` -`))if(p.startsWith("id: "))s=p.slice(4).trim();else if(p.startsWith("data: "))try{n(JSON.parse(p.slice(6)))}catch{}}}}catch(a){if(i||l!=null&&l.aborted)return;r==null||r(a)}if(i)return;await new Promise(a=>setTimeout(a,3e3))}})(),()=>{i=!0}}function tp({onSignedIn:e}){const[t,n]=N.useState(""),[r,l]=N.useState(""),[i,s]=N.useState(""),[u,a]=N.useState(!1),c=async m=>{m.preventDefault(),a(!0),s("");try{await J.login(t.trim(),r),e(await J.me())}catch(y){s(y.message),a(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:c,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:"Behavision"}),o.jsx("p",{className:"sub",children:"Sign in to your company account."}),o.jsxs("label",{children:["Email",o.jsx("input",{type:"email",value:t,autoComplete:"username",autoFocus:!0,required:!0,onChange:m=>n(m.target.value),placeholder:"you@company.com"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:r,autoComplete:"current-password",required:!0,onChange:m=>l(m.target.value)})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:u||!t||!r,children:u?"Signing in…":"Sign in"}),o.jsx("p",{className:"foot",children:"Accounts are created by Loyaly. Ask your account manager if you need one."})]})})}function er(e,t,n=[]){const[r,l]=N.useState(null),[i,s]=N.useState(null),[u,a]=N.useState(!0),c=N.useRef(!1),m=N.useRef(!0),y=N.useCallback(async()=>{if(!c.current){c.current=!0;try{const h=await e();if(!m.current)return;l(h),s(null)}catch(h){if(!m.current)return;s(h)}finally{c.current=!1,m.current&&a(!1)}}},n);return N.useEffect(()=>{if(m.current=!0,y(),!t)return()=>{m.current=!1};const h=setInterval(y,t);return()=>{m.current=!1,clearInterval(h)}},[y,t]),{data:r,error:i,loading:u,reload:y}}function np(e){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!e){n(null);return}let r=!0,l=null;return J.cameraSnapshot(e).then(i=>{if(!r){URL.revokeObjectURL(i);return}l=i,n(i)}).catch(()=>{r&&n(null)}),()=>{r=!1,l&&URL.revokeObjectURL(l)}},[e]),t}function Cc({url:e,alt:t}){const n=typeof e=="string"&&e.startsWith("/"),r=np(n?e:null),l=n?r:e;return l?o.jsx("img",{src:l,alt:t,loading:"lazy"}):null}function rp({site:e,onClose:t}){const[n,r]=N.useState(null),[l,i]=N.useState(!1),[s,u]=N.useState(""),a=async()=>{i(!0),u(""),r(null);try{r(await J.siteCheck(e.site_id))}catch(c){u(c.message)}finally{i(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsxs("h2",{children:["Is ",e.name," working?"]}),o.jsx("p",{className:"sub",children:"Checks the whole chain, from the shop’s PC to head office."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[!n&&!l&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Nothing is changed and no one is disturbed — this reads what the shop has already reported."}),o.jsx("button",{className:"primary",onClick:a,children:"Run the check"})]}),l&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsx("b",{children:"Checking…"})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"banner "+(n.ok?"ok":"warn"),children:o.jsxs("div",{children:[o.jsx("b",{children:n.ok?"This shop is working.":"This shop needs attention."}),!n.ok&&o.jsx(o.Fragment,{children:" Work down the list — the first failure usually explains the rest."})]})}),o.jsx("ol",{className:"checklist",children:n.steps.map(c=>o.jsxs("li",{className:c.status,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:c.status==="pass"?"✓":c.status==="fail"?"✕":c.status==="warn"?"!":"–"}),o.jsxs("div",{children:[o.jsx("b",{children:c.name}),o.jsx("span",{className:"sub",children:c.detail}),c.advice&&o.jsx("span",{className:"advice-line",children:c.advice})]})]},c.name))}),o.jsx("button",{className:"ghost",onClick:a,children:"Check again"})]}),o.jsx(lp,{site:e})]})]})})}function lp({site:e}){const[t,n]=N.useState(null),[r,l]=N.useState(!1),[i,s]=N.useState(""),[u,a]=N.useState(""),c=async()=>{l(!0),s("");try{n(await J.enrolmentCode(e.site_id,{label:u.trim()}))}catch(m){s(m.message)}finally{l(!1)}};return o.jsxs("section",{className:"claim",children:[o.jsx("h3",{children:"Set up a shop PC"}),t?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"code","aria-live":"polite",children:t.code}),o.jsxs("p",{className:"sub",children:["Copy this now — it cannot be shown again. It works once, and stops working ",sp(t.expires_at),"."]}),o.jsxs("div",{className:"row",children:[o.jsx("button",{className:"ghost",onClick:()=>ip(t.code),children:"Copy"}),o.jsx("button",{className:"ghost",onClick:()=>n(null),children:"Done"})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Creates a one-time code to type into Behavision on the shop’s computer. Use one for a new shop, a replacement PC, or a reinstall."}),o.jsxs("label",{className:"field",children:[o.jsx("span",{children:"What is this PC? (optional)"}),o.jsx("input",{value:u,placeholder:"counter PC",onChange:m=>a(m.target.value)})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"ghost",onClick:c,disabled:r,children:r?"Creating…":"Create an installation code"})]})]})}function ip(e){var t;try{(t=navigator.clipboard)==null||t.writeText(e)}catch{}}function sp(e){const t=new Date(e).getTime();if(Number.isNaN(t))return"shortly";const n=Math.round((t-Date.now())/864e5);return n<=0?"today":n===1?"tomorrow":`in ${n} days`}function op(){const{data:e,error:t,loading:n}=er(()=>J.sites(),2e4,[]),{data:r}=er(()=>J.cameras(),6e4,[]),[l,i]=N.useState(null),s=e||[];if(n&&!e)return o.jsx(El,{});if(t)return o.jsx(_l,{error:t});if(!s.length)return o.jsx(pp,{});const u=s.map(h=>{const v=(r||[]).filter(w=>w.site_id===h.site_id);return{site:h,cams:v,verdict:up(h,v)}}),a=h=>u.filter(v=>v.verdict.tone===h).length,c=a("bad"),m=a("warn"),y=a("idle");return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Shops"}),o.jsxs("p",{className:"sub",children:[s.length," ",s.length===1?"shop":"shops",c>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[c," not working"]})]}),m>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"warn",children:[m," needing attention"]})]}),y>0&&o.jsxs(o.Fragment,{children:[" · ",y," not set up yet"]}),!c&&!m&&!y&&o.jsxs(o.Fragment,{children:[" · ",o.jsx("b",{className:"ok",children:"all working"})]})]})]}),o.jsx("div",{className:"grid sites",children:u.map(h=>o.jsx(cp,{site:h.site,cams:h.cams,verdict:h.verdict,onCheck:()=>i(h.site)},h.site.site_id))}),l&&o.jsx(rp,{site:l,onClose:()=>i(null)})]})}function up(e,t){const n=e.fraction_below_gate,r=e.cameras_total||t.length;return e.online?e.dropped>0?{tone:"bad",mark:"✕",words:`${e.dropped} visits lost and unrecoverable`}:r===0?{tone:"idle",mark:"+",headline:"Not set up",words:"No cameras set up yet"}:e.cameras_up===0?{tone:"bad",mark:"✕",words:"No cameras connected"}:e.cameras_up.5?{tone:"bad",mark:"✕",words:`${Ji(n)} of faces too poor to recognise`}:n>.2?{tone:"warn",mark:"!",words:`${Ji(n)} of faces too poor to recognise`}:e.queued>0?{tone:"warn",mark:"!",words:`${e.queued} visits waiting to upload`}:{tone:"ok",mark:"✓",words:`Working — ${r} ${r===1?"camera":"cameras"} connected`}:{tone:"bad",mark:"✕",headline:"Offline",words:`Offline — last heard from ${un(e.last_heartbeat_at)}`}}const ap={ok:"Working",warn:"Needs attention",bad:"Not working",idle:"Not set up"};function cp({site:e,cams:t,verdict:n,onCheck:r}){const l=e.fraction_below_gate,i=n.tone,s=n.headline||ap[i],u=dp(t),a=e.cameras_total||t.length;return o.jsxs("article",{className:"card site state-"+i,onClick:r,role:"button",tabIndex:0,onKeyDown:c=>c.key==="Enter"&&r(),children:[o.jsxs("div",{className:"shot",children:[u.url?o.jsx(Cc,{url:u.url,alt:`View inside ${e.name}`}):o.jsxs("div",{className:"noshot",children:[o.jsx(fp,{}),u.reason&&o.jsx("span",{children:u.reason})]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.name}),o.jsx("span",{children:a>0?`${a} ${a===1?"camera":"cameras"}`:"No cameras yet"})]}),o.jsxs("span",{className:"status "+i,children:[o.jsx("i",{"aria-hidden":"true"}),s]})]}),u.at&&o.jsx("span",{className:"shot-age",children:un(u.at)})]}),o.jsxs("div",{className:"metrics",children:[o.jsx(ri,{label:"Cameras",value:a?`${e.cameras_up}/${a}`:"—",tone:a?e.cameras_up0?Ji(1-l):"—",tone:l?l>.5?"bad":l>.2?"warn":"ok":"idle"}),o.jsx(ri,{label:"Last seen",value:un(e.last_heartbeat_at),tone:e.online?"ok":"bad"})]}),o.jsxs("div",{className:"verdict "+n.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:n.mark}),o.jsx("span",{className:"words",children:n.words}),o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}function ri({label:e,value:t,tone:n}){return o.jsxs("div",{className:"metric",children:[o.jsx("b",{className:n,children:t}),o.jsx("span",{children:e})]})}function dp(e){var r;if(!e.length)return{};let t=null;for(const l of e)!((r=l.snapshot)!=null&&r.available)||!l.snapshot.url||(!t||(l.snapshot_at||"")>(t.snapshot_at||""))&&(t=l);return t?{url:t.snapshot.url,at:t.snapshot_at}:{reason:e.map(l=>{var i;return(i=l.snapshot)==null?void 0:i.reason}).find(Boolean)||"No picture from this shop yet."}}function fp(){return o.jsxs("svg",{className:"shopmark",viewBox:"0 0 40 32","aria-hidden":"true",children:[o.jsx("path",{d:"M4 12h32v18H4z"}),o.jsx("path",{d:"M2 12l4-8h28l4 8"}),o.jsx("path",{d:"M15 30v-9h10v9"})]})}function Ji(e){return`${Math.round(e*100)}%`}function un(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=Math.max(0,(Date.now()-t)/1e3);if(n<90)return"just now";const r=Math.round(n/60);if(r<60)return`${r} min ago`;const l=Math.round(r/60);return l<48?`${l} h ago`:`${Math.round(l/24)} days ago`}function El(){return o.jsxs("div",{className:"state",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]})}function _l({error:e}){return o.jsx("div",{className:"state",children:o.jsx("p",{className:"error",role:"alert",children:e.message})})}function pp(){return o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No shops yet"}),o.jsx("p",{className:"sub",children:"A shop appears here once its PC has been claimed with an enrolment code."})]})}const ou=60;function hp(){const[e,t]=N.useState([]),[n,r]=N.useState("connecting"),[l,i]=N.useState(null),s=N.useRef(new Set);return N.useEffect(()=>{const u=new AbortController;let a=()=>{};return(async()=>{try{const c=await J.arrivals({limit:30}),m=c.arrivals||[];m.forEach(y=>s.current.add(y.visit_id)),t(m.slice().reverse()),r("live"),a=ep({cursor:c.cursor,signal:u.signal,onPage:y=>{const h=(y.arrivals||[]).filter(v=>!s.current.has(v.visit_id));h.length&&(h.forEach(v=>s.current.add(v.visit_id)),r("live"),t(v=>[...h.reverse(),...v].slice(0,ou)))},onError:()=>r("reconnecting")})}catch(c){i(c)}})(),()=>{u.abort(),a()}},[]),l?o.jsx(_l,{error:l}):n==="connecting"&&!e.length?o.jsx(El,{}):o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Live"}),o.jsxs("p",{className:"sub",children:[o.jsx("span",{className:"dot "+(n==="live"?"ok":"warn"),"aria-hidden":"true"}),n==="live"?"Connected":"Reconnecting…"," · ","last ",ou," arrivals"]})]}),e.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"Nobody yet"}),o.jsx("p",{className:"sub",children:"Arrivals appear here the moment a camera recognises someone."})]}):o.jsx("ul",{className:"arrivals",children:e.map(u=>o.jsx(mp,{a:u},u.visit_id))})]})}function mp({a:e}){const t=e.name||e.label||"Unidentified";return o.jsxs("li",{className:"card arrival",children:[o.jsx(vp,{image:e.image,name:t}),o.jsxs("div",{className:"who-col",children:[o.jsx("strong",{children:t}),o.jsxs("span",{className:"sub",children:[e.site,e.camera_id?` · ${e.camera_id}`:""," · ",un(e.occurred_at)]}),e.attributes&&o.jsx(gp,{attrs:e.attributes})]}),e.is_new_visitor?o.jsx("span",{className:"pill new",children:"New"}):o.jsx("span",{className:"pill",children:"Returning"})]})}function vp({image:e,name:t}){return e!=null&&e.available?o.jsx("img",{className:"face",src:e.url,alt:"",loading:"lazy"}):o.jsx("span",{className:"face initials",title:(e==null?void 0:e.reason)||"","aria-hidden":"true",children:yp(t)})}function yp(e){const t=String(e).trim().split(/\s+/).filter(Boolean);return t.length?t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[t.length-1][0]).toUpperCase():"?"}function gp({attrs:e}){const t=[];return e.gender&&t.push(e.gender),e.age&&t.push(`~${Math.round(e.age)}`),e.emotion&&t.push(e.emotion),t.length?o.jsx("span",{className:"attrs",children:t.join(" · ")}):null}const Ur=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],uu=e=>Ur.find(t=>t.id===e)||Ur[Ur.length-1],wp=["Camera","Connection","Test","Walk past"];function kp({sites:e,existing:t,onClose:n,onSaved:r}){var d;const l=!(t!=null&&t.id),[i,s]=N.useState(l?0:2),[u,a]=N.useState(t!=null&&t.id?t:null),[c,m]=N.useState({site_id:(t==null?void 0:t.site_id)||((d=e[0])==null?void 0:d.site_id)||"",make:"hikvision",label:(t==null?void 0:t.label)||"",host:(t==null?void 0:t.host)||"",port:(t==null?void 0:t.port)||554,path:(t==null?void 0:t.path)||"/Streaming/Channels/101",username:(t==null?void 0:t.username)||"",password:""}),[y,h]=N.useState(!1),[v,w]=N.useState(""),x=f=>g=>m(S=>({...S,[f]:g.target.value})),R=f=>{const g=uu(f.target.value);m(S=>({...S,make:g.id,path:g.path||S.path}))},p=async()=>{h(!0),w("");const f={};for(const[g,S]of Object.entries(c))g==="site_id"||g==="make"||S===""||S==null||(f[g]=g==="port"?Number(S):S);try{const g=u!=null&&u.id?await J.updateCamera(u.id,f):await J.createCamera(c.site_id,f);a(g),s(2),r==null||r(g,{keepOpen:!0})}catch(g){w(g.message)}finally{h(!1)}};return o.jsx("div",{className:"overlay",onClick:n,children:o.jsxs("aside",{className:"drawer wizard",onClick:f=>f.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:l?"Set up a camera":(u==null?void 0:u.label)||(t==null?void 0:t.label)}),o.jsx("p",{className:"sub",children:i<2?"The shop’s PC connects to the camera — nothing needs opening to the internet.":"Prove it works before you rely on it."})]}),o.jsx("button",{className:"ghost",onClick:n,children:"Close"})]}),o.jsx("ol",{className:"steps",children:wp.map((f,g)=>o.jsxs("li",{className:g===i?"now":go.jsx("option",{value:f.site_id,children:f.name},f.site_id))})]}),o.jsxs("label",{children:["What should staff call it?",o.jsx("input",{value:c.label,onChange:x("label"),placeholder:"Entrance",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Visits are recorded against this name, so it cannot be changed later."})]}),o.jsxs("label",{children:["Make of camera",o.jsx("select",{value:c.make,onChange:R,children:Ur.map(f=>o.jsx("option",{value:f.id,children:f.label},f.id))}),o.jsx("span",{className:"hint",children:uu(c.make).note||"This only fills in the stream path for you. You can change it on the next step."})]}),o.jsx("button",{className:"primary",disabled:!c.label.trim(),onClick:()=>s(1),children:"Next"})]}),i===1&&o.jsxs("div",{className:"drawer-body",children:[o.jsxs("label",{children:["Camera’s address on the shop’s network",o.jsx("input",{value:c.host,onChange:x("host"),placeholder:"192.168.0.138",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Not a website address. It usually starts 192.168. — look in the camera’s own app, on its label, or in your router’s device list."})]}),o.jsxs("div",{className:"pair",children:[o.jsxs("label",{children:["Port",o.jsx("input",{type:"number",value:c.port,onChange:x("port")})]}),o.jsxs("label",{children:["Stream path",o.jsx("input",{value:c.path,onChange:x("path")})]})]}),o.jsxs("label",{children:["Camera username",o.jsx("input",{value:c.username,onChange:x("username"),placeholder:"admin",name:"camera-account",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:"false"}),o.jsx("span",{className:"hint",children:"The camera’s own login, not your Behavision one."})]}),o.jsxs("label",{children:["Camera password",o.jsx("input",{type:"password",value:c.password,onChange:x("password"),name:"camera-secret",autoComplete:"new-password",placeholder:u!=null&&u.has_password?"(unchanged)":""})]}),v&&o.jsx("p",{className:"error",role:"alert",children:v}),o.jsxs("div",{className:"pair",children:[o.jsx("button",{className:"ghost",onClick:()=>s(0),children:"Back"}),o.jsx("button",{className:"primary",disabled:y||!c.host.trim(),onClick:p,children:y?"Saving…":"Save and test"})]})]}),i>=2&&u&&o.jsx(xp,{camera:u,step:i,onStep:s,onUpdated:f=>{a(f),r==null||r(f,{keepOpen:!0})},onEdit:()=>s(1),onDone:n})]})})}function xp({camera:e,step:t,onStep:n,onUpdated:r,onEdit:l,onDone:i}){const[s,u]=N.useState(e),[a,c]=N.useState(!1),[m,y]=N.useState(""),h=N.useRef(null);N.useEffect(()=>u(e),[e]);const v=s.check||{},w=v.state==="requested"||v.state==="running";N.useEffect(()=>{if(!w)return;let p=!0;const d=async()=>{try{const g=(await J.cameras()).find(S=>S.id===s.id);p&&g&&(u(g),r==null||r(g))}catch{}};return h.current=setInterval(d,4e3),()=>{p=!1,clearInterval(h.current)}},[w,s.id]);const x=async(p,d)=>{c(!0),y("");try{const f=await J.checkCamera(s.id,p,d);u(f),r==null||r(f),n(p==="placement"?3:2)}catch(f){y(f.message)}finally{c(!1)}},R=v.kind==="connection"&&v.state==="done"&&v.ok;return o.jsx(o.Fragment,{children:o.jsxs("div",{className:"drawer-body",children:[t===2?o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can the shop’s PC reach this camera?"}),o.jsx("p",{className:"sub",children:"The PC opens the stream once and takes a single picture. Nothing is recorded."})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can it actually recognise a face?"}),o.jsxs("p",{className:"sub",children:["Someone needs to ",o.jsx("b",{children:"walk through the camera’s view and out of it"}),", the way a customer would. Standing still measures nothing — the check scores the best view of each person as they leave the frame, which is what recognition really uses."]})]}),w&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("b",{children:v.state==="running"?"Running on the shop’s PC…":"Waiting for the shop’s PC…"}),o.jsx("span",{className:"sub",children:v.state==="running"?"This takes about "+(v.seconds||25)+" seconds.":"It picks up the request within a couple of minutes."})]})]}),v.state==="done"&&o.jsx(Sp,{check:v}),m&&o.jsx("p",{className:"error",role:"alert",children:m}),o.jsx("div",{className:"pair",children:t===2?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:l,children:"Change details"}),o.jsx("button",{className:"primary",disabled:a||w,onClick:()=>x("connection"),children:v.state==="done"?"Test again":"Test connection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:()=>n(2),children:"Back"}),o.jsx("button",{className:"primary",disabled:a||w,onClick:()=>x("placement",25),children:v.state==="done"?"Check again":"Start walk-past check"})]})}),t===2&&R&&!w&&o.jsx("button",{className:"primary",onClick:()=>n(3),children:"Next: prove it can recognise faces"}),t===3&&v.state==="done"&&!w&&o.jsx("button",{className:"ghost",onClick:i,children:"Finish"})]})})}function Sp({check:e}){var n,r,l;const t=e.ok?"ok":e.verdict==="marginal"?"warn":"bad";return o.jsxs("div",{className:"outcome "+t,children:[o.jsxs("div",{className:"outcome-head",children:[o.jsx("span",{className:"pill "+t,children:e.ok?"Working":"Not ready"}),o.jsx("b",{children:e.headline||(e.ok?"Working":"Could not be verified")})]}),((n=e.image)==null?void 0:n.available)&&o.jsx("img",{className:"proof",src:e.image.url,alt:"The view from this camera",loading:"lazy"}),((r=e.advice)==null?void 0:r.length)>0&&o.jsx("ul",{className:"advice",children:e.advice.map((i,s)=>o.jsx("li",{children:i},s))}),((l=e.detail)==null?void 0:l.faces)!=null&&o.jsxs("p",{className:"sub",children:[e.detail.faces," ",e.detail.faces===1?"person":"people"," walked past during the check."]})]})}function jp(e){const t=e.check||{};return t.state==="requested"||t.state==="running"?{tone:"idle",mark:"…",words:"Checking now"}:t.state!=="done"?{tone:"idle",mark:"?",words:"Not checked yet"}:t.kind==="placement"?t.ok?{tone:"ok",mark:"✓",words:"Recognises faces here"}:{tone:"bad",mark:"✕",words:t.headline||"Cannot recognise faces here"}:t.ok?{tone:"warn",mark:"!",words:"Stream works — faces not checked yet"}:{tone:"bad",mark:"✕",words:t.headline||"Could not reach the camera"}}function Cp({user:e}){const{data:t,error:n,loading:r,reload:l}=er(()=>J.cameras(),2e4,[]),{data:i}=er(()=>J.sites(),0,[]),[s,u]=N.useState(null),a=["admin","owner","manager"].includes(e.role),c=t||[],m=c.filter(v=>v.connected).length,y=c.filter(v=>v.connected===!1).length,h=c.filter(v=>v.connected==null).length;return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Cameras"}),o.jsxs("p",{className:"sub",children:[c.length," ",c.length===1?"camera":"cameras",m>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"ok",children:[m," connected"]})]}),y>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[y," down"]})]}),h>0&&o.jsxs(o.Fragment,{children:[" · ",h," waiting for the shop PC"]})]}),a&&o.jsx("button",{className:"primary",onClick:()=>u({}),children:"Set up a camera"})]}),r&&!t?o.jsx(El,{}):n?o.jsx(_l,{error:n}):c.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No cameras yet"}),o.jsx("p",{className:"sub",children:"Add one here and the shop’s PC will pick it up within a couple of minutes. Cameras already set up on a shop PC appear here on their own."})]}):o.jsx("div",{className:"grid cams",children:c.map(v=>o.jsx(Np,{cam:v,canEdit:a,onEdit:()=>u(v)},v.id))}),s&&o.jsx(kp,{existing:s.id?s:null,sites:i||[],onClose:()=>{u(null),l()},onSaved:(v,w)=>{w!=null&&w.keepOpen||u(null),l()}})]})}function Np({cam:e,canEdit:t,onEdit:n}){var s,u;const r=e.connected==null?"idle":e.connected?"ok":"bad",l=e.connected==null?"Waiting for the shop PC":e.connected?"Connected":"Not connecting",i=jp(e);return o.jsxs("article",{className:"card cam state-"+r,onClick:t?n:void 0,role:t?"button":void 0,tabIndex:t?0:void 0,onKeyDown:a=>t&&a.key==="Enter"&&n(),children:[o.jsxs("div",{className:"shot",children:[(s=e.snapshot)!=null&&s.available?o.jsx(Cc,{url:e.snapshot.url,alt:`View from ${e.label}`}):o.jsxs("div",{className:"noshot",children:[o.jsx("span",{className:"lens","aria-hidden":"true"}),((u=e.snapshot)==null?void 0:u.reason)||"No picture yet."]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.label||e.camera_id}),o.jsx("span",{children:e.site})]}),o.jsxs("span",{className:"status "+r,children:[o.jsx("i",{"aria-hidden":"true"}),l]})]}),e.snapshot_at&&o.jsx("span",{className:"shot-age",children:un(e.snapshot_at)})]}),o.jsxs("div",{className:"verdict "+i.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:i.mark}),o.jsx("span",{className:"words",children:i.words}),t&&o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}const Ep=["Is everything working today?","Why is footfall low at Chennai?","How many people came in last week?","Which cameras still need checking?"];function _p({open:e,onClose:t}){const[n,r]=N.useState([]),[l,i]=N.useState(""),[s,u]=N.useState(!1),[a,c]=N.useState(!1),m=N.useRef(null),y=N.useRef(null);N.useEffect(()=>{var v;e&&((v=y.current)==null||v.focus())},[e]),N.useEffect(()=>{var v;(v=m.current)==null||v.scrollIntoView({behavior:"smooth",block:"end"})},[n,s]);const h=async v=>{const w=(v??l).trim();if(!w||s)return;const x=[...n,{role:"user",text:w}];r(x),i(""),u(!0);try{const R=await J.ask(x);r(p=>[...p,{role:"assistant",text:R.text,used:R.used}])}catch(R){R.code==="assistant_off"?c(!0):r(p=>[...p,{role:"assistant",text:R.message,failed:!0}])}finally{u(!1)}};return e?o.jsxs("aside",{className:"assistant",role:"complementary","aria-label":"Assistant",children:[o.jsxs("header",{className:"assistant-head",children:[o.jsxs("div",{children:[o.jsx("b",{children:"Ask Behavision"}),o.jsx("span",{className:"sub",children:"It reads your shops’ own data to answer."})]}),o.jsx("button",{className:"ghost",onClick:t,"aria-label":"Close assistant",children:"✕"})]}),o.jsxs("div",{className:"assistant-body",children:[a?o.jsx("p",{className:"sub pad",children:"The assistant is not switched on for this server."}):n.length===0?o.jsxs("div",{className:"suggest",children:[o.jsx("p",{className:"sub",children:"Try asking:"}),Ep.map(v=>o.jsx("button",{className:"chip",onClick:()=>h(v),children:v},v))]}):n.map((v,w)=>{var x;return o.jsxs("div",{className:"bubble "+v.role+(v.failed?" failed":""),children:[v.text,((x=v.used)==null?void 0:x.length)>0&&o.jsxs("span",{className:"used",children:["looked at: ",v.used.map(Pp).join(", ")]})]},w)}),s&&o.jsxs("div",{className:"bubble assistant-thinking",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"})," Looking…"]}),o.jsx("div",{ref:m})]}),!a&&o.jsxs("form",{className:"assistant-ask",onSubmit:v=>{v.preventDefault(),h()},children:[o.jsx("input",{ref:y,value:l,onChange:v=>i(v.target.value),placeholder:"Ask about your shops…",disabled:s}),o.jsx("button",{className:"primary",disabled:s||!l.trim(),children:"Ask"})]})]}):null}function Pp(e){return{list_shops:"your shops",check_shop:"a shop check",list_cameras:"your cameras",check_camera:"a camera check",footfall:"footfall",sales:"sales",find_customer:"customer records"}[e]||e}function Tp(){const{data:e,error:t,loading:n,reload:r}=er(()=>J.clients(),0,[]),[l,i]=N.useState(!1),[s,u]=N.useState(null),a=e||[];return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Companies"}),o.jsx("button",{className:"primary",onClick:()=>{u(null),i(!0)},children:"New company"})]}),s&&o.jsx(Lp,{result:s,onDismiss:()=>u(null)}),n&&!e?o.jsx(El,{}):t?o.jsx(_l,{error:t}):a.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No companies yet"}),o.jsx("p",{className:"sub",children:"Create one, and its owner can sign in straight away."})]}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Company"}),o.jsx("th",{children:"Short name"}),o.jsx("th",{children:"Sites"}),o.jsx("th",{children:"People"}),o.jsx("th",{children:"Created"})]})}),o.jsx("tbody",{children:a.map(c=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:c.name})}),o.jsx("td",{children:o.jsx("code",{children:c.slug})}),o.jsx("td",{className:"num",children:c.sites}),o.jsx("td",{className:"num",children:c.users}),o.jsx("td",{className:"sub",children:un(c.created_at)})]},c.id))})]})}),l&&o.jsx(zp,{onClose:()=>i(!1),onCreated:c=>{i(!1),u(c),r()}})]})}function zp({onClose:e,onCreated:t}){const[n,r]=N.useState({company_name:"",owner_name:"",owner_email:"",password:""}),[l,i]=N.useState(!1),[s,u]=N.useState(""),a=m=>y=>r({...n,[m]:y.target.value}),c=async m=>{m.preventDefault(),i(!0),u("");try{t(await J.createClient(n))}catch(y){u(y.message),i(!1)}};return o.jsx("div",{className:"overlay",onClick:e,children:o.jsxs("aside",{className:"drawer narrow",onClick:m=>m.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"New company"}),o.jsx("button",{className:"ghost",onClick:e,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:c,children:[o.jsxs("label",{children:["Company name",o.jsx("input",{value:n.company_name,onChange:a("company_name"),required:!0,autoFocus:!0})]}),o.jsxs("label",{children:["Owner’s name",o.jsx("input",{value:n.owner_name,onChange:a("owner_name")})]}),o.jsxs("label",{children:["Owner’s email",o.jsx("input",{type:"email",value:n.owner_email,onChange:a("owner_email"),required:!0})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"text",value:n.password,onChange:a("password"),placeholder:"Leave empty to generate one"}),o.jsx("span",{className:"hint",children:"Generated is better — a password you invent for someone else ends up weak and sent over chat."})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),o.jsx("button",{className:"primary",disabled:l,children:l?"Creating…":"Create company"})]})]})})}function Lp({result:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:[e.slug," created."]})," These sign-in details are shown once and cannot be recovered. Send them to the owner now.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Email"}),o.jsx("dd",{children:o.jsx("code",{children:e.owner_email})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Password"}),o.jsx("dd",{children:o.jsx("code",{children:e.password})})]})]})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}const Rp=[{id:"sites",label:"Shops",View:op},{id:"live",label:"Live",View:hp},{id:"cameras",label:"Cameras",View:Cp}],Op=[{id:"clients",label:"Companies",View:Tp}];function Ip(){const[e,t]=N.useState(null),[n,r]=N.useState(!0),[l,i]=N.useState("sites"),[s,u]=N.useState(!1);if(N.useEffect(()=>{(async()=>{if(bf())try{t(await J.me())}catch{sr()}r(!1)})()},[]),n)return o.jsxs("div",{className:"boot",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]});if(!e)return o.jsx(tp,{onSignedIn:t});const a=e.role==="admin"&&!e.client_id,c=a?Op:Rp,m=c.find(v=>v.id===l)||c[0],y=m.View,h=async()=>{await J.logout(),t(null)};return o.jsxs("div",{className:"app",children:[o.jsxs("header",{className:"topbar",children:[o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"mark","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("strong",{children:"Behavision"}),o.jsx("span",{className:"org",children:e.client_name||"Loyaly platform"})]})]}),o.jsx("nav",{className:"tabs",children:c.map(v=>o.jsx("button",{onClick:()=>i(v.id),"aria-current":m.id===v.id?"page":void 0,children:v.label},v.id))}),o.jsxs("div",{className:"who",children:[o.jsxs("button",{className:"ask-btn"+(s?" on":""),onClick:()=>u(v=>!v),children:[o.jsx("span",{"aria-hidden":"true",children:"✳"})," Ask"]}),o.jsx("span",{className:"name",children:e.full_name||e.email}),o.jsx("span",{className:"role",children:a?"platform admin":e.role}),o.jsx("button",{className:"ghost",onClick:h,children:"Sign out"})]})]}),o.jsxs("div",{className:"with-assistant"+(s?" open":""),children:[o.jsx("main",{className:"page",children:o.jsx(y,{user:e})}),o.jsx(_p,{open:s,onClose:()=>u(!1)})]})]})}xc(document.getElementById("root")).render(o.jsx(Ip,{})); diff --git a/server/internal/web/dist/assets/index-pUqVBCLm.css b/server/internal/web/dist/assets/index-CtuyPF09.css similarity index 95% rename from server/internal/web/dist/assets/index-pUqVBCLm.css rename to server/internal/web/dist/assets/index-CtuyPF09.css index a523642..865d5cd 100644 --- a/server/internal/web/dist/assets/index-pUqVBCLm.css +++ b/server/internal/web/dist/assets/index-CtuyPF09.css @@ -1 +1 @@ -:root{--ground: #0E1317;--surface: #161D23;--surface-2: #1D262D;--line: #27333B;--line-soft: #1F2A31;--ink: #E7EEF3;--ink-2: #B4C2CC;--muted: #7C8B97;--accent: #45B0C7;--accent-dim:#123039;--ok: #4FB37B;--ok-dim: #12291F;--warn: #E0A33A;--warn-dim: #2C2313;--bad: #E0655A;--bad-dim: #2B1917;--radius: 10px;--mono: "SFMono-Regular", ui-monospace, Menlo, Consolas, monospace}*{box-sizing:border-box;margin:0}html{color-scheme:dark}body{background:var(--ground);color:var(--ink);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased}button,input,select,textarea{font:inherit;color:inherit}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}code{font-family:var(--mono);font-size:.9em}h1{font-size:22px;font-weight:620;letter-spacing:-.015em}h2{font-size:16px;font-weight:600}h3{font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.sub{color:var(--muted);font-size:13.5px}.num{font-variant-numeric:tabular-nums}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.app{min-height:100vh;display:flex;flex-direction:column}.topbar{position:sticky;top:0;z-index:20;display:flex;align-items:center;gap:28px;padding:0 24px;height:60px;background:var(--surface);border-bottom:1px solid var(--line)}.brand{display:flex;align-items:center;gap:11px}.brand strong{display:block;font-size:15px;font-weight:620;letter-spacing:-.01em}.brand .org{display:block;font-size:12px;color:var(--muted)}.mark{width:18px;height:18px;border-radius:50%;border:2.5px solid var(--accent);box-shadow:inset 0 0 0 3px var(--ground);flex:none}.mark.big{width:30px;height:30px;border-width:3px;margin-bottom:14px}.tabs{display:flex;gap:2px;margin-right:auto}.tabs button{background:none;border:0;border-radius:7px;padding:7px 13px;color:var(--ink-2);cursor:pointer;font-size:14px}.tabs button:hover{background:var(--surface-2);color:var(--ink)}.tabs button[aria-current=page]{background:var(--accent-dim);color:var(--accent);font-weight:550}.who{display:flex;align-items:center;gap:12px}.who .name{font-size:13.5px}.who .role{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.page{flex:1;padding:26px 24px 64px;max-width:1280px;width:100%;margin:0 auto;display:flex;flex-direction:column;gap:20px}.head{display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap}.head h1{margin-right:auto}.head .sub{padding-bottom:2px}button.primary{background:var(--accent);color:#04161b;border:0;border-radius:7px;padding:9px 16px;font-weight:600;cursor:pointer}button.primary:disabled{opacity:.5;cursor:default}button.ghost{background:none;border:1px solid var(--line);border-radius:7px;padding:7px 13px;color:var(--ink-2);cursor:pointer}button.ghost:hover{border-color:var(--muted);color:var(--ink)}.segmented{display:flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}.segmented button{background:none;border:0;padding:7px 14px;color:var(--ink-2);cursor:pointer;font-size:13.5px}.segmented button+button{border-left:1px solid var(--line)}.segmented button[aria-current]{background:var(--accent-dim);color:var(--accent)}.card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius)}.grid{display:grid;gap:14px}.grid.sites{grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:16px}.grid.stats{grid-template-columns:repeat(auto-fit,minmax(190px,1fr))}.card.site{overflow:hidden;padding:0;cursor:pointer;border-left:3px solid var(--line);transition:border-color .15s ease,transform .15s ease}.card.site.state-ok{border-left-color:var(--ok)}.card.site.state-warn{border-left-color:var(--warn)}.card.site.state-bad{border-left-color:var(--bad)}.card.site.state-idle{border-left-color:var(--muted)}.card.site:hover{transform:translateY(-1px)}.card.site:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media (prefers-reduced-motion: reduce){.card.site{transition:none}}.metrics{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--line-soft)}.metric{padding:11px 6px;text-align:center}.metric+.metric{border-left:1px solid var(--line-soft)}.metric b{display:block;font-size:15px;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.01em}.metric b.ok{color:var(--ink)}.metric b.warn{color:var(--warn)}.metric b.bad{color:var(--bad)}.metric b.idle{color:var(--muted)}.metric span{display:block;margin-top:1px;font-size:11px;color:var(--muted)}.shopmark{width:38px;height:30px;fill:none;stroke:var(--line);stroke-width:2;stroke-linejoin:round}.pill{display:inline-block;padding:3px 9px;border-radius:20px;flex:none;font-size:11.5px;font-weight:550;letter-spacing:.01em;background:var(--surface-2);color:var(--ink-2)}.pill.ok{background:var(--ok-dim);color:var(--ok)}.pill.warn{background:var(--warn-dim);color:var(--warn)}.pill.bad{background:var(--bad-dim);color:var(--bad)}.pill.new{background:var(--accent-dim);color:var(--accent)}.dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--muted);margin-right:7px;vertical-align:1px}.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn)}.card.stat{padding:16px 18px;display:flex;flex-direction:column;gap:3px}.stat .value{font-size:30px;font-weight:620;letter-spacing:-.02em;font-variant-numeric:tabular-nums;line-height:1.15}.stat .label{font-size:13.5px;color:var(--ink-2)}.stat .note{font-size:12.5px;color:var(--muted);margin-top:3px}.banner{padding:12px 16px;border-radius:var(--radius);font-size:14px;display:flex;gap:16px;align-items:flex-start}.banner.warn{background:var(--warn-dim);border:1px solid #4A3A18;color:#f0d9a6}.banner.ok{background:var(--ok-dim);border:1px solid #1E4534;color:#c6e9d6}.banner>div{flex:1}.creds{display:flex;gap:26px;margin-top:10px;flex-wrap:wrap}.creds dt{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.creds dd{font-family:var(--mono);font-size:14px;-webkit-user-select:all;user-select:all}.arrivals{list-style:none;padding:0;display:grid;gap:8px}.card.arrival{display:flex;align-items:center;gap:14px;padding:11px 14px}.face{width:46px;height:46px;border-radius:50%;flex:none;object-fit:cover;background:var(--surface-2)}.face.initials{display:grid;place-items:center;color:var(--muted);font-size:15px;font-weight:600;letter-spacing:.02em}.who-col{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.who-col strong{font-weight:570}.attrs{font-size:12.5px;color:var(--muted);text-transform:capitalize}.toolbar{display:flex;gap:10px}.search{flex:1;max-width:380px;background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:9px 13px}.search::placeholder{color:var(--muted)}input::placeholder,textarea::placeholder{color:var(--muted);opacity:1}.tablewrap{overflow-x:auto;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius)}table.rows{border-collapse:collapse;width:100%;min-width:620px}table.rows th,table.rows td{text-align:left;padding:11px 16px;border-bottom:1px solid var(--line-soft)}table.rows tr:last-child td{border-bottom:0}table.rows th{font-size:11.5px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);font-weight:600;background:var(--surface-2)}table.rows tbody tr{cursor:pointer}table.rows tbody tr:hover{background:var(--surface-2)}table.rows td.num{font-variant-numeric:tabular-nums}.chart-card{padding:18px}.chart-head{margin-bottom:16px}.peak{font-size:12.5px;color:var(--muted);margin-bottom:8px}.peak b{color:var(--ink-2);font-weight:600;font-variant-numeric:tabular-nums}.chart{display:flex;align-items:flex-end;gap:3px;height:190px;overflow-x:auto;padding-bottom:4px}.col{flex:1;min-width:16px;display:flex;flex-direction:column;align-items:center;gap:6px;height:100%}.bars{flex:1;width:100%;display:flex;flex-direction:column;justify-content:flex-end}.bar{display:block;width:100%;border-radius:2px 2px 0 0}.bar.new{background:var(--accent)}.bar.returning{background:var(--accent-dim);border-radius:0}.col:hover .bar.returning{background:#1b4552}.tick{font-size:10.5px;color:var(--muted);white-space:nowrap;font-variant-numeric:tabular-nums}.legend{display:flex;gap:18px;align-items:center;margin-top:14px;padding-top:12px;border-top:1px solid var(--line-soft);font-size:12.5px;color:var(--ink-2)}.legend span{display:flex;align-items:center;gap:7px}.swatch{width:10px;height:10px;border-radius:2px;display:inline-block}.swatch.new{background:var(--accent)}.swatch.returning{background:var(--accent-dim)}.pad{padding:24px 0}.overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#04080a9e;display:flex;justify-content:flex-end;z-index:50}.drawer{width:min(560px,100%);background:var(--surface);border-left:1px solid var(--line);height:100%;overflow-y:auto;display:flex;flex-direction:column}.drawer.narrow{width:min(440px,100%)}.drawer-head{position:sticky;top:0;z-index:1;display:flex;align-items:flex-start;gap:16px;padding:18px 22px;background:var(--surface);border-bottom:1px solid var(--line)}.drawer-head h2{margin-right:auto}.drawer-head>div{flex:1}.drawer-body{padding:20px 22px;display:flex;flex-direction:column;gap:14px}.drawer-body+.drawer-body{border-top:1px solid var(--line-soft)}fieldset{border:0;padding:0;margin:0;display:flex;flex-direction:column;gap:14px}fieldset:disabled{opacity:.6}label{display:flex;flex-direction:column;gap:6px;font-size:13px;color:var(--ink-2)}label input[type=text],label input[type=email],label input[type=password],label input:not([type]),.drawer input{background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px;color:var(--ink);font-size:14.5px}label .hint{font-size:12px;color:var(--muted);line-height:1.45}label.check{flex-direction:row;align-items:center;gap:9px}label.check input{width:auto}.timeline{list-style:none;padding:0;display:grid;gap:8px}.timeline li{display:flex;align-items:center;gap:12px;font-size:13.5px;padding:9px 12px;background:var(--ground);border-radius:7px}.timeline .when{font-variant-numeric:tabular-nums}.timeline .where{color:var(--muted);margin-right:auto}.state{display:flex;flex-direction:column;align-items:center;gap:8px;padding:64px 20px;text-align:center;color:var(--ink-2)}.state .sub{max-width:46ch}.boot{min-height:100vh;display:flex;align-items:center;justify-content:center;gap:10px;color:var(--muted)}.error{color:var(--bad);font-size:13.5px}.spinner{width:14px;height:14px;border-radius:50%;border:2px solid var(--line);border-top-color:var(--accent);animation:spin .7s linear infinite;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion: reduce){.spinner{animation:none}}.signin{min-height:100vh;display:grid;place-items:center;padding:24px}.signin .card{width:min(380px,100%);padding:30px;display:flex;flex-direction:column;gap:14px}.signin h1{font-size:20px}.signin .sub{margin-top:-8px;margin-bottom:6px}.signin .foot{font-size:12.5px;color:var(--muted);text-align:center;margin-top:4px;line-height:1.5}@media (max-width: 720px){.topbar{height:auto;flex-wrap:wrap;padding:12px 16px;gap:12px}.tabs{order:3;width:100%;overflow-x:auto}.page{padding:18px 16px 48px}.who .name{display:none}}.pair{display:grid;grid-template-columns:1fr 1fr;gap:14px}select{background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px;color:var(--ink);font-size:14.5px}button.ghost.danger{border-color:#4a211d;color:var(--bad)}button.ghost.danger:hover{border-color:var(--bad)}.drawer.wizard{width:min(560px,100%)}.steps{list-style:none;display:flex;gap:4px;padding:14px 22px;margin:0;border-bottom:1px solid var(--line-soft);background:var(--surface);position:sticky;top:62px;z-index:1}.steps li{flex:1;display:flex;align-items:center;gap:7px;font-size:12.5px;color:var(--muted);min-width:0}.steps li .dot{width:20px;height:20px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:11px;background:var(--surface-2);color:var(--muted)}.steps li.now{color:var(--ink);font-weight:550}.steps li.now .dot{background:var(--accent);color:#04161b}.steps li.done .dot{background:var(--ok-dim);color:var(--ok)}.waiting{display:flex;gap:12px;align-items:center;padding:14px 16px;background:var(--ground);border:1px solid var(--line);border-radius:var(--radius)}.waiting>div{display:flex;flex-direction:column;gap:2px}.outcome{border:1px solid var(--line);border-left-width:3px;border-radius:var(--radius);padding:14px 16px;display:flex;flex-direction:column;gap:12px}.outcome.ok{border-left-color:var(--ok);background:var(--ok-dim)}.outcome.warn{border-left-color:var(--warn);background:var(--warn-dim)}.outcome.bad{border-left-color:var(--bad);background:var(--bad-dim)}.outcome-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.outcome-head b{font-size:14.5px}.proof{width:100%;border-radius:6px;display:block;background:#05090b}.advice{margin:0;padding-left:18px;display:grid;gap:6px;font-size:13.5px;color:var(--ink-2);line-height:1.5}.verified{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:13px}.verified .mark{width:17px;height:17px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:10.5px}.verified.ok{color:var(--ok)}.verified.ok .mark{background:var(--ok-dim)}.verified.warn{color:var(--warn)}.verified.warn .mark{background:var(--warn-dim)}.verified.bad{color:var(--bad)}.verified.bad .mark{background:var(--bad-dim)}.verified.idle{color:var(--muted)}.verified.idle .mark{background:var(--surface-2)}.checklist{list-style:none;padding:0;margin:0;display:grid;gap:2px}.checklist li{display:flex;gap:12px;padding:13px 14px;background:var(--ground);border-radius:8px;border-left:3px solid var(--line)}.checklist li>div{display:flex;flex-direction:column;gap:3px;flex:1}.checklist li.pass{border-left-color:var(--ok)}.checklist li.warn{border-left-color:var(--warn)}.checklist li.fail{border-left-color:var(--bad)}.checklist li.unknown{border-left-color:var(--muted)}.checklist .mark{width:20px;height:20px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:11px;background:var(--surface-2);color:var(--muted)}.checklist li.pass .mark{background:var(--ok-dim);color:var(--ok)}.checklist li.warn .mark{background:var(--warn-dim);color:var(--warn)}.checklist li.fail .mark{background:var(--bad-dim);color:var(--bad)}.advice-line{font-size:13px;color:var(--warn);line-height:1.45}.checklist li.pass .advice-line{color:var(--muted)}.grid.cams{grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:16px}.card.cam{overflow:hidden;border-left:0;padding:0;cursor:pointer;transition:border-color .15s ease,transform .15s ease}.card.cam:hover{border-color:var(--muted);transform:translateY(-1px)}.card.cam:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media (prefers-reduced-motion: reduce){.card.cam{transition:none}}.shot{position:relative;aspect-ratio:16 / 10;background:#05090b;display:grid;place-items:center}.shot img{width:100%;height:100%;object-fit:cover;display:block}.noshot{display:flex;flex-direction:column;align-items:center;gap:10px;color:var(--muted);font-size:12.5px;text-align:center;padding:0 28px;line-height:1.5}.lens{width:34px;height:34px;border-radius:50%;border:2px solid var(--line);position:relative}.lens:after{content:"";position:absolute;top:7px;right:7px;bottom:7px;left:7px;border-radius:50%;border:2px solid var(--line-soft)}.shot-over{position:absolute;inset:auto 0 0 0;display:flex;align-items:flex-end;justify-content:space-between;gap:10px;padding:26px 14px 12px;background:linear-gradient(transparent,#04080ad9)}.shot-name b{display:block;font-size:14.5px;font-weight:600;letter-spacing:-.01em}.shot-name span{display:block;font-size:11.5px;color:#9fb0ba;margin-top:1px}.status{display:flex;align-items:center;gap:6px;flex:none;font-size:11px;font-weight:550;letter-spacing:.01em;padding:4px 9px;border-radius:20px;white-space:nowrap;background:#0e1317b8;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);color:var(--ink-2)}.status i{width:6px;height:6px;border-radius:50%;background:var(--muted)}.status.ok{color:#8fe0b4}.status.ok i{background:var(--ok)}.status.warn{color:#efc77c}.status.warn i{background:var(--warn)}.status.bad{color:#f0a79e}.status.bad i{background:var(--bad)}.status.idle i{background:var(--muted)}.shot-age{position:absolute;top:10px;right:12px;font-size:10.5px;color:#9fb0ba;background:#04080a99;padding:2px 7px;border-radius:20px;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.verdict{display:flex;align-items:center;gap:10px;padding:12px 14px;font-size:13px;border-top:1px solid var(--line-soft)}.verdict .words{flex:1;min-width:0}.verdict .go{color:var(--muted);font-size:14px}.verdict .mark{width:18px;height:18px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:10.5px}.verdict.ok{color:var(--ok)}.verdict.ok .mark{background:var(--ok-dim)}.verdict.warn{color:var(--warn)}.verdict.warn .mark{background:var(--warn-dim)}.verdict.bad{color:var(--bad)}.verdict.bad .mark{background:var(--bad-dim)}.verdict.idle{color:var(--muted)}.verdict.idle .mark{background:var(--surface-2)}.claim{margin-top:22px;padding-top:18px;border-top:1px solid var(--line-soft)}.claim h3{font-size:14px;font-weight:600;margin-bottom:6px}.claim .field{display:block;margin:12px 0}.claim .field span{display:block;font-size:12.5px;color:var(--muted);margin-bottom:5px}.claim .field input{width:100%;background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px}.claim .row{display:flex;gap:8px;margin-top:12px}.claim .code{font-family:var(--mono);font-size:19px;letter-spacing:.08em;background:var(--ground);border:1px solid var(--line);border-radius:8px;padding:14px 12px;text-align:center;margin:12px 0 10px;-webkit-user-select:all;user-select:all;word-break:break-all}.with-assistant{display:flex;flex:1;min-height:0}.with-assistant .page{flex:1;min-width:0}.ask-btn{background:var(--accent-dim);color:var(--accent);border:0;border-radius:7px;padding:7px 13px;cursor:pointer;font-size:13.5px;font-weight:550;display:flex;align-items:center;gap:7px}.ask-btn:hover,.ask-btn.on{background:var(--accent);color:#04161b}.assistant{width:360px;flex:none;border-left:1px solid var(--line);background:var(--surface);display:flex;flex-direction:column;position:sticky;top:60px;height:calc(100vh - 60px)}.assistant-head{display:flex;align-items:flex-start;gap:12px;padding:15px 16px;border-bottom:1px solid var(--line-soft)}.assistant-head>div{flex:1;display:flex;flex-direction:column;gap:2px}.assistant-body{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}.assistant-ask{display:flex;gap:8px;padding:12px 14px;border-top:1px solid var(--line-soft)}.assistant-ask input{flex:1;min-width:0;background:var(--ground);border:1px solid var(--line);border-radius:8px;padding:9px 12px}.bubble{padding:11px 13px;border-radius:12px;font-size:14px;line-height:1.55;white-space:pre-wrap;max-width:100%}.bubble.user{background:var(--accent-dim);color:var(--ink);align-self:flex-end;border-bottom-right-radius:4px}.bubble.assistant{background:var(--ground);border:1px solid var(--line-soft);border-bottom-left-radius:4px}.bubble.failed{border-color:#4a211d;color:var(--bad)}.bubble.assistant-thinking{color:var(--muted);display:flex;align-items:center;gap:9px}.used{display:block;margin-top:8px;padding-top:7px;border-top:1px solid var(--line-soft);font-size:11.5px;color:var(--muted)}.suggest{display:flex;flex-direction:column;align-items:flex-start;gap:8px}.chip{background:var(--ground);border:1px solid var(--line);border-radius:20px;padding:7px 13px;color:var(--ink-2);cursor:pointer;font-size:13px;text-align:left}.chip:hover{border-color:var(--accent);color:var(--accent)}@media (max-width: 900px){.with-assistant{flex-direction:column}.assistant{width:100%;height:60vh;position:static;border-left:0;border-top:1px solid var(--line)}} +:root{--ground: #0E1317;--surface: #161D23;--surface-2: #1D262D;--line: #27333B;--line-soft: #1F2A31;--ink: #E7EEF3;--ink-2: #B4C2CC;--muted: #7C8B97;--accent: #45B0C7;--accent-dim:#123039;--ok: #4FB37B;--ok-dim: #12291F;--warn: #E0A33A;--warn-dim: #2C2313;--bad: #E0655A;--bad-dim: #2B1917;--radius: 10px;--mono: "SFMono-Regular", ui-monospace, Menlo, Consolas, monospace}*{box-sizing:border-box;margin:0}html{color-scheme:dark}body{background:var(--ground);color:var(--ink);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased}button,input,select,textarea{font:inherit;color:inherit}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}code{font-family:var(--mono);font-size:.9em}h1{font-size:22px;font-weight:620;letter-spacing:-.015em}h2{font-size:16px;font-weight:600}h3{font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.sub{color:var(--muted);font-size:13.5px}.num{font-variant-numeric:tabular-nums}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.app{min-height:100vh;display:flex;flex-direction:column}.topbar{position:sticky;top:0;z-index:20;display:flex;align-items:center;gap:28px;padding:0 24px;height:60px;background:var(--surface);border-bottom:1px solid var(--line)}.brand{display:flex;align-items:center;gap:11px}.brand strong{display:block;font-size:15px;font-weight:620;letter-spacing:-.01em}.brand .org{display:block;font-size:12px;color:var(--muted)}.mark{width:18px;height:18px;border-radius:50%;border:2.5px solid var(--accent);box-shadow:inset 0 0 0 3px var(--ground);flex:none}.mark.big{width:30px;height:30px;border-width:3px;margin-bottom:14px}.tabs{display:flex;gap:2px;margin-right:auto}.tabs button{background:none;border:0;border-radius:7px;padding:7px 13px;color:var(--ink-2);cursor:pointer;font-size:14px}.tabs button:hover{background:var(--surface-2);color:var(--ink)}.tabs button[aria-current=page]{background:var(--accent-dim);color:var(--accent);font-weight:550}.who{display:flex;align-items:center;gap:12px}.who .name{font-size:13.5px}.who .role{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.page{flex:1;padding:26px 24px 64px;max-width:1280px;width:100%;margin:0 auto;display:flex;flex-direction:column;gap:20px}.head{display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap}.head h1{margin-right:auto}.head .sub{padding-bottom:2px}button.primary{background:var(--accent);color:#04161b;border:0;border-radius:7px;padding:9px 16px;font-weight:600;cursor:pointer}button.primary:disabled{opacity:.5;cursor:default}button.ghost{background:none;border:1px solid var(--line);border-radius:7px;padding:7px 13px;color:var(--ink-2);cursor:pointer}button.ghost:hover{border-color:var(--muted);color:var(--ink)}.segmented{display:flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}.segmented button{background:none;border:0;padding:7px 14px;color:var(--ink-2);cursor:pointer;font-size:13.5px}.segmented button+button{border-left:1px solid var(--line)}.segmented button[aria-current]{background:var(--accent-dim);color:var(--accent)}.card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius)}.grid{display:grid;gap:14px}.grid.sites{grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:16px}.grid.stats{grid-template-columns:repeat(auto-fit,minmax(190px,1fr))}.card.site{overflow:hidden;padding:0;cursor:pointer;border-left:3px solid var(--line);transition:border-color .15s ease,transform .15s ease}.card.site.state-ok{border-left-color:var(--ok)}.card.site.state-warn{border-left-color:var(--warn)}.card.site.state-bad{border-left-color:var(--bad)}.card.site.state-idle{border-left-color:var(--muted)}.card.site:hover{transform:translateY(-1px)}.card.site:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media (prefers-reduced-motion: reduce){.card.site{transition:none}}.metrics{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--line-soft)}.metric{padding:11px 6px;text-align:center}.metric+.metric{border-left:1px solid var(--line-soft)}.metric b{display:block;font-size:15px;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.01em}.metric b.ok{color:var(--ink)}.metric b.warn{color:var(--warn)}.metric b.bad{color:var(--bad)}.metric b.idle{color:var(--muted)}.metric span{display:block;margin-top:1px;font-size:11px;color:var(--muted)}.shopmark{width:38px;height:30px;fill:none;stroke:var(--line);stroke-width:2;stroke-linejoin:round}.pill{display:inline-block;padding:3px 9px;border-radius:20px;flex:none;font-size:11.5px;font-weight:550;letter-spacing:.01em;background:var(--surface-2);color:var(--ink-2)}.pill.ok{background:var(--ok-dim);color:var(--ok)}.pill.warn{background:var(--warn-dim);color:var(--warn)}.pill.bad{background:var(--bad-dim);color:var(--bad)}.pill.new{background:var(--accent-dim);color:var(--accent)}.dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--muted);margin-right:7px;vertical-align:1px}.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn)}.card.stat{padding:16px 18px;display:flex;flex-direction:column;gap:3px}.stat .value{font-size:30px;font-weight:620;letter-spacing:-.02em;font-variant-numeric:tabular-nums;line-height:1.15}.stat .label{font-size:13.5px;color:var(--ink-2)}.stat .note{font-size:12.5px;color:var(--muted);margin-top:3px}.banner{padding:12px 16px;border-radius:var(--radius);font-size:14px;display:flex;gap:16px;align-items:flex-start}.banner.warn{background:var(--warn-dim);border:1px solid #4A3A18;color:#f0d9a6}.banner.ok{background:var(--ok-dim);border:1px solid #1E4534;color:#c6e9d6}.banner>div{flex:1}.creds{display:flex;gap:26px;margin-top:10px;flex-wrap:wrap}.creds dt{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.creds dd{font-family:var(--mono);font-size:14px;-webkit-user-select:all;user-select:all}.arrivals{list-style:none;padding:0;display:grid;gap:8px}.card.arrival{display:flex;align-items:center;gap:14px;padding:11px 14px}.face{width:46px;height:46px;border-radius:50%;flex:none;object-fit:cover;background:var(--surface-2)}.face.initials{display:grid;place-items:center;color:var(--muted);font-size:15px;font-weight:600;letter-spacing:.02em}.who-col{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.who-col strong{font-weight:570}.attrs{font-size:12.5px;color:var(--muted);text-transform:capitalize}.toolbar{display:flex;gap:10px}.search{flex:1;max-width:380px;background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:9px 13px}.search::placeholder{color:var(--muted)}input::placeholder,textarea::placeholder{color:var(--muted);opacity:1}.tablewrap{overflow-x:auto;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius)}table.rows{border-collapse:collapse;width:100%;min-width:620px}table.rows th,table.rows td{text-align:left;padding:11px 16px;border-bottom:1px solid var(--line-soft)}table.rows tr:last-child td{border-bottom:0}table.rows th{font-size:11.5px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);font-weight:600;background:var(--surface-2)}table.rows tbody tr{cursor:pointer}table.rows tbody tr:hover{background:var(--surface-2)}table.rows td.num{font-variant-numeric:tabular-nums}.chart-card{padding:18px}.chart-head{margin-bottom:16px}.peak{font-size:12.5px;color:var(--muted);margin-bottom:8px}.peak b{color:var(--ink-2);font-weight:600;font-variant-numeric:tabular-nums}.chart{display:flex;align-items:flex-end;gap:3px;height:190px;overflow-x:auto;padding-bottom:4px}.col{flex:1;min-width:16px;display:flex;flex-direction:column;align-items:center;gap:6px;height:100%}.bars{flex:1;width:100%;display:flex;flex-direction:column;justify-content:flex-end}.bar{display:block;width:100%;border-radius:2px 2px 0 0}.bar.new{background:var(--accent)}.bar.returning{background:var(--accent-dim);border-radius:0}.col:hover .bar.returning{background:#1b4552}.tick{font-size:10.5px;color:var(--muted);white-space:nowrap;font-variant-numeric:tabular-nums}.legend{display:flex;gap:18px;align-items:center;margin-top:14px;padding-top:12px;border-top:1px solid var(--line-soft);font-size:12.5px;color:var(--ink-2)}.legend span{display:flex;align-items:center;gap:7px}.swatch{width:10px;height:10px;border-radius:2px;display:inline-block}.swatch.new{background:var(--accent)}.swatch.returning{background:var(--accent-dim)}.pad{padding:24px 0}.overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#04080a9e;display:flex;justify-content:flex-end;z-index:50}.drawer{width:min(560px,100%);background:var(--surface);border-left:1px solid var(--line);height:100%;overflow-y:auto;display:flex;flex-direction:column}.drawer.narrow{width:min(440px,100%)}.drawer-head{position:sticky;top:0;z-index:1;display:flex;align-items:flex-start;gap:16px;padding:18px 22px;background:var(--surface);border-bottom:1px solid var(--line)}.drawer-head h2{margin-right:auto}.drawer-head>div{flex:1}.drawer-body{padding:20px 22px;display:flex;flex-direction:column;gap:14px}.drawer-body+.drawer-body{border-top:1px solid var(--line-soft)}fieldset{border:0;padding:0;margin:0;display:flex;flex-direction:column;gap:14px}fieldset:disabled{opacity:.6}label{display:flex;flex-direction:column;gap:6px;font-size:13px;color:var(--ink-2)}label input[type=text],label input[type=email],label input[type=password],label input:not([type]),.drawer input{background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px;color:var(--ink);font-size:14.5px}label .hint{font-size:12px;color:var(--muted);line-height:1.45}label.check{flex-direction:row;align-items:center;gap:9px}label.check input{width:auto}.timeline{list-style:none;padding:0;display:grid;gap:8px}.timeline li{display:flex;align-items:center;gap:12px;font-size:13.5px;padding:9px 12px;background:var(--ground);border-radius:7px}.timeline .when{font-variant-numeric:tabular-nums}.timeline .where{color:var(--muted);margin-right:auto}.state{display:flex;flex-direction:column;align-items:center;gap:8px;padding:64px 20px;text-align:center;color:var(--ink-2)}.state .sub{max-width:46ch}.boot{min-height:100vh;display:flex;align-items:center;justify-content:center;gap:10px;color:var(--muted)}.error{color:var(--bad);font-size:13.5px}.spinner{width:14px;height:14px;border-radius:50%;border:2px solid var(--line);border-top-color:var(--accent);animation:spin .7s linear infinite;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion: reduce){.spinner{animation:none}}.signin{min-height:100vh;display:grid;place-items:center;padding:24px}.signin .card{width:min(380px,100%);padding:30px;display:flex;flex-direction:column;gap:14px}.signin h1{font-size:20px}.signin .sub{margin-top:-8px;margin-bottom:6px}.signin .foot{font-size:12.5px;color:var(--muted);text-align:center;margin-top:4px;line-height:1.5}@media (max-width: 720px){.topbar{height:auto;flex-wrap:wrap;padding:12px 16px;gap:12px}.tabs{order:3;width:100%;overflow-x:auto}.page{padding:18px 16px 48px}.who .name{display:none}}.pair{display:grid;grid-template-columns:1fr 1fr;gap:14px}select{background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px;color:var(--ink);font-size:14.5px}button.ghost.danger{border-color:#4a211d;color:var(--bad)}button.ghost.danger:hover{border-color:var(--bad)}.drawer.wizard{width:min(560px,100%)}.steps{list-style:none;display:flex;gap:4px;padding:14px 22px;margin:0;border-bottom:1px solid var(--line-soft);background:var(--surface);position:sticky;top:62px;z-index:1}.steps li{flex:1;display:flex;align-items:center;gap:7px;font-size:12.5px;color:var(--muted);min-width:0}.steps li .dot{width:20px;height:20px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:11px;background:var(--surface-2);color:var(--muted)}.steps li.now{color:var(--ink);font-weight:550}.steps li.now .dot{background:var(--accent);color:#04161b}.steps li.done .dot{background:var(--ok-dim);color:var(--ok)}.waiting{display:flex;gap:12px;align-items:center;padding:14px 16px;background:var(--ground);border:1px solid var(--line);border-radius:var(--radius)}.waiting>div{display:flex;flex-direction:column;gap:2px}.outcome{border:1px solid var(--line);border-left-width:3px;border-radius:var(--radius);padding:14px 16px;display:flex;flex-direction:column;gap:12px}.outcome.ok{border-left-color:var(--ok);background:var(--ok-dim)}.outcome.warn{border-left-color:var(--warn);background:var(--warn-dim)}.outcome.bad{border-left-color:var(--bad);background:var(--bad-dim)}.outcome-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.outcome-head b{font-size:14.5px}.proof{width:100%;border-radius:6px;display:block;background:#05090b}.advice{margin:0;padding-left:18px;display:grid;gap:6px;font-size:13.5px;color:var(--ink-2);line-height:1.5}.verified{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:13px}.verified .mark{width:17px;height:17px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:10.5px}.verified.ok{color:var(--ok)}.verified.ok .mark{background:var(--ok-dim)}.verified.warn{color:var(--warn)}.verified.warn .mark{background:var(--warn-dim)}.verified.bad{color:var(--bad)}.verified.bad .mark{background:var(--bad-dim)}.verified.idle{color:var(--muted)}.verified.idle .mark{background:var(--surface-2)}.checklist{list-style:none;padding:0;margin:0;display:grid;gap:2px}.checklist li{display:flex;gap:12px;padding:13px 14px;background:var(--ground);border-radius:8px;border-left:3px solid var(--line)}.checklist li>div{display:flex;flex-direction:column;gap:3px;flex:1}.checklist li.pass{border-left-color:var(--ok)}.checklist li.warn{border-left-color:var(--warn)}.checklist li.fail{border-left-color:var(--bad)}.checklist li.unknown{border-left-color:var(--muted)}.checklist .mark{width:20px;height:20px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:11px;background:var(--surface-2);color:var(--muted)}.checklist li.pass .mark{background:var(--ok-dim);color:var(--ok)}.checklist li.warn .mark{background:var(--warn-dim);color:var(--warn)}.checklist li.fail .mark{background:var(--bad-dim);color:var(--bad)}.advice-line{font-size:13px;color:var(--warn);line-height:1.45}.checklist li.pass .advice-line{color:var(--muted)}.grid.cams{grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:16px}.card.cam{overflow:hidden;border-left:0;padding:0;cursor:pointer;transition:border-color .15s ease,transform .15s ease}.card.cam:hover{border-color:var(--muted);transform:translateY(-1px)}.card.cam:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media (prefers-reduced-motion: reduce){.card.cam{transition:none}}.shot{position:relative;aspect-ratio:16 / 10;background:#05090b;display:grid;place-items:center}.shot img{width:100%;height:100%;object-fit:cover;display:block}.noshot{display:flex;flex-direction:column;align-items:center;gap:10px;color:var(--muted);font-size:12.5px;text-align:center;padding:0 28px;line-height:1.5}.lens{width:34px;height:34px;border-radius:50%;border:2px solid var(--line);position:relative}.lens:after{content:"";position:absolute;top:7px;right:7px;bottom:7px;left:7px;border-radius:50%;border:2px solid var(--line-soft)}.shot-over{position:absolute;inset:auto 0 0 0;display:flex;align-items:flex-end;justify-content:space-between;gap:10px;padding:26px 14px 12px;background:linear-gradient(transparent,#04080ad9)}.shot-name b{display:block;font-size:14.5px;font-weight:600;letter-spacing:-.01em}.shot-name span{display:block;font-size:11.5px;color:#9fb0ba;margin-top:1px}.status{display:flex;align-items:center;gap:6px;flex:none;font-size:11px;font-weight:550;letter-spacing:.01em;padding:4px 9px;border-radius:20px;white-space:nowrap;background:#0e1317b8;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);color:var(--ink-2)}.status i{width:6px;height:6px;border-radius:50%;background:var(--muted)}.status.ok{color:#8fe0b4}.status.ok i{background:var(--ok)}.status.warn{color:#efc77c}.status.warn i{background:var(--warn)}.status.bad{color:#f0a79e}.status.bad i{background:var(--bad)}.status.idle i{background:var(--muted)}.shot-age{position:absolute;top:10px;right:12px;font-size:10.5px;color:#9fb0ba;background:#04080a99;padding:2px 7px;border-radius:20px;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.verdict{display:flex;align-items:center;gap:10px;padding:12px 14px;font-size:13px;border-top:1px solid var(--line-soft)}.verdict .words{flex:1;min-width:0}.verdict .go{color:var(--muted);font-size:14px}.verdict .mark{width:18px;height:18px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:10.5px}.verdict.ok{color:var(--ok)}.verdict.ok .mark{background:var(--ok-dim)}.verdict.warn{color:var(--warn)}.verdict.warn .mark{background:var(--warn-dim)}.verdict.bad{color:var(--bad)}.verdict.bad .mark{background:var(--bad-dim)}.verdict.idle{color:var(--muted)}.verdict.idle .mark{background:var(--surface-2)}.claim{margin-top:22px;padding-top:18px;border-top:1px solid var(--line-soft)}.claim h3{font-size:14px;font-weight:600;margin-bottom:6px}.claim .field{display:block;margin:12px 0}.claim .field span{display:block;font-size:12.5px;color:var(--muted);margin-bottom:5px}.claim .field input{width:100%;background:var(--ground);border:1px solid var(--line);border-radius:7px;padding:9px 12px}.claim .row{display:flex;gap:8px;margin-top:12px}.claim .code{font-family:var(--mono);font-size:19px;letter-spacing:.08em;background:var(--ground);border:1px solid var(--line);border-radius:8px;padding:14px 12px;text-align:center;margin:12px 0 10px;-webkit-user-select:all;user-select:all;word-break:break-all}.with-assistant{display:flex;flex:1;min-height:0}.with-assistant .page{flex:1;min-width:0}.ask-btn{background:var(--accent-dim);color:var(--accent);border:0;border-radius:7px;padding:7px 13px;cursor:pointer;font-size:13.5px;font-weight:550;display:flex;align-items:center;gap:7px}.ask-btn:hover,.ask-btn.on{background:var(--accent);color:#04161b}.assistant{width:360px;flex:none;border-left:1px solid var(--line);background:var(--surface);display:flex;flex-direction:column;position:sticky;top:60px;height:calc(100vh - 60px)}.assistant-head{display:flex;align-items:flex-start;gap:12px;padding:15px 16px;border-bottom:1px solid var(--line-soft)}.assistant-head>div{flex:1;display:flex;flex-direction:column;gap:2px}.assistant-body{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}.assistant-ask{display:flex;gap:8px;padding:12px 14px;border-top:1px solid var(--line-soft)}.assistant-ask input{flex:1;min-width:0;background:var(--ground);border:1px solid var(--line);border-radius:8px;padding:9px 12px}.bubble{padding:11px 13px;border-radius:12px;font-size:14px;line-height:1.55;white-space:pre-wrap;max-width:100%}.bubble.user{background:var(--accent-dim);color:var(--ink);align-self:flex-end;border-bottom-right-radius:4px}.bubble.assistant{background:var(--ground);border:1px solid var(--line-soft);border-bottom-left-radius:4px}.bubble.failed{border-color:#4a211d;color:var(--bad)}.bubble.assistant-thinking{color:var(--muted);display:flex;align-items:center;gap:9px}.used{display:block;margin-top:8px;padding-top:7px;border-top:1px solid var(--line-soft);font-size:11.5px;color:var(--muted)}.suggest{display:flex;flex-direction:column;align-items:flex-start;gap:8px}.chip{background:var(--ground);border:1px solid var(--line);border-radius:20px;padding:7px 13px;color:var(--ink-2);cursor:pointer;font-size:13px;text-align:left}.chip:hover{border-color:var(--accent);color:var(--accent)}@media (max-width: 900px){.with-assistant{flex-direction:column}.assistant{width:100%;height:60vh;position:static;border-left:0;border-top:1px solid var(--line)}}.card.cam .watch{position:absolute;left:10px;top:10px;z-index:2;display:inline-flex;align-items:center;gap:6px;padding:4px 9px;border-radius:999px;border:0;cursor:pointer;font:inherit;font-size:11.5px;font-weight:600;letter-spacing:.02em;color:#fff;background:#0c1014b8;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.card.cam .watch:hover{background:#0c1014e6}.card.cam .watch i{width:7px;height:7px;border-radius:50%;background:#e5484d;box-shadow:0 0 #e5484db3;animation:livepulse 2s infinite}@keyframes livepulse{70%{box-shadow:0 0 0 6px #e5484d00}to{box-shadow:0 0 #e5484d00}}@media (prefers-reduced-motion: reduce){.card.cam .watch i{animation:none}}.drawer.live{max-width:760px}.liveshot{position:relative;background:#000;border-radius:10px;overflow:hidden;aspect-ratio:16 / 9}.liveshot img{width:100%;height:100%;object-fit:contain;display:block}.livewait{position:absolute;top:0;right:0;bottom:0;left:0;display:grid;place-items:center;font-size:13px;color:#ffffffc7;background:#00000059} diff --git a/server/internal/web/dist/assets/index-D6UMLnOQ.js b/server/internal/web/dist/assets/index-D6UMLnOQ.js new file mode 100644 index 0000000..01aca04 --- /dev/null +++ b/server/internal/web/dist/assets/index-D6UMLnOQ.js @@ -0,0 +1,46 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const s of l)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(l){const s={};return l.integrity&&(s.integrity=l.integrity),l.referrerPolicy&&(s.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?s.credentials="include":l.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(l){if(l.ep)return;l.ep=!0;const s=n(l);fetch(l.href,s)}})();var au={exports:{}},cl={},cu={exports:{}},R={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var tr=Symbol.for("react.element"),Ec=Symbol.for("react.portal"),_c=Symbol.for("react.fragment"),Pc=Symbol.for("react.strict_mode"),Tc=Symbol.for("react.profiler"),zc=Symbol.for("react.provider"),Lc=Symbol.for("react.context"),Rc=Symbol.for("react.forward_ref"),Oc=Symbol.for("react.suspense"),Ic=Symbol.for("react.memo"),Fc=Symbol.for("react.lazy"),Zi=Symbol.iterator;function Dc(e){return e===null||typeof e!="object"?null:(e=Zi&&e[Zi]||e["@@iterator"],typeof e=="function"?e:null)}var du={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},fu=Object.assign,pu={};function an(e,t,n){this.props=e,this.context=t,this.refs=pu,this.updater=n||du}an.prototype.isReactComponent={};an.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};an.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function hu(){}hu.prototype=an.prototype;function bs(e,t,n){this.props=e,this.context=t,this.refs=pu,this.updater=n||du}var ei=bs.prototype=new hu;ei.constructor=bs;fu(ei,an.prototype);ei.isPureReactComponent=!0;var Ji=Array.isArray,mu=Object.prototype.hasOwnProperty,ti={current:null},vu={key:!0,ref:!0,__self:!0,__source:!0};function yu(e,t,n){var r,l={},s=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(s=""+t.key),t)mu.call(t,r)&&!vu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1>>1,q=C[Q];if(0>>1;Ql(Ll,L))wtl(ar,Ll)?(C[Q]=ar,C[wt]=L,Q=wt):(C[Q]=Ll,C[gt]=L,Q=gt);else if(wtl(ar,L))C[Q]=ar,C[wt]=L,Q=wt;else break e}}return z}function l(C,z){var L=C.sortIndex-z.sortIndex;return L!==0?L:C.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var i=Date,u=i.now();e.unstable_now=function(){return i.now()-u}}var a=[],c=[],m=1,v=null,h=3,y=!1,k=!1,w=!1,T=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function f(C){for(var z=n(c);z!==null;){if(z.callback===null)r(c);else if(z.startTime<=C)r(c),z.sortIndex=z.expirationTime,t(a,z);else break;z=n(c)}}function g(C){if(w=!1,f(C),!k)if(n(a)!==null)k=!0,Tl(S);else{var z=n(c);z!==null&&zl(g,z.startTime-C)}}function S(C,z){k=!1,w&&(w=!1,p(P),P=-1),y=!0;var L=h;try{for(f(z),v=n(a);v!==null&&(!(v.expirationTime>z)||C&&!Te());){var Q=v.callback;if(typeof Q=="function"){v.callback=null,h=v.priorityLevel;var q=Q(v.expirationTime<=z);z=e.unstable_now(),typeof q=="function"?v.callback=q:v===n(a)&&r(a),f(z)}else r(a);v=n(a)}if(v!==null)var ur=!0;else{var gt=n(c);gt!==null&&zl(g,gt.startTime-z),ur=!1}return ur}finally{v=null,h=L,y=!1}}var E=!1,_=null,P=-1,H=5,O=-1;function Te(){return!(e.unstable_now()-OC||125Q?(C.sortIndex=L,t(c,C),n(a)===null&&C===n(c)&&(w?(p(P),P=-1):w=!0,zl(g,L-Q))):(C.sortIndex=q,t(a,C),k||y||(k=!0,Tl(S))),C},e.unstable_shouldYield=Te,e.unstable_wrapCallback=function(C){var z=h;return function(){var L=h;h=z;try{return C.apply(this,arguments)}finally{h=L}}}})(Su);xu.exports=Su;var Gc=xu.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Yc=N,ke=Gc;function x(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ss=Object.prototype.hasOwnProperty,Xc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,bi={},eo={};function Zc(e){return ss.call(eo,e)?!0:ss.call(bi,e)?!1:Xc.test(e)?eo[e]=!0:(bi[e]=!0,!1)}function Jc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function qc(e,t,n,r){if(t===null||typeof t>"u"||Jc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function de(e,t,n,r,l,s,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=i}var re={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){re[e]=new de(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];re[t]=new de(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){re[e]=new de(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){re[e]=new de(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){re[e]=new de(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){re[e]=new de(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){re[e]=new de(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){re[e]=new de(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){re[e]=new de(e,5,!1,e.toLowerCase(),null,!1,!1)});var ri=/[\-:]([a-z])/g;function li(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ri,li);re[t]=new de(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ri,li);re[t]=new de(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ri,li);re[t]=new de(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){re[e]=new de(e,1,!1,e.toLowerCase(),null,!1,!1)});re.xlinkHref=new de("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){re[e]=new de(e,1,!1,e.toLowerCase(),null,!0,!0)});function si(e,t,n,r){var l=re.hasOwnProperty(t)?re[t]:null;(l!==null?l.type!==0:r||!(2u||l[i]!==s[u]){var a=` +`+l[i].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=i&&0<=u);break}}}finally{Il=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?jn(e):""}function bc(e){switch(e.tag){case 5:return jn(e.type);case 16:return jn("Lazy");case 13:return jn("Suspense");case 19:return jn("SuspenseList");case 0:case 2:case 15:return e=Fl(e.type,!1),e;case 11:return e=Fl(e.type.render,!1),e;case 1:return e=Fl(e.type,!0),e;default:return""}}function as(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Mt:return"Fragment";case Dt:return"Portal";case is:return"Profiler";case ii:return"StrictMode";case os:return"Suspense";case us:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Nu:return(e.displayName||"Context")+".Consumer";case Cu:return(e._context.displayName||"Context")+".Provider";case oi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ui:return t=e.displayName||null,t!==null?t:as(e.type)||"Memo";case be:t=e._payload,e=e._init;try{return as(e(t))}catch{}}return null}function ed(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return as(t);case 8:return t===ii?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function pt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function _u(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function td(e){var t=_u(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,s.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function fr(e){e._valueTracker||(e._valueTracker=td(e))}function Pu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=_u(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Ar(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function cs(e,t){var n=t.checked;return V({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function no(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=pt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Tu(e,t){t=t.checked,t!=null&&si(e,"checked",t,!1)}function ds(e,t){Tu(e,t);var n=pt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?fs(e,t.type,n):t.hasOwnProperty("defaultValue")&&fs(e,t.type,pt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ro(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function fs(e,t,n){(t!=="number"||Ar(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Cn=Array.isArray;function Yt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=pr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Mn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var _n={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nd=["Webkit","ms","Moz","O"];Object.keys(_n).forEach(function(e){nd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),_n[t]=_n[e]})});function Ou(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||_n.hasOwnProperty(e)&&_n[e]?(""+t).trim():t+"px"}function Iu(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Ou(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var rd=V({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ms(e,t){if(t){if(rd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(x(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(x(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(x(61))}if(t.style!=null&&typeof t.style!="object")throw Error(x(62))}}function vs(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ys=null;function ai(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var gs=null,Xt=null,Zt=null;function io(e){if(e=lr(e)){if(typeof gs!="function")throw Error(x(280));var t=e.stateNode;t&&(t=ml(t),gs(e.stateNode,e.type,t))}}function Fu(e){Xt?Zt?Zt.push(e):Zt=[e]:Xt=e}function Du(){if(Xt){var e=Xt,t=Zt;if(Zt=Xt=null,io(e),t)for(e=0;e>>=0,e===0?32:31-(hd(e)/md|0)|0}var hr=64,mr=4194304;function Nn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Hr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,s=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=Nn(u):(s&=i,s!==0&&(r=Nn(s)))}else i=n&~l,i!==0?r=Nn(i):s!==0&&(r=Nn(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,s=t&-t,l>=s||l===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function nr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ie(t),e[t]=n}function wd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Tn),vo=" ",yo=!1;function na(e,t){switch(e){case"keyup":return Gd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ra(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var $t=!1;function Xd(e,t){switch(e){case"compositionend":return ra(t);case"keypress":return t.which!==32?null:(yo=!0,vo);case"textInput":return e=t.data,e===vo&&yo?null:e;default:return null}}function Zd(e,t){if($t)return e==="compositionend"||!yi&&na(e,t)?(e=ea(),zr=hi=rt=null,$t=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xo(n)}}function oa(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?oa(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ua(){for(var e=window,t=Ar();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ar(e.document)}return t}function gi(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sf(e){var t=ua(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&oa(n.ownerDocument.documentElement,n)){if(r!==null&&gi(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,s=Math.min(r.start,l);r=r.end===void 0?s:Math.min(r.end,l),!e.extend&&s>r&&(l=r,r=s,s=l),l=So(n,s);var i=So(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ut=null,Cs=null,Ln=null,Ns=!1;function jo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ns||Ut==null||Ut!==Ar(r)||(r=Ut,"selectionStart"in r&&gi(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ln&&Wn(Ln,r)||(Ln=r,r=Gr(Cs,"onSelect"),0Vt||(e.current=Ls[Vt],Ls[Vt]=null,Vt--)}function D(e,t){Vt++,Ls[Vt]=e.current,e.current=t}var ht={},oe=vt(ht),he=vt(!1),_t=ht;function tn(e,t){var n=e.type.contextTypes;if(!n)return ht;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},s;for(s in n)l[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function me(e){return e=e.childContextTypes,e!=null}function Xr(){$(he),$(oe)}function zo(e,t,n){if(oe.current!==ht)throw Error(x(168));D(oe,t),D(he,n)}function ya(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(x(108,ed(e)||"Unknown",l));return V({},n,r)}function Zr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ht,_t=oe.current,D(oe,e),D(he,he.current),!0}function Lo(e,t,n){var r=e.stateNode;if(!r)throw Error(x(169));n?(e=ya(e,t,_t),r.__reactInternalMemoizedMergedChildContext=e,$(he),$(oe),D(oe,e)):$(he),D(he,n)}var We=null,vl=!1,Xl=!1;function ga(e){We===null?We=[e]:We.push(e)}function gf(e){vl=!0,ga(e)}function yt(){if(!Xl&&We!==null){Xl=!0;var e=0,t=F;try{var n=We;for(F=1;e>=i,l-=i,He=1<<32-Ie(t)+l|n<P?(H=_,_=null):H=_.sibling;var O=h(p,_,f[P],g);if(O===null){_===null&&(_=H);break}e&&_&&O.alternate===null&&t(p,_),d=s(O,d,P),E===null?S=O:E.sibling=O,E=O,_=H}if(P===f.length)return n(p,_),U&&kt(p,P),S;if(_===null){for(;PP?(H=_,_=null):H=_.sibling;var Te=h(p,_,O.value,g);if(Te===null){_===null&&(_=H);break}e&&_&&Te.alternate===null&&t(p,_),d=s(Te,d,P),E===null?S=Te:E.sibling=Te,E=Te,_=H}if(O.done)return n(p,_),U&&kt(p,P),S;if(_===null){for(;!O.done;P++,O=f.next())O=v(p,O.value,g),O!==null&&(d=s(O,d,P),E===null?S=O:E.sibling=O,E=O);return U&&kt(p,P),S}for(_=r(p,_);!O.done;P++,O=f.next())O=y(_,p,P,O.value,g),O!==null&&(e&&O.alternate!==null&&_.delete(O.key===null?P:O.key),d=s(O,d,P),E===null?S=O:E.sibling=O,E=O);return e&&_.forEach(function(fn){return t(p,fn)}),U&&kt(p,P),S}function T(p,d,f,g){if(typeof f=="object"&&f!==null&&f.type===Mt&&f.key===null&&(f=f.props.children),typeof f=="object"&&f!==null){switch(f.$$typeof){case dr:e:{for(var S=f.key,E=d;E!==null;){if(E.key===S){if(S=f.type,S===Mt){if(E.tag===7){n(p,E.sibling),d=l(E,f.props.children),d.return=p,p=d;break e}}else if(E.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===be&&Io(S)===E.type){n(p,E.sibling),d=l(E,f.props),d.ref=wn(p,E,f),d.return=p,p=d;break e}n(p,E);break}else t(p,E);E=E.sibling}f.type===Mt?(d=Et(f.props.children,p.mode,g,f.key),d.return=p,p=d):(g=$r(f.type,f.key,f.props,null,p.mode,g),g.ref=wn(p,d,f),g.return=p,p=g)}return i(p);case Dt:e:{for(E=f.key;d!==null;){if(d.key===E)if(d.tag===4&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){n(p,d.sibling),d=l(d,f.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=rs(f,p.mode,g),d.return=p,p=d}return i(p);case be:return E=f._init,T(p,d,E(f._payload),g)}if(Cn(f))return k(p,d,f,g);if(hn(f))return w(p,d,f,g);Sr(p,f)}return typeof f=="string"&&f!==""||typeof f=="number"?(f=""+f,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,f),d.return=p,p=d):(n(p,d),d=ns(f,p.mode,g),d.return=p,p=d),i(p)):n(p,d)}return T}var rn=Sa(!0),ja=Sa(!1),br=vt(null),el=null,Qt=null,Si=null;function ji(){Si=Qt=el=null}function Ci(e){var t=br.current;$(br),e._currentValue=t}function Is(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function qt(e,t){el=e,Si=Qt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pe=!0),e.firstContext=null)}function _e(e){var t=e._currentValue;if(Si!==e)if(e={context:e,memoizedValue:t,next:null},Qt===null){if(el===null)throw Error(x(308));Qt=e,el.dependencies={lanes:0,firstContext:e}}else Qt=Qt.next=e;return t}var jt=null;function Ni(e){jt===null?jt=[e]:jt.push(e)}function Ca(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Ni(t)):(n.next=l.next,l.next=n),t.interleaved=n,Xe(e,r)}function Xe(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var et=!1;function Ei(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Na(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ke(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function at(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,I&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Xe(e,n)}return l=r.interleaved,l===null?(t.next=t,Ni(r)):(t.next=l.next,l.next=t),r.interleaved=t,Xe(e,n)}function Rr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,di(e,n)}}function Fo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?l=s=i:s=s.next=i,n=n.next}while(n!==null);s===null?l=s=t:s=s.next=t}else l=s=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function tl(e,t,n,r){var l=e.updateQueue;et=!1;var s=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var a=u,c=a.next;a.next=null,i===null?s=c:i.next=c,i=a;var m=e.alternate;m!==null&&(m=m.updateQueue,u=m.lastBaseUpdate,u!==i&&(u===null?m.firstBaseUpdate=c:u.next=c,m.lastBaseUpdate=a))}if(s!==null){var v=l.baseState;i=0,m=c=a=null,u=s;do{var h=u.lane,y=u.eventTime;if((r&h)===h){m!==null&&(m=m.next={eventTime:y,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var k=e,w=u;switch(h=t,y=n,w.tag){case 1:if(k=w.payload,typeof k=="function"){v=k.call(y,v,h);break e}v=k;break e;case 3:k.flags=k.flags&-65537|128;case 0:if(k=w.payload,h=typeof k=="function"?k.call(y,v,h):k,h==null)break e;v=V({},v,h);break e;case 2:et=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[u]:h.push(u))}else y={eventTime:y,lane:h,tag:u.tag,payload:u.payload,callback:u.callback,next:null},m===null?(c=m=y,a=v):m=m.next=y,i|=h;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;h=u,u=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(m===null&&(a=v),l.baseState=a,l.firstBaseUpdate=c,l.lastBaseUpdate=m,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else s===null&&(l.shared.lanes=0);zt|=i,e.lanes=i,e.memoizedState=v}}function Do(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Jl.transition;Jl.transition={};try{e(!1),t()}finally{F=n,Jl.transition=r}}function Va(){return Pe().memoizedState}function Sf(e,t,n){var r=dt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Wa(e))Ha(t,n);else if(n=Ca(e,t,n,r),n!==null){var l=ae();Fe(n,e,r,l),Qa(n,t,r)}}function jf(e,t,n){var r=dt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Wa(e))Ha(t,l);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var i=t.lastRenderedState,u=s(i,n);if(l.hasEagerState=!0,l.eagerState=u,De(u,i)){var a=t.interleaved;a===null?(l.next=l,Ni(t)):(l.next=a.next,a.next=l),t.interleaved=l;return}}catch{}finally{}n=Ca(e,t,l,r),n!==null&&(l=ae(),Fe(n,e,r,l),Qa(n,t,r))}}function Wa(e){var t=e.alternate;return e===B||t!==null&&t===B}function Ha(e,t){Rn=rl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Qa(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,di(e,n)}}var ll={readContext:_e,useCallback:le,useContext:le,useEffect:le,useImperativeHandle:le,useInsertionEffect:le,useLayoutEffect:le,useMemo:le,useReducer:le,useRef:le,useState:le,useDebugValue:le,useDeferredValue:le,useTransition:le,useMutableSource:le,useSyncExternalStore:le,useId:le,unstable_isNewReconciler:!1},Cf={readContext:_e,useCallback:function(e,t){return $e().memoizedState=[e,t===void 0?null:t],e},useContext:_e,useEffect:$o,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ir(4194308,4,Ma.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ir(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ir(4,2,e,t)},useMemo:function(e,t){var n=$e();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=$e();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Sf.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=$e();return e={current:e},t.memoizedState=e},useState:Mo,useDebugValue:Ii,useDeferredValue:function(e){return $e().memoizedState=e},useTransition:function(){var e=Mo(!1),t=e[0];return e=xf.bind(null,e[1]),$e().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=B,l=$e();if(U){if(n===void 0)throw Error(x(407));n=n()}else{if(n=t(),ee===null)throw Error(x(349));Tt&30||Ta(r,t,n)}l.memoizedState=n;var s={value:n,getSnapshot:t};return l.queue=s,$o(La.bind(null,r,s,e),[e]),r.flags|=2048,Jn(9,za.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=$e(),t=ee.identifierPrefix;if(U){var n=Qe,r=He;n=(r&~(1<<32-Ie(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Xn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Ue]=t,e[Kn]=r,tc(e,t,!1,!1),t.stateNode=e;e:{switch(i=vs(n,r),n){case"dialog":M("cancel",e),M("close",e),l=r;break;case"iframe":case"object":case"embed":M("load",e),l=r;break;case"video":case"audio":for(l=0;lon&&(t.flags|=128,r=!0,kn(s,!1),t.lanes=4194304)}else{if(!r)if(e=nl(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),kn(s,!0),s.tail===null&&s.tailMode==="hidden"&&!i.alternate&&!U)return se(t),null}else 2*K()-s.renderingStartTime>on&&n!==1073741824&&(t.flags|=128,r=!0,kn(s,!1),t.lanes=4194304);s.isBackwards?(i.sibling=t.child,t.child=i):(n=s.last,n!==null?n.sibling=i:t.child=i,s.last=i)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=K(),t.sibling=null,n=A.current,D(A,r?n&1|2:n&1),t):(se(t),null);case 22:case 23:return Ai(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ye&1073741824&&(se(t),t.subtreeFlags&6&&(t.flags|=8192)):se(t),null;case 24:return null;case 25:return null}throw Error(x(156,t.tag))}function Rf(e,t){switch(ki(t),t.tag){case 1:return me(t.type)&&Xr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ln(),$(he),$(oe),Ti(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Pi(t),null;case 13:if($(A),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(x(340));nn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return $(A),null;case 4:return ln(),null;case 10:return Ci(t.type._context),null;case 22:case 23:return Ai(),null;case 24:return null;default:return null}}var Cr=!1,ie=!1,Of=typeof WeakSet=="function"?WeakSet:Set,j=null;function Kt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){W(e,t,r)}else n.current=null}function Ws(e,t,n){try{n()}catch(r){W(e,t,r)}}var Xo=!1;function If(e,t){if(Es=Qr,e=ua(),gi(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var i=0,u=-1,a=-1,c=0,m=0,v=e,h=null;t:for(;;){for(var y;v!==n||l!==0&&v.nodeType!==3||(u=i+l),v!==s||r!==0&&v.nodeType!==3||(a=i+r),v.nodeType===3&&(i+=v.nodeValue.length),(y=v.firstChild)!==null;)h=v,v=y;for(;;){if(v===e)break t;if(h===n&&++c===l&&(u=i),h===s&&++m===r&&(a=i),(y=v.nextSibling)!==null)break;v=h,h=v.parentNode}v=y}n=u===-1||a===-1?null:{start:u,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(_s={focusedElem:e,selectionRange:n},Qr=!1,j=t;j!==null;)if(t=j,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,j=e;else for(;j!==null;){t=j;try{var k=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(k!==null){var w=k.memoizedProps,T=k.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?w:Le(t.type,w),T);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var f=t.stateNode.containerInfo;f.nodeType===1?f.textContent="":f.nodeType===9&&f.documentElement&&f.removeChild(f.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(x(163))}}catch(g){W(t,t.return,g)}if(e=t.sibling,e!==null){e.return=t.return,j=e;break}j=t.return}return k=Xo,Xo=!1,k}function On(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var s=l.destroy;l.destroy=void 0,s!==void 0&&Ws(t,n,s)}l=l.next}while(l!==r)}}function wl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Hs(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function lc(e){var t=e.alternate;t!==null&&(e.alternate=null,lc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ue],delete t[Kn],delete t[zs],delete t[vf],delete t[yf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function sc(e){return e.tag===5||e.tag===3||e.tag===4}function Zo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||sc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Qs(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Yr));else if(r!==4&&(e=e.child,e!==null))for(Qs(e,t,n),e=e.sibling;e!==null;)Qs(e,t,n),e=e.sibling}function Ks(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ks(e,t,n),e=e.sibling;e!==null;)Ks(e,t,n),e=e.sibling}var te=null,Re=!1;function qe(e,t,n){for(n=n.child;n!==null;)ic(e,t,n),n=n.sibling}function ic(e,t,n){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(dl,n)}catch{}switch(n.tag){case 5:ie||Kt(n,t);case 6:var r=te,l=Re;te=null,qe(e,t,n),te=r,Re=l,te!==null&&(Re?(e=te,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):te.removeChild(n.stateNode));break;case 18:te!==null&&(Re?(e=te,n=n.stateNode,e.nodeType===8?Yl(e.parentNode,n):e.nodeType===1&&Yl(e,n),Bn(e)):Yl(te,n.stateNode));break;case 4:r=te,l=Re,te=n.stateNode.containerInfo,Re=!0,qe(e,t,n),te=r,Re=l;break;case 0:case 11:case 14:case 15:if(!ie&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var s=l,i=s.destroy;s=s.tag,i!==void 0&&(s&2||s&4)&&Ws(n,t,i),l=l.next}while(l!==r)}qe(e,t,n);break;case 1:if(!ie&&(Kt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){W(n,t,u)}qe(e,t,n);break;case 21:qe(e,t,n);break;case 22:n.mode&1?(ie=(r=ie)||n.memoizedState!==null,qe(e,t,n),ie=r):qe(e,t,n);break;default:qe(e,t,n)}}function Jo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Of),t.forEach(function(r){var l=Wf.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function ze(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=i),r&=~s}if(r=l,r=K()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Df(r/1960))-r,10e?16:e,lt===null)var r=!1;else{if(e=lt,lt=null,ol=0,I&6)throw Error(x(331));var l=I;for(I|=4,j=e.current;j!==null;){var s=j,i=s.child;if(j.flags&16){var u=s.deletions;if(u!==null){for(var a=0;aK()-$i?Nt(e,0):Mi|=n),ve(e,t)}function hc(e,t){t===0&&(e.mode&1?(t=mr,mr<<=1,!(mr&130023424)&&(mr=4194304)):t=1);var n=ae();e=Xe(e,t),e!==null&&(nr(e,t,n),ve(e,n))}function Vf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),hc(e,n)}function Wf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(x(314))}r!==null&&r.delete(t),hc(e,n)}var mc;mc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||he.current)pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pe=!1,zf(e,t,n);pe=!!(e.flags&131072)}else pe=!1,U&&t.flags&1048576&&wa(t,qr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fr(e,t),e=t.pendingProps;var l=tn(t,oe.current);qt(t,n),l=Li(null,t,r,e,l,n);var s=Ri();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,me(r)?(s=!0,Zr(t)):s=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ei(t),l.updater=gl,t.stateNode=l,l._reactInternals=t,Ds(t,r,e,n),t=Us(null,t,r,!0,s,n)):(t.tag=0,U&&s&&wi(t),ue(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Qf(r),e=Le(r,e),l){case 0:t=$s(null,t,r,e,n);break e;case 1:t=Ko(null,t,r,e,n);break e;case 11:t=Ho(null,t,r,e,n);break e;case 14:t=Qo(null,t,r,Le(r.type,e),n);break e}throw Error(x(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),$s(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ko(e,t,r,l,n);case 3:e:{if(qa(t),e===null)throw Error(x(387));r=t.pendingProps,s=t.memoizedState,l=s.element,Na(e,t),tl(t,r,null,n);var i=t.memoizedState;if(r=i.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){l=sn(Error(x(423)),t),t=Go(e,t,r,n,l);break e}else if(r!==l){l=sn(Error(x(424)),t),t=Go(e,t,r,n,l);break e}else for(ge=ut(t.stateNode.containerInfo.firstChild),we=t,U=!0,Oe=null,n=ja(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(nn(),r===l){t=Ze(e,t,n);break e}ue(e,t,r,n)}t=t.child}return t;case 5:return Ea(t),e===null&&Os(t),r=t.type,l=t.pendingProps,s=e!==null?e.memoizedProps:null,i=l.children,Ps(r,l)?i=null:s!==null&&Ps(r,s)&&(t.flags|=32),Ja(e,t),ue(e,t,i,n),t.child;case 6:return e===null&&Os(t),null;case 13:return ba(e,t,n);case 4:return _i(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=rn(t,null,r,n):ue(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Ho(e,t,r,l,n);case 7:return ue(e,t,t.pendingProps,n),t.child;case 8:return ue(e,t,t.pendingProps.children,n),t.child;case 12:return ue(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,s=t.memoizedProps,i=l.value,D(br,r._currentValue),r._currentValue=i,s!==null)if(De(s.value,i)){if(s.children===l.children&&!he.current){t=Ze(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var u=s.dependencies;if(u!==null){i=s.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(s.tag===1){a=Ke(-1,n&-n),a.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var m=c.pending;m===null?a.next=a:(a.next=m.next,m.next=a),c.pending=a}}s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),Is(s.return,n,t),u.lanes|=n;break}a=a.next}}else if(s.tag===10)i=s.type===t.type?null:s.child;else if(s.tag===18){if(i=s.return,i===null)throw Error(x(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Is(i,n,t),i=s.sibling}else i=s.child;if(i!==null)i.return=s;else for(i=s;i!==null;){if(i===t){i=null;break}if(s=i.sibling,s!==null){s.return=i.return,i=s;break}i=i.return}s=i}ue(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,qt(t,n),l=_e(l),r=r(l),t.flags|=1,ue(e,t,r,n),t.child;case 14:return r=t.type,l=Le(r,t.pendingProps),l=Le(r.type,l),Qo(e,t,r,l,n);case 15:return Xa(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Le(r,l),Fr(e,t),t.tag=1,me(r)?(e=!0,Zr(t)):e=!1,qt(t,n),Ka(t,r,l),Ds(t,r,l,n),Us(null,t,r,!0,e,n);case 19:return ec(e,t,n);case 22:return Za(e,t,n)}throw Error(x(156,t.tag))};function vc(e,t){return Wu(e,t)}function Hf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ne(e,t,n,r){return new Hf(e,t,n,r)}function Vi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Qf(e){if(typeof e=="function")return Vi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===oi)return 11;if(e===ui)return 14}return 2}function ft(e,t){var n=e.alternate;return n===null?(n=Ne(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function $r(e,t,n,r,l,s){var i=2;if(r=e,typeof e=="function")Vi(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Mt:return Et(n.children,l,s,t);case ii:i=8,l|=8;break;case is:return e=Ne(12,n,t,l|2),e.elementType=is,e.lanes=s,e;case os:return e=Ne(13,n,t,l),e.elementType=os,e.lanes=s,e;case us:return e=Ne(19,n,t,l),e.elementType=us,e.lanes=s,e;case Eu:return xl(n,l,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Cu:i=10;break e;case Nu:i=9;break e;case oi:i=11;break e;case ui:i=14;break e;case be:i=16,r=null;break e}throw Error(x(130,e==null?e:typeof e,""))}return t=Ne(i,n,t,l),t.elementType=e,t.type=r,t.lanes=s,t}function Et(e,t,n,r){return e=Ne(7,e,r,t),e.lanes=n,e}function xl(e,t,n,r){return e=Ne(22,e,r,t),e.elementType=Eu,e.lanes=n,e.stateNode={isHidden:!1},e}function ns(e,t,n){return e=Ne(6,e,null,t),e.lanes=n,e}function rs(e,t,n){return t=Ne(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Kf(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ml(0),this.expirationTimes=Ml(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ml(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Wi(e,t,n,r,l,s,i,u,a){return e=new Kf(e,t,n,u,a),t===1?(t=1,s===!0&&(t|=8)):t=0,s=Ne(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ei(s),e}function Gf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(kc)}catch(e){console.error(e)}}kc(),ku.exports=xe;var qf=ku.exports,xc,su=qf;xc=su.createRoot,su.hydrateRoot;const Sc="bv.access",Gi="bv.refresh";function Js(e){try{return localStorage.getItem(e)||""}catch{return""}}function iu(e,t){try{t?localStorage.setItem(e,t):localStorage.removeItem(e)}catch{}}function ir(){return{access:Js(Sc),refresh:Js(Gi)}}function Yi(e,t){iu(Sc,e),iu(Gi,t)}function or(){Yi("","")}function bf(){return!!Js(Gi)}class bn extends Error{constructor(t,n,r){super(r),this.status=t,this.code=n}}let Sn=null;async function El(){return Sn||(Sn=(async()=>{const{refresh:e}=ir();if(!e)throw new bn(401,"unauthorized","Signed out.");const t=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e})});if(!t.ok)throw or(),new bn(t.status,"unauthorized","Your session has ended. Sign in again.");const n=await t.json();return Yi(n.access_token,n.refresh_token),n})().finally(()=>{Sn=null}),Sn)}async function G(e,t,n,r=!0){const{access:l}=ir(),s={};l&&(s.Authorization="Bearer "+l),n!==void 0&&(s["Content-Type"]="application/json");const i=await fetch(t,{method:e,headers:s,body:n===void 0?void 0:JSON.stringify(n)});if(i.status===204)return null;const u=await i.text();let a=null;try{a=u?JSON.parse(u):null}catch{}if(i.ok)return a;const c=(a==null?void 0:a.error)||"";if(c==="token_expired"&&r)return await El(),G(e,t,n,!1);throw i.status===401&&or(),new bn(i.status,c,(a==null?void 0:a.message)||`Something went wrong (${i.status}).`)}async function jc(e,t=!0){const{access:n}=ir(),r=await fetch(e,{headers:n?{Authorization:"Bearer "+n}:{}});if(r.ok)return URL.createObjectURL(await r.blob());let l=null;try{l=await r.json()}catch{}const s=(l==null?void 0:l.error)||"";if(s==="token_expired"&&t)return await El(),jc(e,!1);throw r.status===401&&or(),new bn(r.status,s,(l==null?void 0:l.message)||`That picture could not be loaded (${r.status}).`)}const Ft=e=>{const t=new URLSearchParams;for(const[r,l]of Object.entries(e||{}))l!=null&&l!==""&&t.set(r,l);const n=t.toString();return n?"?"+n:""},J={async login(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:t})}),r=await n.json().catch(()=>null);if(!n.ok)throw new bn(n.status,(r==null?void 0:r.error)||"",(r==null?void 0:r.message)||"Could not sign in.");return Yi(r.access_token,r.refresh_token),r.user},async logout(){try{await G("POST","/api/auth/logout")}catch{}or()},me:()=>G("GET","/api/auth/me"),sites:()=>G("GET","/api/sites"),arrivals:e=>G("GET","/api/visits"+Ft(e)),visitors:(e,t=50)=>G("GET","/api/visitors"+Ft({q:e,limit:t})),visitorHistory:(e,t=50)=>G("GET",`/api/visitors/${encodeURIComponent(e)}/history`+Ft({limit:t})),saveProfile:(e,t)=>G("PUT",`/api/visitors/${encodeURIComponent(e)}/profile`,t),footfall:e=>G("GET","/api/reports/footfall"+Ft(e)),conversion:e=>G("GET","/api/reports/conversion"+Ft(e)),cameras:()=>G("GET","/api/cameras"),cameraSnapshot:e=>jc(e),createCamera:(e,t)=>G("POST",`/api/sites/${encodeURIComponent(e)}/cameras`,t),updateCamera:(e,t)=>G("PATCH",`/api/cameras/${encodeURIComponent(e)}`,t),deleteCamera:e=>G("DELETE",`/api/cameras/${encodeURIComponent(e)}`),checkCamera:(e,t,n)=>G("POST",`/api/cameras/${encodeURIComponent(e)}/check`,{kind:t,...n?{seconds:n}:{}}),siteCheck:e=>G("GET",`/api/sites/${encodeURIComponent(e)}/check`),enrolmentCode:(e,t)=>G("POST",`/api/sites/${encodeURIComponent(e)}/enrolment-code`,t||{}),ask:e=>G("POST","/api/assistant",{history:e}),clients:()=>G("GET","/api/admin/clients"),createClient:e=>G("POST","/api/admin/clients",e)};function ep({cursor:e,siteId:t,onPage:n,onError:r,signal:l}){let s=!1,i=e||"";return(async()=>{for(;!s;){try{const{access:a}=ir(),c=await fetch("/api/visits/stream"+Ft({cursor:i,site_id:t}),{headers:{Authorization:"Bearer "+a,Accept:"text/event-stream"},signal:l});if(c.status===401){await El();continue}if(!c.ok||!c.body)throw new Error("stream unavailable");const m=c.body.getReader(),v=new TextDecoder;let h="";for(;!s;){const{value:y,done:k}=await m.read();if(k)break;h+=v.decode(y,{stream:!0});let w;for(;(w=h.indexOf(` + +`))!==-1;){const T=h.slice(0,w);h=h.slice(w+2);for(const p of T.split(` +`))if(p.startsWith("id: "))i=p.slice(4).trim();else if(p.startsWith("data: "))try{n(JSON.parse(p.slice(6)))}catch{}}}}catch(a){if(s||l!=null&&l.aborted)return;r==null||r(a)}if(s)return;await new Promise(a=>setTimeout(a,3e3))}})(),()=>{s=!0}}function tp({cameraId:e,img:t,onState:n,signal:r}){let l=!1;return(async()=>{for(;!l;){try{const{access:i}=ir(),u=await fetch(`/api/cameras/${e}/live`,{headers:{Authorization:"Bearer "+i,Accept:"text/event-stream"},signal:r});if(u.status===401){await El();continue}if(!u.ok||!u.body)throw new Error("live view unavailable");const a=u.body.getReader(),c=new TextDecoder;let m="";for(;!l;){const{value:v,done:h}=await a.read();if(h)break;m+=c.decode(v,{stream:!0});let y;for(;(y=m.indexOf(` + +`))!==-1;){const k=m.slice(0,y);m=m.slice(y+2);let w="message",T="";for(const p of k.split(` +`))p.startsWith("event: ")?w=p.slice(7).trim():p.startsWith("data: ")&&(T=p.slice(6));w==="frame"&&T?(t.current&&(t.current.src="data:image/jpeg;base64,"+T),n==null||n("live")):w==="waiting"&&(n==null||n("waiting"))}}}catch{if(l||r!=null&&r.aborted)return;n==null||n("reconnecting")}if(l)return;await new Promise(i=>setTimeout(i,1500))}})(),()=>{l=!0}}function np({onSignedIn:e}){const[t,n]=N.useState(""),[r,l]=N.useState(""),[s,i]=N.useState(""),[u,a]=N.useState(!1),c=async m=>{m.preventDefault(),a(!0),i("");try{await J.login(t.trim(),r),e(await J.me())}catch(v){i(v.message),a(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:c,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:"Behavision"}),o.jsx("p",{className:"sub",children:"Sign in to your company account."}),o.jsxs("label",{children:["Email",o.jsx("input",{type:"email",value:t,autoComplete:"username",autoFocus:!0,required:!0,onChange:m=>n(m.target.value),placeholder:"you@company.com"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:r,autoComplete:"current-password",required:!0,onChange:m=>l(m.target.value)})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),o.jsx("button",{className:"primary",disabled:u||!t||!r,children:u?"Signing in…":"Sign in"}),o.jsx("p",{className:"foot",children:"Accounts are created by Loyaly. Ask your account manager if you need one."})]})})}function er(e,t,n=[]){const[r,l]=N.useState(null),[s,i]=N.useState(null),[u,a]=N.useState(!0),c=N.useRef(!1),m=N.useRef(!0),v=N.useCallback(async()=>{if(!c.current){c.current=!0;try{const h=await e();if(!m.current)return;l(h),i(null)}catch(h){if(!m.current)return;i(h)}finally{c.current=!1,m.current&&a(!1)}}},n);return N.useEffect(()=>{if(m.current=!0,v(),!t)return()=>{m.current=!1};const h=setInterval(v,t);return()=>{m.current=!1,clearInterval(h)}},[v,t]),{data:r,error:s,loading:u,reload:v}}function rp(e){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!e){n(null);return}let r=!0,l=null;return J.cameraSnapshot(e).then(s=>{if(!r){URL.revokeObjectURL(s);return}l=s,n(s)}).catch(()=>{r&&n(null)}),()=>{r=!1,l&&URL.revokeObjectURL(l)}},[e]),t}function Cc({url:e,alt:t}){const n=typeof e=="string"&&e.startsWith("/"),r=rp(n?e:null),l=n?r:e;return l?o.jsx("img",{src:l,alt:t,loading:"lazy"}):null}function lp({site:e,onClose:t}){const[n,r]=N.useState(null),[l,s]=N.useState(!1),[i,u]=N.useState(""),a=async()=>{s(!0),u(""),r(null);try{r(await J.siteCheck(e.site_id))}catch(c){u(c.message)}finally{s(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsxs("h2",{children:["Is ",e.name," working?"]}),o.jsx("p",{className:"sub",children:"Checks the whole chain, from the shop’s PC to head office."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[!n&&!l&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Nothing is changed and no one is disturbed — this reads what the shop has already reported."}),o.jsx("button",{className:"primary",onClick:a,children:"Run the check"})]}),l&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsx("b",{children:"Checking…"})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"banner "+(n.ok?"ok":"warn"),children:o.jsxs("div",{children:[o.jsx("b",{children:n.ok?"This shop is working.":"This shop needs attention."}),!n.ok&&o.jsx(o.Fragment,{children:" Work down the list — the first failure usually explains the rest."})]})}),o.jsx("ol",{className:"checklist",children:n.steps.map(c=>o.jsxs("li",{className:c.status,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:c.status==="pass"?"✓":c.status==="fail"?"✕":c.status==="warn"?"!":"–"}),o.jsxs("div",{children:[o.jsx("b",{children:c.name}),o.jsx("span",{className:"sub",children:c.detail}),c.advice&&o.jsx("span",{className:"advice-line",children:c.advice})]})]},c.name))}),o.jsx("button",{className:"ghost",onClick:a,children:"Check again"})]}),o.jsx(sp,{site:e})]})]})})}function sp({site:e}){const[t,n]=N.useState(null),[r,l]=N.useState(!1),[s,i]=N.useState(""),[u,a]=N.useState(""),c=async()=>{l(!0),i("");try{n(await J.enrolmentCode(e.site_id,{label:u.trim()}))}catch(m){i(m.message)}finally{l(!1)}};return o.jsxs("section",{className:"claim",children:[o.jsx("h3",{children:"Set up a shop PC"}),t?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"code","aria-live":"polite",children:t.code}),o.jsxs("p",{className:"sub",children:["Copy this now — it cannot be shown again. It works once, and stops working ",op(t.expires_at),"."]}),o.jsxs("div",{className:"row",children:[o.jsx("button",{className:"ghost",onClick:()=>ip(t.code),children:"Copy"}),o.jsx("button",{className:"ghost",onClick:()=>n(null),children:"Done"})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Creates a one-time code to type into Behavision on the shop’s computer. Use one for a new shop, a replacement PC, or a reinstall."}),o.jsxs("label",{className:"field",children:[o.jsx("span",{children:"What is this PC? (optional)"}),o.jsx("input",{value:u,placeholder:"counter PC",onChange:m=>a(m.target.value)})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),o.jsx("button",{className:"ghost",onClick:c,disabled:r,children:r?"Creating…":"Create an installation code"})]})]})}function ip(e){var t;try{(t=navigator.clipboard)==null||t.writeText(e)}catch{}}function op(e){const t=new Date(e).getTime();if(Number.isNaN(t))return"shortly";const n=Math.round((t-Date.now())/864e5);return n<=0?"today":n===1?"tomorrow":`in ${n} days`}function up(){const{data:e,error:t,loading:n}=er(()=>J.sites(),2e4,[]),{data:r}=er(()=>J.cameras(),6e4,[]),[l,s]=N.useState(null),i=e||[];if(n&&!e)return o.jsx(_l,{});if(t)return o.jsx(Pl,{error:t});if(!i.length)return o.jsx(hp,{});const u=i.map(h=>{const y=(r||[]).filter(k=>k.site_id===h.site_id);return{site:h,cams:y,verdict:ap(h,y)}}),a=h=>u.filter(y=>y.verdict.tone===h).length,c=a("bad"),m=a("warn"),v=a("idle");return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Shops"}),o.jsxs("p",{className:"sub",children:[i.length," ",i.length===1?"shop":"shops",c>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[c," not working"]})]}),m>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"warn",children:[m," needing attention"]})]}),v>0&&o.jsxs(o.Fragment,{children:[" · ",v," not set up yet"]}),!c&&!m&&!v&&o.jsxs(o.Fragment,{children:[" · ",o.jsx("b",{className:"ok",children:"all working"})]})]})]}),o.jsx("div",{className:"grid sites",children:u.map(h=>o.jsx(dp,{site:h.site,cams:h.cams,verdict:h.verdict,onCheck:()=>s(h.site)},h.site.site_id))}),l&&o.jsx(lp,{site:l,onClose:()=>s(null)})]})}function ap(e,t){const n=e.fraction_below_gate,r=e.cameras_total||t.length;return e.online?e.dropped>0?{tone:"bad",mark:"✕",words:`${e.dropped} visits lost and unrecoverable`}:r===0?{tone:"idle",mark:"+",headline:"Not set up",words:"No cameras set up yet"}:e.cameras_up===0?{tone:"bad",mark:"✕",words:"No cameras connected"}:e.cameras_up.5?{tone:"bad",mark:"✕",words:`${qs(n)} of faces too poor to recognise`}:n>.2?{tone:"warn",mark:"!",words:`${qs(n)} of faces too poor to recognise`}:e.queued>0?{tone:"warn",mark:"!",words:`${e.queued} visits waiting to upload`}:{tone:"ok",mark:"✓",words:`Working — ${r} ${r===1?"camera":"cameras"} connected`}:{tone:"bad",mark:"✕",headline:"Offline",words:`Offline — last heard from ${un(e.last_heartbeat_at)}`}}const cp={ok:"Working",warn:"Needs attention",bad:"Not working",idle:"Not set up"};function dp({site:e,cams:t,verdict:n,onCheck:r}){const l=e.fraction_below_gate,s=n.tone,i=n.headline||cp[s],u=fp(t),a=e.cameras_total||t.length;return o.jsxs("article",{className:"card site state-"+s,onClick:r,role:"button",tabIndex:0,onKeyDown:c=>c.key==="Enter"&&r(),children:[o.jsxs("div",{className:"shot",children:[u.url?o.jsx(Cc,{url:u.url,alt:`View inside ${e.name}`}):o.jsxs("div",{className:"noshot",children:[o.jsx(pp,{}),u.reason&&o.jsx("span",{children:u.reason})]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.name}),o.jsx("span",{children:a>0?`${a} ${a===1?"camera":"cameras"}`:"No cameras yet"})]}),o.jsxs("span",{className:"status "+s,children:[o.jsx("i",{"aria-hidden":"true"}),i]})]}),u.at&&o.jsx("span",{className:"shot-age",children:un(u.at)})]}),o.jsxs("div",{className:"metrics",children:[o.jsx(ls,{label:"Cameras",value:a?`${e.cameras_up}/${a}`:"—",tone:a?e.cameras_up0?qs(1-l):"—",tone:l?l>.5?"bad":l>.2?"warn":"ok":"idle"}),o.jsx(ls,{label:"Last seen",value:un(e.last_heartbeat_at),tone:e.online?"ok":"bad"})]}),o.jsxs("div",{className:"verdict "+n.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:n.mark}),o.jsx("span",{className:"words",children:n.words}),o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}function ls({label:e,value:t,tone:n}){return o.jsxs("div",{className:"metric",children:[o.jsx("b",{className:n,children:t}),o.jsx("span",{children:e})]})}function fp(e){var r;if(!e.length)return{};let t=null;for(const l of e)!((r=l.snapshot)!=null&&r.available)||!l.snapshot.url||(!t||(l.snapshot_at||"")>(t.snapshot_at||""))&&(t=l);return t?{url:t.snapshot.url,at:t.snapshot_at}:{reason:e.map(l=>{var s;return(s=l.snapshot)==null?void 0:s.reason}).find(Boolean)||"No picture from this shop yet."}}function pp(){return o.jsxs("svg",{className:"shopmark",viewBox:"0 0 40 32","aria-hidden":"true",children:[o.jsx("path",{d:"M4 12h32v18H4z"}),o.jsx("path",{d:"M2 12l4-8h28l4 8"}),o.jsx("path",{d:"M15 30v-9h10v9"})]})}function qs(e){return`${Math.round(e*100)}%`}function un(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=Math.max(0,(Date.now()-t)/1e3);if(n<90)return"just now";const r=Math.round(n/60);if(r<60)return`${r} min ago`;const l=Math.round(r/60);return l<48?`${l} h ago`:`${Math.round(l/24)} days ago`}function _l(){return o.jsxs("div",{className:"state",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]})}function Pl({error:e}){return o.jsx("div",{className:"state",children:o.jsx("p",{className:"error",role:"alert",children:e.message})})}function hp(){return o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No shops yet"}),o.jsx("p",{className:"sub",children:"A shop appears here once its PC has been claimed with an enrolment code."})]})}const ou=60;function mp(){const[e,t]=N.useState([]),[n,r]=N.useState("connecting"),[l,s]=N.useState(null),i=N.useRef(new Set);return N.useEffect(()=>{const u=new AbortController;let a=()=>{};return(async()=>{try{const c=await J.arrivals({limit:30}),m=c.arrivals||[];m.forEach(v=>i.current.add(v.visit_id)),t(m.slice().reverse()),r("live"),a=ep({cursor:c.cursor,signal:u.signal,onPage:v=>{const h=(v.arrivals||[]).filter(y=>!i.current.has(y.visit_id));h.length&&(h.forEach(y=>i.current.add(y.visit_id)),r("live"),t(y=>[...h.reverse(),...y].slice(0,ou)))},onError:()=>r("reconnecting")})}catch(c){s(c)}})(),()=>{u.abort(),a()}},[]),l?o.jsx(Pl,{error:l}):n==="connecting"&&!e.length?o.jsx(_l,{}):o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Live"}),o.jsxs("p",{className:"sub",children:[o.jsx("span",{className:"dot "+(n==="live"?"ok":"warn"),"aria-hidden":"true"}),n==="live"?"Connected":"Reconnecting…"," · ","last ",ou," arrivals"]})]}),e.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"Nobody yet"}),o.jsx("p",{className:"sub",children:"Arrivals appear here the moment a camera recognises someone."})]}):o.jsx("ul",{className:"arrivals",children:e.map(u=>o.jsx(vp,{a:u},u.visit_id))})]})}function vp({a:e}){const t=e.name||e.label||"Unidentified";return o.jsxs("li",{className:"card arrival",children:[o.jsx(yp,{image:e.image,name:t}),o.jsxs("div",{className:"who-col",children:[o.jsx("strong",{children:t}),o.jsxs("span",{className:"sub",children:[e.site,e.camera_id?` · ${e.camera_id}`:""," · ",un(e.occurred_at)]}),e.attributes&&o.jsx(wp,{attrs:e.attributes})]}),e.is_new_visitor?o.jsx("span",{className:"pill new",children:"New"}):o.jsx("span",{className:"pill",children:"Returning"})]})}function yp({image:e,name:t}){return e!=null&&e.available?o.jsx("img",{className:"face",src:e.url,alt:"",loading:"lazy"}):o.jsx("span",{className:"face initials",title:(e==null?void 0:e.reason)||"","aria-hidden":"true",children:gp(t)})}function gp(e){const t=String(e).trim().split(/\s+/).filter(Boolean);return t.length?t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[t.length-1][0]).toUpperCase():"?"}function wp({attrs:e}){const t=[];return e.gender&&t.push(e.gender),e.age&&t.push(`~${Math.round(e.age)}`),e.emotion&&t.push(e.emotion),t.length?o.jsx("span",{className:"attrs",children:t.join(" · ")}):null}function kp({camera:e,onClose:t}){const n=N.useRef(null),[r,l]=N.useState("waiting"),[s,i]=N.useState(!1);N.useEffect(()=>{const c=new AbortController,m=tp({cameraId:e.id,img:n,onState:h=>{l(h),h==="live"&&i(!1)},signal:c.signal}),v=setTimeout(()=>i(!0),12e3);return()=>{m(),c.abort(),clearTimeout(v)}},[e.id]);const u=e.connected===!1?"This camera was not connecting when the shop PC last reported. Check it is powered on and reachable on the shop’s network.":e.connected==null?"The shop PC has not reported on this camera yet. It may still be starting up.":"The shop PC is not sending frames. It may be offline, or its Behavision app may not be running.",a=s&&r!=="live"?u:{waiting:"Asking the shop PC…",live:"Live · about 4 frames a second",reconnecting:"Reconnecting…"}[r];return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer live",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:e.label}),o.jsx("p",{className:"sub",children:e.site})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[o.jsxs("div",{className:"liveshot",children:[o.jsx("img",{ref:n,alt:`Live view from ${e.label}`}),r!=="live"&&o.jsx("div",{className:"livewait",children:o.jsx("span",{children:s?"No picture yet":a})})]}),o.jsx("p",{className:"hint",style:{marginTop:10},children:r==="live"?"Live · about 4 frames a second. The shop only uploads while this is open.":a})]})]})})}const Ur=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],uu=e=>Ur.find(t=>t.id===e)||Ur[Ur.length-1],xp=["Camera","Connection","Test","Walk past"];function Sp({sites:e,existing:t,onClose:n,onSaved:r}){var d;const l=!(t!=null&&t.id),[s,i]=N.useState(l?0:2),[u,a]=N.useState(t!=null&&t.id?t:null),[c,m]=N.useState({site_id:(t==null?void 0:t.site_id)||((d=e[0])==null?void 0:d.site_id)||"",make:"hikvision",label:(t==null?void 0:t.label)||"",host:(t==null?void 0:t.host)||"",port:(t==null?void 0:t.port)||554,path:(t==null?void 0:t.path)||"/Streaming/Channels/101",username:(t==null?void 0:t.username)||"",password:""}),[v,h]=N.useState(!1),[y,k]=N.useState(""),w=f=>g=>m(S=>({...S,[f]:g.target.value})),T=f=>{const g=uu(f.target.value);m(S=>({...S,make:g.id,path:g.path||S.path}))},p=async()=>{h(!0),k("");const f={};for(const[g,S]of Object.entries(c))g==="site_id"||g==="make"||S===""||S==null||(f[g]=g==="port"?Number(S):S);try{const g=u!=null&&u.id?await J.updateCamera(u.id,f):await J.createCamera(c.site_id,f);a(g),i(2),r==null||r(g,{keepOpen:!0})}catch(g){k(g.message)}finally{h(!1)}};return o.jsx("div",{className:"overlay",onClick:n,children:o.jsxs("aside",{className:"drawer wizard",onClick:f=>f.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:l?"Set up a camera":(u==null?void 0:u.label)||(t==null?void 0:t.label)}),o.jsx("p",{className:"sub",children:s<2?"The shop’s PC connects to the camera — nothing needs opening to the internet.":"Prove it works before you rely on it."})]}),o.jsx("button",{className:"ghost",onClick:n,children:"Close"})]}),o.jsx("ol",{className:"steps",children:xp.map((f,g)=>o.jsxs("li",{className:g===s?"now":go.jsx("option",{value:f.site_id,children:f.name},f.site_id))})]}),o.jsxs("label",{children:["What should staff call it?",o.jsx("input",{value:c.label,onChange:w("label"),placeholder:"Entrance",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Visits are recorded against this name, so it cannot be changed later."})]}),o.jsxs("label",{children:["Make of camera",o.jsx("select",{value:c.make,onChange:T,children:Ur.map(f=>o.jsx("option",{value:f.id,children:f.label},f.id))}),o.jsx("span",{className:"hint",children:uu(c.make).note||"This only fills in the stream path for you. You can change it on the next step."})]}),o.jsx("button",{className:"primary",disabled:!c.label.trim(),onClick:()=>i(1),children:"Next"})]}),s===1&&o.jsxs("div",{className:"drawer-body",children:[o.jsxs("label",{children:["Camera’s address on the shop’s network",o.jsx("input",{value:c.host,onChange:w("host"),placeholder:"192.168.0.138",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Not a website address. It usually starts 192.168. — look in the camera’s own app, on its label, or in your router’s device list."})]}),o.jsxs("div",{className:"pair",children:[o.jsxs("label",{children:["Port",o.jsx("input",{type:"number",value:c.port,onChange:w("port")})]}),o.jsxs("label",{children:["Stream path",o.jsx("input",{value:c.path,onChange:w("path")})]})]}),o.jsxs("label",{children:["Camera username",o.jsx("input",{value:c.username,onChange:w("username"),placeholder:"admin",name:"camera-account",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:"false"}),o.jsx("span",{className:"hint",children:"The camera’s own login, not your Behavision one."})]}),o.jsxs("label",{children:["Camera password",o.jsx("input",{type:"password",value:c.password,onChange:w("password"),name:"camera-secret",autoComplete:"new-password",placeholder:u!=null&&u.has_password?"(unchanged)":""})]}),y&&o.jsx("p",{className:"error",role:"alert",children:y}),o.jsxs("div",{className:"pair",children:[o.jsx("button",{className:"ghost",onClick:()=>i(0),children:"Back"}),o.jsx("button",{className:"primary",disabled:v||!c.host.trim(),onClick:p,children:v?"Saving…":"Save and test"})]})]}),s>=2&&u&&o.jsx(jp,{camera:u,step:s,onStep:i,onUpdated:f=>{a(f),r==null||r(f,{keepOpen:!0})},onEdit:()=>i(1),onDone:n})]})})}function jp({camera:e,step:t,onStep:n,onUpdated:r,onEdit:l,onDone:s}){const[i,u]=N.useState(e),[a,c]=N.useState(!1),[m,v]=N.useState(""),h=N.useRef(null);N.useEffect(()=>u(e),[e]);const y=i.check||{},k=y.state==="requested"||y.state==="running";N.useEffect(()=>{if(!k)return;let p=!0;const d=async()=>{try{const g=(await J.cameras()).find(S=>S.id===i.id);p&&g&&(u(g),r==null||r(g))}catch{}};return h.current=setInterval(d,4e3),()=>{p=!1,clearInterval(h.current)}},[k,i.id]);const w=async(p,d)=>{c(!0),v("");try{const f=await J.checkCamera(i.id,p,d);u(f),r==null||r(f),n(p==="placement"?3:2)}catch(f){v(f.message)}finally{c(!1)}},T=y.kind==="connection"&&y.state==="done"&&y.ok;return o.jsx(o.Fragment,{children:o.jsxs("div",{className:"drawer-body",children:[t===2?o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can the shop’s PC reach this camera?"}),o.jsx("p",{className:"sub",children:"The PC opens the stream once and takes a single picture. Nothing is recorded."})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can it actually recognise a face?"}),o.jsxs("p",{className:"sub",children:["Someone needs to ",o.jsx("b",{children:"walk through the camera’s view and out of it"}),", the way a customer would. Standing still measures nothing — the check scores the best view of each person as they leave the frame, which is what recognition really uses."]})]}),k&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("b",{children:y.state==="running"?"Running on the shop’s PC…":"Waiting for the shop’s PC…"}),o.jsx("span",{className:"sub",children:y.state==="running"?"This takes about "+(y.seconds||25)+" seconds.":"It picks up the request within a couple of minutes."})]})]}),y.state==="done"&&o.jsx(Cp,{check:y}),m&&o.jsx("p",{className:"error",role:"alert",children:m}),o.jsx("div",{className:"pair",children:t===2?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:l,children:"Change details"}),o.jsx("button",{className:"primary",disabled:a||k,onClick:()=>w("connection"),children:y.state==="done"?"Test again":"Test connection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:()=>n(2),children:"Back"}),o.jsx("button",{className:"primary",disabled:a||k,onClick:()=>w("placement",25),children:y.state==="done"?"Check again":"Start walk-past check"})]})}),t===2&&T&&!k&&o.jsx("button",{className:"primary",onClick:()=>n(3),children:"Next: prove it can recognise faces"}),t===3&&y.state==="done"&&!k&&o.jsx("button",{className:"ghost",onClick:s,children:"Finish"})]})})}function Cp({check:e}){var n,r,l;const t=e.ok?"ok":e.verdict==="marginal"?"warn":"bad";return o.jsxs("div",{className:"outcome "+t,children:[o.jsxs("div",{className:"outcome-head",children:[o.jsx("span",{className:"pill "+t,children:e.ok?"Working":"Not ready"}),o.jsx("b",{children:e.headline||(e.ok?"Working":"Could not be verified")})]}),((n=e.image)==null?void 0:n.available)&&o.jsx("img",{className:"proof",src:e.image.url,alt:"The view from this camera",loading:"lazy"}),((r=e.advice)==null?void 0:r.length)>0&&o.jsx("ul",{className:"advice",children:e.advice.map((s,i)=>o.jsx("li",{children:s},i))}),((l=e.detail)==null?void 0:l.faces)!=null&&o.jsxs("p",{className:"sub",children:[e.detail.faces," ",e.detail.faces===1?"person":"people"," walked past during the check."]})]})}function Np(e){const t=e.check||{};return t.state==="requested"||t.state==="running"?{tone:"idle",mark:"…",words:"Checking now"}:t.state!=="done"?{tone:"idle",mark:"?",words:"Not checked yet"}:t.kind==="placement"?t.ok?{tone:"ok",mark:"✓",words:"Recognises faces here"}:{tone:"bad",mark:"✕",words:t.headline||"Cannot recognise faces here"}:t.ok?{tone:"warn",mark:"!",words:"Stream works — faces not checked yet"}:{tone:"bad",mark:"✕",words:t.headline||"Could not reach the camera"}}function Ep({user:e}){const{data:t,error:n,loading:r,reload:l}=er(()=>J.cameras(),2e4,[]),{data:s}=er(()=>J.sites(),0,[]),[i,u]=N.useState(null),[a,c]=N.useState(null),m=["admin","owner","manager"].includes(e.role),v=t||[],h=v.filter(w=>w.connected).length,y=v.filter(w=>w.connected===!1).length,k=v.filter(w=>w.connected==null).length;return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Cameras"}),o.jsxs("p",{className:"sub",children:[v.length," ",v.length===1?"camera":"cameras",h>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"ok",children:[h," connected"]})]}),y>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[y," down"]})]}),k>0&&o.jsxs(o.Fragment,{children:[" · ",k," waiting for the shop PC"]})]}),m&&o.jsx("button",{className:"primary",onClick:()=>u({}),children:"Set up a camera"})]}),r&&!t?o.jsx(_l,{}):n?o.jsx(Pl,{error:n}):v.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No cameras yet"}),o.jsx("p",{className:"sub",children:"Add one here and the shop’s PC will pick it up within a couple of minutes. Cameras already set up on a shop PC appear here on their own."})]}):o.jsx("div",{className:"grid cams",children:v.map(w=>o.jsx(_p,{cam:w,canEdit:m,onEdit:()=>u(w),onWatch:()=>c(w)},w.id))}),i&&o.jsx(Sp,{existing:i.id?i:null,sites:s||[],onClose:()=>{u(null),l()},onSaved:(w,T)=>{T!=null&&T.keepOpen||u(null),l()}}),a&&o.jsx(kp,{camera:a,onClose:()=>c(null)})]})}function _p({cam:e,canEdit:t,onEdit:n,onWatch:r}){var u,a;const l=e.connected==null?"idle":e.connected?"ok":"bad",s=e.connected==null?"Waiting for the shop PC":e.connected?"Connected":"Not connecting",i=Np(e);return o.jsxs("article",{className:"card cam state-"+l,onClick:t?n:void 0,role:t?"button":void 0,tabIndex:t?0:void 0,onKeyDown:c=>t&&c.key==="Enter"&&n(),children:[o.jsxs("div",{className:"shot",children:[(u=e.snapshot)!=null&&u.available?o.jsx(Cc,{url:e.snapshot.url,alt:`View from ${e.label}`}):o.jsxs("div",{className:"noshot",children:[o.jsx("span",{className:"lens","aria-hidden":"true"}),((a=e.snapshot)==null?void 0:a.reason)||"No picture yet."]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.label||e.camera_id}),o.jsx("span",{children:e.site})]}),o.jsxs("span",{className:"status "+l,children:[o.jsx("i",{"aria-hidden":"true"}),s]})]}),e.snapshot_at&&o.jsx("span",{className:"shot-age",children:un(e.snapshot_at)}),o.jsxs("button",{className:"watch",title:"Watch this camera now",onClick:c=>{c.stopPropagation(),r()},children:[o.jsx("i",{"aria-hidden":"true"}),"Live"]})]}),o.jsxs("div",{className:"verdict "+i.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:i.mark}),o.jsx("span",{className:"words",children:i.words}),t&&o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}const Pp=["Is everything working today?","Why is footfall low at Chennai?","How many people came in last week?","Which cameras still need checking?"];function Tp({open:e,onClose:t}){const[n,r]=N.useState([]),[l,s]=N.useState(""),[i,u]=N.useState(!1),[a,c]=N.useState(!1),m=N.useRef(null),v=N.useRef(null);N.useEffect(()=>{var y;e&&((y=v.current)==null||y.focus())},[e]),N.useEffect(()=>{var y;(y=m.current)==null||y.scrollIntoView({behavior:"smooth",block:"end"})},[n,i]);const h=async y=>{const k=(y??l).trim();if(!k||i)return;const w=[...n,{role:"user",text:k}];r(w),s(""),u(!0);try{const T=await J.ask(w);r(p=>[...p,{role:"assistant",text:T.text,used:T.used}])}catch(T){T.code==="assistant_off"?c(!0):r(p=>[...p,{role:"assistant",text:T.message,failed:!0}])}finally{u(!1)}};return e?o.jsxs("aside",{className:"assistant",role:"complementary","aria-label":"Assistant",children:[o.jsxs("header",{className:"assistant-head",children:[o.jsxs("div",{children:[o.jsx("b",{children:"Ask Behavision"}),o.jsx("span",{className:"sub",children:"It reads your shops’ own data to answer."})]}),o.jsx("button",{className:"ghost",onClick:t,"aria-label":"Close assistant",children:"✕"})]}),o.jsxs("div",{className:"assistant-body",children:[a?o.jsx("p",{className:"sub pad",children:"The assistant is not switched on for this server."}):n.length===0?o.jsxs("div",{className:"suggest",children:[o.jsx("p",{className:"sub",children:"Try asking:"}),Pp.map(y=>o.jsx("button",{className:"chip",onClick:()=>h(y),children:y},y))]}):n.map((y,k)=>{var w;return o.jsxs("div",{className:"bubble "+y.role+(y.failed?" failed":""),children:[y.text,((w=y.used)==null?void 0:w.length)>0&&o.jsxs("span",{className:"used",children:["looked at: ",y.used.map(zp).join(", ")]})]},k)}),i&&o.jsxs("div",{className:"bubble assistant-thinking",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"})," Looking…"]}),o.jsx("div",{ref:m})]}),!a&&o.jsxs("form",{className:"assistant-ask",onSubmit:y=>{y.preventDefault(),h()},children:[o.jsx("input",{ref:v,value:l,onChange:y=>s(y.target.value),placeholder:"Ask about your shops…",disabled:i}),o.jsx("button",{className:"primary",disabled:i||!l.trim(),children:"Ask"})]})]}):null}function zp(e){return{list_shops:"your shops",check_shop:"a shop check",list_cameras:"your cameras",check_camera:"a camera check",footfall:"footfall",sales:"sales",find_customer:"customer records"}[e]||e}function Lp(){const{data:e,error:t,loading:n,reload:r}=er(()=>J.clients(),0,[]),[l,s]=N.useState(!1),[i,u]=N.useState(null),a=e||[];return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Companies"}),o.jsx("button",{className:"primary",onClick:()=>{u(null),s(!0)},children:"New company"})]}),i&&o.jsx(Op,{result:i,onDismiss:()=>u(null)}),n&&!e?o.jsx(_l,{}):t?o.jsx(Pl,{error:t}):a.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No companies yet"}),o.jsx("p",{className:"sub",children:"Create one, and its owner can sign in straight away."})]}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Company"}),o.jsx("th",{children:"Short name"}),o.jsx("th",{children:"Sites"}),o.jsx("th",{children:"People"}),o.jsx("th",{children:"Created"})]})}),o.jsx("tbody",{children:a.map(c=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:c.name})}),o.jsx("td",{children:o.jsx("code",{children:c.slug})}),o.jsx("td",{className:"num",children:c.sites}),o.jsx("td",{className:"num",children:c.users}),o.jsx("td",{className:"sub",children:un(c.created_at)})]},c.id))})]})}),l&&o.jsx(Rp,{onClose:()=>s(!1),onCreated:c=>{s(!1),u(c),r()}})]})}function Rp({onClose:e,onCreated:t}){const[n,r]=N.useState({company_name:"",owner_name:"",owner_email:"",password:""}),[l,s]=N.useState(!1),[i,u]=N.useState(""),a=m=>v=>r({...n,[m]:v.target.value}),c=async m=>{m.preventDefault(),s(!0),u("");try{t(await J.createClient(n))}catch(v){u(v.message),s(!1)}};return o.jsx("div",{className:"overlay",onClick:e,children:o.jsxs("aside",{className:"drawer narrow",onClick:m=>m.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"New company"}),o.jsx("button",{className:"ghost",onClick:e,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:c,children:[o.jsxs("label",{children:["Company name",o.jsx("input",{value:n.company_name,onChange:a("company_name"),required:!0,autoFocus:!0})]}),o.jsxs("label",{children:["Owner’s name",o.jsx("input",{value:n.owner_name,onChange:a("owner_name")})]}),o.jsxs("label",{children:["Owner’s email",o.jsx("input",{type:"email",value:n.owner_email,onChange:a("owner_email"),required:!0})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"text",value:n.password,onChange:a("password"),placeholder:"Leave empty to generate one"}),o.jsx("span",{className:"hint",children:"Generated is better — a password you invent for someone else ends up weak and sent over chat."})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:l,children:l?"Creating…":"Create company"})]})]})})}function Op({result:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:[e.slug," created."]})," These sign-in details are shown once and cannot be recovered. Send them to the owner now.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Email"}),o.jsx("dd",{children:o.jsx("code",{children:e.owner_email})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Password"}),o.jsx("dd",{children:o.jsx("code",{children:e.password})})]})]})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}const Ip=[{id:"sites",label:"Shops",View:up},{id:"live",label:"Live",View:mp},{id:"cameras",label:"Cameras",View:Ep}],Fp=[{id:"clients",label:"Companies",View:Lp}];function Dp(){const[e,t]=N.useState(null),[n,r]=N.useState(!0),[l,s]=N.useState("sites"),[i,u]=N.useState(!1);if(N.useEffect(()=>{(async()=>{if(bf())try{t(await J.me())}catch{or()}r(!1)})()},[]),n)return o.jsxs("div",{className:"boot",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]});if(!e)return o.jsx(np,{onSignedIn:t});const a=e.role==="admin"&&!e.client_id,c=a?Fp:Ip,m=c.find(y=>y.id===l)||c[0],v=m.View,h=async()=>{await J.logout(),t(null)};return o.jsxs("div",{className:"app",children:[o.jsxs("header",{className:"topbar",children:[o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"mark","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("strong",{children:"Behavision"}),o.jsx("span",{className:"org",children:e.client_name||"Loyaly platform"})]})]}),o.jsx("nav",{className:"tabs",children:c.map(y=>o.jsx("button",{onClick:()=>s(y.id),"aria-current":m.id===y.id?"page":void 0,children:y.label},y.id))}),o.jsxs("div",{className:"who",children:[o.jsxs("button",{className:"ask-btn"+(i?" on":""),onClick:()=>u(y=>!y),children:[o.jsx("span",{"aria-hidden":"true",children:"✳"})," Ask"]}),o.jsx("span",{className:"name",children:e.full_name||e.email}),o.jsx("span",{className:"role",children:a?"platform admin":e.role}),o.jsx("button",{className:"ghost",onClick:h,children:"Sign out"})]})]}),o.jsxs("div",{className:"with-assistant"+(i?" open":""),children:[o.jsx("main",{className:"page",children:o.jsx(v,{user:e})}),o.jsx(Tp,{open:i,onClose:()=>u(!1)})]})]})}xc(document.getElementById("root")).render(o.jsx(Dp,{})); diff --git a/server/internal/web/dist/index.html b/server/internal/web/dist/index.html index 0d40333..5389b89 100644 --- a/server/internal/web/dist/index.html +++ b/server/internal/web/dist/index.html @@ -5,8 +5,8 @@ Behavision - - + +
diff --git a/web/src/api.js b/web/src/api.js index 8914a10..528369c 100644 --- a/web/src/api.js +++ b/web/src/api.js @@ -261,3 +261,70 @@ export function streamArrivals({ cursor, siteId, onPage, onError, signal }) { run() return () => { stopped = true } } + +// streamCameraLive renders one camera's live view into an . +// +// Frames arrive base64 over SSE for the same reason the snapshot is fetched +// rather than linked: an cannot send an Authorization header, and minting +// a URL that works without a session — for LIVE video of a shop floor — would +// be a far worse trade than the 33% base64 costs. +// +// The frame is written straight into `img.src` as a data URL rather than an +// object URL. Object URLs would have to be revoked one per frame, several times +// a second, and a single missed revoke is a leak that grows for as long as the +// view is open. A data URL is owned by the element and replaced by the next one. +export function streamCameraLive({ cameraId, img, onState, signal }) { + let stopped = false + + const run = async () => { + while (!stopped) { + try { + const { access } = tokens() + const res = await fetch(`/api/cameras/${cameraId}/live`, { + headers: { Authorization: 'Bearer ' + access, Accept: 'text/event-stream' }, + signal, + }) + if (res.status === 401) { await refresh(); continue } + if (!res.ok || !res.body) throw new Error('live view unavailable') + + const reader = res.body.getReader() + const decoder = new TextDecoder() + let buf = '' + while (!stopped) { + const { value, done } = await reader.read() + if (done) break + buf += decoder.decode(value, { stream: true }) + let split + while ((split = buf.indexOf('\n\n')) !== -1) { + const chunk = buf.slice(0, split) + buf = buf.slice(split + 2) + let event = 'message', data = '' + for (const line of chunk.split('\n')) { + if (line.startsWith('event: ')) event = line.slice(7).trim() + else if (line.startsWith('data: ')) data = line.slice(6) + } + if (event === 'frame' && data) { + if (img.current) img.current.src = 'data:image/jpeg;base64,' + data + onState?.('live') + } else if (event === 'waiting') { + // The server has registered us; the shop PC has not started + // pushing yet. Saying so beats an empty box, because the wait is + // a real second or two while the agent is asked. + onState?.('waiting') + } + } + } + } catch (err) { + if (stopped || signal?.aborted) return + onState?.('reconnecting') + } + if (stopped) return + // The server caps one push so a tab left open for a week does not leave + // a shop uploading for a week. Reconnecting is how a viewer who IS still + // watching carries on, so this is a normal event, not an error. + await new Promise(r => setTimeout(r, 1500)) + } + } + run() + return () => { stopped = true } +} diff --git a/web/src/styles.css b/web/src/styles.css index ace010f..2cba8bd 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -497,3 +497,42 @@ button.ghost.danger:hover { border-color: var(--bad); } .assistant { width: 100%; height: 60vh; position: static; border-left: 0; border-top: 1px solid var(--line); } } + + +/* ------------------------------------------------------- live camera view */ +/* Deliberately a small affordance on the picture rather than a big play + button: opening it makes a shop PC start uploading, so it is an action + somebody chooses, not one a page does on their behalf. */ +.card.cam .watch { + position: absolute; left: 10px; top: 10px; z-index: 2; + display: inline-flex; align-items: center; gap: 6px; + padding: 4px 9px; border-radius: 999px; border: 0; cursor: pointer; + font: inherit; font-size: 11.5px; font-weight: 600; letter-spacing: .02em; + color: #fff; background: rgba(12, 16, 20, .72); + backdrop-filter: blur(6px); +} +.card.cam .watch:hover { background: rgba(12, 16, 20, .9); } +.card.cam .watch i { + width: 7px; height: 7px; border-radius: 50%; background: #E5484D; + box-shadow: 0 0 0 0 rgba(229, 72, 77, .7); + animation: livepulse 2s infinite; +} +@keyframes livepulse { + 70% { box-shadow: 0 0 0 6px rgba(229, 72, 77, 0); } + 100% { box-shadow: 0 0 0 0 rgba(229, 72, 77, 0); } +} +@media (prefers-reduced-motion: reduce) { + .card.cam .watch i { animation: none; } +} + +.drawer.live { max-width: 760px; } +.liveshot { + position: relative; background: #000; border-radius: 10px; overflow: hidden; + aspect-ratio: 16 / 9; +} +.liveshot img { width: 100%; height: 100%; object-fit: contain; display: block; } +.livewait { + position: absolute; inset: 0; display: grid; place-items: center; + font-size: 13px; color: rgba(255, 255, 255, .78); + background: rgba(0, 0, 0, .35); +} diff --git a/web/src/views/CameraLive.jsx b/web/src/views/CameraLive.jsx new file mode 100644 index 0000000..38fdef3 --- /dev/null +++ b/web/src/views/CameraLive.jsx @@ -0,0 +1,85 @@ +import { useEffect, useRef, useState } from 'react' +import { streamCameraLive } from '../api.js' + +// The live view of one camera. +// +// It is a few frames a second, not video, and the label says so rather than +// letting somebody conclude the camera is stuttering. That is the honest limit +// of relaying through the agent's outbound connection; true 25 fps would need +// WebRTC and a TURN server, which is a different piece of infrastructure. +// +// **Nothing is uploaded from the shop until this component is mounted**, and it +// stops within seconds of it going away. That is the whole reason a live view +// is affordable at all, and why this is a deliberate action rather than +// something every camera card does on its own. +export default function CameraLive({ camera, onClose }) { + const img = useRef(null) + const [state, setState] = useState('waiting') + // Nothing has arrived after a sensible wait. Its own state, because "the + // shop PC has not answered" is a different thing to tell somebody than + // "connecting", and leaving a spinner up forever tells them nothing at all. + const [stalled, setStalled] = useState(false) + + useEffect(() => { + const ctrl = new AbortController() + const stop = streamCameraLive({ + cameraId: camera.id, img, + onState: s => { setState(s); if (s === 'live') setStalled(false) }, + signal: ctrl.signal, + }) + // Generous: the server holds the agent's poll, the agent then has to reach + // the camera, and a cold start is a couple of seconds even when everything + // works. + const t = setTimeout(() => setStalled(true), 12000) + return () => { stop(); ctrl.abort(); clearTimeout(t) } + }, [camera.id]) + + // What to say when nothing arrives. The two causes need different actions - + // one is the camera, the other is the PC - so they must not share a message. + const stalledNote = camera.connected === false + ? 'This camera was not connecting when the shop PC last reported. Check it is powered on and reachable on the shop’s network.' + : camera.connected == null + ? 'The shop PC has not reported on this camera yet. It may still be starting up.' + : 'The shop PC is not sending frames. It may be offline, or its Behavision app may not be running.' + + const note = stalled && state !== 'live' + ? stalledNote + : { + waiting: 'Asking the shop PC…', + live: 'Live · about 4 frames a second', + reconnecting: 'Reconnecting…', + }[state] + + return ( +
+ +
+ ) +} diff --git a/web/src/views/Cameras.jsx b/web/src/views/Cameras.jsx index df8bb6a..f8998b6 100644 --- a/web/src/views/Cameras.jsx +++ b/web/src/views/Cameras.jsx @@ -2,6 +2,7 @@ import { useState } from 'react' import { api } from '../api.js' import { usePolled } from '../hooks.js' import Shot from './Shot.jsx' +import CameraLive from './CameraLive.jsx' import { ago, Loading, Problem } from './Sites.jsx' import CameraSetup from './CameraSetup.jsx' @@ -39,6 +40,10 @@ export default function Cameras({ user }) { usePolled(() => api.cameras(), 20000, []) const { data: sites } = usePolled(() => api.sites(), 0, []) const [editing, setEditing] = useState(null) + // Only one camera streams at a time, on purpose. Every open view makes a + // shop PC upload, so a grid that went live all at once would put an estate's + // worth of cameras on the wire because somebody opened a page. + const [watching, setWatching] = useState(null) const canEdit = ['admin', 'owner', 'manager'].includes(user.role) const list = cams || [] @@ -76,7 +81,8 @@ export default function Cameras({ user }) {
{list.map(c => ( setEditing(c)} /> + onEdit={() => setEditing(c)} + onWatch={() => setWatching(c)} /> ))}
) @@ -90,11 +96,15 @@ export default function Cameras({ user }) { onSaved={(_, opts) => { if (!opts?.keepOpen) setEditing(null); reload() }} /> )} + + {watching && ( + setWatching(null)} /> + )} ) } -function CameraCard({ cam, canEdit, onEdit }) { +function CameraCard({ cam, canEdit, onEdit, onWatch }) { // Three states, not two. A camera nobody has tried yet is not a camera that // is down, and telling an operator to check the cabling on a camera the shop // PC has not even seen sends them to the wrong building. @@ -136,6 +146,18 @@ function CameraCard({ cam, canEdit, onEdit }) { {cam.snapshot_at && ( {ago(cam.snapshot_at)} )} + + {/* Always offered, including when this card says the camera is down. + `connected` is head office's LAST REPORT and can be two minutes + stale, so gating on it hid the button during every reconnect - and + "is that camera really down?" is precisely the moment somebody wants + to look. A hidden control says "you cannot" when the honest answer + is "here is why", which the live view itself can give. + stopPropagation because the card itself opens Edit. */} +