App · project 14 of 37
Clutch Coach.
A coach uploads a phone video and gets one player's shooting, movement and form, with time-tagged fixes and drills.
BeforeA clipboard tally of makes and misses, and a phone full of practice video nobody has time to watch back.
AfterOne player's report from that video: makes and misses by zone, distance and speed, and every form slip tagged to the second with its drill.
What it is worthEvery shot, sprint and form fix found and timed, with the correction drawn on the video, free and on your own device. Instead of counting shots by hand and scrubbing through video to find the one rep worth talking about.
How to use it
- Press Show me how for the 30-second tour of the sample report, then tap any coaching moment to watch that rep with the fix drawn on it.
- Film from the side: phone on a tripod level with the free-throw line, about 15 ft back, landscape, the whole player and the rim in view. Upload the video.
- Tap 1 Mark the hoop (tap the rim and size the ring), 2 Mark the court (the four corners of the paint, then the court type) and 3 Pick the player, then press Build report and keep the tab open.
- Read the report: field goals and the shot chart, distance and speed, the form scorecard against its targets, and the coaching moments with their drills. Answer Yes or No on any shot it could not credit by itself.
- Download the report for the player or copy the summary; open Clips to play the clips back to back or export a video.
Where it helps most
- A youth or school coach who wants one player's shooting numbers and form fixes from practice video, without sensors or a paid service.
- A parent or player working on a shot at home: the same drill filmed each week shows whether the arc, the drift and the trigger are improving.
- A trainer who wants time-tagged clips of the exact reps to talk through, with the correction already drawn.
The idea
It started at a youth basketball game, when another parent said someone should make an app that finds your kid's highlights. I built that first: a reel cut from the crowd noise and the plays. Then I changed my mind. A coach does not need a highlight reel; a coach needs to know, one player at a time, how many shots went in, from where, how hard the player worked and what is wrong with the shot, with what to do about it. The tools that do this today want sensors in the gym, a paid upload service or someone keeping score on every play. I wanted it from the phone video a parent or coach already has, for free.
The build
Claude built it as one page that runs entirely in the browser. A vision model (YOLOv8n from Ultralytics, run with onnxruntime-web in a Web Worker) finds the people four times a second, and the coach's tap starts a tracker that follows one player by look and path. Shots are counted at about 30 frames a second in the hoop's own coordinates: the rim is re-found every frame by template matching, the ball is found from the difference between frames, and a make is called when the ball is seen inside the rim. The ball's flight is traced back from the rim to where it left the hands, which says who shot and from where; the four paint corners turn the picture into a court map in feet, corrected when the camera pans or zooms. Form comes from physics: one gravity curve is fitted to the flight (the rim's width in pixels sets the scale), which gives the entry angle, and the player's own height is the ruler for release height and drift. It was tuned on free shooting videos from GitHub, checked by eye frame by frame, and on a synthetic 76-second workout with 12 shots and six planted mistakes: all 12 shots found with make or miss right, 5 of 7 planted mistakes flagged at the right second, release time within 0.05 s, shot spots about 2 ft off. A 'Show me how' tour walks through the sample report. Limits, honestly: the far-corner three lands about 5 ft off; filmed from behind, most releases cannot be read, so film from the side; teammates in the same jersey can swap; counting shots plays the video at normal speed and the full analysis took about 4 times the video's length on a laptop, so a 40-minute game is slow; form flags have not yet been proven on real players who have the mistakes. The version that runs inside Claude also asks Claude for form feedback from still frames and a written improvement plan; those need claude.ai and are hidden here. The vision model's weights are AGPL-3.0, so they will be swapped for an Apache-licensed model before anything is sold. On iPhones the page asks for playback audio on the first tap, so the reel's sound plays even on silent.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: Clutch Coach
You are a computer-vision engineer, a front-end developer and a basketball shooting coach. Build "Clutch Coach": a free web page that turns one phone video of a basketball workout or game into a report on ONE player: shooting, shot locations, movement and shooting form, with time-tagged coaching fixes and drills. Everything runs in the browser; nothing is uploaded.
DELIVERABLE
- One page (index.html, one CSS file, one JS file) plus local files: onnxruntime-web 1.22.0 (wasm build, single thread) in vendor/, the YOLOv8n COCO model exported to ONNX (input images 1x3x640x640, output 1x84x8400) stored as base64 inside model/yolov8n.json, local woff2 fonts, a sample video with its precomputed analysis and its truth file. No CDN.
- It must run under a strict Content-Security-Policy: no inline scripts. The detector runs in a Web Worker started from a blob: URL that importScripts the vendor files, so the policy needs worker-src blob: and script-src 'wasm-unsafe-eval'.
- Videos are loaded as blob: URLs so seeking works without server range support. Hidden working videos stay rendered (2 px, opacity 0.01), never display:none, or their frames stop updating.
SETUP: THREE TAPS
1. Mark the hoop: tap the rim, size a ring to it with a slider, save.
2. Mark the court: tap the 4 corners of the paint in order and pick the court type (high school, college, NBA, FIBA) so the paint's size in feet is known. Reject 4 taps that do not make a usable shape, with a message.
3. Pick the player: tap them on a detected box; ask for a jersey number and an optional name and team.
Then Build report. Show a progress panel with the steps (scanning frames, tracking the player, watching the rim, working out who shot and how far they ran), frames done, players seen and time left.
THE ENGINE
- Vision: YOLOv8n finds people and the ball 4 times a second (persons > 0.28, ball > 0.12, NMS). Cap the samples so long videos stay bounded.
- Tracking: build tracklets by greedy matching with camera-pan compensation; end a tracklet at an ambiguous crossing instead of guessing; chain tracklets outward from the coach's tap with a torso colour signature; re-find the player only by an unmistakable look.
- Shots: play the video at normal speed with requestVideoFrameCallback. Every frame, re-find the hoop by ZNCC template matching (multi-scale global search when lost) and work in hoop-aligned coordinates. Find the ball with a three-frame difference plus size, shape and fill filters. A make: the ball seen inside the rim area at least twice, or seen above the rim followed by net motion above 0.35.
- Who shot and from where: keep a ring buffer of half-size frames and trace the ball backward from its first sighting above the rim to the end of its rising arc (the release). The shooter is the person nearest the release point: credit automatically when sure, otherwise ask the coach Yes or No.
- Court map: a 4-point homography from the paint corners, corrected for pan and zoom from the hoop's position and size. Shot spot = the shooter's feet at release. Zones: paint, mid-range, corner three, above-the-break three.
- Movement: from the player's feet on the court map: distance, top 1-second speed, sprints (1 s at 13 ft/s or more), time in each zone.
FORM, FROM PHYSICS
- Release = the end of the ball's fastest climb before the apex. Fit one parabola to the flight with gravity's curvature set by the rim's pixel width (the rim is 18 in). Ignore frames where the ball is cut off at the top of the picture or tangled in the rim, and only accept a release above the shoulders.
- Entry angle: with the court marked, atan((16.1 T^2 - 3) / (D - 1.5)) from flight time T and distance D; without it, read the slope off the picture only if the camera is side-on (gravity check and sideways-travel check). Skip, never guess, when the release is hidden.
- Release height = (feet - release point) / standing height. Drift = feet before the jump vs after landing. Catch to release = time since the run into the spot ended.
- Targets: entry angle 40 degrees or more (45 ideal), release 0.8x height or more, drift 2 ft or less (2.5 without the court), catch to release 1.2 s or less. Also flag walking between spots (9 ft or more, 2.5 s or more, never faster than 7.5 ft/s).
- Each missed target becomes a coaching moment tied to its time: title, what was measured, the fix in plain words, a drill and the reps. Also mark good reps.
THE REPORT
- Hero: form score ring, player name, the top flags as chips, field goals, entry angle, drift, top speed.
- Video stage with an AI view (boxes, the ball's trace, the correction drawn on the frame), Player Cam, slow-mo and full screen; a session timeline with lanes for shots, pace and fixes; click anywhere to jump.
- Coaching moments as cards with All, Fixes and Good filters; tapping one plays that rep with its correction drawn.
- Player report rail: shooting by zone, a shot chart on a drawn court, a heat map, the form scorecard with target bands, priorities with drills, a quick read, the shot list with Yes and No for uncredited shots. Download the report as a stand-alone HTML page; copy a short summary.
- Clips tab: clips around each shot and burst, Tight, Standard and Generous sizes, play back to back, export a 16:9 or 9:16 video with MediaRecorder (MP4 where supported, else WebM), a CSV clip list.
- Tabs: Compare (what coaches pay for player stats today, each price linked to its source page and dated), How it works (the steps plus the sample's measured accuracy, computed live from the truth file), Status (what was checked, what was not, known bugs).
- A 'Show me how' tour: five steps that light the report, the setup, the timeline, a playing coaching moment and the report rail.
- iPhone: on the first tap set navigator.audioSession.type to 'playback' and loop a silent same-origin mp3 on older iPhones, so the reel's sound plays even on silent.
SAMPLE AND HONESTY
- Ship a synthetic side-on workout (one shooter, a passer, a FIBA court, real-gravity ball flights) with 12 shots and planted mistakes (a flat arc, fades, shooting on the move, a low release, a slow trigger, walking between reps), its exact truth file, and the app's precomputed analysis so the page opens with a finished report.
- Say plainly what is not proven: form flags on real players, footage filmed from behind, crowded games, long videos.
FINISH AND STRESS TEST
- Dark sports look (Barlow and Barlow Condensed, orange accent), works at 320x568, 393x700, 740x360 and 1366x800 with no sideways scroll; on phones the tap-to-mark controls sit below the picture, never over it.
- Re-run the sample from scratch and compare with its truth: shots found, make or miss, shot spots in feet, planted mistakes caught at the right second, false flags. Run it on free real shooting clips and check every release by eye on frame strips.
- Push every control: the rim slider at both ends, four taps on one spot, every court type, uploading a file the browser cannot play, fast repeated taps, every tab; no NaN, no negative distances, no console errors.
Get the code5 files, exactly as they run on this site · free under the MIT license
index.html343 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Clutch Coach: free basketball shot and form stats</title>
<meta name="description" content="Free and on your device: upload a basketball video, tap the rim, the paint and one player, and get makes, misses, a shot chart and form fixes.">
<link rel="icon" href="/favicon.svg">
<link rel="stylesheet" href="./coach.css">
</head>
<body>
<header class="top">
<a class="brand" href="#studio" aria-label="Clutch home">
<svg width="30" height="30" viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="14" fill="none" stroke="#FF5A1F" stroke-width="3"/><path d="M4 16h24M16 2c-5 4-5 24 0 28M16 2c5 4 5 24 0 28" fill="none" stroke="#FF5A1F" stroke-width="2"/></svg>
<b>CLUTCH</b><small>Coach</small>
</a>
<a class="home" href="/all/">Free tools ›</a>
<nav class="nav" aria-label="Sections">
<a href="#studio" data-view="studio">Report</a>
<a href="#plans" data-view="plans">Compare</a>
<a href="#how" data-view="how">How it works</a>
<a href="#status" data-view="status">Status</a>
</nav>
<div class="spacer"></div>
<span class="pill" id="enginePill"><span class="dot warn" id="engineDot"></span><span id="engineTxt">Loading on-device AI…</span></span>
</header>
<div class="main" role="main">
<!-- ============ STUDIO ============ -->
<section class="view" id="view-studio">
<div class="studio">
<div>
<section class="card hero" id="hero" hidden aria-label="Session summary"></section>
<div class="card setup">
<div class="source">
<div class="ic"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#8C96AA" stroke-width="2"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m10 9 5 3-5 3z" fill="#8C96AA"/></svg></div>
<div class="meta"><b id="srcName">Sample workout · #8 spot shooting</b><span id="srcSub">Synthetic practice footage · free to use</span></div>
</div>
<input type="file" id="fileIn" accept="video/*" hidden>
<button class="btn" id="uploadBtn" type="button"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 16V4m0 0-5 5m5-5 5 5M4 20h16"/></svg>Upload video</button>
<button class="btn" id="sampleBtn" type="button" hidden>Use sample workout</button>
<button class="btn ghost" id="tourBtn" type="button">Show me how</button>
</div>
<div class="card setup steps3" role="group" aria-label="Set up the report">
<button class="stepbtn" id="hoopBtn" type="button"><i>1</i><span><b id="hoopTxt">Mark the hoop</b><small>Tap the rim once</small></span></button>
<button class="stepbtn" id="courtBtn" type="button"><i>2</i><span><b id="courtTxt">Mark the court</b><small>Tap the 4 corners of the paint</small></span></button>
<button class="stepbtn" id="followBtn" type="button"><i>3</i><span><b id="followTxt">Pick the player</b><small>Tap them once</small></span></button>
<button class="btn primary" id="analyzeBtn" type="button"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><path d="M4 12h3l2-6 4 12 2-6h5"/></svg><span id="analyzeTxt">Build report</span></button>
</div>
<div class="card stagewrap">
<div class="stage" id="stage">
<canvas id="view"></canvas>
<div class="hud" id="hud"></div>
<div class="livehud" id="liveHud" hidden></div>
<div class="coachcard" id="coachCard" hidden></div>
<div class="drop">Drop a game video</div>
<div class="pickbar" id="pickbar" hidden><span id="pickMsg">Tap the player you want to follow</span><span id="hoopCtl" hidden><label for="rimSize" class="sr">Rim size</label><input type="range" id="rimSize" min="1.5" max="14" step="0.1" value="5" aria-label="Rim size"><button class="btn sm primary" id="hoopSave" type="button">Save hoop</button></span><span id="courtCtl" hidden><label for="courtStd" class="sr">Court type</label><select id="courtStd" aria-label="Court type"></select><button class="btn sm ghost" id="courtUndo" type="button">Undo</button><button class="btn sm primary" id="courtSave" type="button" disabled>Save court</button></span><button class="btn sm ghost" id="pickCancel" type="button">Cancel</button></div>
<div class="scan" id="scan" hidden>
<div class="scanbox">
<h3 id="scanTitle">Analyzing game</h3>
<ol class="steps" id="steps">
<li data-s="vision"><i></i>Scanning frames for players and the ball</li>
<li data-s="track"><i></i>Tracking your player</li>
<li data-s="shots"><i></i>Watching the rim for makes and misses</li>
<li data-s="score"><i></i>Working out who shot, from where, and how far they ran</li>
</ol>
<div class="bar"><b id="scanBar"></b></div>
<div class="scanstats num"><span id="scanFrames">0 frames</span><span id="scanPeople">0 players seen</span><span id="scanEta"></span></div>
</div>
</div>
</div>
<div class="transport">
<button class="iconbtn" id="playBtn" type="button" aria-label="Play"><svg id="playIc" width="18" height="18" viewBox="0 0 24 24" fill="#EDF1F7"><path d="M7 4.5v15l13-7.5z"/></svg></button>
<button class="iconbtn" id="prevBtn" type="button" aria-label="Previous highlight"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#EDF1F7" stroke-width="2.2"><path d="M6 5v14M19 5l-9 7 9 7z"/></svg></button>
<button class="iconbtn" id="nextBtn" type="button" aria-label="Next highlight"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#EDF1F7" stroke-width="2.2"><path d="M18 5v14M5 5l9 7-9 7z"/></svg></button>
<span class="time num" id="timeTxt">0:00 / 0:00</span>
<div class="spacer"></div>
<button class="toggle" id="camToggle" type="button" aria-pressed="false"><span class="sw"></span>Player Cam</button>
<button class="toggle" id="aiToggle" type="button" aria-pressed="true"><span class="sw"></span>AI view</button>
<button class="toggle" id="slowToggle" type="button" aria-pressed="false"><span class="sw"></span>Slow-mo</button>
<button class="iconbtn" id="fsBtn" type="button" aria-label="Full screen"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#EDF1F7" stroke-width="2.2"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg></button>
</div>
<div class="tl">
<div class="tlhead">
<h3>Session timeline</h3>
<div class="legend"><span><i class="lg mk"></i>Make</span><span><i class="lg ms"></i>Miss</span><span><i class="lg" style="background:#56627c"></i>Walk</span><span><i class="lg" style="background:#2EE6C5"></i>Jog</span><span><i class="lg" style="background:#FFC24B"></i>Run</span><span><i class="lg" style="background:#FF5A1F"></i>Sprint</span><span><i class="lg fx"></i>Fix</span><span><i class="lg gd"></i>Good rep</span></div>
</div>
<canvas id="tl" aria-label="Session timeline. Click a marker to watch it, or anywhere to jump."></canvas>
</div>
</div>
<section class="card moments" id="momentsCard" hidden aria-labelledby="momentsH">
<div class="mhead">
<div><h2 id="momentsH">Coaching moments</h2><p id="momentsSub">Every moment is time-tagged. Tap one to watch it with the correction drawn on the video.</p></div>
<div class="seg" role="group" aria-label="Show"><button type="button" data-mf="all" aria-pressed="true">All</button><button type="button" data-mf="fix" aria-pressed="false">Fixes</button><button type="button" data-mf="good" aria-pressed="false">Good reps</button></div>
</div>
<div class="mlist" id="moments"></div>
</section>
</div>
<aside class="card rail" aria-label="Player report">
<div class="tabs" role="tablist">
<button role="tab" id="tabReport" aria-selected="true" aria-controls="paneReport" type="button">Player report</button>
<button role="tab" id="tabClips" aria-selected="false" aria-controls="paneClips" type="button">Clips</button>
</div>
<div id="paneReport" role="tabpanel" aria-labelledby="tabReport" class="pane">
<div class="list" id="report"><div class="empty">Loading…</div></div>
<div class="railfoot">
<div class="row">
<button class="btn" id="formBtn" type="button"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#c9b8ff" stroke-width="2"><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6"/></svg>Form feedback</button>
<button class="btn primary" id="planBtn" type="button">Improvement plan</button>
</div>
<div class="row">
<button class="btn" id="reportDl" type="button">Download report</button>
<button class="btn" id="reportCopy" type="button">Copy summary</button>
</div>
<button class="btn" id="verifyBtn" type="button" hidden><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#2EE6C5" stroke-width="2.2"><path d="M4 12l5 5L20 6"/></svg><span id="verifyTxt">Check the tracking with Claude</span></button>
</div>
</div>
<div id="paneClips" role="tabpanel" aria-labelledby="tabClips" class="pane" hidden>
<div class="railhead">
<div class="tiles">
<div class="tile"><b class="num" id="tClips">0</b><span>clips</span></div>
<div class="tile"><b class="num" id="tReel">0:00</b><span>reel length</span></div>
<div class="tile trk"><b class="num" id="tPlayer">–</b><span id="tPlayerLbl">your player in</span></div>
</div>
<div class="stats num" id="shotStats" hidden></div>
<div class="filters" role="group" aria-label="Reel size">
<button class="chip" data-size="tight" type="button" aria-pressed="false">Tight</button>
<button class="chip" data-size="standard" type="button" aria-pressed="true">Standard</button>
<button class="chip" data-size="generous" type="button" aria-pressed="false">Generous</button>
<button class="chip" id="mineOnly" type="button" aria-pressed="false">My player first</button>
</div>
</div>
<div class="list" id="list"><div class="empty">Build the report to cut clips.</div></div>
<div class="railfoot">
<button class="btn primary" id="reelBtn" type="button"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M7 4.5v15l13-7.5z"/></svg>Play clips back to back</button>
<div class="row">
<button class="btn" id="exportBtn" type="button">Export video</button>
<button class="btn" id="vertBtn" type="button">Export 9:16</button>
</div>
<div class="row">
<button class="btn" id="claudeBtn" type="button">Caption with Claude</button>
<button class="btn" id="recapBtn" type="button">Message to player</button>
</div>
<button class="btn ghost sm" id="csvBtn" type="button">Download clip list (CSV)</button>
</div>
</div>
</aside>
</div>
</section>
<!-- ============ PLANS ============ -->
<section class="view doc" id="view-plans" hidden>
<h1>What coaches pay for player stats</h1>
<p class="lead">Player stats today come from a scorekeeper, sensors or a paid upload service. Clutch Coach gets shooting, shot locations and movement for one player from an ordinary phone video, on the device, for $0. Prices were checked on Nov 22, 2026.</p>
<div class="tablewrap">
<table>
<thead><tr><th>Product</th><th>What coaches get</th><th>Price</th><th>Needs</th><th>Games</th><th>Coaching advice</th></tr></thead>
<tbody>
<tr class="us"><td><b>Clutch Coach (this prototype)</b></td><td>Makes and misses at the rim, shot chart by zone, who shot, distance run, top speed and sprints for one player; time-tagged form fixes with drills (the Claude version adds a form review and a week's practice plan)</td><td class="price">$0</td><td>Phone video, three taps of setup</td><td class="yes">Yes, plus workouts</td><td class="yes">Yes, per shot</td></tr>
<tr><td><a href="https://apps.apple.com/us/app/homecourt-basketball-training/id1258520424">HomeCourt</a></td><td>Live shot tracking from a phone during workouts, 100+ drills</td><td class="price">Free tier · $7.99/mo · $69.99/yr</td><td>Phone on a tripod at practice</td><td class="no">Workouts</td><td class="part">Drills, ratings</td></tr>
<tr><td><a href="https://apps.apple.com/au/app/superstat/id6760096828">Superstat</a></td><td>Upload a game; box score, shot maps and highlights back within hours</td><td class="price">A$15–20/game · A$229.99/season (AU App Store)</td><td>Upload; waits hours</td><td class="yes">Yes</td><td class="part">AI insights</td></tr>
<tr><td><a href="https://www.softwareadvice.co.uk/software/653266/SportsVisio">SportsVisio</a></td><td>Upload; AI box score and player reels; sold mostly to leagues</td><td class="price">Per game, monthly or season packs</td><td>Upload; league account</td><td class="yes">Yes</td><td class="no">No</td></tr>
<tr><td><a href="https://www.hudl.com/pricing/club/basketball">Hudl</a></td><td>Team video and tagging; Assist stats are an add-on done by Hudl's staff</td><td class="price">$400–$1,600 per team/yr · Assist extra</td><td>Coach-run team account</td><td class="yes">Yes</td><td class="no">No</td></tr>
<tr><td><a href="https://www.shottracker.com/faq">ShotTracker</a></td><td>70+ live stats from sensors in the rafters, the ball and players' shoes</td><td class="price">About $45,000 to install (<a href="https://frontofficesports.com/shottrackers-new-backers/" style="color:var(--muted)">FOS</a>)</td><td>Sensors installed in the gym</td><td class="yes">Yes</td><td class="no">No</td></tr>
<tr><td><a href="https://gc.com/pricing/perfect-plan-finder">GameChanger</a></td><td>Box scores and season stats from a live scorebook</td><td class="price">$99.99/yr individual</td><td>Someone scoring every play</td><td class="yes">Yes</td><td class="no">No</td></tr>
</tbody>
</table>
</div>
<h2>Where the paid tools are still ahead</h2>
<div class="grid3">
<div class="box"><h3>Full box score</h3><p>Rebounds, assists, steals and turnovers need ball possession tracking for all ten players. Superstat, SportsVisio and ShotTracker have it; Clutch counts shots and movement for one player.</p></div>
<div class="box"><h3>Live in the gym</h3><p>HomeCourt and ShotTracker give numbers during practice. Clutch works on the video afterward, at about the video's length.</p></div>
<div class="box"><h3>No setup taps</h3><p>Paid tools find the court and hoop on their own. Clutch asks the coach for three taps, which is also what makes it free and accurate.</p></div>
</div>
</section>
<section class="view doc" id="view-status" hidden>
<h1>Status and checks</h1>
<p class="lead">Where Clutch Coach stands: what has been checked and how, what is still unchecked, and the known bugs.</p>
<h2>Tuned on free real footage</h2>
<p class="lead" style="margin-top:0">Before you film anything, the form engine was run on 5 free real shooting videos from GitHub (one outdoor shooter from 4 camera spots, and one indoor practice filmed from behind). Every release was checked by eye on frame strips.</p>
<div class="tablewrap"><table style="min-width:720px">
<thead><tr><th>Footage</th><th>Shots</th><th>Release found</th><th>Release point by eye</th><th>Entry angle</th><th>Physics check</th><th>Flags</th></tr></thead>
<tbody>
<tr><td>Outdoor, side-on, 4 clips (<a href="https://github.com/chonyy/basketball-shot-detection">chonyy</a>, <a href="https://github.com/chonyy/AI-basketball-analysis">chonyy</a>)</td><td class="num">23</td><td class="num yes">22</td><td class="yes">11 of 13 checked on the right frame; 2 off by 2 to 3 frames</td><td class="num">42° to 53° (median 47°)</td><td class="yes">Ball's fall matched gravity at the rim's scale within 20% on 22 of 22</td><td class="yes">None. Steady shooter, nothing to flag</td></tr>
<tr><td>Indoor practice, handheld, from behind (<a href="https://github.com/avishah3/AI-Basketball-Shot-Detection-Tracker">avishah3</a>)</td><td class="num">30</td><td class="num part">13</td><td class="part">3 of 6 checked right; dribbles were read as releases (fixed)</td><td class="part">2 shots; the rest skipped because the ball flies away from the lens</td><td class="part">Fails on most shots, so angles aren't read off the picture</td><td class="part">2 slow-trigger flags, not verified</td></tr>
</tbody>
</table></div>
<h2>What changed because of it</h2>
<ol class="read">
<li><b>Arc is now the angle the ball drops into the rim</b> (45° ideal, flagged under 40°). The old "4 ft over the rim" rule flagged almost every real shot: real mid-range shots peak 3 to 4 ft over the rim.</li>
<li><b>Release is found by fitting one gravity curve</b> to the flight, ignoring frames where the ball is cut off at the top of the picture or tangled in the rim, and only above the shoulders. Before, it marked the hip or the dribble on 4 of 14 real shots.</li>
<li><b>The angle has two sources.</b> With the court marked: flight time and distance (camera angle doesn't matter). Without it: read off the picture, but only when the camera is side-on and the ball's fall matches gravity.</li>
<li><b>The sample now uses real gravity.</b> The old sample's ball paths weren't physical, which hid the arc problem.</li>
<li><b>No court marks needed for drift and timing:</b> the player's height is the ruler, and the hoop's position corrects for a moving camera.</li>
<li><b>Fewer false flags:</b> release height only flags a push shot (under 0.8×, one real normal shot read 0.84×); drift target 2 ft.</li>
<li>Fixed a crash when you upload your own video after viewing the sample.</li>
</ol>
<h2>Checked on the sample</h2>
<div class="tablewrap"><table style="min-width:640px">
<thead><tr><th>What</th><th>Result</th><th>How it was checked</th></tr></thead>
<tbody>
<tr><td>Planted form mistakes</td><td class="yes">5 of 7 flagged at the right time</td><td>Flat arc (35° measured, true 36°), fade, shooting on the move, slow trigger and the walk. The low release in the far corner and one fade (release hidden) were skipped, not guessed.</td></tr>
<tr><td>False coaching flags</td><td class="part">1 in 4 clean jump shots</td><td>A slow trigger on the rep right after the walk</td></tr>
<tr><td>Release time</td><td class="yes">Within 0.05 s on all 7 jump-shot releases found</td><td>Sample truth</td></tr>
<tr><td>Shot counting</td><td class="yes">12 of 12; make or miss right on all</td><td>Sample truth; 39 of 39 on real clips in an earlier round</td></tr>
<tr><td>Who took the shot</td><td class="part">7 automatic, 0 wrong, 5 the coach confirmed</td><td>FG is 8 of 12, matching the truth</td></tr>
<tr><td>Shot location</td><td class="part">2.0 ft typical error</td><td>The far-corner three still lands at 5 ft</td></tr>
<tr><td>Speed</td><td class="part">Top 11.0 mph (true 14.8); pace 4.0 ft/s (true 4.0)</td><td>Player tracked 80% of the time</td></tr>
</tbody>
</table></div>
<h2>Not checked yet</h2>
<ul class="read">
<li><b>Form flags on a real player who has the mistakes.</b> Real footage so far only shows the engine stays quiet on good shots.</li>
<li>Running inside the real claude.ai viewer (the vision engine, saving files) on a phone and a laptop.</li>
<li>Claude features: Form feedback, Improvement plan, the tracking check, captions. They only run inside claude.ai.</li>
<li>Sound on an iPhone that is on silent. The fix is in, but a headless browser can't test it.</li>
<li>A real game with players crowding the rim, and any video longer than 2 minutes.</li>
</ul>
<h2>Known bugs</h2>
<ul class="read">
<li>No real flat shots or fades were in the free footage, so real-world catching of those mistakes is still unproven. Only "no false flags on good shots" is shown.</li>
<li>Filmed from behind, most releases aren't found and the angle can't be read. Film from the side.</li>
<li>The far-corner three lands at 5 ft and isn't measured.</li>
<li>A shot about 1 ft beyond the three-point line can be called a two.</li>
<li>Catch to release reads 0.7 s high on the rep after a slow walk.</li>
</ul>
</section>
<!-- ============ HOW ============ -->
<section class="view doc" id="view-how" hidden>
<h1>How Clutch Coach measures a player</h1>
<p class="lead">Everything runs on your device from what the camera sees; sound is not used. On this site nothing leaves your device. The version that runs inside Claude also writes form feedback from still frames and a week-long improvement plan; the master prompt on the project page rebuilds it.</p>
<div class="pipeline" style="grid-template-columns:repeat(3,1fr)">
<div class="box"><h3>Hoop</h3><p>You tap the rim once. Every frame, Clutch re-finds it and calls a make when the ball drops through.</p></div>
<div class="box"><h3>Court</h3><p>You tap the 4 paint corners. That turns the picture into a court map in feet, even when the camera pans.</p></div>
<div class="box"><h3>Player</h3><p>You tap the player. A vision model finds everyone 4 times a second and follows your player by look and path.</p></div>
<div class="box"><h3>Who shot</h3><p>The ball is traced backward from the rim to where it left someone's hands. That person and spot become the shot.</p></div>
<div class="box"><h3>Movement</h3><p>Your player's feet on the court map give distance, top speed, sprints and where they spent their time.</p></div>
<div class="box"><h3>Form</h3><p>Ball flight gives the arc and release point. Feet before and after the jump give drift and catch-to-release time. Each miss of a target becomes a time-tagged fix with a drill.</p></div>
</div>
<h2>Checked against the sample workout</h2>
<p class="lead" style="margin-top:0">The sample is synthetic, so every shot spot and every step is known exactly. These numbers come from this app's own analysis of it.</p>
<div class="grid3">
<div class="box"><div class="big num" id="hShots">–</div><p>shots found, makes and misses right.</p></div>
<div class="box"><div class="big num" id="hLoc">–<small>ft</small></div><p>typical error of a shot's location, for shots traced back to the hands.</p></div>
<div class="box"><div class="big num" id="hWho">–</div><p>shots credited automatically; none to the wrong player. The rest ask the coach.</p></div>
<div class="box"><div class="big num" id="hSpeed">–<small>mph</small></div><p id="hSpeedP">top speed, against the true value.</p></div>
<div class="box"><div class="big num" id="hPace">–<small>ft/s</small></div><p id="hPaceP">average pace while on camera, against the true value.</p></div>
<div class="box"><div class="big num" id="hCover">–<small>%</small></div><p>of the workout the player was tracked.</p></div>
</div>
<div class="tablewrap" style="margin-top:12px">
<table style="min-width:620px">
<thead><tr><th>Shot</th><th>True spot</th><th>Measured</th><th>Error</th><th>Result</th><th>Credited</th></tr></thead>
<tbody id="truthRows"></tbody>
</table>
</div>
<h2>Form coaching checked against the sample</h2>
<p class="lead" style="margin-top:0">The sample has 6 deliberate mistakes built in. The coaching engine doesn't know where they are; this compares what it flagged with what was planted.</p>
<div class="grid3">
<div class="box"><div class="big num" id="hForm">–</div><p>planted mistakes flagged at the right moment.</p></div>
<div class="box"><div class="big num" id="hFalse">–</div><p>false flags on reps that had nothing wrong.</p></div>
<div class="box"><h3>Not measured</h3><p>When the ball's release isn't visible (player at the frame edge, far corner), form is skipped instead of guessed.</p></div>
</div>
<div class="tablewrap" style="margin-top:12px">
<table style="min-width:620px">
<thead><tr><th>Time</th><th>Planted mistake</th><th>True value</th><th>Measured</th><th>Result</th></tr></thead>
<tbody id="formRows"></tbody>
</table>
</div>
<h2>Shot counting on real footage</h2>
<div class="tablewrap">
<table style="min-width:640px">
<thead><tr><th>Clip</th><th>Camera</th><th>Clear shots</th><th>Found</th><th>Make or miss right</th></tr></thead>
<tbody>
<tr><td><a href="https://github.com/chonyy/basketball-shot-detection/tree/master/sample">Outdoor court, 3 clips</a></td><td>Phone, steady</td><td class="num">11</td><td class="num yes">11</td><td class="num yes">11</td></tr>
<tr><td><a href="https://github.com/avishah3/AI-Basketball-Shot-Detection-Tracker">Indoor shooting practice</a></td><td>Handheld; jumps and zooms at 1:22</td><td class="num">28</td><td class="num yes">28</td><td class="num yes">28</td></tr>
</tbody>
</table>
</div>
<p class="note">Two more practice shots aren't counted: one rolls around the rim and out of view, and one is cut off by the end of the video. A hoop smaller than about 15 pixels wide is too small to watch, so film from closer or zoom in.</p>
<h2>Known limits</h2>
<p class="note">Vision model: YOLOv8n by Ultralytics, AGPL-3.0, run in the browser with onnxruntime-web (MIT). The page's full code is on its project page.</p>
<div class="grid3">
<div class="box"><h3>Teammates look alike</h3><p>Tracking can jump to a teammate in the same jersey. Tap your player again at another moment, or run the Claude tracking check.</p></div>
<div class="box"><h3>Crowded shots</h3><p>Layups and shots in traffic are harder to trace to the hands. Those land in the shot list with Yes and No buttons.</p></div>
<div class="box"><h3>Real time</h3><p>Counting shots plays the video at normal speed, so a 40-minute game takes about 40 minutes on the device.</p></div>
</div>
</section>
</div>
<div class="mobilebar"><button class="btn primary" id="mReel" type="button">Play clips</button><button class="btn" id="mExport" type="button">Download report</button></div>
<!-- follow dialog -->
<div class="modal" id="followModal" hidden role="dialog" aria-modal="true" aria-labelledby="fmTitle">
<div class="sheet">
<h3 id="fmTitle">Pick this player</h3>
<p>The report covers this player only. Clutch tracks them by jersey color and movement. The jersey number and name label the report.</p>
<div class="field"><label for="fmNum">Jersey number</label><input id="fmNum" inputmode="numeric" maxlength="3" placeholder="8"></div>
<div class="field"><label for="fmName">Name on title cards (optional)</label><input id="fmName" maxlength="28" placeholder="First name"></div>
<div class="field"><label for="fmTeam">Team (optional)</label><input id="fmTeam" maxlength="28" placeholder="Suns"></div>
<div class="acts"><button class="btn ghost" id="fmCancel" type="button">Cancel</button><button class="btn primary" id="fmOk" type="button">Follow player</button></div>
</div>
</div>
<!-- text dialog -->
<div class="modal" id="textModal" hidden role="dialog" aria-modal="true" aria-labelledby="tmTitle">
<div class="sheet">
<h3 id="tmTitle">Family recap</h3>
<p id="tmSub">Written by Claude from your clips. Edit it, then copy.</p>
<div class="field"><label for="tmText" class="sr">Recap text</label><textarea id="tmText"></textarea></div>
<div class="acts"><button class="btn ghost" id="tmClose" type="button">Close</button><button class="btn primary" id="tmCopy" type="button">Copy text</button></div>
</div>
</div>
<!-- export result -->
<div class="modal" id="exportModal" hidden role="dialog" aria-modal="true" aria-labelledby="emTitle">
<div class="sheet">
<h3 id="emTitle">Your reel is ready</h3>
<p id="emSub"></p>
<video id="emVid" controls playsinline style="width:100%;border-radius:10px;background:#000;max-height:50vh"></video>
<div class="acts" style="margin-top:12px"><button class="btn ghost" id="emClose" type="button">Close</button><button class="btn primary" id="emSave" type="button">Save video</button></div>
</div>
</div>
<div class="toast" id="toast" role="status"></div>
<video id="vid" class="hidv" playsinline preload="auto" crossorigin="anonymous"></video>
<video id="scanVid" class="hidv" playsinline muted preload="auto" crossorigin="anonymous"></video>
<script src="./coach.js" defer></script>
<script src="./tour.js" defer></script>
</body>
</html>
coach.js (the whole app: detector worker, tracking, shot counting, court map, form, coaching moments, report, clips)2,487 lines
"use strict";
/* ===================== constants ===================== */
const SPORTS = {
basketball:{label:"Basketball", A:1.0, M:0.35, B:0.6, C:0.25, pre:6, post:3, gap:7, titles:["Crowd erupts","Big reaction","Fast break","Ball in the air"]},
soccer:{label:"Soccer", A:1.0, M:0.3, B:0.5, C:0.4, pre:10, post:4, gap:15, titles:["Goal-mouth chance","Big reaction","Counterattack","Shot on goal"]},
volleyball:{label:"Volleyball", A:0.9, M:0.4, B:0.8, C:0.1, pre:5, post:3, gap:6, titles:["Point won","Big reaction","Long rally","Kill attempt"]},
football:{label:"Football", A:1.0, M:0.5, B:0.3, C:0.3, pre:7, post:4, gap:12, titles:["Big play","Big reaction","Breakaway run","Pass in the air"]},
baseball:{label:"Baseball / Softball", A:1.0, M:0.6, B:0.5, C:0.1, pre:5, post:6, gap:10, titles:["Big hit","Big reaction","Play on the bases","Ball in play"]},
hockey:{label:"Hockey", A:1.0, M:0.5, B:0.2, C:0.4, pre:8, post:4, gap:10, titles:["Scoring chance","Big reaction","Rush up the ice","Shot on net"]},
tennis:{label:"Tennis / Pickleball", A:0.9, M:0.5, B:0.7, C:0.0, pre:6, post:3, gap:8, titles:["Winner","Big reaction","Long rally","Big serve"]},
other:{label:"Other sport", A:1.0, M:0.5, B:0.4, C:0.2, pre:6, post:4, gap:8, titles:["Highlight","Big reaction","Fast action","Ball in the air"]}
};
const SIZES = {tight:{k:1.1, per:0.35, min:4}, standard:{k:0.35, per:0.7, min:7}, generous:{k:0.25, per:1.2, min:10}};
const GRID = 0.25; // seconds per score sample
const $ = s => document.querySelector(s);
const fmt = s => { s = Math.max(0, s||0); const m = Math.floor(s/60), r = Math.floor(s%60); return m + ":" + String(r).padStart(2,"0"); };
const clamp = (v,a,b) => Math.max(a, Math.min(b, v));
/* ===================== state ===================== */
const S = {
source:{name:"Sample game · Suns vs Rockets", sub:"Synthetic demo footage · free to use", url:"", sample:true, file:null},
sport:"basketball", size:"standard", mineFirst:false,
follow:null, // {anchors:[{t,box,sig}], number, name, team, color}
an:null, // analysis
track:null, // [{t,cx,cy,w,h,ok}]
clips:[], active:-1,
engine:"loading", worker:null,
playerCam:false, aiView:true, slow:false, picking:false, pickMode:null, hoops:[], shots:null, hoopDraft:null,
reel:null, busy:false, lastAnalyzeSec:null
};
const vid = $("#vid"), scanVid = $("#scanVid"), view = $("#view"), vctx = view.getContext("2d");
[vid, scanVid].forEach(v => v.addEventListener("error", () => { if (v.hasAttribute("crossorigin") && v.src) { const u = v.src; v.removeAttribute("crossorigin"); v.src = u; S.tainted = true; } }));
let cam = {x:.5, y:.5, z:1};
/* ===================== capabilities ===================== */
const caps = {};
function cap(name){
// sghadimi.com: no claude.ai capabilities. Saving is a plain browser download; Claude features are hidden.
if (name !== "downloads") return Promise.resolve(null);
return Promise.resolve({ save: async ({filename, data}) => {
const blob = data instanceof Blob ? data : new Blob([data], {type: /\.csv$/.test(filename) ? "text/csv" : /\.html$/.test(filename) ? "text/html" : "application/octet-stream"});
const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = filename; document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 4000);
return {status: "saved"};
} });
}
/* ===================== detector worker ===================== */
const WORKER_SRC = `
let session=null;
function nms(arr, iouT){ arr.sort((a,b)=>b[4]-a[4]); const keep=[];
for(const b of arr){ let ok=true; for(const k of keep){ const x1=Math.max(b[0]-b[2]/2,k[0]-k[2]/2), y1=Math.max(b[1]-b[3]/2,k[1]-k[3]/2), x2=Math.min(b[0]+b[2]/2,k[0]+k[2]/2), y2=Math.min(b[1]+b[3]/2,k[1]+k[3]/2);
const inter=Math.max(0,x2-x1)*Math.max(0,y2-y1); const iou=inter/(b[2]*b[3]+k[2]*k[3]-inter); if(iou>iouT){ok=false;break;} } if(ok) keep.push(b); if(keep.length>40) break; }
return keep; }
self.onmessage = async (e) => {
const m = e.data;
if (m.type === "init") {
try {
importScripts(m.base + "vendor/ort.wasm.min.js");
ort.env.wasm.numThreads = 1; ort.env.wasm.proxy = false;
ort.env.wasm.wasmPaths = { mjs: m.base + "vendor/ort-wasm-simd-threaded.mjs", wasm: m.base + "vendor/ort-wasm-simd-threaded.wasm" };
const wb = await fetch(m.base + "vendor/ort-wasm-simd-threaded.wasm"); if(!wb.ok) throw new Error("runtime " + wb.status);
ort.env.wasm.wasmBinary = await wb.arrayBuffer();
const mb = await fetch(m.base + "model/yolov8n.json"); if(!mb.ok) throw new Error("model " + mb.status);
const mj = await mb.json(); const bin = atob(mj.data); const bytes = new Uint8Array(bin.length);
for (let i=0;i<bin.length;i++) bytes[i] = bin.charCodeAt(i);
session = await ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
self.postMessage({ type: "ready" });
} catch (err) { self.postMessage({ type: "error", message: String(err && err.message || err) }); }
return;
}
if (m.type === "detect") {
try {
const d = m.data, n = 640*640, f = new Float32Array(3*n);
for (let i=0,p=0;i<n;i++,p+=4){ f[i]=d[p]/255; f[i+n]=d[p+1]/255; f[i+2*n]=d[p+2]/255; }
const out = await session.run({ images: new ort.Tensor("float32", f, [1,3,640,640]) });
const o = out[session.outputNames[0]].data, N = 8400, P = [], B = [];
for (let j=0;j<N;j++){
const sp = o[4*N+j], sb = o[36*N+j];
if (sp > 0.28) P.push([o[j],o[N+j],o[2*N+j],o[3*N+j],sp]);
if (sb > 0.12) B.push([o[j],o[N+j],o[2*N+j],o[3*N+j],sb]);
}
self.postMessage({ type: "det", id: m.id, persons: nms(P,0.5), balls: nms(B,0.4).slice(0,3) });
} catch (err) { self.postMessage({ type: "det", id: m.id, persons: [], balls: [], error: String(err) }); }
}
};`;
const pending = new Map(); let detId = 0;
function initEngine(){
try {
const base = new URL(".", location.href).href;
const w = new Worker(URL.createObjectURL(new Blob([WORKER_SRC], {type:"text/javascript"})));
w.onmessage = (e) => {
const m = e.data;
if (m.type === "ready") { S.engine = "ready"; S.worker = w; setEngine(); }
else if (m.type === "error") { S.engine = "off"; S.engineErr = m.message; setEngine(); }
else if (m.type === "det") { const r = pending.get(m.id); if (r) { pending.delete(m.id); r(m); } }
};
w.onerror = () => { S.engine = "off"; setEngine(); };
w.postMessage({type:"init", base});
} catch(e) { S.engine = "off"; setEngine(); }
}
function setEngine(){
const d = $("#engineDot"), t = $("#engineTxt");
if (S.engine === "ready") { d.className = "dot"; t.textContent = "On-device AI ready · nothing uploaded"; }
else if (S.engine === "off") { d.className = "dot warn"; t.textContent = "Vision model unavailable · using sound + motion"; }
else { d.className = "dot warn"; t.textContent = "Loading on-device AI…"; }
}
function detect(imageData){
if (S.engine !== "ready") return Promise.resolve({persons:[], balls:[]});
return new Promise(res => { const id = ++detId; pending.set(id, res); S.worker.postMessage({type:"detect", id, data:imageData.data}, [imageData.data.buffer]); });
}
/* ===================== media helpers ===================== */
function seek(v, t){
return new Promise(res => {
let fin = false;
const finish = () => { if (!fin) { fin = true; res(); } };
const done = () => {
v.removeEventListener("seeked", done);
if (v.requestVideoFrameCallback) { v.requestVideoFrameCallback(() => finish()); setTimeout(finish, 250); }
else setTimeout(finish, 30);
};
v.addEventListener("seeked", done);
v.currentTime = clamp(t, 0, Math.max(0, (v.duration||0) - 0.05));
setTimeout(finish, 3000);
});
}
function loaded(v){ return new Promise(res => { if (v.readyState >= 2 && v.duration) return res(); const f = () => { v.removeEventListener("loadeddata", f); res(); }; v.addEventListener("loadeddata", f); }); }
const C640 = document.createElement("canvas"); C640.width = C640.height = 640;
const c640 = C640.getContext("2d", {willReadFrequently:true});
const CSM = document.createElement("canvas"); CSM.width = 96; CSM.height = 54;
const csm = CSM.getContext("2d", {willReadFrequently:true});
function letterbox(v){
const vw = v.videoWidth, vh = v.videoHeight, r = 640 / Math.max(vw, vh);
c640.fillStyle = "#727272"; c640.fillRect(0,0,640,640);
c640.drawImage(v, 0, 0, vw*r, vh*r);
return {r, w:vw*r, h:vh*r};
}
// appearance signature of the torso region: 12 hue bins weighted by saturation + 3 neutral bins
function signature(box, lb, img){
const sig = new Float32Array(15);
const x0 = Math.round((box[0]-box[2]*0.28)*lb.w), x1 = Math.round((box[0]+box[2]*0.28)*lb.w);
const y0 = Math.round((box[1]-box[3]*0.30)*lb.h), y1 = Math.round((box[1]+box[3]*0.02)*lb.h);
let n = 0;
for (let y = Math.max(0,y0); y < Math.min(640,y1); y += 2) for (let x = Math.max(0,x0); x < Math.min(640,x1); x += 2) {
const p = (y*640 + x)*4, r = img[p]/255, g = img[p+1]/255, b = img[p+2]/255;
const mx = Math.max(r,g,b), mn = Math.min(r,g,b), dl = mx - mn, sat = mx ? dl/mx : 0;
if (sat > 0.28 && mx > 0.18) {
let h = mx === r ? ((g-b)/dl)%6 : mx === g ? (b-r)/dl + 2 : (r-g)/dl + 4; h = (h*60 + 360) % 360;
sig[Math.floor(h/30)] += sat;
} else sig[mx > 0.72 ? 12 : mx > 0.3 ? 13 : 14] += 0.8;
n++;
}
let s = 0; for (let i=0;i<15;i++) s += sig[i];
if (s > 0) for (let i=0;i<15;i++) sig[i] = +(sig[i]/s).toFixed(3);
return Array.from(sig);
}
const bhat = (a,b) => { let s = 0; for (let i=0;i<a.length;i++) s += Math.sqrt(a[i]*b[i]); return s; };
/* ===================== audio analysis ===================== */
async function analyzeAudio(buf, onProgress){
try {
const AC = window.AudioContext || window.webkitAudioContext;
const ctx = new AC();
const ab = await ctx.decodeAudioData(buf);
ctx.close && ctx.close();
const sr = ab.sampleRate, n = ab.length, ch = ab.numberOfChannels;
const data = new Float32Array(n);
for (let c=0;c<ch;c++){ const d = ab.getChannelData(c); for (let i=0;i<n;i++) data[i] += d[i]/ch; }
const win = Math.round(sr*GRID), m = Math.floor(n/win), rms = new Float32Array(m), hf = new Float32Array(m);
for (let k=0;k<m;k++){
let s = 0, h = 0, prev = data[k*win];
for (let i=k*win;i<(k+1)*win;i++){ const x = data[i]; s += x*x; const dx = x - prev; h += dx*dx; prev = x; }
rms[k] = 20*Math.log10(Math.sqrt(s/win) + 1e-5); hf[k] = 10*Math.log10(h/win + 1e-9);
if (k % 2000 === 0) onProgress && onProgress(k/m);
}
return {rms:Array.from(rms), hf:Array.from(hf)};
} catch(e) { console.warn("audio", e); return null; }
}
/* ===================== full analysis ===================== */
async function analyze(){
if (S.busy) return;
S.busy = true; stopReel(); vid.pause();
const t0 = performance.now();
const scan = $("#scan"); scan.hidden = false;
const stepEl = s => document.querySelector(`#steps li[data-s="${s}"]`);
const setStep = (s, st) => { const el = stepEl(s); el.classList.remove("on","done"); if (st) el.classList.add(st); };
["vision","track","shots","score"].forEach(s => setStep(s, null));
stepEl("track").style.display = S.follow ? "" : "none";
stepEl("shots").style.display = S.hoops.length ? "" : "none";
const bar = $("#scanBar"); bar.style.width = "2%";
$("#analyzeBtn").disabled = true; setHud();
try {
scanVid.src = S.source.url; await loaded(scanVid);
const dur = scanVid.duration, vw = scanVid.videoWidth, vh = scanVid.videoHeight;
// sound is not used: plays are found from what the camera sees
const audio = null; bar.style.width = "4%";
// 2. vision
setStep("vision","on");
const step = Math.max(S.follow ? 0.25 : 0.5, dur / 900);
const frames = []; let prevSmall = null, prevHist = null, people = 0;
const tStart = performance.now();
for (let t = 0.05; t < dur - 0.05; t += step) {
await seek(scanVid, t);
// motion + cut on small frame
csm.drawImage(scanVid, 0, 0, 96, 54);
const sm = csm.getImageData(0,0,96,54).data, gray = new Float32Array(96*54), hist = new Float32Array(16);
for (let i=0,p=0;i<gray.length;i++,p+=4){ const g = (sm[p]*0.3 + sm[p+1]*0.59 + sm[p+2]*0.11); gray[i] = g; hist[Math.min(15, g>>4)]++; }
let motion = 0, mx = 0, my = 0, mw = 0, cut = 0;
if (prevSmall) {
for (let i=0;i<gray.length;i++){ const d = Math.abs(gray[i]-prevSmall[i]); motion += d; if (d > 22){ mx += (i%96)*d; my += Math.floor(i/96)*d; mw += d; } }
motion /= gray.length;
let hd = 0; for (let i=0;i<16;i++) hd += Math.abs(hist[i]-prevHist[i]); cut = hd/gray.length > 0.6 ? 1 : 0;
}
prevSmall = gray; prevHist = hist;
const fr = {t:+t.toFixed(2), m:+motion.toFixed(2), cut, ax: mw ? +(mx/mw/96).toFixed(3) : null, ay: mw ? +(my/mw/54).toFixed(3) : null, p:[], b:[]};
if (S.engine === "ready") {
const lb = letterbox(scanVid);
const img = c640.getImageData(0,0,640,640);
const pix = new Uint8ClampedArray(img.data);
const det = await detect(img);
for (const d of det.persons) {
const box = [d[0]/lb.w, d[1]/lb.h, d[2]/lb.w, d[3]/lb.h];
if (box[3] < 0.05 || box[1] > 1.02) continue;
fr.p.push([+box[0].toFixed(4), +box[1].toFixed(4), +box[2].toFixed(4), +box[3].toFixed(4), +d[4].toFixed(2), signature(box, lb, pix)]);
}
for (const d of det.balls) fr.b.push([+(d[0]/lb.w).toFixed(4), +(d[1]/lb.h).toFixed(4), +d[4].toFixed(2)]);
people = Math.max(people, fr.p.length);
S.scanPreview = {t, persons:fr.p, balls:fr.b};
vctx.save(); drawFrameTo(vctx, view.width, view.height, scanVid, {scan:true}); vctx.restore();
}
frames.push(fr);
const k = frames.length, total = Math.ceil(dur/step);
bar.style.width = (10 + 78*k/total) + "%";
$("#scanFrames").textContent = k + " / " + total + " frames";
$("#scanPeople").textContent = people + " players in view";
const el = (performance.now() - tStart)/1000, eta = el/k*(total-k);
$("#scanEta").textContent = k > 3 ? "about " + Math.ceil(eta) + "s left" : "";
if (k % 4 === 0) await new Promise(r => setTimeout(r, 0));
}
setStep("vision","done");
S.an = {v:1, duration:dur, vw, vh, step, audio, frames, vision: S.engine === "ready"};
// 3. track
if (S.follow) { setStep("track","on"); S.track = buildTrack(); setStep("track","done"); } else S.track = null;
if (S.hoops.length) { setStep("shots","on"); await analyzeShots(p => bar.style.width = (88 + p*6) + "%"); setStep("shots","done"); }
bar.style.width = "94%";
setStep("score","on");
S.lastAnalyzeSec = (performance.now() - t0)/1000;
attributeShots();
rescore(true);
renderReport();
await makeThumbs();
setStep("score","done"); bar.style.width = "100%";
toast(S.shots ? `Report ready: ${S.shots.filter(x => x.mine === true).length} shots for your player (${Math.round(S.lastAnalyzeSec)}s)` : `Report ready (${Math.round(S.lastAnalyzeSec)}s). Mark the hoop to count shots.`);
renderHow();
} catch(e) {
console.error(e); toast("Analysis stopped: " + (e.message || e) + ". Try a shorter MP4 or MOV file.");
} finally {
S.busy = false; S.scanPreview = null; $("#analyzeBtn").disabled = false;
setTimeout(() => { scan.hidden = true; }, 500);
$("#analyzeTxt").textContent = "Re-run analysis"; setHud(); drawStage();
}
}
/* ===================== made-basket detector ===================== */
// Training-free: the parent marks the rim once. Each frame we (1) re-find the hoop by template
// matching (multi-scale search if the camera jumps), (2) find the moving ball near it by background
// difference, and (3) call a make when the ball goes from above the rim to inside the net.
function grayOf(img){ const d = img.data, n = img.width*img.height, g = new Float32Array(n); for (let i=0,p=0;i<n;i++,p+=4) g[i] = d[p]*0.299 + d[p+1]*0.587 + d[p+2]*0.114; return g; }
function resizeGray(src, sw, sh, dw, dh){ const out = new Float32Array(dw*dh); for (let y=0;y<dh;y++){ const sy = Math.min(sh-1, (y+0.5)*sh/dh - 0.5); const y0 = Math.max(0, Math.floor(sy)), y1 = Math.min(sh-1, y0+1), fy = sy - y0; for (let x=0;x<dw;x++){ const sx = Math.min(sw-1, (x+0.5)*sw/dw - 0.5); const x0 = Math.max(0, Math.floor(sx)), x1 = Math.min(sw-1, x0+1), fx = sx - x0; out[y*dw+x] = (src[y0*sw+x0]*(1-fx) + src[y0*sw+x1]*fx)*(1-fy) + (src[y1*sw+x0]*(1-fx) + src[y1*sw+x1]*fx)*fy; } } return out; }
function makeTmpl(g, tw, th){ let s = 0, s2 = 0; for (const v of g){ s += v; s2 += v*v; } const n = g.length, m = s/n; return {g, tw, th, mean:m, std:Math.sqrt(Math.max(1e-6, s2/n - m*m))}; }
function zncc(img, iw, x, y, T, step){
// zero-mean normalized cross-correlation on a (sub-sampled) grid; template stats on the same grid
let s = 0, s2 = 0, st = 0, t1 = 0, t2 = 0, n = 0; const tw = T.tw, th = T.th, tg = T.g;
for (let j=0;j<th;j+=step){ const r = (y+j)*iw + x, tr = j*tw; for (let i=0;i<tw;i+=step){ const v = img[r+i], u = tg[tr+i]; s += v; s2 += v*v; st += v*u; t1 += u; t2 += u*u; n++; } }
const m = s/n, mt = t1/n, sd = Math.sqrt(Math.max(1e-6, s2/n - m*m)), sdt = Math.sqrt(Math.max(1e-6, t2/n - mt*mt));
return (st/n - m*mt)/(sd*sdt);
}
function searchTmpl(img, iw, ih, T, x0, y0, x1, y1, step){
let best = -2, bx = 0, by = 0;
x0 = Math.max(0, x0|0); y0 = Math.max(0, y0|0); x1 = Math.min(iw - T.tw, x1|0); y1 = Math.min(ih - T.th, y1|0);
for (let y=y0;y<=y1;y+=step) for (let x=x0;x<=x1;x+=step){ const v = zncc(img, iw, x, y, T, step > 1 ? 2 : 1); if (v > best){ best = v; bx = x; by = y; } }
return {v:best, x:bx, y:by};
}
function components(mask, w, h){
const lab = new Int32Array(w*h), out = []; let id = 0; const st = [];
for (let i=0;i<w*h;i++){ if (!mask[i] || lab[i]) continue; id++; let minx=w, miny=h, maxx=0, maxy=0, area=0; st.push(i); lab[i] = id;
while (st.length){ const p = st.pop(), x = p % w, y = (p / w)|0; area++; if (x<minx) minx=x; if (x>maxx) maxx=x; if (y<miny) miny=y; if (y>maxy) maxy=y;
if (x>0 && mask[p-1] && !lab[p-1]){ lab[p-1]=id; st.push(p-1); } if (x<w-1 && mask[p+1] && !lab[p+1]){ lab[p+1]=id; st.push(p+1); }
if (y>0 && mask[p-w] && !lab[p-w]){ lab[p-w]=id; st.push(p-w); } if (y<h-1 && mask[p+w] && !lab[p+w]){ lab[p+w]=id; st.push(p+w); } }
out.push({minx, miny, maxx, maxy, area}); }
return out;
}
function openMask(m, w, h){ // cross-shaped erode then dilate
const e = new Uint8Array(w*h), d = new Uint8Array(w*h);
for (let y=1;y<h-1;y++) for (let x=1;x<w-1;x++){ const p = y*w+x; e[p] = m[p] && m[p-1] && m[p+1] && m[p-w] && m[p+w] ? 1 : 0; }
for (let y=1;y<h-1;y++) for (let x=1;x<w-1;x++){ const p = y*w+x; d[p] = e[p] || e[p-1] || e[p+1] || e[p-w] || e[p+w] ? 1 : 0; }
return d;
}
// Follow the ball backwards in time from where it first came near the rim, to where it left the shooter's hands.
// Uses a three-frame difference inside a search window that follows the ball's own path.
function backtrackBall(ring, W, H, x, y, ballD){
const n = ring.length; if (n < 4) return [];
const pts = [{t:ring[n-1].t, x, y}]; let px = x, py = y, vx = 0, vy = 0, miss = 0;
ballD = Math.max(3, ballD);
for (let k=n-2; k>=1; k--) {
if (ring[n-1].t - ring[k].t > 2.2) break;
const A = ring[k].g, P = ring[k-1].g, N = ring[k+1].g;
const qx = px - vx, qy = py - vy, R = Math.round(Math.max(10, 2.2*Math.hypot(vx, vy)) + ballD*1.5);
const x0 = Math.max(1, Math.round(qx - R)), x1 = Math.min(W-2, Math.round(qx + R)), y0 = Math.max(1, Math.round(qy - R)), y1 = Math.min(H-2, Math.round(qy + R));
const ww = x1 - x0 + 1, hh = y1 - y0 + 1; if (ww < 4 || hh < 4) break;
const m = new Uint8Array(ww*hh);
for (let yy=0; yy<hh; yy++) for (let xx=0; xx<ww; xx++) { const i = (y0+yy)*W + x0 + xx, a = A[i]; m[yy*ww+xx] = Math.abs(a - P[i]) > 14 && Math.abs(a - N[i]) > 14 ? 1 : 0; }
let best = null, bd = 1e9;
for (const c of components(m, ww, hh)) {
const cw = c.maxx - c.minx + 1, ch = c.maxy - c.miny + 1, d = Math.max(cw, ch);
if (d < 0.45*ballD || d > 2.4*ballD || cw/ch < 0.4 || cw/ch > 2.5 || c.area/(cw*ch) < 0.35) continue;
const cx = x0 + c.minx + cw/2, cy = y0 + c.miny + ch/2, dd = Math.hypot(cx - qx, cy - qy);
if (dd < bd) { bd = dd; best = {x:cx, y:cy}; }
}
if (best) {
const nvx = px - best.x, nvy = py - best.y;
vx = pts.length > 1 ? vx*0.5 + nvx*0.5 : nvx; vy = pts.length > 1 ? vy*0.5 + nvy*0.5 : nvy;
px = best.x; py = best.y; miss = 0; pts.push({t:ring[k].t, x:px, y:py});
} else { miss++; px = qx; py = qy; if (miss >= 3) break; }
}
return pts;
}
let SHOT_MODE = "diff3";
let MADE_RULE = (made, above, net, deep) => deep >= 2 || (above && net > 0.35);
async function analyzeShots(onProgress){
if (!S.hoops || !S.hoops.length) { S.shots = null; return null; }
const v = scanVid;
if (v.src !== S.source.url) v.src = S.source.url;
await loaded(v);
const vw = v.videoWidth, vh = v.videoHeight, PW = Math.min(960, vw), PH = Math.round(PW*vh/vw);
const cv = document.createElement("canvas"); cv.width = PW; cv.height = PH; const cx = cv.getContext("2d", {willReadFrequently:true});
const frame = async (t) => { await seek(v, t); cx.drawImage(v, 0, 0, PW, PH); return grayOf(cx.getImageData(0, 0, PW, PH)); };
// templates from each hoop's marking frame
const H = [];
for (const hp of S.hoops) {
const g = await frame(hp.t);
const w0 = hp.w*PW, rcx = hp.cx*PW, rcy = hp.cy*PH;
const tx0 = Math.max(0, Math.round(rcx - 1.1*w0)), ty0 = Math.max(0, Math.round(rcy - 1.6*w0));
const tx1 = Math.min(PW, Math.round(rcx + 1.1*w0)), ty1 = Math.min(PH, Math.round(rcy + 1.0*w0));
const tw = tx1 - tx0, th = ty1 - ty0, tg = new Float32Array(tw*th);
for (let j=0;j<th;j++) for (let i=0;i<tw;i++) tg[j*tw+i] = g[(ty0+j)*PW + tx0 + i];
const scales = [0.6,0.7,0.8,0.9,1.0,1.1,1.25,1.4].map(s => { const w2 = Math.max(8, Math.round(tw*s)), h2 = Math.max(8, Math.round(th*s)); return {s, T:makeTmpl(resizeGray(tg, tw, th, w2, h2), w2, h2)}; });
H.push({w0, rel:{x:rcx - tx0, y:rcy - ty0}, T:makeTmpl(tg, tw, th), tg, tw, th, scales, mx:tx0, my:ty0, s:1, lost:0, bg:null, bgKey:"", traj:[], net:[], lastGlobal:-9, poses:[], releases:[], lastNear:null});
}
const dur = v.duration;
const gFull = new Float32Array(PW*PH);
const fillGray = (x0, y0, x1, y1) => {
x0 = Math.max(0, x0|0); y0 = Math.max(0, y0|0); x1 = Math.min(PW, Math.ceil(x1)); y1 = Math.min(PH, Math.ceil(y1));
if (x1 <= x0 || y1 <= y0) return;
const d = cx.getImageData(x0, y0, x1 - x0, y1 - y0).data, rw = x1 - x0;
for (let y=y0, p=0; y<y1; y++) for (let x=x0; x<x1; x++, p+=4) gFull[y*PW + x] = d[p]*0.299 + d[p+1]*0.587 + d[p+2]*0.114;
};
const grab = () => {
cx.drawImage(v, 0, 0, PW, PH);
// only read the pixels around each hoop; the whole frame only when a hoop is lost
let x0 = PW, y0 = PH, x1 = 0, y1 = 0, full = false;
for (const h of H) {
if (h.lost >= 2) full = true;
const w = h.w0*h.s, pad = 0.8*h.w0*h.s + 2, tw = h.tw*h.s, th = h.th*h.s, rcx = h.mx + h.rel.x*h.s, ry = h.my + h.rel.y*h.s;
x0 = Math.min(x0, h.mx - pad, rcx - 3.6*w); y0 = Math.min(y0, h.my - pad, ry - 4.6*w);
x1 = Math.max(x1, h.mx + tw + pad, rcx + 3.6*w); y1 = Math.max(y1, h.my + th + pad, ry + 2.1*w);
}
if (full) fillGray(0, 0, PW, PH); else fillGray(x0, y0, x1, y1);
return gFull;
};
// a half-size grayscale copy of every recent frame, for tracing the ball back to the shooter's hands
const BW = Math.round(PW/2), BH = Math.round(PH/2), bcv = document.createElement("canvas"); bcv.width = BW; bcv.height = BH;
const bcx = bcv.getContext("2d", {willReadFrequently:true}); const ring = []; const RING = 64;
const pushRing = (t) => {
bcx.drawImage(v, 0, 0, BW, BH); const d = bcx.getImageData(0, 0, BW, BH).data, g8 = new Uint8Array(BW*BH);
for (let i=0,p=0;i<g8.length;i++,p+=4) g8[i] = (d[p]*77 + d[p+1]*150 + d[p+2]*29) >> 8;
ring.push({t, g:g8}); if (ring.length > RING) ring.shift();
};
const processFrame = (t) => {
const g = grab();
pushRing(t);
for (const h of H) {
// 1. hoop
const sc = h.s, cur = sc === 1 ? h.T : h.scales.find(q => q.s === sc).T, pad = Math.round(0.8*h.w0*sc);
let r = searchTmpl(g, PW, PH, cur, h.mx - pad, h.my - pad, h.mx + pad, h.my + pad, 2);
if (r.v > 0.3) r = searchTmpl(g, PW, PH, cur, r.x - 2, r.y - 2, r.x + 2, r.y + 2, 1);
if (r.v > 0.5) { h.mx = r.x; h.my = r.y; h.lost = 0; }
else if (++h.lost >= 3 && t - h.lastGlobal > 0.5) {
h.lastGlobal = t;
// coarse global search on a half-size frame at several scales
const QW = PW >> 1, QH = PH >> 1, q = resizeGray(g, PW, PH, QW, QH); let best = {v:-2};
for (const S_ of h.scales) { const tq = makeTmpl(resizeGray(S_.T.g, S_.T.tw, S_.T.th, Math.max(6, S_.T.tw>>1), Math.max(6, S_.T.th>>1)), Math.max(6, S_.T.tw>>1), Math.max(6, S_.T.th>>1));
const rr = searchTmpl(q, QW, QH, tq, 0, 0, QW, QH, 2); if (rr.v > best.v) best = {...rr, s:S_.s}; }
if (best.v > 0.5) { const T2 = h.scales.find(q2 => q2.s === best.s).T; const rf = searchTmpl(g, PW, PH, T2, best.x*2 - 4, best.y*2 - 4, best.x*2 + 4, best.y*2 + 4, 1);
if (rf.v > 0.55) { h.mx = rf.x; h.my = rf.y; h.s = best.s; h.lost = 0; h.bg = null; } }
}
const w = h.w0*h.s, rcx = h.mx + h.rel.x*h.s, ry = h.my + h.rel.y*h.s;
// 2. ball near the rim
const R0x = Math.max(0, Math.round(rcx - 3.6*w)), R0y = Math.max(0, Math.round(ry - 4.5*w)), R1x = Math.min(PW, Math.round(rcx + 3.5*w)), R1y = Math.min(PH, Math.round(ry + 2*w));
const rw = R1x - R0x, rh = R1y - R0y; if (rw < 8 || rh < 8) continue;
const key = rw + "x" + rh;
const roi = new Float32Array(rw*rh); for (let j=0;j<rh;j++) for (let i=0;i<rw;i++) roi[j*rw+i] = g[(R0y+j)*PW + R0x + i];
if (!h.bg || h.bgKey !== key) { h.bg = roi.slice(); h.bgKey = key; h.p1 = null; h.p2 = null; }
const m = new Uint8Array(rw*rh); let cnt = 0;
if (h.lost > 0) { h.p2 = h.p1; h.p1 = roi; continue; } // hoop not found this frame: don't guess
if (SHOT_MODE === "bg") { for (let i=0;i<rw*rh;i++){ m[i] = Math.abs(roi[i] - h.bg[i]) > 22 ? 1 : 0; cnt += m[i]; h.bg[i] = h.bg[i]*0.9 + roi[i]*0.1; } }
else {
// three-frame difference in hoop-aligned coordinates: survives a panning camera
if (!h.p1 || !h.p2) { h.p2 = h.p1; h.p1 = roi; continue; }
for (let i=0;i<rw*rh;i++){ m[i] = Math.abs(roi[i] - h.p1[i]) > 18 && Math.abs(roi[i] - h.p2[i]) > 18 ? 1 : 0; cnt += m[i]; }
h.p2 = h.p1; h.p1 = roi;
}
if (cnt > 0.2*rw*rh) { h.bg = roi.slice(); continue; } // whole view moved: skip
const fg = openMask(m, rw, rh);
const prev = h.traj.length && t - h.traj[h.traj.length-1].t < 0.3 ? h.traj[h.traj.length-1] : null;
let best = null;
for (const c of components(fg, rw, rh)) {
const ww = c.maxx - c.minx + 1, hh = c.maxy - c.miny + 1, d = Math.max(ww, hh);
if (d < 0.25*w || d > 1.1*w) continue;
if (ww/hh < 0.45 || ww/hh > 2.2) continue;
const fill = c.area/(ww*hh); if (fill < 0.45) continue;
const bx = R0x + c.minx + ww/2, by = R0y + c.miny + hh/2;
let sc2 = fill; if (prev) sc2 -= Math.hypot(bx - prev.x, by - prev.y)/(3*w);
if (!best || sc2 > best.s) best = {s:sc2, x:bx, y:by, c};
}
// the ball itself must not count as net movement
if (best) { const c = best.c; for (let y=Math.max(0,c.miny-2); y<=Math.min(rh-1,c.maxy+2); y++) for (let x=Math.max(0,c.minx-2); x<=Math.min(rw-1,c.maxx+2); x++) fg[y*rw+x] = 0; }
// net motion under the rim
const nx0 = Math.round(rcx - 0.35*w - R0x), nx1 = Math.round(rcx + 0.35*w - R0x), ny0 = Math.round(ry + 0.2*w - R0y), ny1 = Math.round(ry + 0.9*w - R0y);
let nm = 0, nc = 0; for (let y=Math.max(0,ny0); y<Math.min(rh,ny1); y++) for (let x=Math.max(0,nx0); x<Math.min(rw,nx1); x++){ nm += fg[y*rw+x]; nc++; }
h.net.push({t, v: nc ? nm/nc : 0});
if (best) {
h.traj.push({t, x:best.x, y:best.y, cx:rcx, ry, w});
// a shot reaches the rim from above: trace it back the first time the ball shows up above the rim
const aboveRim = Math.abs(best.x - rcx) < 2*w && best.y < ry - 0.3*w && best.y > ry - 4.2*w;
if (aboveRim) {
if (h.lastNear == null || t - h.lastNear > 0.8) h.releases.push({t, path: backtrackBall(ring, BW, BH, best.x/2, best.y/2, 0.5*w/2)});
h.lastNear = t;
}
}
if (!h.poses.length || t - h.poses[h.poses.length-1][0] >= 0.1) h.poses.push([+t.toFixed(2), rcx/PW, ry/PH, w/PW]);
}
};
let lastT = -1;
if (v.requestVideoFrameCallback) {
// decode by playing (every frame, much faster than seeking); muted, double speed
await seek(v, 0);
v.muted = true; v.playbackRate = 1;
await new Promise((res) => {
let done = false; const fin = () => { if (!done) { done = true; v.pause(); res(); } };
const step = (now, meta) => {
if (done) return;
const t = meta.mediaTime;
if (t > lastT + 0.02) { processFrame(t); lastT = t; onProgress && onProgress(t/dur); }
if (v.ended || t >= dur - 0.05) return fin();
v.requestVideoFrameCallback(step);
};
v.requestVideoFrameCallback(step);
v.addEventListener("ended", fin, {once:true});
const guard = setInterval(() => { if (done) return clearInterval(guard); if (v.paused && !v.ended) v.play().catch(()=>{}); }, 1000);
v.play().catch(() => fin());
setTimeout(fin, (dur + 30)*1000*2);
});
v.playbackRate = 1;
} else {
for (let t = 0; t < dur; t += 1/15) { await seek(v, t); processFrame(t); onProgress && onProgress(t/dur); if ((t*15|0) % 8 === 0) await new Promise(r => setTimeout(r, 0)); }
}
// 3. shot events
const shots = [];
H.forEach((h, hi) => {
const ev = []; let cur = null;
for (const p of h.traj) {
const near = Math.abs(p.x - p.cx) < 1.6*p.w && p.y > p.ry - 3*p.w && p.y < p.ry + 1.2*p.w;
if (!near) continue;
if (!cur || p.t - cur.last > 0.8) { if (cur) ev.push(cur); cur = {start:p.t, last:p.t, pts:[]}; }
cur.last = p.t; cur.pts.push(p);
}
if (cur) ev.push(cur);
for (const e of ev) {
let above = false, made = false, top = 9, deep = 0;
for (const p of e.pts) {
top = Math.min(top, (p.y - p.ry)/p.w);
if (p.y < p.ry - 0.05*p.w && Math.abs(p.x - p.cx) < 1.3*p.w) above = true;
if (above && p.y > p.ry + 0.2*p.w && Math.abs(p.x - p.cx) < 0.7*p.w) made = true;
if (above && p.y > p.ry + 0.2*p.w && p.y < p.ry + 1.2*p.w && Math.abs(p.x - p.cx) < 0.5*p.w) deep++;
}
if (e.pts.length < 3 || top > -0.3) continue;
let net = 0; for (const q of h.net) if (q.t >= e.start - 0.1 && q.t <= e.last + 0.6) net = Math.max(net, q.v);
const p0 = e.pts[0];
let rimT = e.start; for (const p of e.pts) if (p.y < p.ry + 0.1*p.w && Math.abs(p.x - p.cx) < 1.3*p.w) rimT = p.t;
const rel = h.releases.find(r => r.t >= e.start - 0.1 && r.t <= e.last + 0.05);
const path = rel ? rel.path : []; // newest first
// release = going back in time past the top of the arc, the point where the ball stops dropping (in the image)
let rIdx = -1;
if (path.length >= 4) {
let apex = 0; for (let i=1;i<path.length;i++) if (path[i].y < path[apex].y) apex = i;
rIdx = apex; let flat = 0;
for (let i=apex+1;i<path.length;i++) {
if (path[i].y >= path[rIdx].y - 0.5) { rIdx = i; flat = 0; } else if (++flat >= 2) break;
if (path[0].t - path[i].t > 1.8) break;
}
}
const first = rIdx >= 0 ? path[rIdx] : null;
const release = first && rIdx >= 2 ? {t:+first.t.toFixed(2), x:first.x*2/PW, y:first.y*2/PH, n:rIdx+1} : null;
// the flight, release to rim, for arc and drawing
const flight = (rIdx >= 0 ? path.slice(0, rIdx+1).reverse().map(p => [+p.t.toFixed(2), +(p.x*2/PW).toFixed(4), +(p.y*2/PH).toFixed(4)]) : [])
.concat(e.pts.filter(p => p.t <= rimT + 0.05).map(p => [+p.t.toFixed(2), +(p.x/PW).toFixed(4), +(p.y/PH).toFixed(4)]));
shots.push({t:+e.start.toFixed(2), end:+e.last.toFixed(2), made: MADE_RULE(made, above, net, deep), rimT:+rimT.toFixed(2), release, flight, dbg:{made, above, net:+net.toFixed(3), deep}, hoop:hi, net:+net.toFixed(2), rim:[p0.cx/PW, p0.ry/PH, p0.w/PW]});
}
});
shots.sort((a,b) => a.t - b.t);
S.hoopPoses = H.map(h => h.poses);
S.shots = shots;
return shots;
}
/* ===================== coach engine: court, movement, shooting ===================== */
const COURTS = {
hs:{label:"High school / youth (US)", lane:12, ft:19, r3:19.75, corner3:null, hoopY:5.25},
college:{label:"College (US)", lane:12, ft:19, r3:22.15, corner3:21.65, hoopY:5.25},
nba:{label:"NBA", lane:16, ft:19, r3:23.75, corner3:22, hoopY:5.25},
fiba:{label:"FIBA / international", lane:16.08, ft:19.03, r3:22.15, corner3:21.65, hoopY:5.17}
};
// 4-point homography (image -> court), solved by Gaussian elimination
function homography(src, dst){
const A = [], b = [];
for (let i=0;i<4;i++){ const [x,y] = src[i], [u,v] = dst[i];
A.push([x,y,1,0,0,0,-u*x,-u*y]); b.push(u); A.push([0,0,0,x,y,1,-v*x,-v*y]); b.push(v); }
const n = 8, M = A.map((r,i) => r.concat([b[i]]));
for (let c=0;c<n;c++){ let p = c; for (let r=c+1;r<n;r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
[M[c], M[p]] = [M[p], M[c]]; if (Math.abs(M[c][c]) < 1e-12) return null;
for (let r=0;r<n;r++) if (r !== c){ const f = M[r][c]/M[c][c]; for (let k=c;k<=n;k++) M[r][k] -= f*M[c][k]; } }
const h = M.map((r,i) => r[n]/r[i]); return [h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7],1];
}
function applyH(H, x, y){ const w = H[6]*x + H[7]*y + H[8]; return [(H[0]*x + H[1]*y + H[2])/w, (H[3]*x + H[4]*y + H[5])/w]; }
function invertH(H){
const [a,b,c,d,e,f,g,h,i] = H, A = e*i - f*h, B = -(d*i - f*g), C = d*h - e*g, det = a*A + b*B + c*C;
if (Math.abs(det) < 1e-12) return null;
return [A/det, -(b*i - c*h)/det, (b*f - c*e)/det, B/det, (a*i - c*g)/det, -(a*f - c*d)/det, C/det, -(a*h - b*g)/det, (a*e - b*d)/det];
}
function courtSpec(){ return COURTS[(S.calib && S.calib.std) || "hs"]; }
function buildCalib(){
const c = S.calib; if (!c || c.pts.length !== 4) { S.H = null; S.Hinv = null; return; }
const K = COURTS[c.std], L = K.lane/2;
// aspect-correct the taps (video pixels) so feet come out square
const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9;
const src = c.pts.map(p => [p[0]*vw, p[1]*vh]);
S.H = homography(src, [[-L,0],[L,0],[L,K.ft],[-L,K.ft]]); S.Hinv = S.H && invertH(S.H);
}
// camera moves: undo pan/zoom with the hoop's tracked position and size
function poseAt(t){
const P = S.hoopPoses && S.hoopPoses[S.calib && S.calib.hoop || 0]; if (!P || !P.length) return null;
let lo = 0, hi = P.length-1; while (hi - lo > 1){ const m = (lo+hi)>>1; if (P[m][0] <= t) lo = m; else hi = m; }
return Math.abs(P[lo][0]-t) < Math.abs(P[hi][0]-t) ? P[lo] : P[hi];
}
function toCourt(nx, ny, t){
if (!S.H) return null;
const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9;
let x = nx*vw, y = ny*vh;
const a = poseAt(t), b = S.calib && poseAt(S.calib.t);
if (a && b && a[3] > 0) { const k = b[3]/a[3]; x = b[1]*vw + (x - a[1]*vw)*k; y = b[2]*vh + (y - a[2]*vh)*k; }
const [X, Y] = applyH(S.H, x, y);
return [X, Y];
}
function fromCourt(X, Y, t){
if (!S.Hinv) return null;
const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9;
let [x, y] = applyH(S.Hinv, X, Y);
const a = poseAt(t), b = S.calib && poseAt(S.calib.t);
if (a && b && b[3] > 0) { const k = a[3]/b[3]; x = a[1]*vw + (x - b[1]*vw)*k; y = a[2]*vh + (y - b[2]*vh)*k; }
return [x/vw, y/vh];
}
function zoneOf(X, Y){
const K = courtSpec(); if (Y > 47) return "back";
const d = Math.hypot(X, Y - K.hoopY);
const corner = K.corner3 ? (Math.abs(X) >= K.corner3 && Y <= 14) : false;
if (corner) return "corner3";
if (d >= K.r3) return "three";
if (Math.abs(X) <= K.lane/2 && Y <= K.ft) return "paint";
return "mid";
}
const ZONES = {paint:"Paint", mid:"Mid-range", corner3:"Corner 3", three:"Above-the-break 3", back:"Backcourt"};
// who took each shot: the person nearest the point where the ball left the hands
function attributeShots(){
// sharpen each release to where the ball starts its free climb (the shot engine's guess can include the gather or the pass)
for (const sh of S.shots || []) { if (sh._rel0 === undefined) sh._rel0 = sh.release || null; const r = refineRelease(sh); sh._fit = !!(r && r.fit); sh.release = sh._fit ? Object.assign({}, sh._rel0 || {}, {t:r.t, x:r.x, y:r.y}) : sh._rel0; }
if (!S.shots) return;
const F = S.an && S.an.frames;
for (const sh of S.shots) {
const tRel = sh.release ? sh.release.t : (sh.rimT || sh.t) - 1.0;
sh.relT = +tRel.toFixed(2);
// the people in view at release
let people = [];
if (F && F.length) { let best = null; for (const f of F) if (!best || Math.abs(f.t - tRel) < Math.abs(best.t - tRel)) best = f; if (best && Math.abs(best.t - tRel) < 0.6) people = best.p; }
let shooter = null, how = "guess";
if (sh.release && people.length) {
let bd = 1e9; for (const p of people) { const top = p[1] - p[3]/2; const dx = Math.max(0, Math.abs(sh.release.x - p[0]) - p[2]/2), dy = Math.max(0, top - sh.release.y, sh.release.y - (p[1] + p[3]/2)); const d = Math.hypot(dx, dy*0.6)/p[3]; if (d < bd) { bd = d; shooter = p; } }
how = bd < 0.35 ? "traced" : "guess";
if (bd > 0.9) shooter = null;
}
if (!shooter && people.length) {
// fallback: the person farthest from the rim (rebounders wait under it)
let bd = -1; for (const p of people) { const d = Math.hypot(p[0] - sh.rim[0], (p[1] - sh.rim[1])*0.56); if (d > bd) { bd = d; shooter = p; } }
how = "guess";
}
// better: follow the ball's shooter back to the set position just before the jump, where the detector sees them standing
sh._local = sh.release && sh._fit ? localTrack(sh, sh.release) : null;
const setBox = sh._local && localAt(sh._local, tRel - 0.45);
if (setBox) { shooter = [setBox.cx, setBox.cy, setBox.w, setBox.h]; how = "traced"; }
sh.shooterBox = shooter ? shooter.slice(0,4) : null; sh.how = how;
// is it our player?
let mine = null, sure = false;
const relDist = (b) => { const dx = Math.max(0, Math.abs(sh.release.x - b[0]) - b[2]/2), dy = Math.max(0, (b[1] - b[3]/2) - sh.release.y, sh.release.y - (b[1] + b[3]/2)); return Math.hypot(dx, dy*0.6)/b[3]; };
if (S.track && shooter) {
const tk = trackAt(setBox ? tRel - 0.45 : tRel);
if (tk && tk.ok) {
const same = Math.hypot(tk.cx - shooter[0], tk.cy - shooter[1]) < 0.5*shooter[3];
if (same) { mine = true; sure = how === "traced"; }
else if (how === "traced" && sh.release && relDist([tk.cx, tk.cy, tk.w, tk.h]) > 0.8) { mine = false; sure = true; }
else mine = null; // close call: ask the coach
}
}
if (!S.follow) { mine = true; sure = true; } // no one picked: every shot at this hoop counts (one-player workout)
if (sh.coach != null) { mine = sh.coach; sure = true; } // the coach's answer always wins
sh.mine = mine; sh.sure = sure;
// where it was taken from: the traced shooter, or our tracked player when the coach says it was theirs
let src = shooter;
if (((sh.coach === true && !setBox) || (how !== "traced" && mine === true)) && S.track) { const tk = trackAt(tRel); if (tk && tk.ok) src = [tk.cx, tk.cy, tk.w, tk.h]; }
const pre = setBox && localMedian(sh._local, tRel - 0.6, tRel - 0.28);
const feet = src ? [src[0], src[1] + src[3]/2] : null;
const cxy = pre && pre.court && src === shooter ? pre.court : feet ? toCourt(feet[0], feet[1], tRel) : null;
sh.court = cxy && cxy[1] > -4 && cxy[1] < 60 && Math.abs(cxy[0]) < 32 ? cxy.map(v => +v.toFixed(1)) : null;
if (sh.court) { const K = courtSpec(); sh.dist = +Math.hypot(sh.court[0], sh.court[1] - K.hoopY).toFixed(1); sh.zone = zoneOf(sh.court[0], sh.court[1]); sh.pts = (sh.zone === "three" || sh.zone === "corner3") ? 3 : 2; }
else { sh.dist = null; sh.zone = null; sh.pts = null; }
}
}
function movementStats(){
const tr = S.track; if (!tr || !S.H) return null;
const pts = [];
for (const q of tr) { if (!q.ok) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (!c || c[1] < -4 || c[1] > 60 || Math.abs(c[0]) > 32) continue; pts.push({t:q.t, x:c[0], y:c[1]}); }
if (pts.length < 4) return null;
// smooth: median of 3, then a short moving average
const med = pts.map((p, i) => { if (i === 0 || i === pts.length-1) return {...p}; const xs = [pts[i-1].x, p.x, pts[i+1].x].sort((a,b)=>a-b), ys = [pts[i-1].y, p.y, pts[i+1].y].sort((a,b)=>a-b); return {t:p.t, x:xs[1], y:ys[1]}; });
const sm = med.map((p, i) => { let x = 0, y = 0, n = 0; for (let j=Math.max(0,i-1); j<=Math.min(med.length-1,i+1); j++){ if (Math.abs(med[j].t - p.t) < 0.6){ x += med[j].x; y += med[j].y; n++; } } return {t:p.t, x:x/n, y:y/n}; });
let dist = 0, tracked = 0; const sp = [];
for (let i=1;i<sm.length;i++){ const dt = sm[i].t - sm[i-1].t; if (dt <= 0 || dt > 0.7) continue; const d = Math.hypot(sm[i].x - sm[i-1].x, sm[i].y - sm[i-1].y); const v = d/dt; if (v > 32) continue; dist += d; tracked += dt; sp.push({t:sm[i].t, v}); }
// top speed over 1 s windows; sprints = 1 s or more at 13 ft/s (about 9 mph) or faster
let top = 0; for (let i=0;i<sp.length;i++){ let s = 0, n = 0; for (let j=i; j<sp.length && sp[j].t - sp[i].t < 1.0; j++){ s += sp[j].v; n++; } if (n >= 3) top = Math.max(top, s/n); }
let sprints = 0, run = 0, last = null;
for (const q of sp){ if (q.v >= 13 && (!last || q.t - last < 0.6)) { run += last ? q.t - last : 0; } else if (q.v < 13) { if (run >= 1.0) sprints++; run = 0; } last = q.t; }
if (run >= 1.0) sprints++;
const zoneT = {paint:0, mid:0, corner3:0, three:0, back:0};
for (let i=1;i<sm.length;i++){ const dt = sm[i].t - sm[i-1].t; if (dt > 0 && dt <= 0.7) zoneT[zoneOf(sm[i].x, sm[i].y)] += dt; }
return {dist, tracked, top, sprints, zoneT, path:sm};
}
function shootingStats(){
if (!S.shots) return null;
const mine = S.shots.filter(s => s.mine === true);
const unsure = S.follow ? S.shots.filter(s => s.mine == null || (!s.sure && s.coach == null)).length : 0;
const made = mine.filter(s => s.made).length;
const z = {}; for (const k of Object.keys(ZONES)) z[k] = {m:0, a:0};
let pts = 0, threesA = 0, threesM = 0;
for (const s of mine) { if (s.zone) { z[s.zone].a++; if (s.made) z[s.zone].m++; } if (s.made && s.pts) pts += s.pts; if (s.pts === 3) { threesA++; if (s.made) threesM++; } }
return {att:mine.length, made, pts, threesA, threesM, zones:z, unsure, shots:mine};
}
/* ===================== form metrics and coaching moments ===================== */
const FORM = {
arc:{label:"Entry angle", unit:"°", good:v => v >= 40, target:"40°+ (45° ideal)"},
rel:{label:"Release height", unit:"× height", good:v => v >= 0.8, target:"0.8×+ (above the shoulders)"},
drift:{label:"Landing drift", unit:"ft", good:v => v <= 2, target:"≤ 2 ft"},
trigger:{label:"Catch to release", unit:"s", good:v => v <= 1.25, target:"≤ 1.2 s"}
};
const RULES = {
arc:{title:"Flat arc", fix:"The ball comes in too flat, so the rim looks smaller. Shoot up through the ball with the elbow under it, and aim to drop it in at about 45 degrees.", drill:"Arc ladder: 5 spots 3 ft from the rim, make 10 that clear an imaginary ball on the front rim", reps:"5 × 10 makes"},
rel:{title:"Low release", fix:"Finish with the ball above the forehead and the wrist over the eyebrow, so defenders can't get to it.", drill:"Wall line: tape a line 2 ft above head height, 25 one-hand shots that cross it", reps:"2 × 25"},
drift:{title:"Drifting on the shot", fix:"Set both feet before the catch, jump straight up and land on the same spot, chest still facing the rim.", drill:"Spot landing: tape an X, catch, shoot and land on it with both feet", reps:"3 × 10 from 15 ft"},
set:{title:"Shooting on the move", fix:"Hop into the catch so both feet are set before the ball arrives.", drill:"1-2 step catch-and-shoot from both wings", reps:"4 × 8"},
trigger:{title:"Slow trigger", fix:"Catch in the shot pocket and go. Aim for about 0.7 s from catch to release.", drill:"Partner passes; shoot before the partner finishes saying 'one'", reps:"3 × 10"},
walk:{title:"Walking between reps", fix:"Move to the next spot at game speed. Walking reps don't build game legs.", drill:"Every rep ends with a sprint to the next spot", reps:"Whole workout"}
};
function flightFit(sh){
// one parabola through the ball's free flight: x linear and y quadratic in time, outliers trimmed
const seen = new Set();
let F = (sh.flight || []).filter(p => p[0] <= (sh.rimT || 1e9) + 0.05).sort((a, b) => a[0] - b[0]).filter(p => { const k = p[0].toFixed(2); if (seen.has(k)) return false; seen.add(k); return true; });
if (F.length < 8) return null;
// stop at the first time the ball comes back down to the rim; drop samples clipped by the frame edge or tangled in the rim and net
let ai = 0; for (let i=0;i<F.length;i++) { if (F[i][2] < F[ai][2]) ai = i; else if (F[i][2] > F[ai][2] + 0.08 && F[i][2] >= sh.rim[1]) break; }
let end = F.length; for (let k=ai;k<F.length;k++) if (F[k][2] >= sh.rim[1]) { end = k + 1; break; }
const rw = sh.rim[2];
F = F.slice(0, end).filter(p => p[2] > 0.035 && p[1] > 0.01 && p[1] < 0.99 && Math.hypot((p[1] - sh.rim[0])*16/9, p[2] - sh.rim[1]) > rw*16/9*1.3);
if (F.length < 8) return null;
ai = 0; for (let i=0;i<F.length;i++) if (F[i][2] < F[ai][2]) ai = i;
const ta = F[ai][0], AR = 16/9;
const solve = (A, b) => { const n = b.length, M = A.map((r, i) => r.concat(b[i])); for (let c=0;c<n;c++){ let pv = c; for (let r=c+1;r<n;r++) if (Math.abs(M[r][c]) > Math.abs(M[pv][c])) pv = r; [M[c], M[pv]] = [M[pv], M[c]]; if (!M[c][c]) return null; for (let r=0;r<n;r++) if (r !== c) { const f = M[r][c]/M[c][c]; for (let k=c;k<=n;k++) M[r][k] -= f*M[c][k]; } } return M.map((r, i) => r[n]/r[i]); };
// gravity sets the curve: 16.1 ft/s^2 times the pixels per foot at the rim (rim = 18 in). The free fit may scale it by up to 25% for depth.
const vw = vid.videoWidth || 16, vh = vid.videoHeight || 9, g2 = 16.1 * (rw*vw/1.5) / vh;
const fit = (pts) => { const A = [[0,0,0],[0,0,0],[0,0,0]], by = [0,0,0], A2 = [[0,0],[0,0]], bx = [0,0], A3 = [[0,0],[0,0]], b3 = [0,0];
for (const p of pts) { const u = p[0] - ta, r = [1, u, u*u]; for (let i=0;i<3;i++){ for (let j=0;j<3;j++) A[i][j] += r[i]*r[j]; by[i] += r[i]*p[2]; } for (let i=0;i<2;i++){ for (let j=0;j<2;j++) A2[i][j] += r[i]*r[j]; bx[i] += r[i]*p[1]; } }
const free = solve(A, by), cx = solve(A2, bx); if (!free || !cx) return null;
const c2 = clamp(free[2], g2*0.75, g2*1.25);
for (const p of pts) { const u = p[0] - ta, r = [1, u]; for (let i=0;i<2;i++){ for (let j=0;j<2;j++) A3[i][j] += r[i]*r[j]; b3[i] += r[i]*(p[2] - c2*u*u); } }
const c01 = solve(A3, b3); if (!c01) return null;
return {cx, cy:[c01[0], c01[1], c2], g:free[2]/g2}; };
const err = (m, p) => { const u = p[0] - ta; return Math.hypot((p[1] - (m.cx[0] + m.cx[1]*u))*AR, p[2] - (m.cy[0] + m.cy[1]*u + m.cy[2]*u*u)); };
// seed on the clean middle of the flight, then grow backward toward the hand
let use = F.filter(p => p[0] >= ta - 0.45 && p[0] <= ta + 0.2);
if (use.length < 6) use = F.slice();
let m = fit(use); if (!m) return null;
for (let it = 0; it < 2; it++) { const e = use.map(p => err(m, p)).sort((a, b) => a - b), cut = Math.max(0.006, e[e.length >> 1]*3); use = use.filter(p => err(m, p) <= cut); if (use.length < 5) return null; m = fit(use) || m; }
const tol = Math.max(0.007, sh.rim[2]*AR*0.3);
// a jump shot leaves the hands above the shoulders: below that line the ball is still being dribbled or carried
const shoulder = (p) => { const Fr = S.an && S.an.frames; if (!Fr || !Fr.length) return 1; let fr = Fr[0]; for (const q of Fr) if (Math.abs(q.t - p[0]) < Math.abs(fr.t - p[0])) fr = q; let best = null, bd = 1e9; for (const b of fr.p) { const d = Math.abs(b[0] - p[1]); if (d < b[2]*0.9 && d < bd) { bd = d; best = b; } } return best ? best[1] - best[3]/2 + best[3]*0.22 : 1; };
let rel = use[0], miss = 0;
for (let i = F.indexOf(use[0]) - 1; i >= 0; i--) { if (F[i][2] > shoulder(F[i])) break; if (err(m, F[i]) <= tol) { rel = F[i]; miss = 0; use = [F[i]].concat(use); m = fit(use) || m; } else if (++miss >= 2) break; }
if (rel[2] > shoulder(rel)) return null;
const pts = F.filter(p => p[0] >= rel[0] && err(m, p) <= tol*1.5);
const res = pts.reduce((s, p) => s + err(m, p), 0) / Math.max(1, pts.length);
if (m.cy[2] <= 0) return null;
const tApex = ta - m.cy[1]/(2*m.cy[2]), yApex = m.cy[0] + m.cy[1]*(tApex - ta) + m.cy[2]*(tApex - ta)**2;
const disc = m.cy[1]**2 - 4*m.cy[2]*(m.cy[0] - sh.rim[1]), tRim = ta + (-m.cy[1] + Math.sqrt(Math.max(0, disc)))/(2*m.cy[2]);
return {m, ta, rel, res, tol, n:pts.length, tApex, yApex, tRim, at:(t) => { const u = t - ta; return [m.cx[0] + m.cx[1]*u, m.cy[0] + m.cy[1]*u + m.cy[2]*u*u]; }};
}
function refineRelease(sh){
const r0 = sh._rel0 !== undefined ? sh._rel0 : sh.release;
const ff = flightFit(sh); sh._ff = ff;
// a real shot climbs at least two rim-widths to the top of its arc, and its flight fits one parabola
if (!ff || ff.res > ff.tol || ff.rel[2] - ff.yApex < sh.rim[2]*1.78*2) return r0 ? {t:r0.t, x:r0.x, y:r0.y, fit:false} : null;
return {t:ff.rel[0], x:ff.rel[1], y:ff.rel[2], fit:true};
}
function courtMedian(a, b){
const xs = [], ys = [];
for (const q of S.track || []) { if (!q.ok || q.t < a || q.t > b) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (c) { xs.push(c[0]); ys.push(c[1]); } }
if (!xs.length) return null;
xs.sort((u,v) => u-v); ys.sort((u,v) => u-v);
return [xs[xs.length>>1], ys[ys.length>>1]];
}
function localTrack(sh, r){
// follow the shooter for ~2.5 s around the release from the detections alone: nearest box each frame, same look
const F = S.an && S.an.frames; if (!F || !F.length || !r) return null;
let f0 = 0; for (let i=0;i<F.length;i++) if (Math.abs(F[i].t - (r.t - 0.45)) < Math.abs(F[f0].t - (r.t - 0.45))) f0 = i;
let seed = null, bd = 1e9;
for (const p of F[f0].p) { const dx = Math.abs(p[0] - r.x), top = p[1] - p[3]/2, dy = r.y < top ? (top - r.y)/p[3] : r.y > p[1] + p[3]/2 ? 9 : 0; const d = dx/p[3] + dy; if (d < bd) { bd = d; seed = p; } }
if (!seed || bd > 1.2) return null;
const out = [{t:F[f0].t, cx:seed[0], cy:seed[1], w:seed[2], h:seed[3]}];
for (const dir of [-1, 1]) {
let cur = seed, miss = 0;
for (let i = f0 + dir; i >= 0 && i < F.length && Math.abs(F[i].t - r.t) < 3.2; i += dir) {
let best = null, bc = 1e9;
for (const p of F[i].p) { const d = Math.hypot(p[0] - cur[0], (p[1] + p[3]/2) - (cur[1] + cur[3]/2)), sim = bhat(p[5], cur[5]); if (d < 0.07 + miss*0.03 && sim > 0.6) { const c = d - sim*0.05; if (c < bc) { bc = c; best = p; } } }
if (!best) { if (++miss > 2) break; continue; }
miss = 0; cur = best; out.push({t:F[i].t, cx:best[0], cy:best[1], w:best[2], h:best[3]});
}
}
return out.sort((a, b) => a.t - b.t);
}
function localAt(L, t){ if (!L || !L.length) return null; let a = null, b = null; for (const q of L) { if (q.t <= t) a = q; if (q.t >= t && !b) b = q; } if (!a || !b) return null; if (b.t - a.t > 0.6) return null; const u = b.t > a.t ? (t - a.t)/(b.t - a.t) : 0; return {cx:a.cx + (b.cx-a.cx)*u, cy:a.cy + (b.cy-a.cy)*u, w:a.w + (b.w-a.w)*u, h:a.h + (b.h-a.h)*u}; }
function localCourt(L, t){ const k = localAt(L, t); return k ? toCourt(k.cx, k.cy + k.h/2, t) : null; }
function localMedian(L, a, b){ const xs = [], ys = [], hs = [], fy = []; for (const q of L || []) { if (q.t < a || q.t > b) continue; const c = toCourt(q.cx, q.cy + q.h/2, q.t); if (c) { xs.push(c[0]); ys.push(c[1]); } hs.push(q.h); fy.push(q.cy + q.h/2); } if (!hs.length) return null; const md = v => { v.sort((u,w) => u-w); return v[v.length>>1]; }; return {court: xs.length ? [md(xs), md(ys)] : null, h:md(hs), feet:md(fy)}; }
function standingAt(t){
// set position: feet and standing height in the half second before the jump
if (!S.track) return null;
const hs = [], fy = [];
for (const q of S.track) if (q.ok && q.t >= t - 0.95 && q.t <= t - 0.3) { hs.push(q.h); fy.push(q.cy + q.h/2); }
if (!hs.length) return null;
hs.sort((a,b) => a-b); fy.sort((a,b) => a-b);
return {h: hs[hs.length>>1], feet: fy[fy.length>>1]};
}
function courtAt(t){ const tk = trackAt(t); if (!tk || !tk.ok) return null; return toCourt(tk.cx, tk.cy + tk.h/2, t); }
function shotForm(sh){
const f = {};
if (sh.mine !== true) return f;
const r = sh._fit && sh.release ? {t:sh.release.t, x:sh.release.x, y:sh.release.y, fit:true} : null;
if (!r) { f.unmeasured = "release not seen"; f.flags = []; return f; }
const t = r.t, layup = sh.dist != null && sh.dist < 8;
f.relPt = r; f.layup = layup;
const L = sh._local || localTrack(sh, r); f.local = L;
// arc: the angle the ball comes down into the rim (45 degrees is ideal), and how high it peaked over the rim
const ff = sh._ff || flightFit(sh), vw = vid.videoWidth || 16, vh = vid.videoHeight || 9;
if (ff && ff.res <= ff.tol) {
f.arcFt = +Math.max(0, (sh.rim[1] - ff.yApex) * vh / (sh.rim[2]*vw/1.5)).toFixed(1);
const tf = ff.tRim - ff.tApex, T = ff.tRim - t;
const vyPx = 2*ff.m.cy[2]*tf*vh, vxPx = Math.abs(ff.m.cx[1])*vw;
// with the court marked: gravity and the shot's distance give the true angle from the flight times alone.
// without it: read the angle off the picture, but only for a side-on camera (a ball flying toward or away from the lens looks steeper than it is)
// ballistics: tan(entry) = (g T^2 / 2 - rise) / D, with T the time from release to the rim, D the distance and rise = rim minus release height (about 3 ft)
if (sh.dist && sh.dist >= 8 && T > 0.3) { f.arc = Math.round(Math.atan2(16.1*T*T - 3, Math.max(1, sh.dist - 1.5))*180/Math.PI); f.arcHow = "court"; }
// side-on check: the ball's fall must match gravity at the rim's scale (within 20%), or the flight runs toward or away from the lens
// and the sideways travel in the picture must cover most of the distance that flight time implies (a shot at 45 degrees covers about 16 T^2 - 3 ft)
else if (!S.H && ff.m.g >= 0.8 && ff.m.g <= 1.25 && Math.abs(ff.at(ff.tRim)[0] - r.x)*vw/(sh.rim[2]*vw/1.5) >= 0.75*(16.1*T*T - 3)) { f.arc = Math.round(Math.atan2(vyPx, vxPx)*180/Math.PI); f.arcHow = "picture"; }
f.ff = ff;
}
const pre = localMedian(L, t - 0.6, t - 0.28), stand = localMedian(L, t - 1.0, t - 0.5) || pre;
if (pre) {
f.st = {h:stand.h, feet:pre.feet};
f.rel = +((pre.feet - r.y) / stand.h).toFixed(2);
// floor positions in feet: the court map when it's marked, otherwise the player's own height (about 5.75 ft) as the ruler
const k = 5.75 / (stand.h * vh), approx = !S.H;
const floorAt = (q) => { if (S.H) return toCourt(q.cx, q.cy + q.h/2, q.t); const a = poseAt(q.t), b = poseAt(t), z = a && b && a[3] > 0 ? b[3]/a[3] : 1, ox = a ? a[1] : 0, oy = a ? a[2] : 0; return [(q.cx - ox)*z*vw*k, (q.cy + q.h/2 - oy)*z*vh*k]; };
const medFloor = (a, b) => { const P = (L || []).filter(q => q.t >= a && q.t <= b).map(floorAt).filter(Boolean); if (!P.length) return null; const md = v => v.sort((x, y) => x - y)[v.length >> 1]; return [md(P.map(c => c[0])), md(P.map(c => c[1]))]; };
const p0 = medFloor(t - 0.6, t - 0.28), p1 = medFloor(t + 0.6, t + 1.25);
// more than 6 ft is a tracking slip, not a jump shot
if (p0 && p1) { const d = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]); if (d <= 6) { f.drift = +d.toFixed(1); if (S.H) { f.p0 = p0; f.p1 = p1; } f.approx = approx; } }
// catch to release: time since the run into the spot ended (two quick steps in a row)
if (L) {
const C = L.filter(q => q.t <= t - 0.45).map(q => ({t:q.t, c:floorAt(q)})).filter(q => q.c);
const v = i => Math.hypot(C[i].c[0] - C[i-1].c[0], C[i].c[1] - C[i-1].c[1]) / Math.max(0.1, C[i].t - C[i-1].t);
for (let i = C.length - 1; i >= 2; i--) if (v(i) > 3.5 && v(i-1) > 3.5) { f.trigger = +(t - C[i].t).toFixed(1); break; }
}
} else f.unmeasured = "shooter not found at the release";
if (layup) { delete f.arc; delete f.rel; delete f.trigger; delete f.set; delete f.drift; }
f.flags = Object.keys(FORM).filter(k => f[k] != null && !FORM[k].good(f[k]) && !(k === "drift" && f.approx && f[k] <= 2.5));
if (ff) f.g = +ff.m.g.toFixed(2);
f.score = Math.max(0, 100 - f.flags.length * 22);
return f;
}
function speedSeries(){
const mv = movementStats(); if (!mv) return null;
const P = mv.path, out = [];
for (let i=1;i<P.length;i++){ const dt = P[i].t - P[i-1].t; if (dt <= 0 || dt > 0.7) continue; out.push({t:P[i].t, v:Math.hypot(P[i].x - P[i-1].x, P[i].y - P[i-1].y)/dt}); }
// smooth over about a second
return out.map((q, i) => { let s = 0, n = 0; for (let j=Math.max(0,i-2); j<=Math.min(out.length-1,i+2); j++){ s += out[j].v; n++; } return {t:q.t, v:s/n}; });
}
const INTENSITY = [{max:5.5, name:"Walk", col:"#56627c"}, {max:9, name:"Jog", col:"#2EE6C5"}, {max:14, name:"Run", col:"#FFC24B"}, {max:99, name:"Sprint", col:"#FF5A1F"}];
const intensityOf = v => INTENSITY.find(z => v < z.max);
function coachMoments(){
const M = [];
if (S.shots) for (const sh of S.shots) {
if (sh.mine !== true) continue;
sh.form = shotForm(sh);
const f = sh.form, t = f.relPt ? f.relPt.t : (sh.relT || sh.t);
if (f.flags && f.flags.length) {
for (const k of f.flags) M.push({t, kind:"fix", key:k, shot:sh, title:RULES[k].title, metric:`${FORM[k].label}: ${k === "drift" && f.approx ? "about " : ""}${fmtV(k, f[k])}${k === "arc" && f.arcFt != null ? `, ${f.arcFt} ft over the rim` : ""} (target ${FORM[k].target})`, fix:RULES[k].fix, drill:RULES[k].drill, reps:RULES[k].reps});
} else if (f.arc != null || f.drift != null) {
const bits = []; if (f.arc != null) bits.push(`${f.arc}° into the rim${f.arcFt != null ? `, ${f.arcFt} ft over it` : ""}`); if (f.drift != null) bits.push(`landed ${f.drift} ft from takeoff`); if (f.trigger != null) bits.push(`${f.trigger} s catch to release`);
M.push({t, kind:"good", shot:sh, title: f.layup ? "Clean finish" : "Good rep", metric: bits.join(" · "), fix:"Repeat this one: feet set, straight up, high finish."});
}
}
const sp = speedSeries(); S.speed = sp;
if (sp && sp.length > 4) {
// walking with somewhere to go: a move between spots of 9+ ft that never got past a jog
let a = null, dist = 0, peak = 0;
for (let i=1;i<sp.length;i++){
const moving = sp[i].v > 1.5;
if (moving) { if (a == null) { a = sp[i-1].t; dist = 0; peak = 0; } dist += sp[i].v*(sp[i].t - sp[i-1].t); peak = Math.max(peak, sp[i].v); }
if ((!moving || i === sp.length-1) && a != null) { const b = sp[i-1].t; if (b - a >= 2.5 && dist >= 9 && peak < 7.5) M.push({t:a, end:b, kind:"fix", key:"walk", title:RULES.walk.title, metric:`${Math.round(dist)} ft in ${(b-a).toFixed(1)} s, top ${(peak*0.6818).toFixed(1)} mph (game speed 8+ mph)`, fix:RULES.walk.fix, drill:RULES.walk.drill, reps:RULES.walk.reps}); a = null; }
}
// best burst
let best = null; for (const q of sp) if (!best || q.v > best.v) best = q;
if (best && best.v >= 13) M.push({t:best.t - 0.5, kind:"good", title:"Top-speed burst", metric:`${(best.v*0.6818).toFixed(1)} mph`, fix:"This is game speed. Ask for it on every transition rep."});
}
M.sort((a,b) => a.t - b.t);
S.moments = M;
return M;
}
function formSummary(){
const shots = (S.shots || []).filter(s => s.mine === true && s.form && !s.form.layup);
const out = {};
for (const k of Object.keys(FORM)) {
const v = shots.map(s => s.form[k]).filter(x => x != null);
if (!v.length) continue;
v.sort((a,b) => a-b);
out[k] = {median: v[v.length>>1], n: v.length, flagged: v.filter(x => !FORM[k].good(x)).length};
}
const sc = shots.map(s => s.form.score).filter(x => x != null);
out.score = sc.length ? Math.round(sc.reduce((a,b) => a+b, 0)/sc.length) : null;
return out;
}
/* ===================== coaching UI: hero, scorecard, moments, timeline lanes, overlays ===================== */
const fmtV = (k, v) => /^[°×]/.test(FORM[k].unit) ? `${v}${FORM[k].unit.split(" ")[0]}` : `${v} ${FORM[k].unit.split(" ")[0]}`;
const GAUGE = {arc:{lo:25,hi:60,t:40,dir:1}, rel:{lo:0.5,hi:1.7,t:0.8,dir:1}, drift:{lo:0,hi:5,t:2,dir:-1}, set:{lo:0,hi:10,t:3,dir:-1}, trigger:{lo:0,hi:2.5,t:1.25,dir:-1}};
const SHORT = {arc:"ARC", rel:"LOW", drift:"DRIFT", trigger:"SLOW", walk:"WALK"};
function gaugeHTML(k, v){
const g = GAUGE[k]; if (!g || v == null) return "";
const P = x => clamp((x - g.lo)/(g.hi - g.lo), 0, 1)*100, okA = g.dir > 0 ? P(g.t) : 0, okB = g.dir > 0 ? 100 : P(g.t);
return `<div class="gtrack" aria-hidden="true"><span class="ok" style="left:${okA}%;width:${okB-okA}%"></span><span class="v ${FORM[k].good(v) ? "ok2" : ""}" style="left:${P(v)}%"></span></div>`;
}
const who = () => S.follow && S.follow.number ? "#" + S.follow.number : "Player";
function fixCounts(){
const c = {};
for (const m of S.moments || []) if (m.kind === "fix") (c[m.key] = c[m.key] || []).push(m);
return Object.entries(c).sort((a, b) => b[1].length - a[1].length || a[1][0].t - b[1][0].t);
}
function ringSVG(score){
const r = 40, C = 2*Math.PI*r, f = score == null ? 0 : score/100, col = score == null ? "#5D6679" : score >= 75 ? "#3DDC84" : score >= 55 ? "#FFC24B" : "#FF5A1F";
return `<div class="ring"><svg viewBox="0 0 92 92" aria-hidden="true"><circle cx="46" cy="46" r="${r}" fill="none" stroke="rgba(255,255,255,.08)" stroke-width="7"/><circle cx="46" cy="46" r="${r}" fill="none" stroke="${col}" stroke-width="7" stroke-linecap="round" stroke-dasharray="${(C*f).toFixed(1)} ${C.toFixed(1)}"/></svg><b class="num">${score == null ? "–" : score}<small>FORM</small></b></div>`;
}
function renderHero(){
const H = $("#hero"); if (!H) return;
const sh = shootingStats(), mv = movementStats(), fs = formSummary();
if (!(sh && sh.att) && !mv) { H.hidden = true; return; }
H.hidden = false;
const fc = fixCounts();
const prio = fc.slice(0, 3).map(([k, L]) => `<button type="button" data-goto="${L[0].t}">${esc(RULES[k].title)} ×${L.length}</button>`).join("") || `<button type="button" class="okp">No form flags</button>`;
const dur = vid.duration || (S.an && S.an.duration) || 0, cov = mv && dur ? Math.round(mv.tracked/dur*100) : null;
const kpi = (v, lab, note, ok) => `<div class="kpi"><b class="num">${v}</b><span>${lab}</span>${note ? `<em class="${ok ? "ok" : "bad"}">${note}</em>` : ""}</div>`;
H.innerHTML = `${ringSVG(fs.score)}
<div style="min-width:0"><div class="lab">Session report</div><h1>${esc(S.follow && S.follow.name ? S.follow.name : (S.follow && S.follow.number ? "Player #" + S.follow.number : "Shooting workout"))}</h1>
<div class="meta num">${esc(S.source.sample ? "Spot-shooting workout" : "Workout")} · ${fmt(dur)} · ${sh ? sh.att + " shots" : ""}${cov != null ? ` · on camera ${cov}%` : ""}</div>
<div class="prio" aria-label="Top fixes">${prio}</div></div>
<div class="kpis">
${sh && sh.att ? kpi(`${sh.made}/${sh.att}`, "field goals", pct(sh.made, sh.att), sh.made/sh.att >= 0.5) : ""}
${fs.arc ? kpi(fs.arc.median + "°", "entry angle", fs.arc.flagged ? `${fs.arc.flagged} flat · target 40°+` : "on target", !fs.arc.flagged) : ""}
${fs.drift ? kpi(fs.drift.median.toFixed(1), "drift, ft", fs.drift.flagged ? `${fs.drift.flagged} drifted` : "lands square", !fs.drift.flagged) : ""}
${mv ? kpi((mv.top*0.6818).toFixed(1), "top mph", `${Math.round(mv.dist)} ft run`, true) : ""}
</div>`;
}
$("#hero").addEventListener("click", e => { const b = e.target.closest("[data-goto]"); if (!b) return; const m = (S.moments || []).find(q => Math.abs(q.t - +b.dataset.goto) < 0.01); if (m) playMoment(m); });
function scorecardHTML(){
const fs = formSummary(), keys = Object.keys(FORM).filter(k => fs[k]);
if (!keys.length) return "";
let h = `<div class="rsec"><h3>Form scorecard <small>median of ${fs[keys[0]].n} jump shots</small></h3><div class="sc">`;
for (const k of keys) { const z = fs[k]; h += `<div class="srow"><span class="nm">${FORM[k].label}</span><span class="val num" style="color:${z.flagged ? "#ff9b73" : "var(--good)"}">${fmtV(k, z.median)}</span>${gaugeHTML(k, z.median)}<small>Target ${FORM[k].target} · ${z.flagged ? `${z.flagged} of ${z.n} off target` : "every rep on target"}</small></div>`; }
h += `</div></div>`;
const fc = fixCounts();
if (fc.length) {
h += `<div class="rsec"><h3>Priorities this week <small>most frequent first</small></h3><ol class="plist">`;
for (const [k, L] of fc.slice(0, 4)) h += `<li><div><b>${esc(RULES[k].title)}</b> <span class="sub">×${L.length}</span><p>${esc(RULES[k].fix)}</p><p style="color:var(--muted)"><b style="font-size:13px;letter-spacing:.06em">Drill</b> ${esc(RULES[k].drill)} · <span style="color:var(--warn)">${esc(RULES[k].reps)}</span></p><div class="acts">${L.slice(0, 4).map(m => `<button class="mini num" type="button" data-mt="${m.t}">▶ ${fmt(m.t)}</button>`).join("")}</div></div></li>`;
h += `</ol></div>`;
}
return h;
}
function renderMoments(){
const card = $("#momentsCard"), L = $("#moments"); if (!card) return;
const M = S.moments || [];
if (!M.length) { card.hidden = true; L.innerHTML = ""; return; }
card.hidden = false;
const f = S.mFilter || "all", show = M.map((m, i) => [m, i]).filter(([m]) => f === "all" || m.kind === f);
const nf = M.filter(m => m.kind === "fix").length, ng = M.length - nf;
$("#momentsSub").textContent = `${nf} to fix, ${ng} to repeat. Tap one to watch it with the correction drawn on the video.`;
L.innerHTML = show.map(([m, i]) => {
const sh = m.shot, n = sh ? S.shots.indexOf(sh) + 1 : 0, v = m.key && sh && sh.form ? sh.form[m.key] : null;
const gauge = m.key && GAUGE[m.key] && v != null ? `<div class="gauge"><div class="gl"><span>${FORM[m.key].label}</span><span><b class="num">${fmtV(m.key, v)}</b> · target ${FORM[m.key].target}</span></div>${gaugeHTML(m.key, v)}</div>` : `<div class="gauge"><div class="gl"><span>${esc(m.metric)}</span></div></div>`;
const kind = m.kind === "fix" ? (sh ? `Fix · shot ${n}` : "Fix · movement") : (sh ? `Good · shot ${n}` : "Good · movement");
return `<button type="button" class="mcard ${m.kind}" data-m="${i}"><div class="mtop"><span class="tc num"><svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M7 4.5v15l13-7.5z"/></svg>${fmt(m.t)}${m.end ? "–" + fmt(m.end) : ""}</span><span class="mkind">${kind}${sh ? (sh.made ? " · made" : " · miss") : ""}</span></div><h4>${esc(m.title)}</h4>${gauge}<p class="mfix">${esc(m.fix)}</p>${m.drill ? `<div class="drill"><b>Drill:</b> ${esc(m.drill)} <em>${esc(m.reps)}</em></div>` : ""}</button>`;
}).join("");
}
document.querySelectorAll("[data-mf]").forEach(b => b.onclick = () => { S.mFilter = b.dataset.mf; document.querySelectorAll("[data-mf]").forEach(c => c.setAttribute("aria-pressed", c === b)); renderMoments(); });
$("#moments").addEventListener("click", e => { const b = e.target.closest("[data-m]"); if (b) playMoment(S.moments[+b.dataset.m]); });
$("#report").addEventListener("click", e => { const b = e.target.closest("[data-mt]"); if (!b) return; const m = (S.moments || []).find(q => Math.abs(q.t - +b.dataset.mt) < 0.01); if (m) playMoment(m); });
function playMoment(m){
S.focusM = m;
const sh = m.shot;
if (m.end) playRange(Math.max(0, m.t - 0.6), m.end + 0.6);
else if (sh) playRange(Math.max(0, (sh.relT || sh.t) - 1.8), (sh.rimT || sh.end) + 1.9);
else playRange(Math.max(0, m.t - 1), m.t + 3);
$("#stage").scrollIntoView({behavior:"smooth", block:"nearest"});
}
function momentsAt(now){
const M = S.moments || [];
const hit = M.filter(m => m.end ? now >= m.t - 0.3 && now <= m.end + 0.4 : m.shot ? now >= (m.shot.relT || m.t) - 1.4 && now <= (m.shot.rimT || m.t + 1) + 1.9 : now >= m.t - 0.8 && now <= m.t + 2.4);
if (!hit.length) return [];
const fx = hit.filter(m => m.kind === "fix");
return fx.length ? fx : hit.slice(0, 1);
}
let coachKey = "";
function updateCoachCard(){
const C = $("#coachCard"), now = vid.currentTime || 0;
const ms = (S.aiView && !S.reel && !S.picking && !S.busy) ? momentsAt(now) : [];
const key = ms.map(m => m.t + m.title).join("|");
if (key !== coachKey) {
coachKey = key;
if (!ms.length) C.hidden = true;
else {
const m = ms[0], sh = m.shot, n = sh ? S.shots.indexOf(sh) + 1 : 0;
C.className = "coachcard " + m.kind; C.hidden = false;
C.innerHTML = `<div class="k"><span>${m.kind === "fix" ? "Coach's fix" : "Keep this"}${sh ? " · shot " + n : ""}</span><span class="num">${fmt(m.t)}</span></div><h4>${esc(ms.map(q => q.title).join(" + "))}</h4>${ms.map(q => `<div class="mt num">${esc(q.metric)}</div>`).join("")}<p>${esc(m.fix)}</p>`;
}
}
document.querySelectorAll(".mcard").forEach(el => { const m = (S.moments || [])[+el.dataset.m]; el.classList.toggle("now", !!m && ms.includes(m)); });
}
function speedNow(t){
const sp = S.speed; if (!sp || !sp.length) return null;
let lo = 0, hi = sp.length - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (sp[mid].t < t) lo = mid; else hi = mid; }
const q = Math.abs(sp[lo].t - t) < Math.abs(sp[hi].t - t) ? sp[lo] : sp[hi];
return Math.abs(q.t - t) < 0.8 ? q.v : null;
}
function updateLiveHud(){
const L = $("#liveHud");
if (!S.aiView || S.reel || S.picking || S.busy || !(S.moments || S.speed)) { L.hidden = true; return; }
const now = vid.currentTime || 0, v = speedNow(now), z = v != null ? intensityOf(v) : null;
const mine = (S.shots || []).filter(s => s.mine === true && (s.rimT || s.end) <= now + 0.05), mk = mine.filter(s => s.made).length;
const last = mine.filter(s => s.form && s.form.arc != null).pop();
const seg = INTENSITY.map((q, i) => `<i style="background:${z && INTENSITY.indexOf(z) >= i ? z.col : ""}"></i>`).join("");
L.hidden = false;
L.innerHTML = `<div class="g"><span>Speed</span><b class="num">${v != null ? (v*0.6818).toFixed(1) : "–"}<small>MPH</small></b><div class="bar5">${seg}</div></div>
<div class="g"><span>Shots</span><b class="num">${mk}/${mine.length}</b></div>
${last ? `<div class="g"><span>Last arc</span><b class="num" style="color:${FORM.arc.good(last.form.arc) ? "var(--good)" : "#ff9b73"}">${last.form.arc}<small>°</small></b></div>` : ""}`;
}
function pill(ctx, x, y, text, bg, fg, px, align){
ctx.font = `700 ${Math.round(13*px*1.35)}px "Barlow Condensed", Arial Narrow, sans-serif`;
const w = ctx.measureText(text).width + 14*px, h = 20*px, x0 = align === "right" ? x - w : align === "left" ? x : x - w/2;
ctx.fillStyle = bg; roundRect(ctx, x0, y - h/2, w, h, 5*px); ctx.fill();
ctx.fillStyle = fg; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillText(text, x0 + 7*px, y + px);
ctx.textBaseline = "alphabetic";
}
function arrow(ctx, a, b, col, px){
const ang = Math.atan2(b[1]-a[1], b[0]-a[0]), L = 12*px;
ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 3*px; ctx.lineCap = "round";
ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();
ctx.beginPath(); ctx.moveTo(b[0], b[1]); ctx.lineTo(b[0] - L*Math.cos(ang - 0.45), b[1] - L*Math.sin(ang - 0.45)); ctx.lineTo(b[0] - L*Math.cos(ang + 0.45), b[1] - L*Math.sin(ang + 0.45)); ctx.closePath(); ctx.fill();
}
function drawCoachOverlay(ctx, map, vw, vh, s, px, now){
if (!S.shots) return;
const sh = S.shots.find(q => q.mine === true && q.release && now >= (q.relT || q.t) - 1.4 && now <= (q.rimT || q.end) + 1.9);
if (!sh || !sh.form) return;
const f = sh.form; if (!f.relPt) return;
const rt = f.relPt.t, bad = k => f.flags && f.flags.includes(k);
const ftPx = sh.rim[2]*vw*s/1.5; // screen px per foot at the rim
const R = map(f.relPt.x, f.relPt.y), rim = map(sh.rim[0], sh.rim[1]);
ctx.save();
// moving into the shot: feet direction before release
if (bad("set") && now < rt + 0.4 && f.p0m && f.p1m) {
const a = fromCourt(f.p0m[0], f.p0m[1], now), b = fromCourt(f.p1m[0], f.p1m[1], now);
if (a && b) { const A = map(a[0], a[1]), B = map(b[0], b[1]); arrow(ctx, A, B, "#FF8A5C", px); pill(ctx, (A[0]+B[0])/2, Math.max(A[1], B[1]) + 22*px, `MOVING ${f.set} FT/S · SET FEET FIRST`, "#FF8A5C", "#1A0B03", px); }
}
if (now >= rt - 0.05) {
// release point and height
if (f.st && bad("rel")) {
const ty = f.st.feet - 1.25*f.st.h, T = map(f.relPt.x, ty);
ctx.setLineDash([6*px, 5*px]); ctx.strokeStyle = "#3DDC84"; ctx.lineWidth = 2.2*px;
ctx.beginPath(); ctx.moveTo(T[0] - 46*px, T[1]); ctx.lineTo(T[0] + 46*px, T[1]); ctx.stroke(); ctx.setLineDash([]);
pill(ctx, T[0] + 50*px, T[1], "RELEASE HERE", "#3DDC84", "#04130a", px, "left");
arrow(ctx, [R[0], R[1] - 4*px], [T[0], T[1] + 8*px], "rgba(61,220,132,.8)", px*0.7);
}
ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.arc(R[0], R[1], 5*px, 0, 7); ctx.fill();
ctx.strokeStyle = bad("rel") ? "#FF8A5C" : "#3DDC84"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.arc(R[0], R[1], 9*px, 0, 7); ctx.stroke();
if (now < rt + 0.5) pill(ctx, R[0] - 14*px, R[1] - 2*px, f.rel != null ? `RELEASE ${f.rel}× HEIGHT` : "RELEASE", bad("rel") ? "#FF8A5C" : "rgba(237,241,247,.92)", "#0A0D13", px, "right");
// target arc (ghost), only when the arc is flat
if (bad("arc")) {
// the arc that drops into the rim at 45 degrees from the same release point
const dx = Math.abs(rim[0] - R[0]), dy = R[1] - rim[1]; let hLo = 1, hHi = 5000, H = 0;
for (let it=0; it<40; it++){ H = (hLo + hHi)/2; const D = 2*H*(1 + Math.sqrt(Math.max(0, (H + dy)/H))); if (D > dx) hHi = H; else hLo = H; }
const apexY = rim[1] - H, y0 = R[1], y1 = rim[1];
let hgt = 0, lo = 0, hi = 4000; for (let it=0; it<40; it++){ hgt = (lo+hi)/2; let mn = 1e9; for (let u=0; u<=1; u+=0.02) mn = Math.min(mn, (1-u)*y0 + u*y1 - 4*hgt*u*(1-u)); if (mn > apexY) lo = hgt; else hi = hgt; }
ctx.setLineDash([7*px, 6*px]); ctx.strokeStyle = "rgba(61,220,132,.9)"; ctx.lineWidth = 2.4*px; ctx.beginPath();
let ax = R[0], ay = 1e9;
for (let u=0; u<=1.0001; u+=0.02){ const x = R[0] + (rim[0]-R[0])*u, y = (1-u)*y0 + u*y1 - 4*hgt*u*(1-u); u ? ctx.lineTo(x, y) : ctx.moveTo(x, y); if (y < ay) { ay = y; ax = x; } }
ctx.stroke(); ctx.setLineDash([]);
pill(ctx, ax, ay - 16*px, "TARGET · 45° INTO THE RIM", "#3DDC84", "#04130a", px);
}
// the real flight, drawn as it happens
const pts = (sh.flight || []).filter(p => p[0] <= now + 0.02);
if (pts.length > 1) {
const col = bad("arc") ? "#FF8A5C" : "#3DDC84";
ctx.shadowColor = col; ctx.shadowBlur = 12*px; ctx.strokeStyle = col; ctx.lineWidth = 3.4*px; ctx.lineJoin = "round"; ctx.lineCap = "round";
ctx.beginPath(); pts.forEach((p, i) => { const [x, y] = map(p[1], p[2]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }); ctx.stroke(); ctx.shadowBlur = 0;
let ap = sh.flight[0]; for (const p of sh.flight) if (p[2] < ap[2]) ap = p;
if (now >= ap[0] && f.arc != null) { const A = map(ap[1], ap[2]); ctx.fillStyle = col; ctx.beginPath(); ctx.arc(A[0], A[1], 4*px, 0, 7); ctx.fill(); pill(ctx, A[0], A[1] - 18*px, `${f.arcFt != null ? f.arcFt + " FT OVER RIM · " : ""}${f.arc}° IN`, col, "#0A0D13", px); }
}
// landing: takeoff to landing on the floor
if (f.p0 && f.p1 && now >= rt + 0.25) {
const a = fromCourt(f.p0[0], f.p0[1], now), b = fromCourt(f.p1[0], f.p1[1], now);
if (a && b) {
const A = map(a[0], a[1]), B = map(b[0], b[1]), col = bad("drift") ? "#FF8A5C" : "#3DDC84";
ctx.strokeStyle = "rgba(255,255,255,.85)"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.ellipse(A[0], A[1], 13*px, 4.5*px, 0, 0, 7); ctx.stroke();
if (Math.hypot(B[0]-A[0], B[1]-A[1]) > 6*px) arrow(ctx, A, B, col, px);
pill(ctx, (A[0]+B[0])/2, Math.max(A[1], B[1]) + 26*px, bad("drift") ? `DRIFT ${f.drift} FT · LAND WHERE YOU JUMP` : `LANDED ${f.drift} FT`, col, "#0A0D13", px);
}
}
}
ctx.restore();
}
/* ===================== scoring ===================== */
function robustZ(arr, win){
const n = arr.length, out = new Float32Array(n);
if (!n) return out;
// moving average baseline
const pre = new Float64Array(n+1); for (let i=0;i<n;i++) pre[i+1] = pre[i] + arr[i];
const res = new Float32Array(n);
for (let i=0;i<n;i++){ const a = Math.max(0, i-win), b = Math.min(n, i+win+1); res[i] = arr[i] - (pre[b]-pre[a])/(b-a); }
const sorted = Array.from(res).map(Math.abs).sort((x,y)=>x-y);
const mad = sorted[Math.floor(sorted.length/2)] * 1.4826 || 1;
for (let i=0;i<n;i++) out[i] = clamp(res[i]/mad, -3, 7);
return out;
}
function interpFrames(frames, key, n, fn){
const out = new Float32Array(n); if (!frames.length) return out;
let j = 0;
for (let i=0;i<n;i++){
const t = i*GRID;
while (j < frames.length-2 && frames[j+1].t < t) j++;
const a = frames[j], b = frames[Math.min(j+1, frames.length-1)];
const va = fn ? fn(a) : a[key], vb = fn ? fn(b) : b[key];
const u = b.t > a.t ? clamp((t-a.t)/(b.t-a.t), 0, 1) : 0;
out[i] = va + (vb-va)*u;
}
return out;
}
function gauss(arr, sigma){
const r = Math.ceil(sigma*3), k = []; let s = 0;
for (let i=-r;i<=r;i++){ const w = Math.exp(-i*i/(2*sigma*sigma)); k.push(w); s += w; }
const out = new Float32Array(arr.length);
for (let i=0;i<arr.length;i++){ let v = 0, ws = 0; for (let j=-r;j<=r;j++){ const q = i+j; if (q>=0 && q<arr.length){ v += arr[q]*k[j+r]; ws += k[j+r]; } } out[i] = v/ws; }
return out;
}
function series(){
const an = S.an, n = Math.max(1, Math.floor(an.duration/GRID));
let za = new Float32Array(n), zh = new Float32Array(n);
if (an.audio) {
const r = robustZ(an.audio.rms, 80), h = robustZ(an.audio.hf, 80);
for (let i=0;i<n;i++){ za[i] = (r[i]||0)*0.7 + (h[i]||0)*0.3; zh[i] = r[i]||0; }
}
const motion = interpFrames(an.frames, "m", n);
const zm = robustZ(Array.from(motion), 40);
const ball = interpFrames(an.frames, null, n, f => { let v = 0; for (const b of f.b) if (b[1] < 0.42) v = Math.max(v, 0.6 + b[2]); return v; });
const spread = interpFrames(an.frames, null, n, f => {
if (f.p.length < 3) return 0;
let cx = 0, cy = 0; for (const p of f.p){ cx += p[0]; cy += p[1]; } cx /= f.p.length; cy /= f.p.length;
let s = 0; for (const p of f.p) s += Math.hypot(p[0]-cx, (p[1]-cy)*0.56); return -s/f.p.length;
});
const zc = robustZ(Array.from(spread), 40);
let inv = new Float32Array(n), pres = new Float32Array(n);
if (S.track) {
const tr = S.track;
pres = interpFrames(tr, null, n, f => f.ok ? 1 : 0);
inv = interpFrames(tr, null, n, (f) => {
if (!f.ok) return 0;
const fr = an.frames[f.i]; let near = 0;
const tx = fr.b.length ? fr.b[0][0] : fr.ax, ty = fr.b.length ? fr.b[0][1] : fr.ay;
if (tx != null) near = 1 - clamp(Math.hypot(f.cx - tx, (f.cy - ty)*0.56)/0.3, 0, 1);
return 0.35 + 0.65*near;
});
}
return {n, za, zh, zm, ball, zc, inv, pres};
}
function rescore(fresh){
if (!S.an) return;
const sp = SPORTS[S.sport], sz = SIZES[S.size], X = series(); S.X = X;
const P = S.track ? (S.mineFirst ? 2.2 : 0.8) : 0;
const raw = new Float32Array(X.n);
const hasAudio = !!S.an.audio;
for (let i=0;i<X.n;i++) raw[i] = (hasAudio ? sp.A : 0)*X.za[i] + sp.M*(hasAudio ? 1 : 1.6)*X.zm[i] + sp.B*2*X.ball[i] + sp.C*X.zc[i] + P*X.inv[i];
const useShots = S.sport === "basketball" && S.shots && S.shots.length;
if (useShots) for (const sh of S.shots) { const i0 = Math.round(sh.t/GRID); for (let d=-2; d<=6; d++){ const i = i0 + d; if (i >= 0 && i < X.n) raw[i] += sh.made ? 5 : 2.2; } }
const sc = gauss(raw, 0.75/GRID); S.score = sc;
let mean = 0; for (const v of sc) mean += v; mean /= sc.length;
let sd = 0; for (const v of sc) sd += (v-mean)**2; sd = Math.sqrt(sd/sc.length) || 1;
S.scoreStats = {mean, sd};
const half = Math.round(sp.gap/2/GRID), thr = mean + sz.k*sd, peaks = [];
for (let i=1;i<sc.length;i++){
if (sc[i] < thr) continue;
let isMax = true;
for (let j=Math.max(0,i-half); j<=Math.min(sc.length-1,i+half); j++) if (sc[j] > sc[i] || (sc[j] === sc[i] && j < i)) { isMax = false; break; }
if (isMax) peaks.push(i);
}
peaks.sort((a,b) => sc[b]-sc[a]);
const capN = Math.max(sz.min, Math.round(S.an.duration/60*sz.per));
const chosen = peaks.slice(0, capN).sort((a,b) => a-b);
const old = fresh ? [] : S.clips;
const clips = [];
for (const i of chosen) {
const peak = i*GRID;
// lock peak to the start of the reaction: walk back while audio is rising
let start = Math.max(0, peak - sp.pre), end = Math.min(S.an.duration, peak + sp.post);
const prev = clips[clips.length-1];
if (prev && start < prev.end) {
if (peak - prev.peak >= 3.5) { const mid = Math.max(prev.peak + 1.5, peak - sp.pre*0.6); prev.end = Math.min(prev.end, mid); start = Math.max(start, prev.end); }
else { if (sc[i] > prev.raw) { prev.peak = peak; prev.raw = sc[i]; } prev.end = Math.max(prev.end, Math.min(end, prev.start + 14)); continue; }
}
clips.push({start, end, peak, raw:sc[i]});
}
clips.forEach((c, k) => {
const lo = Math.max(0, Math.round((c.peak-1.5)/GRID)), hi = Math.min(X.n-1, Math.round((c.peak+1.5)/GRID));
let a = -9, m = -9, b = 0, iv = 0, pr = 0;
for (let i=lo;i<=hi;i++){ a = Math.max(a, X.za[i]); m = Math.max(m, X.zm[i]); b = Math.max(b, X.ball[i]); iv = Math.max(iv, X.inv[i]); }
const s0 = Math.round(c.start/GRID), s1 = Math.round(c.end/GRID); let cnt = 0;
for (let i=s0;i<s1 && i<X.n;i++){ pr += X.pres[i]; cnt++; }
pr = cnt ? pr/cnt : 0;
const tags = [];
let ti = 3;
if (hasAudio && a > 2.2) { tags.push(["Crowd roar","hot"]); ti = 0; }
else if (hasAudio && a > 1.0) { tags.push(["Crowd reaction",""]); ti = 1; }
if (m > 1.4) { tags.push(["Fast action",""]); if (ti > 1) ti = 2; }
if (b > 0.5) tags.push(["Ball in the air",""]);
c.shot = null;
if (useShots) {
const inClip = S.shots.filter(sh => sh.t >= c.start - 0.3 && sh.t <= c.end);
if (inClip.some(sh => sh.made)) { tags.unshift(["Made basket","hot"]); ti = 0; c.shot = "made"; }
else if (inClip.length) { tags.unshift(["Missed shot",""]); if (ti > 1) ti = 3; c.shot = "miss"; }
}
const mine = !!(S.track && pr > 0.45);
if (mine) tags.push([(S.follow.number ? "#" + S.follow.number : "Your player") + " on screen","trk"]);
const prevClip = old.find(o => Math.abs(o.peak - c.peak) < 1.5);
c.id = "c" + Math.round(c.peak*4);
c.title = sp.titles[ti];
if (c.shot === "made") c.title = "Bucket!"; else if (c.shot === "miss") c.title = "Shot attempt";
c.tags = tags; c.mine = !!mine; c.presence = pr;
c.pct = clamp(Math.round(50 + 18*(c.raw - mean)/sd), 1, 99);
c.keep = prevClip ? prevClip.keep : true;
c.thumb = prevClip ? prevClip.thumb : (S.thumbCache && S.thumbCache[c.id]) || null;
c.ai = prevClip ? prevClip.ai : null;
if (c.ai) { c.title = c.ai.title || c.title; }
if (prevClip && prevClip.trimmed) { c.start = prevClip.start; c.end = prevClip.end; c.trimmed = true; }
});
if (S.mineFirst && S.track) clips.sort((a,b) => (b.mine - a.mine) || (a.start - b.start));
S.clips = clips;
renderRail(); drawTimeline();
if (!fresh) makeThumbs();
}
/* ===================== tracking ===================== */
function buildTrack(){
const an = S.an, F = an.frames; if (!S.follow || !F.length || !an.vision) return null;
// 1. multi-object tracklets: every detection is claimed by at most one track per frame
const tid = F.map(f => new Array(f.p.length).fill(-1));
const T = []; let active = [];
for (let i=0;i<F.length;i++){
const P = F[i].p;
let sx = 0, sy = 0; // camera pan between samples
if (i > 0 && F[i-1].p.length && P.length) {
const dxs = [], dys = [];
for (const p of P) { let bd = 1, bq = null; for (const q of F[i-1].p) { const d = Math.hypot(p[0]-q[0], p[1]-q[1]); if (d < bd && bhat(p[5], q[5]) > 0.7) { bd = d; bq = q; } } if (bq && bd < 0.25) { dxs.push(p[0]-bq[0]); dys.push(p[1]-bq[1]); } }
if (dxs.length >= 2) { dxs.sort((x,y)=>x-y); dys.sort((x,y)=>x-y); sx = dxs[dxs.length>>1]; sy = dys[dys.length>>1]; }
}
const pairs = [];
active.forEach((tr, a) => {
const px = tr.x + tr.vx + sx, py = tr.y + tr.vy + sy;
P.forEach((p, k) => {
const d = Math.hypot(p[0]-px, (p[1]-py)*0.8), sim = bhat(p[5], tr.sig), hz = Math.abs(Math.log((p[3]+1e-3)/(tr.h+1e-3)));
if (d < 0.16 + 0.05*tr.miss && sim > 0.55) pairs.push([d*2.2 + (1-sim)*1.2 + hz*0.4, a, k]);
});
});
pairs.sort((u,v) => u[0]-v[0]);
const usedA = new Set(), usedK = new Set();
// a crossing with a look-alike makes the match ambiguous: end the tracklet instead of guessing
const firstCost = new Map(), contested = new Set();
for (const [c, a] of pairs) { if (!firstCost.has(a)) firstCost.set(a, c); else if (c - firstCost.get(a) < 0.07 && !contested.has(a)) contested.add(a); }
for (const a of contested) { active[a].miss = 99; usedA.add(a); }
for (const [, a, k] of pairs) {
if (usedA.has(a) || usedK.has(k)) continue;
usedA.add(a); usedK.add(k);
const tr = active[a], p = P[k];
tr.vx = (p[0]-tr.x-sx)*0.5 + tr.vx*0.5; tr.vy = (p[1]-tr.y-sy)*0.5 + tr.vy*0.5;
tr.x = p[0]; tr.y = p[1]; tr.h = p[3]; tr.miss = 0;
for (let j=0;j<15;j++) tr.sig[j] = tr.sig[j]*0.85 + p[5][j]*0.15;
tr.items.push([i,k]); tid[i][k] = tr.id;
}
active.forEach((tr, a) => { if (!usedA.has(a) || tr.miss >= 99) { tr.miss++; tr.x += tr.vx*0.5 + sx; tr.y += tr.vy*0.5 + sy; tr.vx *= 0.5; tr.vy *= 0.5; } });
active = active.filter(tr => tr.miss <= 3);
P.forEach((p, k) => { if (!usedK.has(k)) { const tr = {id:T.length, x:p[0], y:p[1], h:p[3], vx:0, vy:0, sig:p[5].slice(), miss:0, items:[[i,k]]}; T.push(tr); active.push(tr); tid[i][k] = tr.id; } });
}
// 2. chain tracklets outward from each anchor
const out = F.map((f,i) => ({t:f.t, i, ok:false, cx:0, cy:0, w:0, h:0, dist:1e9}));
const det = (it) => F[it[0]].p[it[1]];
for (const anc of S.follow.anchors) {
let fi = 0; for (let i=0;i<F.length;i++) if (Math.abs(F[i].t-anc.t) < Math.abs(F[fi].t-anc.t)) fi = i;
let best = -1, bs = -9;
F[fi].p.forEach((p, k) => { const s = bhat(p[5], anc.sig) - Math.hypot(p[0]-anc.box[0], p[1]-anc.box[1])*4; if (s > bs) { bs = s; best = k; } });
if (best < 0) continue;
const chain = new Set([tid[fi][best]]);
for (const dir of [1, -1]) {
let cur = T[tid[fi][best]];
for (let guard = 0; guard < 400; guard++) {
const edge = dir > 0 ? cur.items[cur.items.length-1] : cur.items[0];
const eP = det(edge);
let cand = null, cs = 1e9, second = 1e9;
for (const tr of T) {
if (chain.has(tr.id)) continue;
const st = dir > 0 ? tr.items[0] : tr.items[tr.items.length-1];
const gap = (st[0] - edge[0])*dir;
if (gap < 1 || gap > 6) continue;
const p = det(st), d = Math.hypot(p[0]-eP[0], p[1]-eP[1]), sim = bhat(p[5], anc.sig);
const c = d*1.5 + (1-sim)*2 + gap*0.05;
if (sim > 0.65 && d < 0.10 + gap*0.025) { if (c < cs) { second = cs; cs = c; cand = tr; } else if (c < second) second = c; }
}
if (!cand || second - cs < 0.08) {
// lost: pick the player up again later, but only if their look is unmistakable in that frame
cand = null; let bestSim = 0.85;
for (const tr of T) {
if (chain.has(tr.id) || tr.items.length < 3) continue;
const st = dir > 0 ? tr.items[0] : tr.items[tr.items.length-1];
const gap = (st[0] - edge[0])*dir; if (gap < 1 || gap > 60) continue;
const p = det(st), sim = bhat(p[5], anc.sig);
if (sim <= bestSim) continue;
const rivals = F[st[0]].p.filter(q => q !== p && bhat(q[5], anc.sig) > 0.72).length;
if (!rivals) { bestSim = sim; cand = tr; }
}
if (!cand) break;
}
chain.add(cand.id); cur = cand;
}
}
for (const id of chain) for (const it of T[id].items) {
const dist = Math.abs(F[it[0]].t - anc.t);
if (dist < out[it[0]].dist) { const p = det(it); out[it[0]] = {t:F[it[0]].t, i:it[0], ok:true, cx:p[0], cy:p[1], w:p[2], h:p[3], dist}; }
}
}
return out;
}
function trackAt(t){
const tr = S.track; if (!tr || !tr.length) return null;
let lo = 0, hi = tr.length-1;
while (hi - lo > 1){ const m = (lo+hi)>>1; if (tr[m].t <= t) lo = m; else hi = m; }
const a = tr[lo], b = tr[hi];
if (!a.ok && !b.ok) return null;
if (!a.ok) return b; if (!b.ok) return a;
const u = b.t > a.t ? clamp((t-a.t)/(b.t-a.t), 0, 1) : 0;
return {ok:true, cx:a.cx+(b.cx-a.cx)*u, cy:a.cy+(b.cy-a.cy)*u, w:a.w+(b.w-a.w)*u, h:a.h+(b.h-a.h)*u};
}
function frameAt(t){
const F = S.an && S.an.frames; if (!F || !F.length) return null;
let lo = 0, hi = F.length-1;
while (hi - lo > 1){ const m = (lo+hi)>>1; if (F[m].t <= t) lo = m; else hi = m; }
const f = Math.abs(F[lo].t - t) < Math.abs(F[hi].t - t) ? F[lo] : F[hi];
return Math.abs(f.t - t) <= Math.max(0.6, S.an.step) ? f : null;
}
/* ===================== thumbnails ===================== */
let thumbJob = 0;
async function makeThumbs(){
const job = ++thumbJob; S.thumbCache = S.thumbCache || {};
const need = S.clips.filter(c => !c.thumb);
if (!need.length) return;
try {
if (scanVid.src.indexOf(S.source.url) < 0 && scanVid.currentSrc !== S.source.url) scanVid.src = S.source.url;
await loaded(scanVid);
const c = document.createElement("canvas"); c.width = 320; c.height = 180; const x = c.getContext("2d");
for (const clip of need) {
if (job !== thumbJob) return;
await seek(scanVid, Math.max(0, clip.peak - 1.2));
x.drawImage(scanVid, 0, 0, 320, 180);
clip.thumb = c.toDataURL("image/jpeg", 0.72); S.thumbCache[clip.id] = clip.thumb;
const img = document.querySelector(`[data-thumb="${clip.id}"]`); if (img) img.src = clip.thumb;
}
} catch(e) { console.warn("thumbs", e); }
}
/* ===================== drawing ===================== */
function sizeCanvas(){
const r = view.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1);
const w = Math.round(r.width*d), h = Math.round(r.height*d);
if (view.width !== w || view.height !== h) { view.width = w; view.height = h; }
const tl = $("#tl"), tr = tl.getBoundingClientRect();
if (tl.width !== Math.round(tr.width*d)) { tl.width = Math.round(tr.width*d); tl.height = Math.round(tr.height*d); }
}
function cropFor(v, W, H, opts){
const vw = v.videoWidth, vh = v.videoHeight;
const outAspect = W/H;
let cw, ch;
const usePlayer = opts.playerCam;
if (opts.vertical) { ch = vh / (usePlayer ? 1.15 : 1); cw = ch*outAspect; if (cw > vw){ cw = vw; ch = cw/outAspect; } }
else if (usePlayer) { cw = vw/1.75; ch = cw/outAspect; if (ch > vh){ ch = vh; cw = ch*outAspect; } }
else return null;
// target center
const t = v.currentTime, tk = trackAt(t);
let tx = 0.5, ty = 0.5;
if (tk && tk.ok) { tx = tk.cx; ty = tk.cy - tk.h*0.1; }
else { const f = frameAt(t); if (f && f.ax != null) { tx = f.ax; ty = f.ay; } }
const st = opts.camState || cam;
const k = opts.snap ? 1 : 0.09;
st.x += (tx - st.x)*k; st.y += (ty - st.y)*k;
let cx = st.x*vw - cw/2, cy = st.y*vh - ch/2;
cx = clamp(cx, 0, vw-cw); cy = clamp(cy, 0, vh-ch);
return {x:cx, y:cy, w:cw, h:ch};
}
function drawFrameTo(ctx, W, H, v, opts){
ctx.fillStyle = "#05070B"; ctx.fillRect(0,0,W,H);
if (!v.videoWidth) return;
const vw = v.videoWidth, vh = v.videoHeight;
const crop = cropFor(v, W, H, opts) || {x:0, y:0, w:vw, h:vh};
const s = Math.min(W/crop.w, H/crop.h), dw = crop.w*s, dh = crop.h*s, dx = (W-dw)/2, dy = (H-dh)/2;
ctx.drawImage(v, crop.x, crop.y, crop.w, crop.h, dx, dy, dw, dh);
const map = (nx, ny) => [dx + (nx*vw - crop.x)*s, dy + (ny*vh - crop.y)*s];
const px = W/1000;
// AI overlay
if (opts.scan && S.scanPreview) {
ctx.lineWidth = Math.max(1.5, 2*px);
for (const p of S.scanPreview.persons) { const [x,y] = map(p[0]-p[2]/2, p[1]-p[3]/2); ctx.strokeStyle = "rgba(255,90,31,.9)"; ctx.strokeRect(x, y, p[2]*vw*s, p[3]*vh*s); }
for (const b of S.scanPreview.balls) { const [x,y] = map(b[0], b[1]); ctx.strokeStyle = "#FFC24B"; ctx.beginPath(); ctx.arc(x, y, 14*px, 0, 7); ctx.stroke(); }
return;
}
if (opts.ai && !opts.clean) {
const f = frameAt(v.currentTime);
if (f) {
ctx.lineWidth = Math.max(1, 1.4*px);
for (const p of f.p) {
const [x,y] = map(p[0]-p[2]/2, p[1]-p[3]/2), w = p[2]*vw*s, h = p[3]*vh*s, c = Math.min(w,h)*0.22;
ctx.strokeStyle = "rgba(237,241,247,.55)";
ctx.beginPath();
ctx.moveTo(x, y+c); ctx.lineTo(x, y); ctx.lineTo(x+c, y);
ctx.moveTo(x+w-c, y); ctx.lineTo(x+w, y); ctx.lineTo(x+w, y+c);
ctx.moveTo(x, y+h-c); ctx.lineTo(x, y+h); ctx.lineTo(x+c, y+h);
ctx.moveTo(x+w-c, y+h); ctx.lineTo(x+w, y+h); ctx.lineTo(x+w, y+h-c);
ctx.stroke();
}
for (const b of f.b) { const [x,y] = map(b[0], b[1]); ctx.strokeStyle = "#FFC24B"; ctx.lineWidth = 2*px; ctx.beginPath(); ctx.arc(x, y, 12*px, 0, 7); ctx.stroke(); }
}
}
// shot result at the rim
if ((opts.ai || opts.reel) && S.sport === "basketball" && S.shots) {
const now = v.currentTime, sh = S.shots.find(q => now >= q.t - 0.4 && now <= q.end + 1.4);
if (sh) {
const [rx, ry] = map(sh.rim[0], sh.rim[1]), rw = sh.rim[2]*vw*s/2;
const col = sh.made ? "#3DDC84" : "#FFC24B";
ctx.strokeStyle = col; ctx.lineWidth = Math.max(2, 3*px);
ctx.beginPath(); ctx.ellipse(rx, ry, rw*1.25, rw*0.45, 0, 0, Math.PI*2); ctx.stroke();
if (now >= sh.end - 0.2) {
const lab = sh.made ? "MADE" : "MISS";
ctx.font = `700 ${Math.round(18*px*1.3)}px Barlow Condensed, Arial Narrow, sans-serif`;
const tw = ctx.measureText(lab).width + 16*px;
ctx.fillStyle = col; roundRect(ctx, rx - tw/2, ry - rw*1.1 - 30*px, tw, 24*px, 5*px); ctx.fill();
ctx.fillStyle = "#06140c"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(lab, rx, ry - rw*1.1 - 18*px);
ctx.textAlign = "left"; ctx.textBaseline = "alphabetic";
}
}
}
if (S.picking && S.pickMode === "hoop" && S.hoopDraft && !opts.reel) {
const hd = S.hoopDraft, [rx, ry] = map(hd.cx, hd.cy), rw = hd.w*vw*s/2;
ctx.strokeStyle = "#FFC24B"; ctx.lineWidth = Math.max(2, 2.5*px); ctx.setLineDash([6*px, 4*px]);
ctx.beginPath(); ctx.ellipse(rx, ry, rw, rw*0.32, 0, 0, Math.PI*2); ctx.stroke(); ctx.setLineDash([]);
}
if (S.picking && S.pickMode === "court" && S.courtDraft && !opts.reel) {
const pts = S.courtDraft.pts.map(p => map(p[0], p[1]));
ctx.strokeStyle = "#2EE6C5"; ctx.lineWidth = Math.max(2, 2.5*px); ctx.beginPath(); pts.forEach((p, i) => i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])); if (pts.length === 4) ctx.closePath(); ctx.stroke();
ctx.font = `700 ${Math.round(15*px*1.3)}px Barlow Condensed, sans-serif`; ctx.textAlign = "center"; ctx.textBaseline = "middle";
pts.forEach((p, i) => { ctx.fillStyle = "#2EE6C5"; ctx.beginPath(); ctx.arc(p[0], p[1], 11*px, 0, 7); ctx.fill(); ctx.fillStyle = "#04201b"; ctx.fillText(String(i+1), p[0], p[1] + px); });
ctx.textAlign = "left"; ctx.textBaseline = "alphabetic";
} else if (S.Hinv && opts.ai && !opts.reel && !S.picking) {
ctx.strokeStyle = "rgba(46,230,197,.45)"; ctx.lineWidth = Math.max(1.2, 1.6*px);
for (const L of courtLines()) { ctx.beginPath(); let first = true; for (const [X, Y] of L) { const q = fromCourt(X, Y, v.currentTime); if (!q) continue; const [sx, sy] = map(q[0], q[1]); first ? ctx.moveTo(sx, sy) : ctx.lineTo(sx, sy); first = false; } ctx.stroke(); }
}
if (opts.ai && !opts.reel && !S.picking && S.moments) drawCoachOverlay(ctx, map, vw, vh, s, px, v.currentTime);
// follow marker
const tk = trackAt(v.currentTime);
if (tk && tk.ok && (opts.ai || opts.reel) ) {
const [x,y] = map(tk.cx, tk.cy + tk.h/2), rw = tk.w*vw*s*0.75;
ctx.strokeStyle = "#2EE6C5"; ctx.lineWidth = Math.max(2, 3*px);
ctx.beginPath(); ctx.ellipse(x, y, rw, rw*0.28, 0, 0, Math.PI*2); ctx.stroke();
const [hx, hy] = map(tk.cx, tk.cy - tk.h/2);
const tag = S.follow && S.follow.number ? "#" + S.follow.number : "YOU";
ctx.font = `700 ${Math.round(16*px*1.4)}px Barlow Condensed, Arial Narrow, sans-serif`;
const tw = ctx.measureText(tag).width + 14*px;
ctx.fillStyle = "#2EE6C5"; roundRect(ctx, hx - tw/2, hy - 34*px, tw, 22*px, 5*px); ctx.fill();
ctx.beginPath(); ctx.moveTo(hx-6*px, hy-12*px); ctx.lineTo(hx+6*px, hy-12*px); ctx.lineTo(hx, hy-5*px); ctx.fill();
ctx.fillStyle = "#04201b"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(tag, hx, hy - 23*px);
ctx.textAlign = "left"; ctx.textBaseline = "alphabetic";
}
}
function roundRect(ctx, x, y, w, h, r){ ctx.beginPath(); ctx.moveTo(x+r,y); ctx.arcTo(x+w,y,x+w,y+h,r); ctx.arcTo(x+w,y+h,x,y+h,r); ctx.arcTo(x,y+h,x,y,r); ctx.arcTo(x,y,x+w,y,r); ctx.closePath(); }
function drawStage(){
sizeCanvas();
if (S.busy && S.scanPreview) return;
if (S.reel) { drawReelFrame(vctx, view.width, view.height, S.reel, false); return; }
drawFrameTo(vctx, view.width, view.height, vid, {ai:S.aiView, playerCam:S.playerCam});
if (S.picking && S.pickMode === "player") drawPickOverlay();
}
function drawPickOverlay(){
const f = S.pickDet; if (!f) return;
const W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight;
const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2;
vctx.fillStyle = "rgba(5,7,11,.35)"; vctx.fillRect(0,0,W,H);
f.forEach((p, k) => {
const x = dx + (p[0]-p[2]/2)*vw*s, y = dy + (p[1]-p[3]/2)*vh*s, w = p[2]*vw*s, h = p[3]*vh*s;
vctx.strokeStyle = k === S.pickHover ? "#2EE6C5" : "rgba(46,230,197,.55)"; vctx.lineWidth = k === S.pickHover ? 4 : 2;
roundRect(vctx, x, y, w, h, 6); vctx.stroke();
if (k === S.pickHover) { vctx.fillStyle = "rgba(46,230,197,.15)"; vctx.fill(); }
});
}
/* timeline: three lanes (shots, pace, coaching) over a time axis */
const TLG = 66, TLR = 10;
function tlX(t, W, d, dur){ return TLG*d + clamp(t/dur, 0, 1)*(W - (TLG + TLR)*d); }
function drawTimeline(){
const c = $("#tl"); sizeCanvas();
const rw = c.getBoundingClientRect().width; if (!rw) return;
const x = c.getContext("2d"), W = c.width, H = c.height, d = W / rw;
x.clearRect(0,0,W,H);
const dur = (S.an && S.an.duration) || vid.duration || 1, X = t => tlX(t, W, d, dur);
const lanes = {shots:[6, 46], pace:[54, 116], coach:[124, 156]}, axisY = 160*d;
const L = (k, i) => lanes[k][i]*d;
S.tlHits = [];
// lane backgrounds and labels
x.font = `600 ${10.5*d}px "Barlow Condensed", Arial Narrow, sans-serif`; x.textBaseline = "middle";
for (const [k, lab] of [["shots","SHOTS"],["pace","PACE"],["coach","COACH"]]) {
x.fillStyle = "rgba(255,255,255,.025)"; roundRect(x, TLG*d - 4*d, L(k,0), W - (TLG - 4 + TLR)*d + 4*d, L(k,1) - L(k,0), 7*d); x.fill();
x.fillStyle = "#6B7489"; x.fillText(lab.split("").join(String.fromCharCode(8202)), 4*d, (L(k,0) + L(k,1))/2);
}
// grid + axis
const stepS = dur > 1800 ? 300 : dur > 600 ? 120 : dur > 180 ? 30 : 10;
x.strokeStyle = "rgba(255,255,255,.05)"; x.lineWidth = 1; x.fillStyle = "#5D6679"; x.font = `${10.5*d}px Barlow, sans-serif`; x.textAlign = "center";
for (let s = 0; s <= dur + 0.01; s += stepS) { const px = X(s); x.beginPath(); x.moveTo(px, L("shots",0)); x.lineTo(px, L("coach",1)); x.stroke(); x.fillText(fmt(s), px, axisY + 9*d); }
x.textAlign = "left";
// pace: intensity bars
const sp = S.speed;
if (sp && sp.length) {
const top = L("pace",0) + 4*d, base = L("pace",1) - 3*d, vmax = 22;
for (let i=1;i<sp.length;i++){
const dt = sp[i].t - sp[i-1].t; if (dt <= 0 || dt > 0.8) continue;
const v = sp[i].v, z = intensityOf(v), h = clamp(v/vmax, 0.04, 1)*(base - top);
x.fillStyle = z.col; x.globalAlpha = 0.85; x.fillRect(X(sp[i-1].t), base - h, Math.max(1, X(sp[i].t) - X(sp[i-1].t)) + 0.4, h);
}
x.globalAlpha = 1;
// 9 mph sprint line
const sy = base - 13/vmax*(base - top); x.strokeStyle = "rgba(255,90,31,.35)"; x.setLineDash([3*d, 4*d]); x.beginPath(); x.moveTo(X(0), sy); x.lineTo(X(dur), sy); x.stroke(); x.setLineDash([]);
x.fillStyle = "rgba(255,138,92,.75)"; x.font = `600 ${9.5*d}px "Barlow Condensed", sans-serif`; x.textAlign = "right"; x.fillText("9 MPH", X(dur) - 3*d, sy - 6*d); x.textAlign = "left";
} else if (S.track && S.X) {
for (let i=0, n=S.X.pres.length; i<n; i++) if (S.X.pres[i] > 0.5) { x.fillStyle = "rgba(46,230,197,.5)"; x.fillRect(X(i/n*dur), L("pace",1) - 8*d, (W - (TLG+TLR)*d)/n + 0.5, 5*d); }
}
// shots
if (S.shots) S.shots.forEach((sh, i) => {
const t = sh.relT || sh.t, px = X(t), cy = (L("shots",0) + L("shots",1))/2 + 5*d, mine = sh.mine === true || !S.follow;
const r = (mine ? 6.5 : 4)*d, flagged = sh.form && sh.form.flags && sh.form.flags.length;
if (flagged) { x.strokeStyle = "rgba(255,90,31,.55)"; x.lineWidth = 2*d; x.beginPath(); x.arc(px, cy, r + 4*d, 0, 7); x.stroke(); }
x.beginPath(); x.arc(px, cy, r, 0, 7);
if (sh.made) { x.fillStyle = mine ? "#3DDC84" : "rgba(61,220,132,.35)"; x.fill(); } else { x.strokeStyle = mine ? "#C3CBD9" : "rgba(140,150,170,.4)"; x.lineWidth = 1.8*d; x.stroke(); }
if (mine) { x.fillStyle = "#8C96AA"; x.font = `600 ${10*d}px "Barlow Condensed", sans-serif`; x.textAlign = "center"; x.fillText(String(i+1), px, L("shots",0) + 7*d); x.textAlign = "left"; }
const m = (S.moments || []).find(q => q.shot === sh);
S.tlHits.push({x:px, y:cy, m: m || {t, shot:sh, kind:"shot"}});
});
// coaching flags
const M = S.moments || [], cy = (L("coach",0) + L("coach",1))/2, stackAt = {}; let lastLab = -1e9;
for (const m of M) {
const col = m.kind === "fix" ? "#FF5A1F" : "#3DDC84";
if (m.end) {
const a = X(m.t), b = X(m.end);
x.fillStyle = "rgba(255,90,31,.16)"; roundRect(x, a, L("coach",0) + 4*d, b - a, L("coach",1) - L("coach",0) - 8*d, 5*d); x.fill();
x.strokeStyle = "rgba(255,90,31,.6)"; x.lineWidth = 1.2*d; x.stroke();
x.fillStyle = "#ff9b73"; x.font = `700 ${10*d}px "Barlow Condensed", sans-serif`; x.textAlign = "center"; if (b - a > 40*d) x.fillText("WALKING", (a+b)/2, cy + d); x.textAlign = "left";
S.tlHits.push({x:(a+b)/2, y:cy, m}); continue;
}
const px = X(m.t), k = Math.round(m.t*4), off = (stackAt[k] = (stackAt[k] || 0) + 1) - 1, yy = cy - 6*d + off*11*d - (M.filter(q => !q.end && Math.round(q.t*4) === k).length > 1 ? 0 : -6*d);
x.save(); x.translate(px, yy); x.rotate(Math.PI/4); x.fillStyle = col; x.fillRect(-4.2*d, -4.2*d, 8.4*d, 8.4*d); x.restore();
if (m.kind === "fix" && px - lastLab > 44*d) { x.fillStyle = "#ffb495"; x.font = `700 ${9.5*d}px "Barlow Condensed", sans-serif`; x.fillText(SHORT[m.key] || "", px + 8*d, yy + d); lastLab = px; }
S.tlHits.push({x:px, y:yy, m});
}
// playhead
const now = vid.currentTime || 0, ph = X(now);
x.fillStyle = "rgba(237,241,247,.95)"; x.fillRect(ph - d, L("shots",0) - 2*d, 2*d, L("coach",1) - L("shots",0) + 4*d);
x.beginPath(); x.arc(ph, L("shots",0) - 1*d, 3.5*d, 0, 7); x.fill();
x.textBaseline = "alphabetic";
}
/* ===================== rail ===================== */
function renderRail(){
const L = $("#list");
if (!S.clips.length) { L.innerHTML = `<div class="empty">${S.an ? "No standout moments at this setting. Try Generous." : "Run the analysis to find plays."}</div>`; updateTiles(); return; }
L.innerHTML = "";
S.clips.forEach((c, k) => {
const el = document.createElement("div");
el.className = "clip" + (c.keep ? "" : " off") + (k === S.active ? " active" : "");
el.dataset.k = k;
const tags = c.tags.map(t => `<span class="tag ${t[1]}">${esc(t[0])}</span>`).join("") + (c.ai ? `<span class="tag ai">Claude</span>` : "");
let cap = "";
if (c.aiBusy) cap = `<div class="shimmer"></div><div class="shimmer" style="width:60%"></div>`;
else if (c.ai) {
cap = `<div class="cap">${esc(c.ai.caption || "")}</div>`;
if (S.follow && c.ai.followed === false) cap += `<div class="cap flag">Claude can't see ${S.follow.number ? "#" + esc(S.follow.number) : "your player"} in this play. <button class="mini" data-act="drop">Remove</button></div>`;
}
el.innerHTML = `
<button class="th" data-act="play" aria-label="Play clip ${k+1}"><img data-thumb="${c.id}" alt="" ${c.thumb ? `src="${c.thumb}"` : ""}><span class="play"><svg width="26" height="26" viewBox="0 0 24 24" fill="#fff"><path d="M7 4.5v15l13-7.5z"/></svg></span><em class="num">${fmt(c.end - c.start)}</em></button>
<div style="min-width:0;padding-right:34px">
<h4>${esc(c.title)}</h4>
<div class="sub num">${fmt(c.start)}–${fmt(c.end)} · Play ${k+1}</div>
${cap}
<div class="tags">${tags}</div>
<div class="clipbar"><div class="meter" title="Highlight score"><b style="width:${c.pct}%"></b></div><span class="sub num" style="margin:0">${c.pct}</span>
<button class="mini" data-act="s-" aria-label="Start earlier">−1s</button><button class="mini" data-act="e+" aria-label="End later">+1s</button></div>
</div>
<label class="keep" title="Keep in reel"><input type="checkbox" ${c.keep ? "checked" : ""} data-act="keep" aria-label="Keep play ${k+1} in reel"><span></span></label>`;
L.appendChild(el);
});
updateTiles();
}
function updateTiles(){
const kept = S.clips.filter(c => c.keep);
$("#tClips").textContent = S.clips.length;
$("#tReel").textContent = fmt(kept.reduce((s,c) => s + (c.end - c.start), 0) + (kept.length ? 3.5 : 0));
if (S.follow && S.track) { $("#tPlayer").textContent = S.clips.filter(c => c.mine).length; $("#tPlayerLbl").textContent = (S.follow.number ? "#" + S.follow.number : "your player") + " on screen in"; }
else { $("#tPlayer").textContent = "–"; $("#tPlayerLbl").textContent = "tap Follow"; }
const st = $("#shotStats");
if (S.sport === "basketball" && S.shots) {
const made = S.shots.filter(x => x.made).length, n = S.shots.length;
st.innerHTML = n ? `Shots <b class="mk">${made}</b><b>/${n}</b> made · ${Math.round(made/n*100)}% · ${S.hoops.length} hoop${S.hoops.length > 1 ? "s" : ""} watched` : `No shots seen at the marked hoop${S.hoops.length > 1 ? "s" : ""}. Check the ring matches the rim.`;
st.hidden = false;
} else st.hidden = true;
const any = kept.length > 0;
["#reelBtn","#exportBtn","#vertBtn","#claudeBtn","#recapBtn","#csvBtn"].forEach(s => $(s).disabled = !any);
}
function esc(s){ return String(s).replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); }
$("#list").addEventListener("click", (e) => {
const el = e.target.closest(".clip"); if (!el) return;
const k = +el.dataset.k, c = S.clips[k], act = e.target.closest("[data-act]") && e.target.closest("[data-act]").dataset.act;
if (act === "keep") { c.keep = e.target.checked; el.classList.toggle("off", !c.keep); updateTiles(); drawTimeline(); return; }
if (act === "drop") { c.keep = false; renderRail(); drawTimeline(); return; }
if (act === "s-") { c.start = Math.max(0, c.start - 1); c.trimmed = true; renderRail(); drawTimeline(); return; }
if (act === "e+") { c.end = Math.min(S.an.duration, c.end + 1); c.trimmed = true; renderRail(); drawTimeline(); return; }
if (e.target.closest(".keep")) return;
playClip(k);
});
/* ===================== playback ===================== */
let clipStop = null;
async function playClip(k){
stopReel(); ensureAudio();
const c = S.clips[k]; S.active = k; clipStop = c.end;
document.querySelectorAll(".clip").forEach(n => n.classList.toggle("active", +n.dataset.k === k));
await seek(vid, c.start); snapCam(); drawTimeline();
vid.playbackRate = S.slow ? 0.5 : 1;
try { await vid.play(); } catch(e){}
}
function snapCam(){ const o = {ai:false, playerCam:true, snap:true}; if (vid.videoWidth) cropFor(vid, 16, 9, o); }
/* iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio. */
let silentEl = null;
function iosUnlock(){
try { if (navigator.audioSession && navigator.audioSession.type !== "playback") navigator.audioSession.type = "playback"; } catch(e){}
if (!("audioSession" in navigator)) { try { if (!silentEl) { silentEl = new Audio("audio/silence.mp3"); silentEl.loop = true; silentEl.setAttribute("playsinline", ""); } const p = silentEl.play(); if (p && p.catch) p.catch(()=>{}); } catch(e){} }
}
function wakeAudio(){ iosUnlock(); if (S.audioCtx && S.audioCtx.state !== "running") { try { const p = S.audioCtx.resume(); if (p && p.catch) p.catch(()=>{}); } catch(e){} } }
["pointerdown","touchend","click","keydown"].forEach(ev => document.addEventListener(ev, () => { if (S.audioCtx) wakeAudio(); }, {passive:true, capture:true}));
document.addEventListener("visibilitychange", () => { if (!document.hidden && S.audioCtx) wakeAudio(); });
function ensureAudio(){
iosUnlock();
if (S.audioCtx) { if (S.audioCtx.state !== "running") wakeAudio(); return; }
try {
const AC = window.AudioContext || window.webkitAudioContext; const ctx = new AC();
const src = ctx.createMediaElementSource(vid), gain = ctx.createGain();
src.connect(gain); gain.connect(ctx.destination);
S.audioCtx = ctx; S.recDest = ctx.createMediaStreamDestination(); gain.connect(S.recDest);
} catch(e) { console.warn("audio graph", e); }
}
function loop(){
if (!vid.paused || S.reel) drawStage();
if (!vid.paused) {
if (clipStop != null && !S.reel && vid.currentTime >= clipStop) { vid.pause(); clipStop = null; }
$("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration);
if ((loop.n = (loop.n||0)+1) % 3 === 0) { drawTimeline(); updateCoachCard(); updateLiveHud(); }
}
requestAnimationFrame(loop);
}
vid.addEventListener("play", () => $("#playIc").innerHTML = '<path d="M6 4h4v16H6zM14 4h4v16h-4z"/>');
vid.addEventListener("pause", () => { $("#playIc").innerHTML = '<path d="M7 4.5v15l13-7.5z"/>'; drawStage(); drawTimeline(); });
vid.addEventListener("seeked", () => { drawStage(); drawTimeline(); updateCoachCard(); updateLiveHud(); $("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration); });
vid.addEventListener("loadeddata", () => { drawStage(); drawTimeline(); $("#timeTxt").textContent = fmt(vid.currentTime) + " / " + fmt(vid.duration); });
$("#playBtn").onclick = async () => { if (S.reel) { stopReel(); return; } ensureAudio(); clipStop = null; vid.playbackRate = S.slow ? 0.5 : 1; if (vid.paused) { try { await vid.play(); } catch(e){} } else vid.pause(); };
$("#prevBtn").onclick = () => jump(-1);
$("#nextBtn").onclick = () => jump(1);
function jump(dir){
if (!S.clips.length) return;
const t = vid.currentTime;
let k = dir > 0 ? S.clips.findIndex(c => c.start > t + 0.5) : -1;
if (dir < 0) { for (let i=S.clips.length-1;i>=0;i--) if (S.clips[i].start < t - 1.5) { k = i; break; } }
if (k < 0) k = dir > 0 ? 0 : S.clips.length-1;
playClip(k);
}
function bindToggle(id, key, after){ const b = $(id); b.onclick = () => { S[key] = !S[key]; b.setAttribute("aria-pressed", S[key]); after && after(); drawStage(); }; }
bindToggle("#camToggle", "playerCam", () => { snapCam(); if (S.playerCam && !S.track) toast("Player Cam follows the action. Follow a player to lock onto them."); });
bindToggle("#aiToggle", "aiView");
bindToggle("#slowToggle", "slow", () => { vid.playbackRate = S.slow ? 0.5 : 1; });
$("#fsBtn").onclick = () => { const st = $("#stage"); try { (st.requestFullscreen || st.webkitRequestFullscreen).call(st).catch(()=>toast("Full screen isn't available here.")); } catch(e){ toast("Full screen isn't available here."); } };
// timeline: click a marker to watch that moment, or drag to scrub
(function(){
const c = $("#tl"); let down = false, moved = false;
const tOf = (e) => { const r = c.getBoundingClientRect(), dur = (S.an && S.an.duration) || vid.duration; if (!dur) return null; return clamp((e.clientX - r.left - TLG)/(r.width - TLG - TLR), 0, 1)*dur; };
const hitOf = (e) => { const r = c.getBoundingClientRect(), d = c.width / r.width, X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d; let best = null, bd = 13*d; for (const h of S.tlHits || []) { const dd = Math.hypot(h.x - X, (h.y - Y)*0.6); if (dd < bd) { bd = dd; best = h; } } return best; };
const go = (e) => { const t = tOf(e); if (t == null) return; stopReel(); clipStop = null; vid.currentTime = t; S.active = S.clips.findIndex(k => t >= k.start && t <= k.end); };
c.addEventListener("pointerdown", e => { down = true; moved = false; c.setPointerCapture(e.pointerId); c._hit = hitOf(e); if (!c._hit) go(e); });
c.addEventListener("pointermove", e => { if (down) { moved = true; if (!c._hit) go(e); } else c.style.cursor = hitOf(e) ? "pointer" : "col-resize"; });
c.addEventListener("pointerup", () => { down = false; const h = c._hit; c._hit = null; if (h && !moved) { const m = h.m; if (m.kind === "shot") { const q = m.shot; playRange(Math.max(0, (q.relT || q.t) - 1.8), (q.rimT || q.end) + 1.9); } else playMoment(m); } renderRail(); });
})();
/* ===================== reel ===================== */
function reelInfo(){
const f = S.follow, sp = SPORTS[S.sport];
const who = f && (f.name || f.number) ? [f.name, f.number ? "#" + f.number : ""].filter(Boolean).join(" · ") : "Game highlights";
const team = f && f.team ? f.team : (S.source.sample ? "Suns" : sp.label);
return {who, team, sport:sp.label};
}
function drawTitleCard(ctx, W, H, u, end){
const px = Math.min(W, H*16/9)/1000, info = reelInfo();
const g = ctx.createLinearGradient(0,0,W,H); g.addColorStop(0, "#0B0F18"); g.addColorStop(1, "#1a0e08");
ctx.fillStyle = g; ctx.fillRect(0,0,W,H);
const a = clamp(u*3, 0, 1), out = clamp((1-u)*4, 0, 1), al = Math.min(a, out);
ctx.globalAlpha = al;
ctx.fillStyle = "#FF5A1F"; ctx.fillRect(W*0.08, H*0.5 - 3*px, (W*0.22)*clamp(u*2.2,0,1), 6*px);
ctx.fillStyle = "#EDF1F7"; ctx.textAlign = "left"; ctx.textBaseline = "alphabetic";
const big = W < H ? 96 : 120;
if (!end) {
ctx.font = `700 ${Math.round(big*px)}px Barlow Condensed, Arial Narrow, sans-serif`;
ctx.fillText(info.who.toUpperCase(), W*0.08, H*0.5 - 24*px);
ctx.font = `600 ${Math.round(30*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillStyle = "#8C96AA";
const kept = S.clips.filter(c => c.keep).length;
ctx.fillText(`${info.team.toUpperCase()} · ${info.sport.toUpperCase()} · ${kept} PLAYS`, W*0.08, H*0.5 + 48*px);
} else {
ctx.font = `700 ${Math.round(80*px)}px Barlow Condensed, Arial Narrow, sans-serif`;
ctx.fillText("CLUTCH", W*0.08, H*0.5 - 24*px);
ctx.font = `600 ${Math.round(28*px)}px Barlow Condensed, Arial Narrow, sans-serif`; ctx.fillStyle = "#8C96AA";
ctx.fillText("MADE WITH CLUTCH HIGHLIGHT STUDIO", W*0.08, H*0.5 + 44*px);
}
ctx.globalAlpha = 1;
}
function drawReelFrame(ctx, W, H, R, recording){
if (R.phase === "title" || R.phase === "end") { drawTitleCard(ctx, W, H, (performance.now() - R.t0)/R.len, R.phase === "end"); return; }
drawFrameTo(ctx, W, H, vid, {ai:false, reel:true, playerCam:S.playerCam || R.vertical, vertical:R.vertical, camState:R.cam});
const c = R.clips[R.i]; if (!c) return;
const px = Math.min(W, H*16/9)/1000;
const vertical = W < H;
// lower third
const text = (c.ai && c.ai.caption) ? c.ai.caption : c.title;
const shotLab = c.shot === "made" ? " · MADE BASKET" : c.shot === "miss" ? " · SHOT ATTEMPT" : "";
const lt = (vid.currentTime - c.start);
const a = clamp(lt*2.5, 0, 1);
ctx.globalAlpha = a;
const x = vertical ? W*0.06 : 34*px, y = vertical ? H*0.80 : H - 96*px;
ctx.font = `600 ${Math.round((vertical ? 40 : 30)*px)}px Barlow Condensed, Arial Narrow, sans-serif`;
const maxW = vertical ? W*0.88 : W*0.62;
const lines = wrap(ctx, text.toUpperCase(), maxW - 30*px);
const lh = (vertical ? 44 : 33)*px, boxH = 34*px + lines.length*lh;
ctx.fillStyle = "rgba(10,13,19,.84)"; roundRect(ctx, x, y - boxH + 26*px, maxW, boxH, 8*px); ctx.fill();
ctx.fillStyle = "#FF5A1F"; ctx.fillRect(x, y - boxH + 26*px, 6*px, boxH);
ctx.fillStyle = "#8C96AA"; ctx.font = `600 ${Math.round((vertical ? 22 : 17)*px)}px Barlow Condensed, Arial Narrow, sans-serif`;
ctx.fillText(`PLAY ${R.i+1} OF ${R.clips.length}${shotLab}${c.mine && S.follow && S.follow.number ? " · #" + S.follow.number : ""}`, x + 20*px, y - boxH + 50*px);
ctx.fillStyle = "#EDF1F7"; ctx.font = `600 ${Math.round((vertical ? 40 : 30)*px)}px Barlow Condensed, Arial Narrow, sans-serif`;
lines.forEach((l, j) => ctx.fillText(l, x + 20*px, y - boxH + 52*px + (j+1)*lh));
ctx.globalAlpha = 1;
// fades
const toEnd = c.end - vid.currentTime;
const fade = Math.max(clamp(1 - lt/0.35, 0, 1), clamp(1 - toEnd/0.35, 0, 1));
if (fade > 0) { ctx.fillStyle = `rgba(5,7,11,${fade})`; ctx.fillRect(0,0,W,H); }
// brand bug
ctx.fillStyle = "rgba(237,241,247,.7)"; ctx.font = `700 ${Math.round(18*px)}px Barlow Condensed, sans-serif`; ctx.textAlign = "right";
ctx.fillText("CLUTCH", W - 24*px, 36*px); ctx.textAlign = "left";
}
function wrap(ctx, text, maxW){ const words = text.split(/\s+/), lines = []; let cur = ""; for (const w of words){ const t = cur ? cur + " " + w : w; if (ctx.measureText(t).width > maxW && cur){ lines.push(cur); cur = w; } else cur = t; } if (cur) lines.push(cur); return lines.slice(0,3); }
async function runReel({record=false, vertical=false}={}){
const clips = S.clips.filter(c => c.keep).slice().sort((a,b) => a.start - b.start);
if (!clips.length) return null;
stopReel(); ensureAudio(); clipStop = null;
const token = {};
const R = {token, clips, i:-1, phase:"title", t0:performance.now(), len:2200, vertical, cam:{x:.5,y:.5}};
S.reel = R; setHud();
let rec = null, chunks = [], canvas = null, ctx = null, rafId = 0, mime = "";
if (record) {
canvas = document.createElement("canvas");
if (vertical) { canvas.width = 720; canvas.height = 1280; } else { canvas.width = 1280; canvas.height = 720; }
ctx = canvas.getContext("2d");
const stream = canvas.captureStream(30);
if (S.recDest) S.recDest.stream.getAudioTracks().forEach(t => stream.addTrack(t));
const types = ["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm"];
mime = types.find(t => window.MediaRecorder && MediaRecorder.isTypeSupported(t)) || "";
if (!window.MediaRecorder) { toast("This browser can't record video. Try Chrome or Safari on a laptop."); S.reel = null; return null; }
rec = new MediaRecorder(stream, mime ? {mimeType:mime, videoBitsPerSecond:5e6} : undefined);
rec.ondataavailable = e => e.data.size && chunks.push(e.data);
rec.start(500);
const paint = () => { if (S.reel !== R) return; drawReelFrame(ctx, canvas.width, canvas.height, R, true); rafId = requestAnimationFrame(paint); };
paint();
R.progress = $("#scan"); $("#scanTitle").textContent = vertical ? "Recording 9:16 reel" : "Recording reel";
}
const total = clips.reduce((s,c) => s + c.end - c.start, 0) + 3.7;
const startedAt = performance.now();
const showProg = () => {
if (!record) return;
const el = (performance.now() - startedAt)/1000;
$("#scan").hidden = false; $("#scan").classList.add("rec"); $("#steps").style.display = "none";
$("#scanBar").style.width = clamp(el/total*100, 0, 100) + "%";
$("#scanFrames").textContent = fmt(el) + " / " + fmt(total); $("#scanPeople").textContent = "Keep this tab open"; $("#scanEta").textContent = "";
};
const wait = ms => new Promise(r => { const t0 = performance.now(); const f = () => { if (S.reel !== R) return r(); showProg(); if (performance.now() - t0 >= ms) r(); else requestAnimationFrame(f); }; f(); });
await wait(R.len);
for (let i=0;i<clips.length && S.reel === R;i++){
const c = clips[i]; R.i = i; R.phase = "clip";
await seek(vid, c.start);
R.cam.x = .5; R.cam.y = .5; cropFor(vid, 16, 9, {playerCam:true, snap:true, camState:R.cam});
vid.playbackRate = 1;
try { await vid.play(); } catch(e){}
await new Promise(r => { const f = () => { if (S.reel !== R || vid.currentTime >= c.end || vid.ended) return r(); showProg(); requestAnimationFrame(f); }; f(); });
vid.pause();
}
if (S.reel === R) { R.phase = "end"; R.t0 = performance.now(); R.len = 1500; await wait(1500); }
const finished = S.reel === R;
cancelAnimationFrame(rafId);
let blob = null;
if (rec) {
await new Promise(r => { rec.onstop = r; rec.stop(); });
blob = new Blob(chunks, {type: mime || "video/webm"});
$("#steps").style.display = ""; $("#scan").hidden = true; $("#scan").classList.remove("rec"); $("#scanTitle").textContent = "Analyzing game";
}
if (S.reel === R) S.reel = null;
setHud(); drawStage();
return finished ? {blob, mime} : null;
}
function stopReel(){ if (S.reel) { S.reel = null; vid.pause(); $("#steps").style.display = ""; $("#scan").classList.remove("rec"); $("#scan").hidden = !S.busy; setHud(); } }
$("#reelBtn").onclick = () => { runReel(); };
$("#mReel").onclick = () => $("#reelBtn").click();
async function doExport(vertical){
if (S.busy) return;
toast("Recording in real time. Keep this tab open.");
const r = await runReel({record:true, vertical});
if (!r || !r.blob || !r.blob.size) { toast("Recording stopped."); return; }
const ext = /mp4/.test(r.mime) ? "mp4" : "webm";
S.exported = {blob:r.blob, name:`clutch-${vertical ? "vertical-" : ""}reel.${ext}`};
const url = URL.createObjectURL(r.blob);
$("#emVid").src = url;
$("#emSub").textContent = `${(r.blob.size/1e6).toFixed(1)} MB · ${ext.toUpperCase()} · ${vertical ? "1080×1920 style 9:16" : "1280×720"}`;
$("#exportModal").hidden = false;
}
$("#exportBtn").onclick = () => doExport(false);
$("#mExport").onclick = () => $("#reportDl").click();
$("#vertBtn").onclick = () => doExport(true);
$("#emClose").onclick = () => { $("#exportModal").hidden = true; $("#emVid").pause(); };
$("#emSave").onclick = async () => {
const dl = await cap("downloads");
if (!dl) { toast("Saving isn't available in this view. Open the artifact in claude.ai to save."); return; }
try { await dl.save({filename:S.exported.name, data:S.exported.blob}); toast("Saved."); }
catch(e){ toast(e && e.code === "declined" ? "Save cancelled." : "Couldn't save: " + ((e && e.message) || "unavailable")); }
};
$("#csvBtn").onclick = async () => {
const rows = [["play","start","end","title","shot","caption","score","kept","tags"]].concat(S.clips.map((c,k) => [k+1, fmt(c.start), fmt(c.end), c.title, c.shot || "", (c.ai && c.ai.caption) || "", c.pct, c.keep ? "yes" : "no", c.tags.map(t => t[0]).join("; ")]));
const csv = rows.map(r => r.map(v => `"${String(v).replace(/"/g,'""')}"`).join(",")).join("\n");
const dl = await cap("downloads");
if (!dl) { try { await navigator.clipboard.writeText(csv); toast("Saving isn't available here, so the clip list was copied instead."); } catch(e){ toast("Saving isn't available in this view."); } return; }
try { await dl.save({filename:"clutch-clips.csv", data:csv}); } catch(e){ if (e && e.code !== "declined") toast("Couldn't save the list."); }
};
/* ===================== Claude ===================== */
async function grabStills(c){
if (scanVid.currentSrc.indexOf(S.source.url) < 0 && scanVid.src !== S.source.url) scanVid.src = S.source.url;
await loaded(scanVid);
const out = [], cv = document.createElement("canvas"); cv.width = 768; cv.height = Math.round(768*scanVid.videoHeight/scanVid.videoWidth);
const x = cv.getContext("2d");
for (const t of [c.peak - 2.4, c.peak - 0.6, c.peak + 1.0]) {
await seek(scanVid, clamp(t, c.start, c.end));
x.drawImage(scanVid, 0, 0, cv.width, cv.height);
const tk = trackAt(scanVid.currentTime);
if (tk && tk.ok) { x.strokeStyle = "#2EE6C5"; x.lineWidth = 3; roundRect(x, (tk.cx-tk.w/2)*cv.width - 4, (tk.cy-tk.h/2)*cv.height - 4, tk.w*cv.width + 8, tk.h*cv.height + 8, 6); x.stroke(); }
out.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.8)));
}
return out;
}
function parseJSON(t){ try { const m = String(t).match(/\{[\s\S]*\}/); return m ? JSON.parse(m[0]) : null; } catch(e){ return null; } }
$("#claudeBtn").onclick = async () => {
const sample = await cap("sample");
if (!sample) { toast("Claude captions work when this page is opened in claude.ai."); return; }
let images = true; try { const l = await sample.limits(); images = !!(l && l.images); } catch(e){}
if (!images) { toast("Image captions aren't enabled for this page yet."); return; }
const kept = S.clips.filter(c => c.keep);
kept.forEach(c => c.aiBusy = true); renderRail();
const sp = SPORTS[S.sport], f = S.follow;
for (const c of kept) {
try {
const imgs = await grabStills(c);
const who = f ? `The family is following ${f.name ? f.name + ", " : ""}the player ${f.number ? "wearing #" + f.number : "marked"}${f.team ? " on the " + f.team : ""}. A teal box marks where our tracker thinks that player is; the tracker can be wrong.` : "No specific player is being followed.";
const prompt = `You caption youth ${sp.label.toLowerCase()} highlight clips for parents. Three frames from one clip, in time order (about 2.4s before the peak, at the peak, and 1s after). ${who}
${c.shot ? "Our rim detector says this clip contains a " + (c.shot === "made" ? "made basket" : "missed shot") + "; correct it if the frames clearly show otherwise. " : ""}Describe only what is visible. Do not invent scores, names or outcomes you cannot see; if unsure, say "attempt" rather than "scores".
Reply with JSON only, no prose:
{"title":"3-5 word headline, upper case style","caption":"one sentence, max 16 words, for an on-screen lower third","action":"score|shot|pass|save|block|steal|tackle|serve|rally|run|other","followed":true|false|null,"numbers_seen":[jersey numbers you can read],"confidence":0-1}
"followed" = whether the followed player is visibly involved in the main action (null if no player is followed).`;
const r = await sample(prompt, {images: imgs, modelTier:"default"});
const j = parseJSON(r && r.text);
if (j) { c.ai = {title:j.title, caption:j.caption, action:j.action, followed: f ? (j.followed === true ? true : j.followed === false ? false : null) : null, nums:j.numbers_seen || [], conf:j.confidence}; if (j.title) c.title = j.title; }
} catch(e) {
c.aiBusy = false; renderRail();
if (e && e.code === "rate_limited") { toast("Claude is busy. Try again in a minute."); break; }
if (e && (e.code === "not_granted" || e.code === "declined")) { toast("Captions need your OK to ask Claude."); break; }
toast("Couldn't caption a clip.");
}
c.aiBusy = false; renderRail();
}
kept.forEach(c => c.aiBusy = false); renderRail();
};
// Claude reads the jersey number on crops along the track and removes stretches where it's someone else
$("#verifyBtn").onclick = async () => {
const f = S.follow, tr = S.track;
if (!f || !tr) return;
if (!f.number) { toast("Add the jersey number first: tap Follow again on your player."); return; }
const sample = await cap("sample");
if (!sample) { toast("Tracking checks work when this page is opened in claude.ai."); return; }
let images = true; try { const l = await sample.limits(); images = !!(l && l.images); } catch(e){}
if (!images) { toast("Image checks aren't enabled for this page yet."); return; }
const pts = []; let lastT = -9;
for (const q of tr) if (q.ok && q.t - lastT >= 2.5) { pts.push(q); lastT = q.t; }
const picks = pts.length > 24 ? pts.filter((_, i) => i % Math.ceil(pts.length/24) === 0) : pts;
if (!picks.length) { toast("Nothing to check yet."); return; }
const btn = $("#verifyBtn"); btn.disabled = true;
if (scanVid.src !== S.source.url) scanVid.src = S.source.url;
await loaded(scanVid);
const vw = scanVid.videoWidth, vh = scanVid.videoHeight, cv = document.createElement("canvas"); cv.width = 160; cv.height = 240; const x = cv.getContext("2d");
const res = []; let wrong = 0, ok = 0, unread = 0;
try {
for (let b = 0; b < picks.length; b += 6) {
const batch = picks.slice(b, b + 6), imgs = [];
$("#verifyTxt").textContent = `Checking ${Math.min(b + 6, picks.length)} of ${picks.length}…`;
for (const q of batch) {
await seek(scanVid, q.t);
const bw = q.w*vw*1.5, bh = q.h*vh*1.25, sx = q.cx*vw - bw/2, sy = q.cy*vh - bh/2;
x.fillStyle = "#000"; x.fillRect(0, 0, 160, 240);
x.drawImage(scanVid, sx, sy, bw, bh, 0, 0, 160, 240);
imgs.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.85)));
}
const prompt = `You will see ${batch.length} cropped images of youth ${SPORTS[S.sport].label.toLowerCase()} players, in order. For each image, read the jersey number of the main player in the center of the crop. Use null when no number is clearly readable; do not guess. Reply with JSON only: {"numbers":[one entry per image, in order]}`;
const r = await sample(prompt, {images: imgs, modelTier:"default"});
const j = parseJSON(r && r.text), nums = (j && Array.isArray(j.numbers)) ? j.numbers : [];
batch.forEach((q, i) => {
const n = nums[i] == null ? null : String(nums[i]).replace(/[^0-9]/g, "");
if (!n) { unread++; return; }
if (n === f.number) ok++;
else { wrong++; for (const t2 of S.track) if (t2.ok && Math.abs(t2.t - q.t) <= 1.3) t2.ok = false; }
});
}
S.verify = {checked: picks.length, ok, wrong, unread};
rescore(false); drawStage();
toast(`Claude checked ${picks.length} spots: ${ok} were #${f.number}, ${wrong} were someone else (removed), ${unread} unreadable.`);
} catch(e) {
if (e && e.code === "rate_limited") toast("Claude is busy. Try again in a minute.");
else if (e && (e.code === "not_granted" || e.code === "declined")) toast("The check needs your OK to ask Claude.");
else toast("The check stopped early.");
} finally { btn.disabled = false; $("#verifyTxt").textContent = S.verify ? `Checked: ${S.verify.ok} of ${S.verify.checked} confirmed` : "Check the tracking with Claude"; }
};
$("#recapBtn").onclick = async () => {
const sample = await cap("sample");
const kept = S.clips.filter(c => c.keep);
const lines = kept.map((c,k) => `${k+1}. ${fmt(c.start)} ${c.ai && c.ai.caption ? c.ai.caption : c.title}${c.mine ? " (our player involved)" : ""}`).join("\n");
const info = reelInfo();
if (!sample) { $("#tmText").value = `${info.who} · ${info.team}\n\n${lines}`; $("#tmSub").textContent = "Claude isn't available in this view, so here is the play list. Edit it, then copy."; $("#textModal").hidden = false; return; }
$("#tmText").value = "Writing…"; $("#tmSub").textContent = "Written by Claude from your clips. Edit it, then copy."; $("#textModal").hidden = false;
try {
const r = await sample(`Write a warm, short recap (3 sentences, under 70 words) of a youth ${SPORTS[S.sport].label.toLowerCase()} game for a family group chat. Player: ${info.who}. Team: ${info.team}. Only use these highlight notes; do not invent scores or results:\n${lines}\nPlain text only.`, {modelTier:"quick", onText: ({text}) => { $("#tmText").value = text; }});
$("#tmText").value = r.text;
} catch(e){ $("#tmText").value = `${info.who} · ${info.team}\n\n${lines}`; $("#tmSub").textContent = "Claude couldn't write this one, so here is the play list."; }
};
$("#tmClose").onclick = () => $("#textModal").hidden = true;
$("#tmCopy").onclick = async () => { try { await navigator.clipboard.writeText($("#tmText").value); toast("Copied."); } catch(e){ toast("Copy isn't available here. Select the text and copy it."); } };
/* ===================== follow a player ===================== */
$("#followBtn").onclick = async () => {
if (S.picking) return endPick();
if (!vid.videoWidth) return;
vid.pause(); stopReel();
S.picking = true; S.pickMode = "player"; $("#stage").classList.add("picking"); $("#pickbar").hidden = false;
$("#pickMsg").textContent = "Tap the player you want the report for"; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = true;
// detections for this frame
let persons = null;
if (S.engine === "ready") {
const lb = letterbox(vid); const img = c640.getImageData(0,0,640,640); const pix = new Uint8ClampedArray(img.data);
const det = await detect(img);
persons = det.persons.map(d => { const box = [d[0]/lb.w, d[1]/lb.h, d[2]/lb.w, d[3]/lb.h]; return [...box, d[4], signature(box, lb, pix)]; }).filter(p => p[3] > 0.05);
} else { const f = frameAt(vid.currentTime); persons = f ? f.p : []; }
S.pickDet = persons; S.pickHover = -1; drawStage();
if (!persons.length) { toast("No players found in this frame. Move to a moment where your player is clearly visible."); endPick(); }
};
function endPick(){ S.picking = false; S.pickMode = null; S.hoopDraft = null; S.courtDraft = null; S.pickDet = null; $("#courtCtl").hidden = true; $("#stage").classList.remove("picking"); $("#pickbar").hidden = true; drawStage(); }
$("#pickCancel").onclick = endPick;
function pickAt(e){
const r = view.getBoundingClientRect(), d = view.width / r.width;
const X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight;
const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2;
const nx = (X - dx)/(vw*s), ny = (Y - dy)/(vh*s);
let best = -1, bd = 1e9;
(S.pickDet||[]).forEach((p,k) => { const inside = Math.abs(nx-p[0]) < p[2]/2 + 0.01 && Math.abs(ny-p[1]) < p[3]/2 + 0.01; const dd = Math.hypot(nx-p[0], ny-p[1]) - (inside ? 1 : 0); if (dd < bd){ bd = dd; best = k; } });
return bd < 0.12 ? best : -1;
}
view.addEventListener("pointermove", e => { if (!S.picking || S.pickMode !== "player") return; const k = pickAt(e); if (k !== S.pickHover){ S.pickHover = k; drawStage(); } });
view.addEventListener("click", e => {
if (!S.picking) { if (!S.reel) $("#playBtn").click(); return; }
if (S.pickMode === "court") {
const r = view.getBoundingClientRect(), d = view.width / r.width, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight;
const sc = Math.min(W/vw, H/vh), dx = (W-vw*sc)/2, dy = (H-vh*sc)/2;
const nx = ((e.clientX - r.left)*d - dx)/(vw*sc), ny = ((e.clientY - r.top)*d - dy)/(vh*sc);
if (nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1) courtTap(nx, ny); return;
}
if (S.pickMode === "hoop") {
const r = view.getBoundingClientRect(), d = view.width / r.width, W = view.width, H = view.height, vw = vid.videoWidth, vh = vid.videoHeight;
const s = Math.min(W/vw, H/vh), dx = (W-vw*s)/2, dy = (H-vh*s)/2;
const nx = ((e.clientX - r.left)*d - dx)/(vw*s), ny = ((e.clientY - r.top)*d - dy)/(vh*s);
if (nx < 0 || nx > 1 || ny < 0 || ny > 1) return;
S.hoopDraft = {t: vid.currentTime, cx: nx, cy: ny, w: (+$("#rimSize").value)/100};
$("#pickMsg").textContent = "Match the ring to the rim"; $("#hoopCtl").hidden = false; drawStage(); return;
}
const k = pickAt(e); if (k < 0) return;
const p = S.pickDet[k];
S.pendingAnchor = {t: vid.currentTime, box: p.slice(0,4), sig: p[5]};
endPick();
const f = S.follow || {};
$("#fmNum").value = f.number || ""; $("#fmName").value = f.name || ""; $("#fmTeam").value = f.team || (S.source.sample ? "Suns" : "");
$("#fmTitle").textContent = S.follow ? "Same player, another moment" : "Pick this player";
$("#followModal").hidden = false; setTimeout(() => $("#fmNum").focus(), 50);
});
$("#fmCancel").onclick = () => { $("#followModal").hidden = true; S.pendingAnchor = null; };
$("#fmOk").onclick = () => {
const num = $("#fmNum").value.replace(/[^0-9]/g, "").slice(0,3), name = $("#fmName").value.trim(), team = $("#fmTeam").value.trim();
const sameNum = S.follow && S.follow.number === num;
if (!S.follow || !sameNum) S.follow = {anchors:[], number:num, name, team};
S.follow.name = name; S.follow.team = team;
S.follow.anchors.push(S.pendingAnchor); S.pendingAnchor = null;
$("#followModal").hidden = true;
applyFollow();
};
function applyFollow(quiet){
$("#followTxt").textContent = S.follow ? "Player " + (S.follow.number ? "#" + S.follow.number : "picked") : "Pick the player";
$("#followBtn").classList.toggle("on", !!S.follow);
$("#verifyBtn").hidden = !S.follow;
if (S.an) { S.track = buildTrack(); attributeShots(); rescore(false); renderReport(); if (!quiet) toast(S.track ? "Tracking updated. The teal band shows when they're on screen." : "Press Build report to track this player."); }
setHud(); drawStage();
}
/* ===================== hoop marking ===================== */
$("#hoopBtn").onclick = () => {
if (S.picking) { endPick(); return; }
if (!vid.videoWidth) return;
vid.pause(); stopReel();
S.picking = true; S.pickMode = "hoop"; S.hoopDraft = null;
$("#stage").classList.add("picking"); $("#pickbar").hidden = false; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = true;
$("#pickMsg").textContent = S.hoops.length >= 2 ? "Tap a rim to replace the older hoop" : "Pause where the rim is clear, then tap its middle";
drawStage();
};
$("#rimSize").addEventListener("input", () => { if (S.hoopDraft) { S.hoopDraft.w = (+$("#rimSize").value)/100; drawStage(); } });
$("#hoopSave").onclick = () => {
const hd = S.hoopDraft; if (!hd) return;
S.hoops.push({t: hd.t, cx: hd.cx, cy: hd.cy, w: hd.w});
if (S.hoops.length > 2) S.hoops.shift();
endPick(); updateHoopBtn();
if (S.an) runShots(); else toast("Hoop saved. Press Build report when the setup is done.");
};
function updateHoopBtn(){
$("#hoopTxt").textContent = S.hoops.length ? (S.hoops.length === 1 ? "Hoop marked" : "2 hoops marked") : "Mark the hoop";
$("#hoopBtn").classList.toggle("on", S.hoops.length > 0);
$("#courtTxt").textContent = S.calib ? "Court marked" : "Mark the court";
$("#courtBtn").classList.toggle("on", !!S.calib);
if (S.calib) $("#courtBtn small").textContent = COURTS[S.calib.std].label;
}
async function runShots(){
if (S.busy || !S.hoops.length) return;
S.busy = true; stopReel(); vid.pause();
const scan = $("#scan"); scan.hidden = false;
document.querySelectorAll("#steps li").forEach(li => { li.classList.remove("on","done"); li.style.display = li.dataset.s === "shots" ? "" : "none"; });
const li = document.querySelector('#steps li[data-s="shots"]'); li.classList.add("on");
$("#scanTitle").textContent = "Counting shots"; $("#scanFrames").textContent = ""; $("#scanPeople").textContent = "Plays at normal speed"; $("#scanEta").textContent = "";
const bar = $("#scanBar"); bar.style.width = "2%"; setHud();
try {
const t0 = performance.now();
await analyzeShots(p => { bar.style.width = (2 + p*96) + "%"; $("#scanFrames").textContent = Math.round(p*100) + "%"; });
li.classList.remove("on"); li.classList.add("done");
attributeShots();
if (S.an) rescore(false); else { renderRail(); drawTimeline(); }
updateTiles(); renderReport();
const made = S.shots.filter(x => x.made).length;
toast(S.shots.length ? `${S.shots.length} shots, ${made} made (${Math.round((performance.now()-t0)/1000)}s)` : "No shots seen. Make sure the ring sits on the rim.");
} catch(e) { console.error(e); toast("Shot counting stopped: " + (e.message || e)); }
finally {
S.busy = false; document.querySelectorAll("#steps li").forEach(li2 => li2.style.display = "");
setTimeout(() => { scan.hidden = true; $("#scanTitle").textContent = "Analyzing game"; }, 500); setHud(); drawStage();
}
}
/* ===================== source loading ===================== */
async function loadSource(src){
stopReel(); S.source = src; S.an = null; S.track = null; S.clips = []; S.score = null; S.thumbCache = {}; S.active = -1;
if (!src.sample) S.follow = null;
S.hoops = []; S.shots = null; S.calib = null; S.H = null; S.Hinv = null; S.hoopPoses = null; S.form = null; S.plan = null; updateHoopBtn && updateHoopBtn();
$("#srcName").textContent = src.name; $("#srcSub").textContent = src.sub;
$("#sampleBtn").hidden = !!src.sample;
vid.src = src.url; await loaded(vid);
$("#srcSub").textContent = src.sub.replace("{dur}", fmt(vid.duration));
applyFollow(); renderRail(); drawTimeline(); renderReport();
}
let sampleBlobUrl = null;
async function loadSample(){
if (!sampleBlobUrl) {
$("#srcSub").textContent = "Loading sample workout…";
try { const r = await fetch("media/workout.mp4"); if (!r.ok) throw 0; sampleBlobUrl = URL.createObjectURL(await r.blob()); }
catch(e) { sampleBlobUrl = "media/workout.mp4"; }
}
await loadSource({name:"Sample workout · #8 spot shooting", sub:"Synthetic practice footage · {dur} · free to use", url:sampleBlobUrl, sample:true});
try {
const j = await (await fetch("media/workout_analysis.json")).json();
S.an = j.an; S.follow = j.follow; S.lastAnalyzeSec = j.seconds; S.hoops = j.hoops || []; S.shots = j.shots || null;
S.hoopPoses = j.hoopPoses || null; S.calib = j.calib || null; buildCalib(); updateHoopBtn();
S.track = buildTrack(); applyFollow(true);
attributeShots(); rescore(true);
S.clips.forEach(c => { const t = j.thumbs && j.thumbs[c.id]; if (t) { c.thumb = t; S.thumbCache[c.id] = t; } });
renderRail(); makeThumbs(); renderReport(); renderHow();
} catch(e) { console.warn("no precomputed analysis", e); renderReport(); }
drawStage();
}
$("#uploadBtn").onclick = () => $("#fileIn").click();
$("#sampleBtn").onclick = () => loadSample();
$("#fileIn").onchange = e => { const f = e.target.files[0]; if (f) useFile(f); e.target.value = ""; };
async function useFile(f){
if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|webm)$/i.test(f.name)) { toast("That file isn't a video. Use MP4, MOV or WebM."); return; }
const url = URL.createObjectURL(f);
await loadSource({name:f.name, sub:`Your video · {dur} · ${(f.size/1e6).toFixed(0)} MB · stays on this device`, url, sample:false, file:f});
$("#analyzeTxt").textContent = "Build report";
toast("Now mark the hoop, the court and the player, then press Build report.");
}
const stage = $("#stage");
["dragenter","dragover"].forEach(ev => stage.addEventListener(ev, e => { e.preventDefault(); stage.classList.add("dragover"); }));
["dragleave","drop"].forEach(ev => stage.addEventListener(ev, e => { e.preventDefault(); stage.classList.remove("dragover"); }));
stage.addEventListener("drop", e => { const f = e.dataTransfer.files[0]; if (f) useFile(f); });
$("#analyzeBtn").onclick = () => analyze();
/* ===================== sport + size ===================== */
S.sport = "basketball";
document.querySelectorAll("[data-size]").forEach(b => b.onclick = () => { S.size = b.dataset.size; document.querySelectorAll("[data-size]").forEach(c => c.setAttribute("aria-pressed", c === b)); rescore(false); });
$("#mineOnly").onclick = () => { if (!S.track) { toast("Follow a player first."); return; } S.mineFirst = !S.mineFirst; $("#mineOnly").setAttribute("aria-pressed", S.mineFirst); rescore(false); };
function setHud(){
const h = [];
h.push(`<span>${esc(SPORTS[S.sport].label)}</span>`);
if (S.busy) h.push(`<span class="live">Analyzing</span>`);
if (S.reel) h.push(`<span class="live">${S.reel.vertical ? "9:16 reel" : "Highlight reel"}</span>`);
if (S.follow) h.push(`<span class="trk">Following ${S.follow.number ? "#" + esc(S.follow.number) : "player"}</span>`);
if (S.playerCam) h.push(`<span class="trk">Player Cam</span>`);
$("#hud").innerHTML = h.join("");
}
/* ===================== court marking ===================== */
const courtSel = $("#courtStd");
Object.entries(COURTS).forEach(([k, v]) => { const o = document.createElement("option"); o.value = k; o.textContent = v.label; courtSel.appendChild(o); });
const COURT_STEPS = ["Tap 1: a baseline corner of the paint", "Tap 2: the other baseline corner", "Tap 3: the free-throw line corner on the same side as 2", "Tap 4: the last free-throw line corner"];
$("#courtBtn").onclick = () => {
if (S.picking) { endPick(); return; }
if (!vid.videoWidth) return;
vid.pause(); stopReel();
S.picking = true; S.pickMode = "court"; S.courtDraft = {t: vid.currentTime, pts: []};
courtSel.value = (S.calib && S.calib.std) || (S.source.sample ? "fiba" : "hs");
$("#stage").classList.add("picking"); $("#pickbar").hidden = false; $("#hoopCtl").hidden = true; $("#courtCtl").hidden = false;
$("#courtSave").disabled = true; $("#pickMsg").textContent = COURT_STEPS[0]; drawStage();
};
$("#courtUndo").onclick = () => { if (!S.courtDraft) return; S.courtDraft.pts.pop(); $("#courtSave").disabled = true; $("#pickMsg").textContent = COURT_STEPS[S.courtDraft.pts.length]; drawStage(); };
$("#courtSave").onclick = () => {
const d = S.courtDraft; if (!d || d.pts.length !== 4) return;
S.calib = {t: d.t, pts: d.pts.slice(), std: courtSel.value, hoop: 0};
buildCalib();
if (!S.H) { toast("Those 4 taps don't make a usable shape. Try again, going around the paint in order."); S.calib = null; return; }
endPick(); updateHoopBtn(); attributeShots(); renderReport(); drawStage();
toast("Court saved. Faint court lines now show on the video; check they sit on the real lines.");
};
function courtTap(nx, ny){
const d = S.courtDraft; if (!d || d.pts.length >= 4) return;
d.pts.push([nx, ny]);
if (d.pts.length < 4) $("#pickMsg").textContent = COURT_STEPS[d.pts.length];
else { $("#pickMsg").textContent = "Pick the court type, then save"; $("#courtSave").disabled = false; }
drawStage();
}
// court lines in court feet, for drawing on video and charts
function courtLines(){
const K = courtSpec(), L = K.lane/2, lines = [];
lines.push([[-L,0],[L,0],[L,K.ft],[-L,K.ft],[-L,0]]); // paint
const ftc = []; for (let a=0;a<=Math.PI;a+=Math.PI/24) ftc.push([6*Math.cos(a), K.ft + 6*Math.sin(a)]); lines.push(ftc); // free-throw circle
const arc = []; const cx = K.corner3 || 0;
if (K.corner3) { const yc = K.hoopY + Math.sqrt(Math.max(0, K.r3*K.r3 - K.corner3*K.corner3)); arc.push([-K.corner3,0],[-K.corner3,yc]); const a0 = Math.atan2(yc - K.hoopY, -K.corner3), a1 = Math.atan2(yc - K.hoopY, K.corner3); for (let a=a0; a>=a1; a-=0.04) arc.push([K.r3*Math.cos(a), K.hoopY + K.r3*Math.sin(a)]); arc.push([K.corner3,yc],[K.corner3,0]); }
else { for (let a=Math.PI; a>=0; a-=0.04) arc.push([K.r3*Math.cos(a), K.hoopY + K.r3*Math.sin(a)]); }
lines.push(arc);
lines.push([[-25,0],[25,0]]);
return lines;
}
/* ===================== tabs ===================== */
function setTab(name){
$("#tabReport").setAttribute("aria-selected", name === "report"); $("#tabClips").setAttribute("aria-selected", name === "clips");
$("#paneReport").hidden = name !== "report"; $("#paneClips").hidden = name !== "clips";
}
$("#tabReport").onclick = () => setTab("report");
$("#tabClips").onclick = () => setTab("clips");
/* ===================== the report ===================== */
const pct = (m, a) => a ? Math.round(m/a*100) + "%" : "–";
const shotKey = sh => "s" + Math.round(sh.t*10);
function quickRead(sh, mv){
const out = [];
if (sh && sh.att) {
out.push(`Shot ${sh.made} of ${sh.att} (${pct(sh.made, sh.att)})${sh.threesA ? `, ${sh.threesM} of ${sh.threesA} from three` : ""}${sh.pts ? `, ${sh.pts} points` : ""}.`);
const zs = Object.entries(sh.zones).filter(([k, z]) => z.a >= 2 && k !== "back");
if (zs.length >= 2) {
zs.sort((a, b) => b[1].m/b[1].a - a[1].m/a[1].a);
const [bk, bz] = zs[0], [wk, wz] = zs[zs.length-1];
if (bz.m/bz.a > wz.m/wz.a) out.push(`Best spot: ${ZONES[bk].toLowerCase()} (${bz.m}/${bz.a}). Coldest: ${ZONES[wk].toLowerCase()} (${wz.m}/${wz.a}).`);
}
const mid = sh.zones.mid.a;
if (sh.att >= 5 && mid/sh.att >= 0.4) out.push(`${Math.round(mid/sh.att*100)}% of shots were long twos. Worth a step back to the line, or a step in toward the rim.`);
const miss = sh.shots.filter(s => !s.made && s.dist != null);
const far = miss.filter(s => s.dist > 18).length;
if (miss.length >= 2 && far/miss.length >= 0.6) out.push(`Most misses came from beyond 18 ft. Range and legs are the first thing to look at in form feedback.`);
} else if (S.hoops.length && S.shots) out.push("No shots by this player yet. If that's wrong, confirm the player on the shots below.");
if (mv) {
const mins = mv.tracked/60;
out.push(`Covered ${Math.round(mv.dist)} ft in ${mins >= 1 ? mins.toFixed(1) + " min" : Math.round(mv.tracked) + " s"} on camera, about ${Math.round(mv.dist/Math.max(mv.tracked,1)*60)} ft per minute. Top speed ${(mv.top*0.6818).toFixed(1)} mph; ${mv.sprints} sprint${mv.sprints === 1 ? "" : "s"}.`);
}
if (sh && sh.unsure) out.push(`${sh.unsure} shot${sh.unsure > 1 ? "s need" : " needs"} your OK: tap Yes or No in the shot list.`);
return out;
}
function renderReport(){
const R = $("#report"); if (!R) return;
if (S.shots || S.track) coachMoments(); else S.moments = null;
const f = S.follow, sh = shootingStats(), mv = movementStats();
let h = "";
h += `<div class="who"><div class="badge">${f && f.number ? "#" + esc(f.number) : "?"}</div><div><b>${esc(f ? (f.name || (f.number ? "Player #" + f.number : "Your player")) : "All shots at the hoop")}</b><span>${esc(f && f.team ? f.team + " · " : "")}${esc(S.source.name || "")}</span></div></div>`;
const need = [];
if (!S.hoops.length) need.push(["Mark the hoop", "Pause where the rim is clear, tap it, and size the ring. Needed for makes and misses."]);
if (!S.calib) need.push(["Mark the court", "Tap the 4 corners of the paint. Needed for shot locations, distance and speed."]);
if (!f) need.push(["Pick the player", "Tap them once. Skip this for a one-player shooting workout: every shot then counts."]);
if (!S.an) need.push(["Build report", "Scans the video. About the video's length, on this device."]);
if (need.length) h += `<div class="rsec"><h3>To finish the report</h3><ul class="checklist">${need.map(n => `<li><b>${esc(n[0])}.</b> ${esc(n[1])}</li>`).join("")}</ul></div>`;
if (sh || mv) {
h += `<div class="rsec"><div class="tiles6">`;
if (sh) h += `<div class="tile"><b class="num">${sh.made}/${sh.att}</b><span>field goals</span><small>${pct(sh.made, sh.att)}</small></div><div class="tile"><b class="num">${sh.threesM}/${sh.threesA}</b><span>threes</span><small>${pct(sh.threesM, sh.threesA)}</small></div><div class="tile"><b class="num">${S.calib ? sh.pts : "–"}</b><span>points</span><small>no free throws</small></div>`;
if (mv) h += `<div class="tile trk"><b class="num">${Math.round(mv.dist)}</b><span>feet run</span><small>${(mv.dist/5280).toFixed(2)} mi</small></div><div class="tile trk"><b class="num">${(mv.top*0.6818).toFixed(1)}</b><span>top mph</span><small>1-second best</small></div><div class="tile trk"><b class="num">${mv.sprints}</b><span>sprints</span><small>1 s at 9+ mph</small></div>`;
h += `</div></div>`;
}
h += scorecardHTML();
const qr = quickRead(sh, mv);
if (qr.length) h += `<div class="rsec"><h3>Quick read</h3><ul class="read">${qr.map(x => `<li>${esc(x)}</li>`).join("")}</ul></div>`;
if (S.plan) h += planHTML(S.plan);
if (sh && S.calib) {
h += `<div class="rsec"><h3>Shot chart <small>tap a shot to watch it</small></h3><canvas class="court" id="chart" aria-label="Shot chart"></canvas>
<table class="ztable num" style="margin-top:8px"><thead><tr><th>Zone</th><th>Made</th><th>%</th><th></th></tr></thead><tbody>${["paint","mid","corner3","three"].map(k => { const z = sh.zones[k]; return `<tr><td>${ZONES[k]}</td><td>${z.m}/${z.a}</td><td>${pct(z.m, z.a)}</td><td><div class="zbar"><b style="width:${z.a ? Math.round(z.m/z.a*100) : 0}%"></b></div></td></tr>`; }).join("")}</tbody></table></div>`;
}
if (mv) {
const tot = Object.values(mv.zoneT).reduce((a, b) => a + b, 0) || 1;
h += `<div class="rsec"><h3>Where they spent the time <small>${Math.round(mv.tracked)} s on camera</small></h3><canvas class="court" id="heat" aria-label="Movement heat map"></canvas>
<table class="ztable num" style="margin-top:8px"><tbody>${["paint","mid","corner3","three","back"].filter(k => mv.zoneT[k] > 0).map(k => `<tr><td>${ZONES[k]}</td><td>${Math.round(mv.zoneT[k]/tot*100)}%</td><td><div class="zbar"><b style="width:${Math.round(mv.zoneT[k]/tot*100)}%;background:var(--track)"></b></div></td></tr>`).join("")}</tbody></table></div>`;
}
if (S.shots && S.shots.length) {
h += `<div class="rsec"><h3>Every shot at the hoop <small>${S.shots.length} seen</small></h3>`;
S.shots.forEach((q, i) => {
const loc = q.dist != null ? `${Math.round(q.dist)} ft · ${ZONES[q.zone]}` : "location needs the court";
let who = "";
if (S.follow) {
const tag = S.follow.number ? "#" + esc(S.follow.number) : "player";
if (q.coach != null) who = `<span class="sub">${q.coach ? "✓ " + tag : "Not " + tag} (you)</span> <button class="mini" data-undo="${i}">Undo</button>`;
else if (q.mine === true && q.sure) who = `<span class="sub" style="color:var(--track)">✓ ${tag}</span>`;
else if (q.mine === false && q.sure) who = `<span class="sub">Not ${tag}</span> <button class="mini" data-yes="${i}">It was</button>`;
else who = `<span class="q">${tag}? <button class="mini" data-yes="${i}">Yes</button><button class="mini" data-no="${i}">No</button></span>`;
}
const fb = S.form && S.form[shotKey(q)];
h += `<div class="shotrow"><button class="mini num" data-play="${i}" aria-label="Watch shot ${i+1}">${i+1}</button><span class="res ${q.made ? "m" : "x"}">${q.made ? "MADE" : "MISS"}</span><span><span class="num">${fmt(q.relT || q.t)}</span> · ${esc(loc)}</span><span>${who}</span>${fb ? `<div class="note">Form ${fb.rating ? fb.rating + "/5" : ""}: ${esc(fb.one_fix || fb.summary || "")}</div>` : ""}</div>`;
});
h += `</div>`;
}
R.innerHTML = h || `<div class="empty">Upload a video to start.</div>`;
if ($("#chart")) drawCourtCanvas($("#chart"), "shots", sh);
if ($("#heat")) drawCourtCanvas($("#heat"), "heat", null, mv);
renderHero(); renderMoments(); coachKey = ""; updateCoachCard(); updateLiveHud(); drawTimeline();
$("#planBtn").disabled = !(sh && sh.att) && !mv;
$("#formBtn").disabled = !(sh && sh.att);
$("#reportDl").disabled = !(sh || mv); $("#reportCopy").disabled = !(sh || mv);
}
$("#report").addEventListener("click", (e) => {
const b = e.target.closest("button"); if (!b) return;
const pick = (k) => S.shots[+b.dataset[k]];
if (b.dataset.play != null) { const q = pick("play"); playRange(Math.max(0, (q.relT || q.t) - 1.2), (q.rimT || q.end) + 1.6); }
else if (b.dataset.yes != null) { pick("yes").coach = true; attributeShots(); renderReport(); }
else if (b.dataset.no != null) { pick("no").coach = false; attributeShots(); renderReport(); }
else if (b.dataset.undo != null) { pick("undo").coach = null; attributeShots(); renderReport(); }
});
async function playRange(a, b){ stopReel(); ensureAudio(); clipStop = b; await seek(vid, a); vid.playbackRate = S.slow ? 0.5 : 1; try { await vid.play(); } catch(e){} }
function drawCourtCanvas(cv, mode, sh, mv){
const d = Math.min(2, window.devicePixelRatio || 1), w = cv.getBoundingClientRect().width || 340, hh = w*0.66;
cv.width = Math.round(w*d); cv.height = Math.round(hh*d); cv.style.height = hh + "px";
const x = cv.getContext("2d"), W = cv.width, H = cv.height, Ymax = 33;
const P = (X, Y) => [(X + 25)/50*W, Y/Ymax*H];
x.fillStyle = "#0f1420"; x.fillRect(0, 0, W, H);
if (mode === "heat" && mv) {
const g = document.createElement("canvas"); g.width = 100; g.height = 66; const gx = g.getContext("2d");
for (const p of mv.path) { if (p.y > Ymax) continue; const [px, py] = [(p.x + 25)/50*100, p.y/Ymax*66]; const r = gx.createRadialGradient(px, py, 0, px, py, 6); r.addColorStop(0, "rgba(46,230,197,.22)"); r.addColorStop(1, "rgba(46,230,197,0)"); gx.fillStyle = r; gx.fillRect(px-6, py-6, 12, 12); }
x.imageSmoothingEnabled = true; x.drawImage(g, 0, 0, W, H);
}
x.strokeStyle = "rgba(237,241,247,.35)"; x.lineWidth = 1.4*d;
for (const L of courtLines()) { x.beginPath(); L.forEach(([X, Y], i) => { const [px, py] = P(X, Y); i ? x.lineTo(px, py) : x.moveTo(px, py); }); x.stroke(); }
const K = courtSpec(), [hx, hy] = P(0, K.hoopY);
x.strokeStyle = "#FF5A1F"; x.lineWidth = 2*d; x.beginPath(); x.arc(hx, hy, 0.75/50*W, 0, 7); x.stroke();
x.strokeStyle = "rgba(237,241,247,.6)"; x.beginPath(); const [b0] = P(-3, 4), [b1] = P(3, 4); x.moveTo(b0, P(0,4)[1]); x.lineTo(b1, P(0,4)[1]); x.stroke();
if (mode === "shots" && S.shots) {
cv._hits = [];
S.shots.forEach((q, i) => {
if (!q.court || q.court[1] > Ymax) return;
const [px, py] = P(q.court[0], q.court[1]), r = 5.5*d;
cv._hits.push({i, px, py});
if (q.mine === false) return;
const unsure = S.follow && q.mine !== true;
if (unsure) { x.strokeStyle = "#8C96AA"; x.lineWidth = 1.5*d; x.beginPath(); x.arc(px, py, r, 0, 7); x.stroke(); }
else if (q.made) { x.fillStyle = "#3DDC84"; x.beginPath(); x.arc(px, py, r, 0, 7); x.fill(); }
else { x.strokeStyle = "#FF8A5C"; x.lineWidth = 2.2*d; x.beginPath(); x.moveTo(px - r, py - r); x.lineTo(px + r, py + r); x.moveTo(px + r, py - r); x.lineTo(px - r, py + r); x.stroke(); }
});
cv.onclick = (e) => { const r = cv.getBoundingClientRect(), X = (e.clientX - r.left)*d, Y = (e.clientY - r.top)*d; let best = null, bd = 18*d; for (const hgt of cv._hits) { const dd = Math.hypot(hgt.px - X, hgt.py - Y); if (dd < bd) { bd = dd; best = hgt; } } if (best) { const q = S.shots[best.i]; playRange(Math.max(0, (q.relT || q.t) - 1.2), (q.rimT || q.end) + 1.6); } };
}
}
/* ===================== Claude: form feedback and plan ===================== */
async function grabPlayer(q){
if (scanVid.src !== S.source.url) scanVid.src = S.source.url;
await loaded(scanVid);
const vw = scanVid.videoWidth, vh = scanVid.videoHeight, cv = document.createElement("canvas"); cv.width = 300; cv.height = 400; const x = cv.getContext("2d");
const out = [], t0 = q.relT || q.t;
for (const dt of [-0.4, -0.12, 0.12, 0.45]) {
const t = Math.max(0, t0 + dt); await seek(scanVid, t);
let box = q.shooterBox; const tk = S.follow && q.mine ? trackAt(t) : null; if (tk && tk.ok) box = [tk.cx, tk.cy, tk.w, tk.h];
if (!box) box = [0.5, 0.55, 0.3, 0.6];
const bh = box[3]*vh*1.7, bw = bh*0.75, sx = box[0]*vw - bw/2, sy = (box[1] - box[3]*0.25)*vh - bh/2;
x.fillStyle = "#000"; x.fillRect(0, 0, 300, 400); x.drawImage(scanVid, sx, sy, bw, bh, 0, 0, 300, 400);
out.push(await new Promise(r => cv.toBlob(r, "image/jpeg", 0.85)));
}
return out;
}
async function claudeReady(){
const sample = await cap("sample");
if (!sample) { toast("Claude features work when this page is opened in claude.ai."); return null; }
try { const l = await sample.limits(); if (!(l && l.images)) { toast("Image features aren't enabled for this page yet."); return null; } } catch(e){}
return sample;
}
$("#formBtn").onclick = async () => {
const sh = shootingStats(); if (!sh || !sh.att) return;
const sample = await claudeReady(); if (!sample) return;
const btn = $("#formBtn"); btn.disabled = true; S.form = S.form || {};
const list = sh.shots.slice(0, 12); let k = 0;
try {
for (const q of list) {
k++; btn.textContent = `Reviewing shot ${k} of ${list.length}…`;
const imgs = await grabPlayer(q);
const prompt = `You are a youth basketball shooting coach. Four frames of one player's shot, in time order: the set-up, the moment the ball leaves the hands, just after, and the follow-through. The shot was ${q.made ? "made" : "missed"}${q.dist != null ? ", from about " + Math.round(q.dist) + " feet" : ""}.
Judge only what you can see. If a frame is too small or blurry to judge something, say "can't see". Keep each field under 14 words, plain words a 12-year-old understands.
Reply with JSON only: {"rating":1-5,"balance":"","elbow":"","release":"","follow_through":"","one_fix":"the single most useful change","drill":"one drill name and how to do it in under 20 words"}`;
const r = await sample(prompt, {images: imgs, modelTier: "default"});
const j = parseJSON(r && r.text); if (j) S.form[shotKey(q)] = j;
renderReport();
}
toast("Form feedback added to each shot. Build the improvement plan next.");
} catch(e) {
toast(e && e.code === "rate_limited" ? "Claude is busy. Try again in a minute." : e && (e.code === "not_granted" || e.code === "declined") ? "Form feedback needs your OK to ask Claude." : "Form feedback stopped early.");
} finally { btn.disabled = false; btn.innerHTML = 'Form feedback'; }
};
function reportFacts(){
const sh = shootingStats(), mv = movementStats(), f = S.follow;
const lines = [];
lines.push(`Player: ${f ? (f.name || "") + (f.number ? " #" + f.number : "") : "one shooter"}${f && f.team ? ", " + f.team : ""}.`);
if (sh) {
lines.push(`Shooting: ${sh.made}/${sh.att} FG, ${sh.threesM}/${sh.threesA} from three.`);
for (const k of ["paint","mid","corner3","three"]) if (sh.zones[k].a) lines.push(`${ZONES[k]}: ${sh.zones[k].m}/${sh.zones[k].a}.`);
sh.shots.forEach((q, i) => { const fb = S.form && S.form[shotKey(q)]; lines.push(`Shot ${i+1}: ${q.made ? "made" : "missed"}${q.dist != null ? ", " + Math.round(q.dist) + " ft, " + ZONES[q.zone] : ""}${fb ? `. Form ${fb.rating}/5; balance: ${fb.balance}; elbow: ${fb.elbow}; release: ${fb.release}; follow-through: ${fb.follow_through}; fix: ${fb.one_fix}` : ""}.`); });
}
if (mv) lines.push(`Movement on camera: ${Math.round(mv.dist)} ft in ${Math.round(mv.tracked)} s, top speed ${(mv.top*0.6818).toFixed(1)} mph, ${mv.sprints} sprints.`);
const fs = formSummary();
for (const k of Object.keys(FORM)) if (fs[k]) lines.push(`${FORM[k].label}: median ${fs[k].median} ${FORM[k].unit} (target ${FORM[k].target}), ${fs[k].flagged} of ${fs[k].n} shots off target.`);
for (const m of S.moments || []) lines.push(`${fmt(m.t)}${m.end ? "–" + fmt(m.end) : ""} ${m.kind === "fix" ? "FIX" : "GOOD"}: ${m.title}. ${m.metric}.`);
return lines.join("\n");
}
$("#planBtn").onclick = async () => {
const sample = await cap("sample");
if (!sample) { toast("The improvement plan works when this page is opened in claude.ai."); return; }
const btn = $("#planBtn"); btn.disabled = true; btn.textContent = "Writing plan…";
try {
const prompt = `You are a youth basketball coach writing a short, encouraging improvement plan for one player from game or practice data. Use only these facts; do not invent numbers.
${reportFacts()}
${S.form ? "" : "No form review was done yet; base the plan on the numbers and say a form review would sharpen it."}
Reply with JSON only:
{"summary":"2 sentences","strengths":["max 3 short items"],"fixes":[{"issue":"","why":"what in the data shows it","drill":"name + how","reps":"e.g. 3 x 10 makes"}],"week":[{"day":"Mon","focus":"","drill":"","minutes":20}]}
At most 3 fixes and 4 practice days.`;
const r = await sample(prompt, {modelTier: "default"});
const j = parseJSON(r && r.text);
if (!j) throw new Error("unreadable");
S.plan = j; renderReport(); setTab("report");
const el = document.querySelector("#report .plan"); el && el.scrollIntoView({behavior:"smooth", block:"start"});
} catch(e) {
toast(e && e.code === "rate_limited" ? "Claude is busy. Try again in a minute." : e && (e.code === "not_granted" || e.code === "declined") ? "The plan needs your OK to ask Claude." : "Couldn't write the plan. Try again.");
} finally { btn.disabled = false; btn.textContent = "Improvement plan"; }
};
function planHTML(p){
const li = a => (a || []).map(x => `<li>${esc(x)}</li>`).join("");
return `<div class="rsec plan"><h3>Improvement plan <small>by Claude</small></h3><p>${esc(p.summary || "")}</p>
${p.strengths && p.strengths.length ? `<h4>Keep doing</h4><ul>${li(p.strengths)}</ul>` : ""}
${p.fixes && p.fixes.length ? `<h4>Work on</h4><ol>${p.fixes.map(f => `<li><b>${esc(f.issue || "")}</b>. ${esc(f.why || "")} <br><span style="color:var(--track)">Drill:</span> ${esc(f.drill || "")} <span class="sub">(${esc(f.reps || "")})</span></li>`).join("")}</ol>` : ""}
${p.week && p.week.length ? `<h4>This week</h4><table class="ztable"><tbody>${p.week.map(d => `<tr><td><b>${esc(d.day || "")}</b></td><td>${esc(d.focus || "")}: ${esc(d.drill || "")}</td><td class="num">${esc(String(d.minutes || ""))} min</td></tr>`).join("")}</tbody></table>` : ""}</div>`;
}
/* ===================== export ===================== */
function summaryText(){
const sh = shootingStats(), mv = movementStats(), f = S.follow;
const L = [`${f ? (f.name || "Player") + (f.number ? " #" + f.number : "") : "Shooting report"}${f && f.team ? " · " + f.team : ""}`, ""];
quickRead(sh, mv).forEach(x => L.push("• " + x));
const fc = fixCounts();
if (fc.length) { L.push("", "Work on:"); fc.slice(0, 3).forEach(([k, M], i) => L.push(`${i+1}. ${RULES[k].title} (${M.map(m => fmt(m.t)).join(", ")}): ${RULES[k].drill}, ${RULES[k].reps}`)); }
if (S.plan) { L.push("", "Plan: " + (S.plan.summary || "")); (S.plan.fixes || []).forEach((x, i) => L.push(`${i+1}. ${x.issue}: ${x.drill} (${x.reps})`)); }
L.push("", "Made with Clutch Coach");
return L.join("\n");
}
function courtSVG(sh){
const K = courtSpec(), Ymax = 33, P = (X, Y) => [((X + 25)/50*500).toFixed(1), (Y/Ymax*330).toFixed(1)];
let s = `<svg viewBox="0 0 500 330" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:520px;background:#0f1420;border-radius:10px">`;
for (const L of courtLines()) s += `<polyline fill="none" stroke="rgba(237,241,247,.4)" stroke-width="1.5" points="${L.map(p => P(p[0], p[1]).join(",")).join(" ")}"/>`;
const h = P(0, K.hoopY); s += `<circle cx="${h[0]}" cy="${h[1]}" r="7.5" fill="none" stroke="#FF5A1F" stroke-width="2"/>`;
for (const q of (sh ? sh.shots : [])) { if (!q.court || q.court[1] > Ymax) continue; const [x, y] = P(q.court[0], q.court[1]);
s += q.made ? `<circle cx="${x}" cy="${y}" r="6" fill="#3DDC84"/>` : `<path d="M${x-6} ${y-6}L${+x+6} ${+y+6}M${+x+6} ${y-6}L${x-6} ${+y+6}" stroke="#FF8A5C" stroke-width="2.5"/>`; }
return s + `</svg>`;
}
function reportHTMLDoc(){
const sh = shootingStats(), mv = movementStats(), f = S.follow;
const title = `${f ? (f.name || "Player") + (f.number ? " #" + f.number : "") : "Shooting report"}`;
const rows = sh ? sh.shots.map((q, i) => { const fb = S.form && S.form[shotKey(q)]; return `<tr><td>${i+1}</td><td>${fmt(q.relT || q.t)}</td><td>${q.made ? "Made" : "Missed"}</td><td>${q.dist != null ? Math.round(q.dist) + " ft · " + ZONES[q.zone] : "–"}</td><td>${fb ? esc(fb.one_fix || "") : ""}</td></tr>`; }).join("") : "";
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)} · Clutch Coach report</title>
<style>body{font:15px/1.5 system-ui,sans-serif;background:#0A0D13;color:#EDF1F7;max-width:760px;margin:0 auto;padding:24px}h1{font-size:28px;margin:0}h2{font-size:17px;text-transform:uppercase;letter-spacing:.08em;color:#8C96AA;margin:26px 0 8px}.t{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.t div{background:#161B27;border:1px solid #222A3A;border-radius:10px;padding:10px}.t b{font-size:24px;display:block}table{width:100%;border-collapse:collapse;font-size:14px}td,th{text-align:left;padding:6px;border-bottom:1px solid #222A3A}li{margin:4px 0}small{color:#8C96AA}</style></head><body>
<h1>${esc(title)}</h1><small>${esc(f && f.team ? f.team + " · " : "")}${esc(S.source.name || "")} · ${new Date().toLocaleDateString()}</small>
<h2>Numbers</h2><div class="t">${sh ? `<div><b>${sh.made}/${sh.att}</b>field goals (${pct(sh.made, sh.att)})</div><div><b>${sh.threesM}/${sh.threesA}</b>threes</div><div><b>${sh.pts}</b>points</div>` : ""}${mv ? `<div><b>${Math.round(mv.dist)} ft</b>run on camera</div><div><b>${(mv.top*0.6818).toFixed(1)} mph</b>top speed</div><div><b>${mv.sprints}</b>sprints</div>` : ""}</div>
<h2>Quick read</h2><ul>${quickRead(sh, mv).map(x => `<li>${esc(x)}</li>`).join("")}</ul>
${S.calib && sh ? `<h2>Shot chart</h2>${courtSVG(sh)}` : ""}
${S.plan ? planHTML(S.plan).replace(/var\\(--track\\)/g, "#2EE6C5") : ""}
${(S.moments || []).length ? `<h2>Coaching moments</h2><table><thead><tr><th>Time</th><th>What</th><th>Measured</th><th>Fix and drill</th></tr></thead><tbody>${S.moments.map(m => `<tr><td>${fmt(m.t)}${m.end ? "–" + fmt(m.end) : ""}</td><td><b style="color:${m.kind === "fix" ? "#FF8A5C" : "#3DDC84"}">${esc(m.title)}</b></td><td>${esc(m.metric)}</td><td>${esc(m.fix)}${m.drill ? `<br><small>Drill: ${esc(m.drill)} (${esc(m.reps)})</small>` : ""}</td></tr>`).join("")}</tbody></table>` : ""}
${rows ? `<h2>Shots</h2><table><thead><tr><th>#</th><th>Time</th><th>Result</th><th>From</th><th>Form note</th></tr></thead><tbody>${rows}</tbody></table>` : ""}
<p><small>Made with Clutch Coach. Stats come from video and can be off; the coach confirmed uncertain shots.</small></p></body></html>`;
}
$("#reportDl").onclick = async () => {
const dl = await cap("downloads"), name = `clutch-report${S.follow && S.follow.number ? "-" + S.follow.number : ""}.html`;
if (!dl) { try { await navigator.clipboard.writeText(summaryText()); toast("Saving isn't available here, so the summary was copied instead."); } catch(e){ toast("Saving isn't available in this view."); } return; }
try { await dl.save({filename: name, data: reportHTMLDoc()}); } catch(e) { if (e && e.code !== "declined") toast("Couldn't save the report."); }
};
$("#reportCopy").onclick = async () => { try { await navigator.clipboard.writeText(summaryText()); toast("Summary copied."); } catch(e){ $("#tmText").value = summaryText(); $("#tmTitle").textContent = "Report summary"; $("#tmSub").textContent = "Copy isn't available here. Select the text and copy it."; $("#textModal").hidden = false; } };
/* ===================== how-it-works numbers ===================== */
async function renderHow(){
if (!S.source.sample || !S.shots) return;
let T; try { T = await (await fetch("media/workout_truth.json")).json(); } catch(e){ return; }
const rows = [], errs = []; let right = 0, auto = 0, wrong = 0, found = 0;
for (const g of T.shots) {
const q = S.shots.find(x => Math.abs((x.rimT || x.t) - g.rim) < 1.6 || (x.t <= g.rim && x.end >= g.rim - 0.3));
if (q) { found++; if (q.made === g.made) right++; }
let err = null;
if (q && q.court) { err = Math.hypot(q.court[0] - g.spot_ft[0], q.court[1] - g.spot_ft[1]); if (q.how === "traced" && q.mine === true) errs.push(err); }
const cred = !q ? "–" : q.coach === true ? "Coach said yes" : q.mine === true && q.sure ? (auto++, "Auto") : q.mine === false && q.sure ? (wrong++, "Wrong player") : "Asks coach";
rows.push(`<tr><td class="num">${fmt(g.release)}</td><td class="num">${Math.round(Math.hypot(g.spot_ft[0], g.spot_ft[1] - 5.17))} ft · ${g.pts}PT</td><td class="num">${q && q.court ? Math.round(q.dist) + " ft · " + q.pts + "PT" : "–"}</td><td class="num">${err != null ? err.toFixed(1) + " ft" : "–"}</td><td class="${q && q.made === g.made ? "yes" : "no"}">${g.made ? "Made" : "Missed"}${q && q.made === g.made ? " ✓" : " ✗"}</td><td class="${cred === "Auto" || cred === "Coach said yes" ? "yes" : cred === "Wrong player" ? "no" : "part"}">${cred}</td></tr>`);
}
errs.sort((a,b) => a-b);
$("#truthRows").innerHTML = rows.join("");
// form flaws planted in the sample, and what the coaching engine made of them
const FLAW = {flat:["arc","Flat arc","entry_angle_deg","° into the rim","° into the rim"], fade:["drift","Fading away","drift_ft"," ft drift"," ft drift"], moving:["drift","Shooting on the move","drift_ft"," ft drift"," ft drift"], low:["arc","Low, flat release","entry_angle_deg","° into the rim","° into the rim"], slow:["trigger","Slow trigger","set_time"," s catch to release"," s catch to release"]};
const fr = []; let caught = 0, planted = 0, falseF = 0, clean = 0;
for (const g of T.shots) {
const q = S.shots.find(x => Math.abs((x.rimT || x.t) - g.rim) < 1.6); const f = q && q.form || {};
if (!g.flaw) { if (g.kind === "jumper" && f.flags) { clean++; falseF += f.flags.length; if (f.flags.length) fr.push(`<tr><td class="num">${fmt(g.release)}</td><td>None (clean rep)</td><td>–</td><td class="num">${f.flags.map(k => FORM[k].label + " " + f[k]).join(", ")}</td><td class="part">False flag</td></tr>`); } continue; }
planted++; const [k, name, tk, unit, mu] = FLAW[g.flaw], v = f[k], hit = (f.flags || []).includes(k); if (hit) caught++;
fr.push(`<tr><td class="num">${fmt(g.release)}</td><td>${name}</td><td class="num">${g[tk]}${unit}</td><td class="num">${v != null ? v + mu : esc(f.unmeasured || "not measured")}</td><td class="${hit ? "yes" : v == null ? "part" : "no"}">${hit ? "Flagged ✓" : v == null ? "Not measured" : "Missed"}</td></tr>`);
}
const wk = (S.moments || []).find(m => m.key === "walk");
if (T.slow_walk) fr.push(`<tr><td class="num">${fmt(T.slow_walk[0])}–${fmt(T.slow_walk[1])}</td><td>Walking between reps</td><td class="num">1.3 m/s walk</td><td class="num">${wk ? fmt(wk.t) + "–" + fmt(wk.end) : "–"}</td><td class="${wk ? "yes" : "no"}">${wk ? "Flagged ✓" : "Missed"}</td></tr>`);
if ($("#formRows")) { $("#formRows").innerHTML = fr.join(""); $("#hForm").innerHTML = `${caught + (wk ? 1 : 0)}<small>of ${planted + (T.slow_walk ? 1 : 0)}</small>`; $("#hFalse").innerHTML = `${falseF}<small>in ${clean} clean reps</small>`; }
$("#hShots").innerHTML = `${right}<small>of ${T.attempts}</small>`;
$("#hLoc").innerHTML = `${errs.length ? errs[Math.floor(errs.length/2)].toFixed(1) : "–"}<small>ft</small>`;
$("#hWho").innerHTML = `${auto}<small>of ${T.attempts}</small>`;
const mv = movementStats();
if (mv) {
$("#hSpeed").innerHTML = `${(mv.top*0.6818).toFixed(1)}<small>mph</small>`; $("#hSpeedP").textContent = `top speed; the true value is ${T.top_speed_mph} mph.`;
$("#hPace").innerHTML = `${(mv.dist/Math.max(1, mv.tracked)).toFixed(1)}<small>ft/s</small>`; $("#hPaceP").textContent = `average pace while on camera; the true value is ${(T.distance_ft/T.duration).toFixed(1)} ft/s.`;
$("#hCover").innerHTML = `${Math.round(mv.tracked/T.duration*100)}<small>%</small>`;
}
}
/* ===================== routing + misc ===================== */
function route(){
const v = (location.hash || "#studio").slice(1);
const name = ["studio","plans","how","status"].includes(v) ? v : "studio";
["studio","plans","how","status"].forEach(n => $("#view-" + n).hidden = n !== name);
document.querySelectorAll(".nav a").forEach(a => a.setAttribute("aria-current", a.dataset.view === name ? "page" : "false"));
$(".mobilebar").style.display = name === "studio" ? "" : "none";
if (name === "studio") requestAnimationFrame(() => { drawStage(); drawTimeline(); });
}
window.addEventListener("hashchange", route);
window.addEventListener("resize", () => { drawStage(); drawTimeline(); });
document.addEventListener("keydown", e => {
if (e.target.matches("input,textarea")) return;
if (e.code === "Space") { e.preventDefault(); $("#playBtn").click(); }
else if (e.key === "ArrowRight") jump(1); else if (e.key === "ArrowLeft") jump(-1);
else if (e.key === "Escape") { stopReel(); endPick(); document.querySelectorAll(".modal").forEach(m => m.hidden = true); }
});
let toastT; function toast(msg){ const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove("show"), 3800); }
// test hook used to precompute the sample analysis
window.__clutch = {S, coachMoments, formSummary, shotForm, speedSeries, attributeShots, renderReport, buildCalib, movementStats, shootingStats, toCourt, setShotMode(m){ SHOT_MODE = m; }, setMadeRule(f){ MADE_RULE = f; }, analyzeShots, runShots, updateHoopBtn, analyze, buildTrack, rescore, applyFollow, signature, setFollow(f){ S.follow = f; applyFollow(); }};
route(); setHud(); initEngine(); loadSample(); requestAnimationFrame(loop);
cap("sample"); cap("downloads");
// sghadimi.com: on phones, bring the picture up under the header while marking the hoop, court or player
new MutationObserver(() => { const st = document.getElementById("stage"); if (!st.classList.contains("picking") || !matchMedia("(max-width:700px), (max-height:500px)").matches) return;
const top = document.querySelector(".top"); scrollTo({top: st.getBoundingClientRect().top + scrollY - (top ? top.offsetHeight : 0) - 8, behavior: "smooth"});
}).observe(document.getElementById("stage"), {attributes: true, attributeFilter: ["class"]});
coach.css (look and layout, phones included)430 lines
@font-face{font-family:"Barlow Condensed";font-weight:600;font-display:swap;src:url(fonts/BarlowCondensed-SemiBold.woff2) format("woff2")}
@font-face{font-family:"Barlow Condensed";font-weight:700;font-display:swap;src:url(fonts/BarlowCondensed-Bold.woff2) format("woff2")}
@font-face{font-family:"Barlow";font-weight:400;font-display:swap;src:url(fonts/Barlow-Regular.woff2) format("woff2")}
@font-face{font-family:"Barlow";font-weight:500;font-display:swap;src:url(fonts/Barlow-Medium.woff2) format("woff2")}
@font-face{font-family:"Barlow";font-weight:600;font-display:swap;src:url(fonts/Barlow-SemiBold.woff2) format("woff2")}
:root{
/* Layout idea: broadcast control room. Stage + timeline on the left, highlight rail on the right; stacks on phones. */
--bg:#0A0D13; --panel:#11151E; --panel-2:#161B27; --line:#222A3A; --ink:#EDF1F7; --muted:#8C96AA; --dim:#5D6679;
--accent:#FF5A1F; --accent-ink:#1A0B03; --track:#2EE6C5; --warn:#FFC24B; --good:#3DDC84; --bad:#FF5C6C;
--display:"Barlow Condensed","Arial Narrow","Roboto Condensed",system-ui,sans-serif;
--body:"Barlow","Segoe UI",system-ui,-apple-system,sans-serif;
--r:14px;
color-scheme:dark;
}
*{box-sizing:border-box}
[hidden]{display:none!important}
html,body{margin:0;min-height:100%}
html{background:#05070A}
body{background:var(--bg);color:var(--ink);font:15px/1.45 var(--body);-webkit-font-smoothing:antialiased}
button,input,select{font:inherit;color:inherit}
button{cursor:pointer}
:focus-visible{outline:2px solid var(--track);outline-offset:2px}
.num{font-variant-numeric:tabular-nums}
h1,h2,h3{font-family:var(--display);letter-spacing:.02em;text-wrap:balance;margin:0}
/* top bar */
.top{display:flex;align-items:center;gap:16px;padding:12px 20px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,#0E121A,#0A0D13);position:sticky;top:0;z-index:20}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink)}
.brand b{font-family:var(--display);font-size:24px;letter-spacing:.12em;font-weight:700}
.brand small{font-family:var(--display);font-size:13px;letter-spacing:.14em;color:var(--muted);text-transform:uppercase;padding-top:4px}
.nav{display:flex;gap:4px;margin-left:12px}
.nav a{font-family:var(--display);text-transform:uppercase;letter-spacing:.08em;font-size:15px;color:var(--muted);text-decoration:none;padding:6px 12px;border-radius:999px}
.nav a[aria-current="page"]{color:var(--ink);background:var(--panel-2);box-shadow:inset 0 0 0 1px var(--line)}
.spacer{flex:1}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:4px 10px;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;background:var(--good);box-shadow:0 0 0 3px rgba(61,220,132,.15)}
.dot.warn{background:var(--warn);box-shadow:0 0 0 3px rgba(255,194,75,.15)}
.dot.busy{background:var(--accent);animation:pulse 1s infinite}
@keyframes pulse{50%{opacity:.35}}
.main{padding:18px 20px 40px;max-width:1480px;margin:0 auto}
.view[hidden]{display:none}
/* studio grid */
.studio{display:grid;grid-template-columns:minmax(0,1fr) 384px;gap:18px;align-items:start}
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r)}
.setup{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:12px;margin-bottom:12px}
.source{display:flex;align-items:center;gap:10px;min-width:0;flex:1 1 260px}
.source .ic{width:38px;height:38px;border-radius:10px;background:var(--panel-2);display:grid;place-items:center;flex:none;border:1px solid var(--line)}
.source .meta{min-width:0}
.source .meta b{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.source .meta span{color:var(--muted);font-size:13px}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;border:1px solid var(--line);background:var(--panel-2);border-radius:10px;padding:9px 14px;font-weight:600;white-space:nowrap;transition:background .15s,border-color .15s,transform .05s}
.btn:hover{border-color:#34405a;background:#1b2231}
.btn:active{transform:translateY(1px)}
.btn.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}
.btn.primary:hover{background:#ff6f3a}
.btn.track{border-color:rgba(46,230,197,.45);color:var(--track)}
.btn.track.on{background:rgba(46,230,197,.12)}
.btn.ghost{background:transparent}
.btn.hoop{border-color:rgba(255,194,75,.45);color:var(--warn)}
.btn.hoop.on{background:rgba(255,194,75,.1)}
.btn.sm{padding:6px 10px;font-size:13.5px;border-radius:8px}
.btn[disabled]{opacity:.45;cursor:not-allowed}
.btn svg{flex:none}
.sports{display:flex;gap:6px;overflow-x:auto;padding:2px;scrollbar-width:none;margin-bottom:12px}
.sports::-webkit-scrollbar{display:none}
.chip{font-family:var(--display);text-transform:uppercase;letter-spacing:.06em;font-size:15px;padding:7px 13px;border-radius:999px;border:1px solid var(--line);background:var(--panel);color:var(--muted);white-space:nowrap}
.chip[aria-pressed="true"]{color:var(--accent-ink);background:var(--ink);border-color:var(--ink)}
/* stage */
.stagewrap{padding:0;overflow:hidden}
.stage{position:relative;aspect-ratio:16/9;background:#05070B;border-radius:var(--r) var(--r) 0 0;overflow:hidden}
.stage canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
.stage.picking canvas{cursor:crosshair}
.hud{position:absolute;right:12px;top:12px;display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end;max-width:60%;pointer-events:none}
.hud span{font-family:var(--display);text-transform:uppercase;letter-spacing:.08em;font-size:13px;padding:4px 9px;border-radius:6px;background:rgba(10,13,19,.62);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);border:1px solid rgba(255,255,255,.08)}
.hud .live{color:var(--accent)}
.hud .trk{color:var(--track)}
.drop{position:absolute;inset:0;display:grid;place-items:center;background:rgba(255,90,31,.12);border:2px dashed var(--accent);border-radius:var(--r) var(--r) 0 0;font-family:var(--display);font-size:24px;letter-spacing:.06em;text-transform:uppercase;opacity:0;pointer-events:none;transition:opacity .15s}
.stage.dragover .drop{opacity:1}
.pickbar{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);background:rgba(10,13,19,.85);border:1px solid rgba(46,230,197,.5);color:var(--ink);padding:8px 12px;border-radius:999px;font-size:14px;display:flex;gap:10px;align-items:center;white-space:nowrap;backdrop-filter:blur(6px)}
.pickbar[hidden]{display:none}
#hoopCtl{display:inline-flex;gap:8px;align-items:center}
#rimSize{width:110px;accent-color:var(--warn)}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
.stats{display:flex;gap:8px;margin-top:8px;align-items:center;font-size:13px;color:var(--muted);flex-wrap:wrap}
.stats b{font-family:var(--display);font-size:20px;color:var(--ink);letter-spacing:.02em}
.stats .mk{color:var(--good)}
.stats[hidden]{display:none}
/* analysis overlay */
.scan{position:absolute;inset:0;display:flex;align-items:flex-end;justify-content:flex-start;padding:16px;background:linear-gradient(0deg,rgba(5,7,11,.92) 0%,rgba(5,7,11,.35) 55%,rgba(5,7,11,0) 100%)}
.scan[hidden]{display:none}
.scan.rec{align-items:flex-start;background:none;padding:12px}
.scan.rec .scanbox{width:min(300px,100%);background:rgba(10,13,19,.82);border:1px solid var(--line);border-radius:12px;padding:10px 12px;backdrop-filter:blur(6px)}
.scan.rec .scanbox h3{font-size:16px}
.scanbox{width:min(440px,100%)}
.scanbox h3{font-size:22px;text-transform:uppercase;letter-spacing:.06em}
.steps{list-style:none;margin:10px 0 12px;padding:0;display:grid;gap:5px;font-size:14px}
.steps li{display:flex;gap:8px;align-items:center;color:var(--dim)}
.steps li.on{color:var(--ink)}
.steps li.done{color:var(--muted)}
.steps li i{width:16px;height:16px;border-radius:50%;border:2px solid currentColor;flex:none;display:grid;place-items:center;font-style:normal;font-size:10px}
.steps li.done i{background:var(--good);border-color:var(--good);color:#04130a}
.steps li.on i{border-color:var(--accent);border-top-color:transparent;animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.bar{height:6px;border-radius:99px;background:rgba(255,255,255,.1);overflow:hidden}
.bar b{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--accent),#ffb35c);transition:width .2s}
.scanstats{display:flex;gap:14px;margin-top:8px;font-size:13px;color:var(--muted)}
/* transport */
.transport{display:flex;align-items:center;gap:8px;padding:10px 12px;border-top:1px solid var(--line);flex-wrap:wrap}
.iconbtn{width:38px;height:38px;border-radius:10px;border:1px solid var(--line);background:var(--panel-2);display:grid;place-items:center}
.iconbtn:hover{border-color:#34405a}
.time{font-family:var(--display);font-size:17px;letter-spacing:.04em;color:var(--muted);min-width:96px}
.toggle{display:inline-flex;align-items:center;gap:7px;font-size:13.5px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:6px 11px;background:transparent}
.toggle[aria-pressed="true"]{color:var(--ink);border-color:#3a465f;background:var(--panel-2)}
.toggle .sw{width:24px;height:14px;border-radius:99px;background:#2a3245;position:relative;flex:none}
.toggle .sw::after{content:"";position:absolute;top:2px;left:2px;width:10px;height:10px;border-radius:50%;background:#7d879b;transition:left .15s,background .15s}
.toggle[aria-pressed="true"] .sw{background:rgba(46,230,197,.3)}
.toggle[aria-pressed="true"] .sw::after{left:12px;background:var(--track)}
/* timeline */
.tl{padding:10px 12px 12px;border-top:1px solid var(--line)}
.tlhead{display:flex;align-items:baseline;justify-content:space-between;gap:10px;margin-bottom:6px}
.tlhead h3{font-size:15px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted)}
.legend{display:flex;gap:12px;font-size:12px;color:var(--muted);flex-wrap:wrap}
.legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:5px;vertical-align:-1px}
#tl{width:100%;height:118px;display:block;cursor:pointer;touch-action:none}
/* rail */
.rail{display:flex;flex-direction:column;max-height:calc(100vh - 90px);position:sticky;top:76px}
.railhead{padding:14px 14px 10px;border-bottom:1px solid var(--line)}
.railhead h2{font-size:22px;text-transform:uppercase;letter-spacing:.06em}
.tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:10px}
.tile{background:var(--panel-2);border:1px solid var(--line);border-radius:10px;padding:8px 10px}
.tile b{display:block;font-family:var(--display);font-size:26px;line-height:1.05;letter-spacing:.02em}
.tile span{font-size:12px;color:var(--muted)}
.tile.trk b{color:var(--track)}
.filters{display:flex;gap:6px;margin-top:10px;flex-wrap:wrap}
.list{overflow:auto;padding:10px;display:grid;gap:10px;flex:1;min-height:120px}
.clip{display:grid;grid-template-columns:128px minmax(0,1fr);gap:10px;padding:8px;border-radius:12px;border:1px solid var(--line);background:var(--panel-2);position:relative;transition:border-color .15s,opacity .15s}
.clip:hover{border-color:#34405a}
.clip.active{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
.clip.off{opacity:.5}
.clip .th{position:relative;border-radius:8px;overflow:hidden;aspect-ratio:16/9;background:#05070B;border:0;padding:0}
.clip .th img{width:100%;height:100%;object-fit:cover;display:block}
.clip .th em{position:absolute;right:5px;bottom:5px;font-style:normal;font-family:var(--display);font-size:12.5px;background:rgba(0,0,0,.7);padding:1px 6px;border-radius:4px}
.clip .th .play{position:absolute;inset:0;display:grid;place-items:center;opacity:0;transition:opacity .15s;background:rgba(0,0,0,.3)}
.clip:hover .th .play{opacity:1}
.clip h4{margin:0;font-family:var(--display);font-size:18px;letter-spacing:.02em;line-height:1.1;text-transform:uppercase}
.clip .sub{font-size:12.5px;color:var(--muted);margin-top:2px}
.clip .cap{font-size:13.5px;margin-top:5px;color:#cfd6e3}
.clip .cap.flag{color:var(--warn)}
.tags{display:flex;gap:4px;flex-wrap:wrap;margin-top:6px}
.tag{font-size:11.5px;padding:2px 7px;border-radius:99px;background:#1f2636;color:#b9c2d3;border:1px solid #2a3346}
.tag.hot{color:#ffb08f;border-color:rgba(255,90,31,.45);background:rgba(255,90,31,.1)}
.tag.trk{color:var(--track);border-color:rgba(46,230,197,.4);background:rgba(46,230,197,.08)}
.tag.ai{color:#c9b8ff;border-color:rgba(160,130,255,.45);background:rgba(160,130,255,.1)}
.clipbar{display:flex;align-items:center;gap:6px;margin-top:7px}
.meter{flex:1;height:4px;border-radius:99px;background:#252d3e;overflow:hidden}
.meter b{display:block;height:100%;background:var(--accent)}
.mini{border:1px solid var(--line);background:transparent;border-radius:7px;padding:3px 7px;font-size:12px;color:var(--muted)}
.mini:hover{color:var(--ink);border-color:#3a465f}
.keep{position:absolute;top:8px;right:8px}
.keep input{position:absolute;opacity:0;width:0;height:0}
.keep span{display:block;width:30px;height:18px;border-radius:99px;background:#2a3245;position:relative;cursor:pointer}
.keep span::after{content:"";position:absolute;top:3px;left:3px;width:12px;height:12px;border-radius:50%;background:#7d879b;transition:left .15s}
.keep input:checked+span{background:rgba(255,90,31,.45)}
.keep input:checked+span::after{left:15px;background:var(--accent)}
.keep input:focus-visible+span{outline:2px solid var(--track);outline-offset:2px}
.shimmer{background:linear-gradient(90deg,#1c2232 0%,#2a3247 50%,#1c2232 100%);background-size:200% 100%;animation:sh 1.2s infinite;border-radius:6px;height:12px;margin-top:6px}
@keyframes sh{to{background-position:-200% 0}}
.railfoot{padding:12px;border-top:1px solid var(--line);display:grid;gap:8px}
.railfoot .row{display:flex;gap:8px}
.railfoot .row .btn{flex:1}
.empty{padding:24px 12px;text-align:center;color:var(--muted);font-size:14px}
/* dialogs */
.modal{position:fixed;inset:0;background:rgba(3,5,8,.72);display:grid;place-items:center;z-index:50;padding:16px}
.modal[hidden]{display:none}
.sheet{width:min(520px,100%);background:var(--panel);border:1px solid var(--line);border-radius:16px;padding:18px;box-shadow:0 30px 80px rgba(0,0,0,.5)}
.sheet h3{font-size:24px;text-transform:uppercase;letter-spacing:.05em}
.sheet p{color:var(--muted);margin:6px 0 14px}
.field{display:grid;gap:5px;margin-bottom:12px}
.field label{font-size:13px;color:var(--muted)}
.field input,.field textarea{background:var(--panel-2);border:1px solid var(--line);border-radius:10px;padding:10px 12px;color:var(--ink);width:100%}
.field textarea{min-height:120px;resize:vertical;line-height:1.5}
.sheet .acts{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}
.swatch{display:inline-block;width:14px;height:14px;border-radius:4px;border:1px solid rgba(255,255,255,.3);vertical-align:-2px;margin-right:6px}
.toast{position:fixed;left:50%;bottom:22px;transform:translateX(-50%) translateY(20px);background:#1b2231;border:1px solid #33405a;color:var(--ink);padding:10px 16px;border-radius:12px;font-size:14px;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;z-index:60;max-width:calc(100% - 32px)}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
/* plans + how */
.doc{max-width:1100px}
.doc h1{font-size:40px;text-transform:uppercase;letter-spacing:.03em;line-height:1}
.doc .lead{color:var(--muted);max-width:68ch;font-size:16.5px;margin:10px 0 22px}
.doc h2{font-size:24px;text-transform:uppercase;letter-spacing:.06em;margin:28px 0 10px}
.tablewrap{overflow-x:auto;border:1px solid var(--line);border-radius:var(--r);background:var(--panel)}
table{border-collapse:collapse;width:100%;min-width:860px;font-size:14px}
th,td{text-align:left;padding:11px 14px;border-bottom:1px solid var(--line);vertical-align:top}
th{font-family:var(--display);text-transform:uppercase;letter-spacing:.08em;font-size:13.5px;color:var(--muted);font-weight:600;background:var(--panel-2)}
tr:last-child td{border-bottom:0}
td a{color:var(--ink);text-decoration-color:#4a5672;text-underline-offset:3px}
tr.us td{background:rgba(255,90,31,.06)}
tr.us td:first-child{box-shadow:inset 3px 0 0 var(--accent)}
.price{font-family:var(--display);font-size:17px;letter-spacing:.02em;white-space:nowrap}
.yes{color:var(--good)} .no{color:var(--dim)} .part{color:var(--warn)}
.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.box{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:16px}
.box h3{font-size:19px;text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}
.box p,.box li{color:#c4ccda;font-size:14.5px}
.box ul{margin:6px 0 0;padding-left:18px}
.pipeline{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;counter-reset:s}
.pipeline .box{position:relative}
.pipeline .box::before{counter-increment:s;content:counter(s,decimal-leading-zero);font-family:var(--display);color:var(--accent);font-size:15px;letter-spacing:.1em;display:block;margin-bottom:4px}
.note{font-size:13px;color:var(--muted);margin-top:10px}
.big{font-family:var(--display);font-size:56px;line-height:1;color:var(--ink)}
.big small{font-size:22px;color:var(--muted);margin-left:6px}
@media (max-width:1100px){
.studio{grid-template-columns:minmax(0,1fr)}
.rail{position:static;max-height:none}
.pipeline{grid-template-columns:repeat(2,1fr)}
}
@media (max-width:700px){
.top{padding:10px 14px;gap:10px;flex-wrap:wrap}
.brand small{display:none}
.nav{margin-left:0;order:3;width:100%;overflow-x:auto}
.top .pill{display:none}
.main{padding:12px 12px 90px}
.grid3{grid-template-columns:1fr}
.pipeline{grid-template-columns:1fr}
.doc h1{font-size:32px}
.clip{grid-template-columns:112px minmax(0,1fr)}
.time{min-width:0;font-size:15px}
.mobilebar{display:flex}
.hud span{font-size:11px;padding:3px 7px}
.toggle{padding:5px 9px;font-size:12.5px}
.transport{gap:6px}
.setup .btn{flex:1 1 auto}
}
.hidv{position:fixed;left:0;top:0;width:2px;height:2px;opacity:0.01;pointer-events:none;z-index:-1}
.steps3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr)) auto;gap:8px;align-items:stretch}
.stepbtn{display:flex;gap:10px;align-items:center;text-align:left;border:1px solid var(--line);background:var(--panel-2);border-radius:10px;padding:8px 10px;min-width:0}
.stepbtn i{font-style:normal;font-family:var(--display);font-size:15px;width:24px;height:24px;border-radius:50%;display:grid;place-items:center;border:1.5px solid var(--dim);color:var(--muted);flex:none}
.stepbtn b{display:block;font-size:14.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.stepbtn small{display:block;font-size:12px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.stepbtn span{min-width:0}
.stepbtn.on{border-color:rgba(61,220,132,.45)}
.stepbtn.on i{background:var(--good);border-color:var(--good);color:#04130a}
.stepbtn:hover{border-color:#34405a}
.tabs{display:flex;gap:4px;padding:10px 10px 0;border-bottom:1px solid var(--line)}
.tabs button{flex:1;font-family:var(--display);text-transform:uppercase;letter-spacing:.08em;font-size:16px;padding:9px 10px;border:0;background:transparent;color:var(--muted);border-bottom:2px solid transparent}
.tabs button[aria-selected="true"]{color:var(--ink);border-bottom-color:var(--accent)}
.pane{display:flex;flex-direction:column;min-height:0;flex:1}
.pane[hidden]{display:none!important}
#report{display:block}
.rsec{padding:4px 2px 14px;border-bottom:1px solid var(--line);margin-bottom:12px}
.rsec:last-child{border-bottom:0}
.rsec h3{font-size:15px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted);margin:0 0 8px;display:flex;justify-content:space-between;align-items:baseline;gap:8px}
.rsec h3 small{font-family:var(--body);text-transform:none;letter-spacing:0;font-size:12px}
.who{display:flex;align-items:center;gap:10px;margin-bottom:10px}
.who .badge{font-family:var(--display);font-size:26px;width:48px;height:48px;border-radius:12px;display:grid;place-items:center;background:rgba(46,230,197,.12);color:var(--track);border:1px solid rgba(46,230,197,.35);flex:none}
.who b{font-family:var(--display);font-size:22px;letter-spacing:.03em;text-transform:uppercase;display:block;line-height:1.1}
.who span{font-size:13px;color:var(--muted)}
.tiles6{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.tile small{display:block;font-size:11.5px;color:var(--dim)}
canvas.court{width:100%;display:block;border-radius:10px;background:#0f1420;border:1px solid var(--line)}
.ztable{width:100%;min-width:0;font-size:13.5px;border-collapse:collapse}
.ztable td,.ztable th{padding:6px 4px;border-bottom:1px solid #1d2433;background:none}
.ztable th{font-size:12px}
.zbar{height:6px;border-radius:99px;background:#252d3e;overflow:hidden;min-width:60px}
.zbar b{display:block;height:100%;background:var(--good)}
.shotrow{display:grid;grid-template-columns:30px 54px minmax(0,1fr) auto;gap:8px;align-items:center;padding:7px 4px;border-bottom:1px solid #1d2433;font-size:13.5px}
.shotrow .res{font-family:var(--display);font-size:13px;padding:2px 7px;border-radius:5px;text-align:center}
.res.m{background:rgba(61,220,132,.15);color:var(--good)} .res.x{background:rgba(255,90,31,.12);color:#ff9b73}
.shotrow .note{grid-column:2 / -1;font-size:13px;color:#c9b8ff;margin-top:-2px}
.shotrow .q{display:flex;gap:4px;align-items:center;color:var(--warn);font-size:12.5px}
.read li{margin:4px 0;color:#d4dbe7;font-size:14px}
.read{margin:0;padding-left:18px}
.plan h4{font-family:var(--display);font-size:16px;text-transform:uppercase;letter-spacing:.05em;margin:10px 0 4px}
.plan p,.plan li{font-size:14px;color:#d4dbe7}
.plan ol,.plan ul{margin:4px 0;padding-left:18px}
.checklist li{margin:6px 0;font-size:14px;color:var(--muted)} .checklist li.ok{color:var(--ink)}
#courtStd{background:var(--panel-2);border:1px solid var(--line);border-radius:8px;padding:5px 6px;color:var(--ink);max-width:170px}
#courtCtl{display:inline-flex;gap:6px;align-items:center}
@media (max-width:700px){ .steps3{grid-template-columns:1fr 1fr} .steps3 .btn.primary{grid-column:1 / -1} .pickbar{flex-wrap:wrap;white-space:normal;justify-content:center;width:calc(100% - 20px);border-radius:14px} }
.mobilebar{display:none;position:fixed;left:0;right:0;bottom:0;padding:10px 12px calc(10px + env(safe-area-inset-bottom));gap:8px;background:rgba(10,13,19,.94);border-top:1px solid var(--line);z-index:30;backdrop-filter:blur(8px)}
.mobilebar .btn{flex:1}
/* ===== premium layer ===== */
:root{--bg:#06080C;--panel:#0F131B;--panel-2:#151A25;--line:rgba(255,255,255,.07);--line-2:rgba(255,255,255,.12);--glass:rgba(12,15,22,.66)}
body{background:
radial-gradient(1100px 520px at 78% -12%,rgba(255,90,31,.10),transparent 60%),
radial-gradient(900px 480px at -10% 8%,rgba(46,230,197,.06),transparent 60%),
linear-gradient(180deg,#07090E,#05070A) fixed;}
.top{background:rgba(7,9,14,.72);backdrop-filter:saturate(140%) blur(14px);-webkit-backdrop-filter:saturate(140%) blur(14px);border-bottom:1px solid var(--line)}
.card{background:linear-gradient(180deg,rgba(21,26,37,.86),rgba(13,17,25,.92));border:1px solid var(--line);box-shadow:inset 0 1px 0 rgba(255,255,255,.045),0 24px 60px -28px rgba(0,0,0,.75);border-radius:18px}
.stage{border-radius:18px 18px 0 0}
.btn{border-color:var(--line-2);background:rgba(255,255,255,.035)}
.btn:hover{background:rgba(255,255,255,.07);border-color:rgba(255,255,255,.18)}
.btn.primary{background:linear-gradient(180deg,#FF6A30,#F0500F);border-color:#FF6A30;box-shadow:0 8px 24px -10px rgba(255,90,31,.8),inset 0 1px 0 rgba(255,255,255,.25)}
.stepbtn{background:rgba(255,255,255,.03);border-color:var(--line-2)}
.tile{background:linear-gradient(180deg,rgba(255,255,255,.045),rgba(255,255,255,.015));border-color:var(--line)}
.lab{font-family:var(--display);text-transform:uppercase;letter-spacing:.14em;font-size:12.5px;color:var(--muted)}
/* hero */
.hero{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:22px;align-items:center;padding:18px 20px;margin-bottom:12px;position:relative;overflow:hidden}
.hero::before{content:"";position:absolute;inset:0;background:radial-gradient(500px 200px at 0% 0%,rgba(46,230,197,.10),transparent 70%),radial-gradient(500px 220px at 100% 100%,rgba(255,90,31,.10),transparent 70%);pointer-events:none}
.hero>*{position:relative}
.ring{width:92px;height:92px;position:relative;flex:none}
.ring svg{width:100%;height:100%;transform:rotate(-90deg)}
.ring b{position:absolute;inset:0;display:grid;place-items:center;font-family:var(--display);font-size:34px;letter-spacing:.01em;line-height:1}
.ring b small{display:block;font-size:10.5px;letter-spacing:.16em;color:var(--muted);margin-top:2px;text-align:center}
.hero h1{font-size:30px;text-transform:uppercase;letter-spacing:.04em;line-height:1}
.hero .meta{color:var(--muted);font-size:13.5px;margin-top:4px}
.prio{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}
.prio button{font:600 12.5px var(--body);border-radius:999px;padding:5px 11px;border:1px solid rgba(255,90,31,.4);background:rgba(255,90,31,.09);color:#ffb495}
.prio button:hover{background:rgba(255,90,31,.18)}
.prio button.okp{border-color:rgba(61,220,132,.4);background:rgba(61,220,132,.08);color:#8ff0b9}
.kpis{display:grid;grid-template-columns:repeat(4,minmax(84px,auto));gap:18px}
.kpi b{display:block;font-family:var(--display);font-size:30px;line-height:1;letter-spacing:.01em}
.kpi span{font-size:12px;color:var(--muted)}
.kpi em{font-style:normal;font-size:11.5px;display:block;margin-top:2px}
.kpi em.bad{color:#ff9b73} .kpi em.ok{color:var(--good)}
/* stage overlays */
.livehud{position:absolute;right:12px;bottom:12px;display:flex;gap:8px;pointer-events:none}
.livehud .g{background:var(--glass);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.09);border-radius:12px;padding:7px 11px;min-width:84px}
.livehud .g span{display:block;font-family:var(--display);text-transform:uppercase;letter-spacing:.14em;font-size:10.5px;color:var(--muted)}
.livehud .g b{font-family:var(--display);font-size:24px;line-height:1.05;letter-spacing:.01em}
.livehud .g b small{font-size:12px;color:var(--muted);margin-left:3px;letter-spacing:.06em}
.livehud .bar5{display:flex;gap:2px;margin-top:4px}
.livehud .bar5 i{flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.12)}
.coachcard{position:absolute;left:14px;bottom:14px;width:min(380px,calc(100% - 28px));background:linear-gradient(180deg,rgba(14,17,25,.86),rgba(9,11,17,.9));backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.1);border-radius:14px;padding:11px 13px 12px;box-shadow:0 18px 40px -16px rgba(0,0,0,.8);pointer-events:none;animation:cin .25s ease-out}
.coachcard::before{content:"";position:absolute;left:0;top:12px;bottom:12px;width:3px;border-radius:0 3px 3px 0;background:var(--accent)}
.coachcard.good::before{background:var(--good)}
@keyframes cin{from{opacity:0;transform:translateY(8px)}}
.coachcard .k{display:flex;justify-content:space-between;gap:8px;font-family:var(--display);text-transform:uppercase;letter-spacing:.14em;font-size:11.5px;color:#ff9b73}
.coachcard.good .k{color:var(--good)}
.coachcard h4{margin:2px 0 4px;font-family:var(--display);font-size:22px;text-transform:uppercase;letter-spacing:.03em;line-height:1.05}
.coachcard .mt{font-size:13px;color:#dfe5ef}
.coachcard p{margin:5px 0 0;font-size:13px;color:#aeb7c7}
/* timeline lanes */
.tl{padding:12px 14px 14px}
#tl{height:178px}
.legend i.lg{width:10px;height:10px;border-radius:3px}
.legend i.mk{background:#3DDC84;border-radius:50%}
.legend i.ms{background:transparent;border:1.5px solid #8C96AA;border-radius:50%}
.legend i.fx{background:#FF5A1F;transform:rotate(45deg) scale(.8);border-radius:2px}
.legend i.gd{background:#3DDC84;transform:rotate(45deg) scale(.8);border-radius:2px}
/* moments */
.moments{margin-top:14px;padding:16px 0 14px}
.mhead{display:flex;justify-content:space-between;align-items:flex-end;gap:14px;padding:0 16px 12px;flex-wrap:wrap}
.mhead h2{font-size:22px;text-transform:uppercase;letter-spacing:.06em}
.mhead p{margin:2px 0 0;color:var(--muted);font-size:13.5px}
.seg{display:inline-flex;padding:3px;border-radius:999px;background:rgba(255,255,255,.04);border:1px solid var(--line)}
.seg button{border:0;background:transparent;color:var(--muted);font:600 13px var(--body);padding:6px 12px;border-radius:999px}
.seg button[aria-pressed="true"]{background:rgba(255,255,255,.1);color:var(--ink)}
.mlist{display:flex;gap:12px;overflow-x:auto;padding:2px 16px 6px;scroll-snap-type:x mandatory;scrollbar-width:thin}
.mcard{flex:0 0 272px;scroll-snap-align:start;text-align:left;border:1px solid var(--line-2);border-radius:14px;padding:12px 13px 13px;background:linear-gradient(180deg,rgba(255,90,31,.07),rgba(255,255,255,.015) 40%);display:flex;flex-direction:column;gap:7px;transition:border-color .15s,transform .15s}
.mcard.good{background:linear-gradient(180deg,rgba(61,220,132,.07),rgba(255,255,255,.015) 40%)}
.mcard:hover{border-color:rgba(255,255,255,.24);transform:translateY(-2px)}
.mcard.now{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
.mcard.good.now{border-color:var(--good);box-shadow:0 0 0 1px var(--good)}
.mtop{display:flex;justify-content:space-between;align-items:center;gap:8px}
.tc{font-family:var(--display);font-size:15px;letter-spacing:.06em;padding:2px 8px;border-radius:6px;background:rgba(255,255,255,.08);display:inline-flex;align-items:center;gap:5px}
.mkind{font-family:var(--display);text-transform:uppercase;letter-spacing:.14em;font-size:11.5px;color:#ff9b73}
.mcard.good .mkind{color:var(--good)}
.mcard h4{margin:0;font-family:var(--display);font-size:21px;text-transform:uppercase;letter-spacing:.03em;line-height:1.05}
.gauge{display:grid;gap:4px}
.gauge .gl{display:flex;justify-content:space-between;font-size:12px;color:var(--muted)}
.gauge .gl b{color:var(--ink);font-weight:600}
.gtrack{position:relative;height:6px;border-radius:99px;background:rgba(255,255,255,.08)}
.gtrack .ok{position:absolute;top:0;bottom:0;border-radius:99px;background:rgba(61,220,132,.28)}
.gtrack .v{position:absolute;top:50%;width:12px;height:12px;border-radius:50%;transform:translate(-50%,-50%);background:var(--accent);box-shadow:0 0 0 3px rgba(255,90,31,.25)}
.gtrack .v.ok2{background:var(--good);box-shadow:0 0 0 3px rgba(61,220,132,.25)}
.mfix{margin:0;font-size:13.5px;color:#d7dde8;line-height:1.4}
.drill{margin-top:auto;font-size:12.5px;color:var(--muted);border-top:1px solid var(--line);padding-top:8px}
.drill b{color:var(--ink);font-weight:600}
.drill em{font-style:normal;color:var(--warn);white-space:nowrap}
/* scorecard in the rail */
.sc{display:grid;gap:10px}
.srow{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 10px;align-items:center}
.srow .nm{font-size:13.5px}
.srow .val{font-family:var(--display);font-size:17px;letter-spacing:.02em;text-align:right}
.srow .gtrack{grid-column:1 / -1}
.srow small{grid-column:1 / -1;font-size:11.5px;color:var(--dim);margin-top:-1px}
.plist{list-style:none;margin:0;padding:0;display:grid;gap:8px;counter-reset:p}
.plist li{display:grid;grid-template-columns:26px minmax(0,1fr);gap:8px;padding:10px;border-radius:12px;background:rgba(255,255,255,.03);border:1px solid var(--line)}
.plist li::before{counter-increment:p;content:counter(p);font-family:var(--display);font-size:16px;width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:rgba(255,90,31,.14);color:#ff9b73}
.plist b{font-family:var(--display);text-transform:uppercase;letter-spacing:.04em;font-size:16px}
.plist p{margin:2px 0 6px;font-size:13px;color:#c9d0dc}
.plist .acts{display:flex;gap:6px;flex-wrap:wrap}
@media (max-width:1100px){ .hero{grid-template-columns:auto minmax(0,1fr)} .kpis{grid-column:1 / -1;grid-template-columns:repeat(4,1fr)} }
@media (max-width:700px){ .hero{padding:14px;gap:14px} .ring{width:74px;height:74px} .ring b{font-size:27px} .hero h1{font-size:23px} .kpis{gap:10px} .kpi b{font-size:23px} #tl{height:160px} .mcard{flex-basis:248px} .coachcard{left:8px;bottom:8px;padding:6px 10px 7px;width:auto;max-width:calc(100% - 16px);border-radius:10px} .coachcard h4{font-size:16px;margin:0} .coachcard .k{font-size:10px} .coachcard p,.coachcard .mt{display:none} .livehud{display:none} }
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
/* sghadimi.com */
.home{font:600 13px var(--body,inherit);color:#8C96AA;text-decoration:none;white-space:nowrap;margin-left:4px}
.home:hover{color:#FF5A1F}
@media (max-width:360px){.home{font-size:12px}}
#formBtn,#planBtn,#verifyBtn,#claudeBtn,#recapBtn{display:none!important}
.railfoot .row:empty{display:none}
.nav a{white-space:nowrap}
@media (max-width:900px){.top .pill{display:none}}
@media (max-width:700px){.mobilebar{display:flex}.pipeline{grid-template-columns:1fr!important}}
@media (max-width:700px), (max-height:500px){
.stage.picking .pickbar{position:fixed;left:10px;right:10px;bottom:calc(10px + env(safe-area-inset-bottom));transform:none;width:auto;z-index:40}
body:has(.stage.picking) .mobilebar{display:none}}
.tour-card{position:fixed;left:50%;bottom:calc(16px + env(safe-area-inset-bottom));transform:translateX(-50%);width:min(420px,calc(100% - 20px));z-index:60;background:#141a26;border:1px solid rgba(255,90,31,.55);border-radius:16px;padding:14px 16px;box-shadow:0 18px 50px rgba(0,0,0,.55)}
.tour-card[hidden]{display:none}
.tour-top{display:flex;justify-content:space-between;align-items:center;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:#8C96AA}
.tour-x{background:none;border:0;color:#8C96AA;font-size:22px;line-height:1;cursor:pointer;padding:2px 6px}
.tour-t{display:block;font-family:var(--display);text-transform:uppercase;letter-spacing:.04em;font-size:20px;margin:4px 0 2px}
.tour-p{margin:0 0 12px;font-size:14px;color:#c9d0dc;line-height:1.45}
.tour-acts{display:flex;gap:8px;justify-content:flex-end}
.tour-lit{outline:3px solid #FF5A1F;outline-offset:4px;border-radius:var(--r)}
body.touring .mobilebar{display:none}
body.touring .main{padding-bottom:220px}
@media (max-height:500px) and (min-width:600px){.tour-card{left:auto;right:10px;top:70px;bottom:auto;transform:none;width:300px}body.touring .main{padding-right:320px;padding-bottom:40px}}
tour.js (the 'Show me how' tour)68 lines
/* Clutch Coach: "Show me how", a 30-second guided tour of the sample report (sghadimi.com).
Five steps. Each lights one part of the page, scrolls it into view and says what it is for; step 4 plays a
coaching moment so the correction is seen on the video. Start: the "Show me how" button, or ?tour=1. */
(() => {
const $ = s => document.querySelector(s);
const STEPS = [
{ el: '#hero', title: 'A finished report', text: 'This is the sample workout, already analysed: player #8’s form score, field goals, entry angle, drift and top speed. Everything here came from one phone video.' },
{ el: '.steps3', title: 'Three taps for your own video', text: 'Upload a video, then tap the rim, the four corners of the paint and your player. Build report does the rest on this device; nothing is uploaded.' },
{ el: '.tl', title: 'The whole session on one line', text: 'Every shot, sprint and form fix is on the timeline. Tap anywhere on it to jump the video there.' },
{ el: '.stagewrap', title: 'Coaching moments', text: 'Each coaching moment is a time-tagged fix with a drill and reps. The first one is playing now, with the correction drawn on the video. The full list sits under the timeline.', play: true },
{ el: '.rail', title: 'Take it with you', text: 'Download the report as a page for the player, copy a short summary, or switch to Clips to play and export the reel.' },
];
let i = -1, card = null, lit = null;
const visible = el => el && !el.hidden && el.offsetParent !== null;
function build() {
card = document.createElement('div');
card.className = 'tour-card'; card.setAttribute('role', 'dialog'); card.setAttribute('aria-live', 'polite'); card.setAttribute('aria-label', 'Guided tour');
card.innerHTML = '<div class="tour-top"><span class="tour-n"></span><button type="button" class="tour-x" aria-label="Close the tour">×</button></div>'
+ '<b class="tour-t"></b><p class="tour-p"></p>'
+ '<div class="tour-acts"><button type="button" class="btn ghost sm tour-back">Back</button><button type="button" class="btn primary sm tour-next">Next</button></div>';
document.body.appendChild(card);
card.querySelector('.tour-x').onclick = stop;
card.querySelector('.tour-back').onclick = () => go(i - 1);
card.querySelector('.tour-next').onclick = () => (i >= STEPS.length - 1 ? stop() : go(i + 1));
}
function go(n) {
if (n < 0) return;
i = n;
if (location.hash && location.hash !== '#studio') location.hash = '#studio';
const s = STEPS[i];
if (s.play) { const m = document.querySelector('#moments .mcard'); if (m) m.click(); }
const el = $(s.el);
if (lit) lit.classList.remove('tour-lit');
lit = visible(el) ? el : null;
if (lit) {
lit.classList.add('tour-lit');
const top = $('.top');
const go = () => scrollTo({ top: Math.max(0, lit.getBoundingClientRect().top + scrollY - (top ? top.offsetHeight : 0) - 10), behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
if (s.play) setTimeout(go, 350); else go();
}
card.querySelector('.tour-n').textContent = `${i + 1} of ${STEPS.length}`;
card.querySelector('.tour-t').textContent = s.title;
card.querySelector('.tour-p').textContent = s.text;
card.querySelector('.tour-back').disabled = i === 0;
card.querySelector('.tour-next').textContent = i === STEPS.length - 1 ? 'Done' : 'Next';
card.querySelector('.tour-next').focus({ preventScroll: true });
}
function start() {
if (!card) build();
card.hidden = false; document.body.classList.add('touring');
go(0);
}
function stop() {
if (lit) lit.classList.remove('tour-lit'); lit = null;
if (card) card.hidden = true;
document.body.classList.remove('touring');
const v = $('#vid'); if (v && !v.paused) { const b = $('#playBtn'); if (b) b.click(); }
const t = $('#tourBtn'); if (t) t.focus();
}
document.addEventListener('keydown', e => { if (e.key === 'Escape' && card && !card.hidden) stop(); });
const btn = $('#tourBtn');
if (btn) btn.addEventListener('click', start);
// ?tour=1 starts it once the sample report is on screen
if (/[?&]tour=1/.test(location.search)) {
const t0 = Date.now(), wait = setInterval(() => { if (visible($('#hero')) || Date.now() - t0 > 15000) { clearInterval(wait); start(); } }, 300);
}
})();
kit/site.py (makes this site copy from the Claude preview page)137 lines
"""Build the sghadimi.com copy of Clutch Coach from the Claude preview page.
The preview is one index.html with its CSS and JS inline. The site's security policy allows no inline scripts, so this
splits them into coach.css and coach.js, and makes the changes the public site needs:
- a title, description, icon and a "Free tools" link back to the site;
- <main> becomes <div class="main" role="main"> so the site does not add its own footer inside the app;
- saving uses a plain browser download (the preview saves through claude.ai);
- the Claude-only buttons (form feedback, improvement plan, tracking check, captions, message) are hidden,
because they only work inside claude.ai; the on-device coaching moments stay;
- the internal hand-off notes on the Status tab (next steps for the owner, the QC prompt with private links) are left out;
- a line naming the vision model's license.
Usage: python3 kit/site.py <preview index.html> <out dir>
The other files (fonts/, audio/, media/, vendor/, model/) are copied unchanged from the preview."""
import sys, os, re
src, out = sys.argv[1], sys.argv[2]
s = open(src, encoding='utf8').read()
def sub1(pat, rep, text, flags=0):
new, n = re.subn(pat, rep, text, count=1, flags=flags)
assert n == 1, 'not found: ' + pat[:60]
return new
def rep1(old, new, text):
assert text.count(old) == 1, 'expected once: ' + old[:60]
return text.replace(old, new)
# The preview may already carry the tour (tour.js beside it) and the phone fixes; take them out here so they are added once.
s = s.replace('\n<script src="tour.js" defer></script>', '')
s = s.replace('\n <button class="btn ghost" id="tourBtn" type="button">Show me how</button>', '')
head_end = s.index('</head>')
css = re.search(r'<style>(.*?)</style>', s[:head_end], re.S).group(1)
s = s[:head_end].replace('<style>' + css + '</style>', '<link rel="stylesheet" href="./coach.css">') + s[head_end:]
js_start = s.index('<script>', s.index('</main>'))
js_end = s.rindex('</script>')
js = s[js_start + len('<script>'):js_end]
js = re.sub(r'\n// on phones, bring the picture up under the header.*?attributeFilter: \["class"\]\}\);\n', '', js, flags=re.S)
css = css.split('\n.nav a{white-space:nowrap}\n')[0] + '\n' if '\n.nav a{white-space:nowrap}\n' in css else css
s = s[:js_start] + '<script src="./coach.js" defer></script>' + s[js_end + len('</script>'):]
# --- head ---
s = rep1('<title>Clutch Coach</title>',
'<title>Clutch Coach: free basketball shooting and form stats from a phone video</title>\n'
'<meta name="description" content="Free and on your device: upload a basketball video, tap the rim, the paint and one player, and get makes and misses, a shot chart, movement and time-tagged form fixes with drills. Nothing is uploaded.">\n'
'<link rel="icon" href="/favicon.svg">', s)
# --- layout: no site footer inside the app ---
s = rep1('<main>', '<div class="main" role="main">', s)
s = rep1('</main>', '</div>', s)
css = sub1(r'(^|\n)main\{', r'\1.main{', css)
css = sub1(r'\n(\s+)main\{', r'\n\1.main{', css)
# --- back to the site ---
s = rep1('<b>CLUTCH</b><small>Coach</small>\n </a>', '<b>CLUTCH</b><small>Coach</small>\n </a>\n <a class="home" href="/all/">Free tools ›</a>', s)
css += ('\n/* sghadimi.com */\n'
'.home{font:600 13px var(--body,inherit);color:#8C96AA;text-decoration:none;white-space:nowrap;margin-left:4px}\n'
'.home:hover{color:#FF5A1F}\n'
'@media (max-width:360px){.home{font-size:12px}}\n'
'#formBtn,#planBtn,#verifyBtn,#claudeBtn,#recapBtn{display:none!important}\n'
'.railfoot .row:empty{display:none}\n')
# --- Claude-only features: say so once, where the pipeline is explained ---
s = rep1('Claude is only asked when you press Form feedback, Improvement plan or the tracking check, and then it gets still frames of your player.',
'On this site nothing leaves your device. The version that runs inside Claude also writes form feedback from still frames and a week-long improvement plan; the master prompt on the project page rebuilds it.', s)
s = rep1('The jersey number lets Claude double-check the tracking and who took each shot.', 'The jersey number and name label the report.', s)
s = rep1('<button class="btn primary" id="mReel" type="button">Improvement plan</button>', '<button class="btn primary" id="mReel" type="button">Play clips</button>', s)
js = rep1('$("#mReel").onclick = () => $("#planBtn").click();', '$("#mReel").onclick = () => $("#reelBtn").click();', js)
# --- Status tab: public part only ---
i = s.index('<h2>Next steps, in order</h2>')
j = s.index('Copy QC prompt</button>') + len('Copy QC prompt</button>')
s = s[:i] + s[j:]
s = sub1(r'<h1>Status, QC and next steps</h1>\s*<p class="lead">.*?</p>',
'<h1>Status and checks</h1>\n <p class="lead">Where Clutch Coach stands: what has been checked and how, what is still unchecked, and the known bugs.</p>', s, re.S)
js = sub1(r'\$\("#qcCopy"\)\.onclick = .*?\n', '', js)
# --- Compare tab: what this copy does, and the Superstat price as its linked store page shows it ---
s = rep1("for one player; Claude form review and a week's practice plan</td>",
"for one player; time-tagged form fixes with drills (the Claude version adds a form review and a week's practice plan)</td>", s)
s = rep1('<td class="price">€10/game · €179.99/season</td>', '<td class="price">A$15–20/game · A$229.99/season (AU App Store)</td>', s)
# --- layout fixes for the site's four test sizes ---
css += ('.nav a{white-space:nowrap}\n'
'@media (max-width:900px){.top .pill{display:none}}\n'
'@media (max-width:700px){.mobilebar{display:flex}.pipeline{grid-template-columns:1fr!important}}\n'
'@media (max-width:700px), (max-height:500px){\n'
' .stage.picking .pickbar{position:fixed;left:10px;right:10px;bottom:calc(10px + env(safe-area-inset-bottom));transform:none;width:auto;z-index:40}\n'
' body:has(.stage.picking) .mobilebar{display:none}}\n')
# On a phone the tap-to-mark controls covered most of the picture; they now sit at the bottom of the screen and the
# picture scrolls up under the header so the whole frame stays tappable.
js += ('\n// sghadimi.com: on phones, bring the picture up under the header while marking the hoop, court or player\n'
'new MutationObserver(() => { const st = document.getElementById("stage"); if (!st.classList.contains("picking") || !matchMedia("(max-width:700px), (max-height:500px)").matches) return;\n'
' const top = document.querySelector(".top"); scrollTo({top: st.getBoundingClientRect().top + scrollY - (top ? top.offsetHeight : 0) - 8, behavior: "smooth"});\n'
'}).observe(document.getElementById("stage"), {attributes: true, attributeFilter: ["class"]});\n')
# --- "Show me how": a 30-second guided tour of the sample report (tour.js, kept beside this script) ---
s = rep1('<button class="btn" id="sampleBtn" type="button" hidden>Use sample workout</button>',
'<button class="btn" id="sampleBtn" type="button" hidden>Use sample workout</button>\n <button class="btn ghost" id="tourBtn" type="button">Show me how</button>', s)
s = rep1('<script src="./coach.js" defer></script>', '<script src="./coach.js" defer></script>\n<script src="./tour.js" defer></script>', s)
css += ('.tour-card{position:fixed;left:50%;bottom:calc(16px + env(safe-area-inset-bottom));transform:translateX(-50%);width:min(420px,calc(100% - 20px));z-index:60;'
'background:#141a26;border:1px solid rgba(255,90,31,.55);border-radius:16px;padding:14px 16px;box-shadow:0 18px 50px rgba(0,0,0,.55)}\n'
'.tour-card[hidden]{display:none}\n'
'.tour-top{display:flex;justify-content:space-between;align-items:center;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:#8C96AA}\n'
'.tour-x{background:none;border:0;color:#8C96AA;font-size:22px;line-height:1;cursor:pointer;padding:2px 6px}\n'
'.tour-t{display:block;font-family:var(--display);text-transform:uppercase;letter-spacing:.04em;font-size:20px;margin:4px 0 2px}\n'
'.tour-p{margin:0 0 12px;font-size:14px;color:#c9d0dc;line-height:1.45}\n'
'.tour-acts{display:flex;gap:8px;justify-content:flex-end}\n'
'.tour-lit{outline:3px solid #FF5A1F;outline-offset:4px;border-radius:var(--r)}\n'
'body.touring .mobilebar{display:none}\n'
'body.touring .main{padding-bottom:220px}\n'
'@media (max-height:500px) and (min-width:600px){.tour-card{left:auto;right:10px;top:70px;bottom:auto;transform:none;width:300px}body.touring .main{padding-right:320px;padding-bottom:40px}}\n')
# --- license line ---
s = rep1('<h2>Known limits</h2>', '<h2>Known limits</h2>\n <p class="note">Vision model: YOLOv8n by Ultralytics, AGPL-3.0, run in the browser with onnxruntime-web (MIT). The page\'s full code is on its project page.</p>', s)
# --- saving: a plain download on the site; Claude is not available here ---
js = sub1(r'function cap\(name\)\{.*?\n\}\n',
'function cap(name){\n'
' // sghadimi.com: no claude.ai capabilities. Saving is a plain browser download; Claude features are hidden.\n'
' if (name !== "downloads") return Promise.resolve(null);\n'
' return Promise.resolve({ save: async ({filename, data}) => {\n'
' const blob = data instanceof Blob ? data : new Blob([data], {type: /\\.csv$/.test(filename) ? "text/csv" : /\\.html$/.test(filename) ? "text/html" : "application/octet-stream"});\n'
' const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = filename; document.body.appendChild(a); a.click();\n'
' setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 4000);\n'
' return {status: "saved"};\n'
' } });\n'
'}\n', js, re.S)
assert '<script>' not in s and '<style>' not in s[:s.index('</head>')]
for f in ('index.html', 'coach.css', 'coach.js'):
pass
os.makedirs(out, exist_ok=True)
open(os.path.join(out, 'index.html'), 'w', encoding='utf8').write(s)
open(os.path.join(out, 'coach.css'), 'w', encoding='utf8').write(css)
open(os.path.join(out, 'coach.js'), 'w', encoding='utf8').write(js)
print('built', out)
Need a tool like this, built for your own work?
Take this one free. If you need your own version, with your lists, your rules and your name on it, I build it and hand it over. Fixed price agreed up front, and the first call is free.