#pragma once
static const char CONTROL_PAGE[] PROGMEM = R"ROBOTPAGE(<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#041116">
<title>Robot / Operation edition v3.12</title>
<style>
:root{color-scheme:dark;--cyan:#58f5e3;--light:#e1fffa;--muted:#8baab0;--line:#24494f;--red:#ff8b88;font:16px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;background:#041116;color:#dbedef}
*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at 50% 35%,#16434b66,transparent 55%),linear-gradient(#18343b30 1px,transparent 1px),linear-gradient(90deg,#18343b30 1px,transparent 1px);background-size:auto,40px 40px,40px 40px;min-width:320px}button,input,select{font:inherit}button,select{color:inherit;border:1px solid #376069;background:#102b32;border-radius:4px;padding:10px 13px;min-height:44px}button{cursor:pointer;touch-action:manipulation}button:hover:not(:disabled){border-color:var(--cyan);background:#21454a}button:disabled{opacity:.4;cursor:not-allowed}button:focus-visible,input:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--cyan);outline-offset:4px}input{accent-color:var(--cyan)}h1,h2,h3,p{margin:0}h2{font-size:16px;font-weight:550}small{font-size:12px}label{font-size:14px;color:var(--muted)}input[type=url]{color:var(--light);background:#051318;border:1px solid var(--line);padding:10px;width:100%;min-width:0;border-radius:4px}input[type=range]{width:100%;cursor:pointer}input[type=checkbox]{width:17px;height:17px;vertical-align:middle}.mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.muted{color:var(--muted)}.shell{max-width:1460px;margin:auto;padding:25px 28px}.mast{display:flex;justify-content:space-between;align-items:center;padding-bottom:19px;border-bottom:1px solid var(--line)}.brand{font-size:22px;letter-spacing:.18em;color:var(--light)}.brand span{font-size:12px;color:var(--cyan);margin-left:18px;letter-spacing:.12em}.tag{border:1px solid var(--line);padding:6px 12px;color:var(--muted);font-size:13px}.tag.online{border-color:var(--cyan);color:var(--cyan)}.title{display:flex;justify-content:space-between;align-items:end;padding:25px 0 19px}.title h1{font-size:27px;font-weight:500;letter-spacing:.06em}.title p{color:var(--muted);font-size:13px}.frame{position:relative;border:1px solid #3a797b;box-shadow:0 0 0 4px #071c22,0 0 24px #55f5e312;padding:19px;background:#041116b0}.frame:before,.frame:after{content:"";position:absolute;width:65px;height:20px;border:2px solid var(--cyan);pointer-events:none}.frame:before{left:-1px;top:-1px;border-bottom:0;border-right:0}.frame:after{right:-1px;bottom:-1px;border-top:0;border-left:0}.grid{display:grid;grid-template-columns:240px minmax(320px,1fr) 320px;gap:18px}.column{display:grid;gap:16px;align-content:start;min-width:0}.panel{border:1px solid var(--line);padding:17px;background:linear-gradient(135deg,#11303855,#06181ddd);min-width:0}.heading{display:flex;justify-content:space-between;gap:12px;align-items:center;margin-bottom:16px}.index{color:#5b888d;font:12px ui-monospace,monospace}.connection{display:grid;gap:9px}.primary{background:#17463f;border-color:#55c4b2;color:var(--light)}.status-list{display:grid;gap:13px;font-size:14px}.status-list div{display:flex;justify-content:space-between;gap:10px}.status-list strong{font-size:13px;color:var(--muted);font-weight:500}.status-list strong.on{color:var(--cyan)}.camera-color{display:flex;align-items:center;gap:12px;padding:18px 0}.swatch{width:32px;height:32px;background:#31454a;border:1px solid #90c7c7;border-radius:50%;box-shadow:0 0 18px #4ae4d211}.camera-color b{font-size:20px;font-weight:400}.toggle{display:flex;gap:9px;align-items:center;line-height:1.6}.hint{font-size:12px;color:var(--muted);line-height:1.8;margin-top:12px}.wheel-panel{min-width:0;text-align:center;padding:14px 8px}.section-label{font-size:12px;color:var(--cyan);letter-spacing:.15em}.wheel-stage{position:relative;max-width:475px;margin:14px auto 0;aspect-ratio:1}.rings{position:absolute;inset:0;width:100%;height:100%;color:var(--cyan);pointer-events:none}.wheel{position:absolute;inset:12%;touch-action:none;cursor:grab;user-select:none;outline-offset:8px}.wheel:active{cursor:grabbing}.wheel svg{width:100%;height:100%;filter:drop-shadow(0 7px 12px #0009);transform:rotate(var(--rotation,0deg));transition:transform .06s linear}.wheel-read{position:absolute;bottom:5%;left:0;right:0;pointer-events:none}.wheel-read b{font-size:32px;font-weight:400;color:var(--light)}.wheel-read span{display:block;font-size:12px;color:var(--muted)}.steering-bar{max-width:350px;margin:10px auto}.steering-bar .ticks{display:flex;justify-content:space-between;font:12px ui-monospace,monospace;color:var(--muted)}.steer-tools{display:flex;gap:10px;justify-content:center;align-items:center;margin-top:15px;flex-wrap:wrap}.steer-tools select{font-size:14px;max-width:100%}.angles{display:flex;justify-content:center;gap:30px;font-size:13px;margin-top:17px;color:var(--muted)}.angles b{font:19px ui-monospace,monospace;color:var(--cyan);margin-left:8px}.pedals{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:20px}.pedals button{min-height:65px;touch-action:none;user-select:none;font-size:17px}.pedals button.active{background:#3c776c;box-shadow:0 0 20px #58f5e333;border-color:var(--cyan)}.pedals small{display:block;color:var(--muted)}.stop{background:#41262c;color:#ffd6d4;border:1px solid #ae6669;min-height:55px;width:100%;font-size:17px;letter-spacing:.08em;margin-top:12px}.stop:hover:not(:disabled){background:#653139;border-color:var(--red)}.servo-row{padding:12px 0;border-top:1px solid var(--line)}.servo-row:first-of-type{border-top:0}.servo-row label{display:flex;justify-content:space-between;gap:8px}.servo-row output{font-family:ui-monospace,monospace;color:var(--light)}.servo-row input{margin:12px 0 7px}.servo-action{display:flex;justify-content:space-between;gap:8px;align-items:center}.servo-action small{color:var(--muted)}.servo-action button{min-height:34px;padding:5px 10px;font-size:12px}.faces{display:grid;grid-template-columns:repeat(3,1fr);gap:7px}.faces button{padding:9px 4px;font-size:13px}.face-current{font-size:13px;color:var(--muted);margin-bottom:13px}.face-current b{color:var(--cyan);font-weight:500}.message{border-left:2px solid var(--cyan);margin-top:18px;padding:10px 15px;font-size:14px;background:#0b2428;color:#b1d9d6;overflow-wrap:anywhere}.message.error{border-color:var(--red);color:#ffc2ba}.settings{border:1px solid var(--line);margin-top:19px;background:#081a1f}.settings summary{cursor:pointer;padding:15px 18px;color:var(--muted);font-size:14px}.settings-inner{padding:0 18px 18px}.cal-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:24px}.cal-grid h3{font-size:14px;margin-bottom:12px}.cal-grid .toggle{margin:10px 0}.cal-grid button{font-size:13px}.mini-buttons{display:grid;grid-template-columns:1fr 1fr;gap:7px}.footer{display:flex;justify-content:space-between;gap:20px;padding:20px 0;font-size:12px;color:#86a2a7}.motion{font-size:13px;color:var(--cyan);padding-top:10px;min-height:32px}kbd{font:12px monospace;border:1px solid var(--line);padding:1px 5px}.log{max-height:110px;overflow:auto;list-style:none;padding:0;margin:0;color:var(--muted);font-size:12px}.log li{padding:4px 0;overflow-wrap:anywhere}.log time{color:#5fa59f;margin-right:8px}
@media(max-width:1100px){.grid{grid-template-columns:210px minmax(290px,1fr)}.right{grid-column:1/-1;grid-template-columns:1fr 1fr}.shell{padding:20px}.wheel-stage{max-width:410px}.cal-grid{grid-template-columns:1fr 1fr}.cal-grid>div:last-child{grid-column:1/-1}}
@media(max-width:660px){.shell{padding:17px 12px}.brand span{display:none}.title{align-items:start;gap:12px}.title p{max-width:120px;font-size:12px}.title h1{font-size:23px}.frame{padding:12px}.grid{display:flex;flex-direction:column}.left{order:0}.wheel-panel{order:1}.right{order:2;display:grid;grid-template-columns:1fr}.left{grid-template-columns:1fr}.left .panel:nth-child(3){order:3}.wheel-stage{max-width:400px;width:100%;margin-top:0}.cal-grid{grid-template-columns:1fr}.cal-grid>div:last-child{grid-column:auto}.angles{gap:18px}.footer{font-size:11px}.title{padding:18px 0}.panel{padding:15px}}
@media(prefers-reduced-motion:reduce){.wheel svg{transition:none}}
.robot-model{width:100%;text-align:left}.robot-model svg{width:100%;display:block;touch-action:none}.model-values,.model-wheels{display:flex;justify-content:space-between;gap:10px}.model-values{font-size:12px;color:var(--cyan,#60efda)}.model-wheels>div{flex:1}.model-wheels button{width:100%;margin:5px 0;font-size:12px;padding:10px}.model-wheels>div>div{display:flex;gap:4px}#model-arm:focus,#model-shade:focus{outline:none;filter:drop-shadow(0 0 5px #6fffe6)}.wheel-panel details{margin:10px 0;width:100%}.wheel-panel summary{cursor:pointer;color:#93d9d2;font-size:12px}.robot-model .section-label{margin-bottom:0}</style>
</head>
<body><main class="shell">
<header class="mast"><div class="brand">Robot<span>CONTROL SYSTEM / V3</span></div><div class="tag" id="badge">Disconnected / preview only</div></header>
<div class="title"><h1>Robot / Operation edition</h1><p>DRIVE / ARM / EXPRESSIONS / VISION</p></div>
<div class="frame"><div class="grid">
<aside class="column left">
<section class="panel"><div class="heading"><h2>Connection</h2><span class="index">01 / LINK</span></div><div class="connection"><label for="address">C6 address</label><input id="address" type="url" value="http://192.168.4.1" spellcheck="false"><button id="connect" class="primary">Connect</button></div><p class="hint">Wi-Fi: Robot<br>Password: 12345678</p></section>
<section class="panel"><div class="heading"><h2>System status</h2><span class="index">02 / STATUS</span></div><div class="status-list"><div><span>Servo controller</span><strong id="pca">Not connected</strong></div><div><span>Expression display</span><strong id="screen">Not connected</strong></div><div><span>Camera</span><strong id="camera">Not connected</strong></div><div><span>Motor timeout guard</span><strong id="watchdog">Not connected</strong></div></div></section>
<section class="panel"><div class="heading"><h2>Camera recognition</h2><span class="index">03 / VISION</span></div><div class="camera-color"><span class="swatch" id="swatch"></span><b id="color-name">Waiting for data</b></div><label class="toggle"><input id="follow" type="checkbox" disabled>Camera-driven expressions and arm</label><p class="hint">Receives MaixCAM color results, not video. Disable camera actions for manual control.</p></section>
</aside>
<section class="wheel-panel" aria-label="Driving">
<div class="robot-model">
<div class="section-label mono">ROBOT / DRAG JOINTS / LIVE TARGETS</div>
<svg id="robot-sketch" viewBox="0 0 600 440" aria-label="Interactive robot side view">
<defs><linearGradient id="shell" x2="0" y2="1"><stop stop-color="#d8f3ed"/><stop offset="1" stop-color="#47767a"/></linearGradient></defs>
<path d="M40 390H560M60 410H540" stroke="#21565a" stroke-dasharray="4 8"/>
<path d="M110 310Q180 290 240 292L265 273H332L355 292Q420 290 490 310L495 330H430L410 360H190L170 330H105Z" fill="url(#shell)" stroke="#70f9e5" stroke-width="2"/>
<path d="M180 355H430V380H180Z" fill="#112e35" stroke="#59aaab"/>
<g fill="#122930" stroke="#62e4d6" stroke-width="3"><circle id="sketch-back" cx="150" cy="365" r="45"/><circle id="sketch-next" cx="450" cy="365" r="45"/></g>
<g fill="#b0d9d1" stroke="#41787a" stroke-width="5" pointer-events="none"><circle cx="150" cy="365" r="29"/><circle cx="450" cy="365" r="29"/></g>
<path d="M270 288V264L300 247L317 280" fill="url(#shell)" stroke="#66dccc" stroke-width="2"/>
<g id="model-arm" role="slider" tabindex="0" aria-label="Arm CH1. Drag or use up/down keys for live control" aria-valuemin="40" aria-valuemax="110" aria-valuenow="90" style="cursor:grab;touch-action:none">
<path d="M286 265L345 154Q357 142 375 158L316 279Z" fill="url(#shell)" stroke="#7bffee" stroke-width="2"/>
<circle cx="300" cy="270" r="18" fill="#0c343b" stroke="#67ffe6" stroke-width="3"/><circle cx="300" cy="270" r="6" fill="#67ffe6"/>
<g id="model-shade" role="slider" tabindex="0" aria-label="Lampshade CH2. Drag or use up/down keys for live control" aria-valuemin="60" aria-valuemax="95" aria-valuenow="90" style="cursor:grab;touch-action:none">
<path d="M363 168L320 125L310 137L350 180Z" fill="url(#shell)" stroke="#7bffee"/>
<path d="M322 124Q280 80 251 51Q220 72 204 121Q241 146 309 141Z" fill="url(#shell)" stroke="#9affef" stroke-width="2"/>
<path d="M248 53L270 24L302 46L280 76Z" fill="#153a42" stroke="#86e5de"/><circle cx="274" cy="43" r="7" fill="#050d17" stroke="#66e7de"/>
<circle cx="360" cy="165" r="16" fill="#0b3038" stroke="#67ffe6" stroke-width="3"/><circle cx="360" cy="165" r="5" fill="#67ffe6"/>
</g></g>
<g fill="#a7ebe2" font-size="14"><text x="40" y="50">Target preview / not measured</text><text x="56" y="432">Rear axle CH5</text><text x="420" y="432">Front axle CH3 →</text></g>
</svg>
<div class="model-values"><span>Arm <b id="model-arm-value">90°</b> · 40–110°</span><span>Lampshade <b id="model-shade-value">90°</b> · 60–95°</span></div>
<p class="hint">Drag joints to send targets. Hardware follows slowly; this is not measured feedback. Use the wheel and drive buttons below.</p>
</div>
<div class="section-label">Steering wheel / Driving</div>
<div class="wheel-stage">
<svg class="rings" viewBox="0 0 500 500" aria-hidden="true"><circle cx="250" cy="250" r="231" fill="none" stroke="currentColor" stroke-width="1" opacity=".3"/><circle cx="250" cy="250" r="215" fill="none" stroke="currentColor" stroke-width="5" stroke-dasharray="180 40 100 40 300 40 60 40 100 450" transform="rotate(-105 250 250)"/><circle cx="250" cy="250" r="198" fill="none" stroke="#a9f9ed" stroke-width="1" stroke-dasharray="2 12" opacity=".55"/><path d="M250 10v22M10 250h22M468 250h22M250 468v22" stroke="currentColor" stroke-width="2"/><path d="M110 94L124 108M376 108L390 94" stroke="#c8fffa" stroke-width="4"/></svg>
<div id="wheel" class="wheel" role="slider" tabindex="0" aria-label="Steering wheel" aria-valuemin="-120" aria-valuemax="120" aria-valuenow="0">
<svg id="rotor" viewBox="0 0 400 400" aria-hidden="true"><defs><linearGradient id="grip" x2="0" y2="1"><stop stop-color="#31474e"/><stop offset=".5" stop-color="#15282f"/><stop offset="1" stop-color="#071418"/></linearGradient></defs><path d="M53 102 Q23 113 25 156 L40 257 Q46 297 82 306 L147 321 Q200 333 253 321 L318 306 Q354 297 360 257 L375 156 Q377 113 347 102 L319 111 L321 189 Q317 209 296 213 L259 207 L240 185 L160 185 L141 207 L104 213 Q83 209 79 189 L81 111 Z" fill="url(#grip)" stroke="#5f8a8e" stroke-width="3"/><path d="M60 121 Q48 145 55 195L64 248 Q67 266 85 271M340 121 Q352 145 345 195L336 248 Q333 266 315 271" fill="none" stroke="#62ecdc" stroke-width="3"/><path d="M141 207L115 258L158 282L242 282L285 258L259 207Z" fill="#14282e" stroke="#35585d" stroke-width="2"/><path d="M181 200L200 192L219 200M184 207L200 201L216 207" fill="none" stroke="#84eee1" stroke-width="2"/><text x="200" y="246" text-anchor="middle" fill="#d5fffa" font-size="16" letter-spacing="4">ROBOT</text><path d="M192 290h16" stroke="#72f9e7" stroke-width="3"/><circle cx="106" cy="236" r="10" fill="#0c1a20" stroke="#47676c"/><circle cx="294" cy="236" r="10" fill="#0c1a20" stroke="#47676c"/></svg></div>
<div class="wheel-read"><b class="mono" id="wheel-angle">0°</b><span>Drag the wheel or use the slider</span></div></div>
<div class="steering-bar"><input id="steer" type="range" min="-120" max="120" value="0" aria-label="Steering input"><div class="ticks"><span>−120°</span><span>0°</span><span>+120°</span></div></div>
<div class="steer-tools"><select id="mode" aria-label="Steering mode"><option value="counter">Counter steering</option><option value="parallel">Parallel steering</option><option value="front">Front steering only</option></select><button id="center">Center steering</button></div>
<div class="angles"><span>Front CH3 <b id="front-angle">90°</b></span><span>Rear CH5 <b id="rear-angle">90°</b></span></div>
<p class="hint">Targets are commands, not measured angles. Use the Test edition for installation calibration.</p>
<div class="pedals"><button id="forward" data-live disabled>Forward<small>Hold to drive</small></button><button id="reverse" data-live disabled>Reverse<small>Hold to drive</small></button></div><button id="stop" class="stop">■ Stop all</button><p id="motion" class="motion">Motor status unavailable</p>
</section>
<aside class="column right">
<section class="panel"><div class="heading"><h2>Arm and lampshade</h2><span class="index">04 / MOTION</span></div>
<div class="servo-row"><label for="servo0">Base rotation · CH0 <output id="out0">90°</output></label><input id="servo0" type="range" min="10" max="170" value="90"><div class="servo-action"><small>10° — 170°</small></div></div>
<div class="servo-row"><label for="servo1">Arm rotation · CH1 <output id="out1">90°</output></label><input id="servo1" type="range" min="40" max="110" value="90"><div class="servo-action"><small>40° — 110°</small></div></div>
<div class="servo-row"><label for="servo2">Lampshade rotation · CH2 <output id="out2">90°</output></label><input id="servo2" type="range" min="60" max="95" value="90"><div class="servo-action"><small>60° — 95°</small></div></div>
<button id="home" data-live disabled style="width:100%;margin-top:10px">Center arm and lampshade</button></section>
<section class="panel"><div class="heading"><h2>Display expressions</h2><span class="index">05 / FACE</span></div><p class="face-current">Last command：<b id="face-current">Not connected</b></p><div class="faces"><button data-face="neutral" data-live disabled>Neutral</button><button data-face="happy" data-live disabled>Happy</button><button data-face="sad" data-live disabled>Sad</button><button data-face="angry" data-live disabled>Angry</button><button data-face="surprise" data-live disabled>Surprised</button><button data-face="curious" data-live disabled>Curious</button><button data-face="look-left" data-live disabled>Look left</button><button data-face="look-right" data-live disabled>Look right</button><button data-face="sleep" data-live disabled>Sleep</button></div><p class="hint">Selecting an expression disables camera actions.</p></section>
</aside></div>
<div id="message" class="message" role="status" aria-live="polite">Connect to the existing robot Wi-Fi, then select Connect. Requires compatible C6 firmware.</div>
</div>
<footer class="footer"><span>Robot / Operation edition v3.12</span><span><kbd>←</kbd> <kbd>→</kbd> Steering wheel · <kbd>Space</kbd> Stop</span></footer>
</main>
<script>
(() => {
'use strict';
const $=id=>document.getElementById(id), moves=[...document.querySelectorAll('[data-live]')];
let base='', online=false, state=null, session=0, op=0, busy=false, moving=null, motorPromise=null, heart=null, polling=null, pollBusy=false, steeringTimer=null, steerBusy=false, steeringPending=false, rotation=0, drag=null;
let dirty=new Set(), lastStateRequest=0, appliedResponse=0;
const names={neutral:'Neutral',happy:'Happy',sad:'Sad',angry:'Angry',surprise:'Surprised',curious:'Curious','look-left':'Look left','look-right':'Look right',sleep:'Sleep'};
const colors={red:['Red','#ff6262'],green:['Green','#59df9b'],blue:['Blue','#66aaff'],purple:['Purple','#bd8aff'],yellow:['Yellow','#ffdb68'],none:['No color detected','#31454a']};
$('address').value=location.protocol==='http:'?location.origin:'http://192.168.4.1';
function msg(s,error=false){$('message').textContent=s;$('message').classList.toggle('error',error);}
function log(s){}
function motorsOn(){return state && (state.motorA!==0||state.motorB!==0);}
function setStatus(id,on,text){$(id).textContent=online?(on?text:'Offline'):'Not connected';$(id).classList.toggle('on',online&&on);}
function render(){
 $('badge').textContent=online?'Connected / C6':'Disconnected / preview only';$('badge').classList.toggle('online',online);
 moves.forEach(b=>{b.disabled=!online||busy;});
 document.querySelectorAll('[data-face]').forEach(b=>{b.disabled=!online||busy||!state?.screenFound;});
 $('home').disabled=!online||busy||!state?.pcaFound;
 $('follow').disabled=!online||busy;
 $('forward').disabled=$('reverse').disabled=!online||busy||!state?.watchdogReady||(!moving&&(motorsOn()||state?.cooldownMs>0));
 $('connect').disabled=busy||!!moving||!!motorPromise;
 $('address').disabled=busy||!!moving||!!motorPromise;
 setStatus('pca',state?.pcaFound,'Connected');setStatus('screen',state?.screenFound,'I2C acknowledged');setStatus('camera',state?.cameraOnline,'Valid data received');setStatus('watchdog',state?.watchdogReady,'Enabled');
 $('motion').textContent=!online?'Motor status unavailable':motorsOn()?'Motor output active / release to stop':'Motor output stopped';
 if(!online)return;
 $('follow').checked=state.cameraFollow;
 const color=colors[state.cameraColor]||colors.none;
 $('color-name').textContent=state.cameraOnline?color[0]:'Waiting for camera data';$('swatch').style.background=state.cameraOnline?color[1]:'#31454a';
 $('face-current').textContent=names[state.face]||state.face;
 state.servos.slice(0,3).forEach((s,i)=>{if(!dirty.has(i)){$('servo'+i).value=s.target;$('out'+i).textContent=s.target+'°';}});
 preview(rotation);paintModel();
}
function accept(data,requestId){
 if(data.firmware!=='robot-v3.11'||JSON.stringify(data.pins)!=='[0,1,2,21]'||!Array.isArray(data.servos)||data.servos.length!==5)throw Error('Firmware mismatch. Upload the compatible C6 firmware first.');
 if(requestId<appliedResponse)return;
 appliedResponse=requestId;state=data;render();
}
async function request(path,fields=null,forceBase=base){
 const id=++lastStateRequest, controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),fields===null?4000:1000),token=session;
 try{const res=await fetch(forceBase+path,{method:fields===null?'GET':'POST',body:fields===null?undefined:new URLSearchParams(fields),cache:'no-store',signal:controller.signal});const data=await res.json();if(!res.ok||data.ok===false)throw Error(data.error||'Command failed');if(token===session)accept(data.state||data,id);return data.state||data;}
 finally{clearTimeout(timeout);}
}

async function readState(){
 const generation=op, currentSession=session;
 try{return await request('/api/state');}
 catch(e){
  if(!(e.name==='AbortError'||e instanceof TypeError)||moving||motorPromise||motorsOn()||generation!==op||currentSession!==session)throw e;
  clearLive();online=false;clearTimeout(steeringTimer);steeringPending=false;render();
  msg('Status timeout. Controls locked; checking again...',true);
  const result=await request('/api/state');
  if(generation!==op||currentSession!==session)throw Error('Connection state changed. Reconnect.');
  online=true;render();msg('Status restored. Previous motion will not resume automatically.');return result;
 }
}

function failed(e){clearLive();online=false;clearTimeout(heart);clearTimeout(polling);moving=null;op++;document.querySelectorAll('.active').forEach(b=>b.classList.remove('active'));msg('Connection/command failed: '+(e.name==='AbortError'?'Request timed out':e.message)+'. Please reconnect.',true);clearTimeout(steeringTimer);steeringPending=false;render();log('Communication failed: '+e.message);}
async function connect(){if(busy||moving||motorPromise)return;try{const u=new URL($('address').value);if(u.protocol!=='http:'||u.username||u.password||u.pathname!=='/'||u.search||u.hash)throw Error('Enter the device address beginning with http://.');base=u.origin;clearLive();session++;op++;online=false;state=null;appliedResponse=0;busy=true;render();await readState();online=true;msg('Connected. Verify installation direction before holding a drive button.');log('Connection established');poll();}catch(e){failed(e);}finally{busy=false;render();}}
function poll(){clearTimeout(polling);if(!online)return;const token=session;polling=setTimeout(async()=>{if(!online||token!==session)return;if(!moving&&!liveBusy&&!livePending.size&&!steerBusy&&!motorPromise&&!busy&&!pollBusy){pollBusy=true;try{await readState();}catch(e){failed(e);}finally{pollBusy=false;}}if(online&&token===session)poll();},1000);}
async function command(path,fields,label){if(!online||busy)return false;busy=true;render();try{await request(path,{...fields,controlEpoch:state.controlEpoch});msg(label);log(label);return true;}catch(e){failed(e);return false;}finally{busy=false;render();}}
function preview(value){rotation=Math.max(-120,Math.min(120,Math.round(value)));$('steer').value=rotation;$('rotor').style.setProperty('--rotation',rotation+'deg');$('wheel-angle').textContent=(rotation>0?'+':'')+rotation+'°';$('wheel').setAttribute('aria-valuenow',rotation);const front=90+Math.trunc(rotation/4)*(Boolean(state?.invert?.[2])?-1:1),rear=90+($('mode').value==='front'?0:Math.trunc(rotation/4)*($('mode').value==='counter'?-1:1)*(Boolean(state?.invert?.[3]??1)?-1:1));$('front-angle').textContent=front+'°';$('rear-angle').textContent=rear+'°';}
function steer(value){preview(value);if(!online)return;livePending.delete(3);livePending.delete(4);steeringPending=true;if(!steeringTimer&&!steerBusy)steeringTimer=setTimeout(flushSteer,100);}
async function flushSteer(){steeringTimer=null;if(!online||steerBusy||!steeringPending)return;if(busy){steeringTimer=setTimeout(flushSteer,100);return;}if(!state.pcaFound){msg('Servo controller offline. Steering preview only.',true);return;}steeringPending=false;steerBusy=true;try{await request('/api/steer',{angle:rotation,mode:$('mode').value,controlEpoch:state.controlEpoch});}catch(e){failed(e);}finally{steerBusy=false;if(steeringPending)steeringTimer=setTimeout(flushSteer,100);}}
async function stop(all=true){
 clearLive();op++;moving=null;clearTimeout(heart);clearTimeout(steeringTimer);steeringPending=false;document.querySelectorAll('.active').forEach(b=>b.classList.remove('active'));
 if(!base){msg('Not connected to the robot.');return;}
 const pending=motorPromise;busy=true;render();let error=null;
 try{try{await request(all?'/api/stop':'/api/drive-stop',{});}catch(e){error=e;}
 if(pending){await pending.catch(()=>{});try{await request(all?'/api/stop':'/api/drive-stop',{});error=null;}catch(e){error=e;}}
 if(error)throw error;online=true;msg(all?'Motors stopped, servo targets frozen and camera actions disabled.':'Motor stop confirmed by C6.');log(all?'Stop all':'Motors stopped');poll();
 }catch(e){failed(e);msg('Stop not confirmed. Check device power and connection.',true);}finally{busy=false;render();}
}
async function heartbeat(token){
 if(!online||!moving||token!==op)return;
 const direction=moving,epoch=state.epoch;
 const work=request('/api/drive',{direction,epoch});motorPromise=work;
 try{await work;if(token===op&&moving)heart=setTimeout(()=>heartbeat(token),180);}
 catch(e){failed(e);stop(false);}
 finally{if(motorPromise===work)motorPromise=null;render();}
}
function start(direction){if(!online||busy||moving||motorPromise||motorsOn()||!state.watchdogReady||state.cooldownMs>0)return;moving=direction;const token=++op;$(direction).classList.add('active');heartbeat(token);}
function release(){if(moving)stop(false);}
['forward','reverse'].forEach(id=>{const b=$(id);b.addEventListener('pointerdown',e=>{if(e.button!==0)return;e.preventDefault();b.setPointerCapture(e.pointerId);start(id);});b.addEventListener('pointerup',release);b.addEventListener('pointercancel',release);b.addEventListener('lostpointercapture',release);b.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.repeat){e.preventDefault();start(id);}});b.addEventListener('keyup',e=>{if(e.key==='Enter')release();});});
$('connect').onclick=connect;$('stop').onclick=()=>stop(true);$('center').onclick=()=>steer(0);$('steer').oninput=e=>steer(e.target.value);$('mode').onchange=()=>steer(rotation);
$('wheel').addEventListener('pointerdown',e=>{if(e.button!==0)return;drag={x:e.clientX,angle:rotation,id:e.pointerId};$('wheel').setPointerCapture(e.pointerId);});
$('wheel').addEventListener('pointermove',e=>{if(drag&&e.pointerId===drag.id)steer(drag.angle+(e.clientX-drag.x)*.75);});
['pointerup','pointercancel','lostpointercapture'].forEach(evt=>$('wheel').addEventListener(evt,()=>{drag=null;}));
document.addEventListener('keydown',e=>{if(['INPUT','SELECT','TEXTAREA'].includes(document.activeElement.tagName))return;if(e.code==='Space'){e.preventDefault();if(!e.repeat)stop(true);}else if(e.key==='ArrowLeft'||e.key==='ArrowRight'){e.preventDefault();steer(rotation+(e.key==='ArrowLeft'?-8:8));}else if(e.key==='Home'){e.preventDefault();steer(0);}});
for(let i=0;i<3;i++)$('servo'+i).oninput=()=>{dirty.add(i);$('out'+i).textContent=$('servo'+i).value+'°';queueLive(i);};
$('home').onclick=async()=>{clearLive();const generation=op;for(let id=0;id<3;id++){if(generation!==op||!await command('/api/servo',{id,angle:90},'Center arm and lampshade'))break;dirty.delete(id);}};
document.querySelectorAll('[data-face]').forEach(b=>b.onclick=()=>command('/api/face',{face:b.dataset.face},'Expression sent: '+b.textContent));
$('follow').onchange=()=>command('/api/camera',{enabled:$('follow').checked?1:0},'Camera actions updated');
window.addEventListener('blur',()=>{clearLive();release();});
document.addEventListener('visibilitychange',()=>{if(document.hidden){clearLive();if(moving||motorPromise||motorsOn())stop(false);}});
window.addEventListener('pagehide',()=>{if(base&&(moving||motorPromise||motorsOn()))fetch(base+'/api/drive-stop',{method:'POST',body:new URLSearchParams(),keepalive:true}).catch(()=>{});});
let modelDrag=null;
let livePending=new Map(),liveTimer=null,liveBusy=false;
function clearLive(){clearTimeout(liveTimer);liveTimer=null;livePending.clear();modelDrag=null;}
function queueLive(id){
 if(!online||busy||moving||!state?.pcaFound)return;
 if(state.cameraFollow){msg('Disable camera actions before manual servo control.',true);return;}
 livePending.set(id,{angle:Number($('servo'+id).value),generation:op,session});
 if(!liveTimer&&!liveBusy)liveTimer=setTimeout(flushLive,100);
}
async function flushLive(){
 liveTimer=null;if(liveBusy)return;
 if(!online||busy||moving||state?.cameraFollow){livePending.clear();return;}
 if(!livePending.size)return;
 const [id,target]=livePending.entries().next().value;livePending.delete(id);
 if(target.generation!==op||target.session!==session)return;
 liveBusy=true;
 try{await request('/api/servo',{id,angle:target.angle,controlEpoch:state.controlEpoch});
 if(target.generation===op&&target.session===session&&!livePending.has(id)&&Number($('servo'+id).value)===target.angle)dirty.delete(id);
 }catch(e){failed(e);}finally{liveBusy=false;if(livePending.size&&online&&!liveTimer)liveTimer=setTimeout(flushLive,100);}
}

function paintModel(){
 const a=Number($('servo1').value),b=Number($('servo2').value);
 $('model-arm').setAttribute('transform','rotate('+(90-a)+' 300 270)');
 $('model-shade').setAttribute('transform','rotate('+(90-b)+' 360 165)');
 $('model-arm').setAttribute('aria-valuenow',a);$('model-shade').setAttribute('aria-valuenow',b);
 $('model-arm-value').textContent=a+'°';$('model-shade-value').textContent=b+'°';
}
function modelValue(id,value){const input=$('servo'+id);input.value=Math.max(Number(input.min),Math.min(Number(input.max),Math.round(value)));dirty.add(id);$('out'+id).textContent=input.value+'°';paintModel();queueLive(id);}
function sendModel(id,generation){if(generation===op)queueLive(id);}
['model-arm','model-shade'].forEach((name,index)=>{
 const el=$(name),id=index+1;
 el.addEventListener('pointerdown',e=>{if(e.button!==0)return;e.preventDefault();e.stopPropagation();if(busy||moving||state?.cameraFollow){msg('Stop driving and disable camera actions before moving joints.',true);return;}modelDrag={id,y:e.clientY,value:Number($('servo'+id).value),generation:op,pointer:e.pointerId};el.setPointerCapture(e.pointerId);});
 el.addEventListener('pointermove',e=>{if(modelDrag?.id===id&&modelDrag.pointer===e.pointerId&&modelDrag.generation===op)modelValue(id,modelDrag.value+(modelDrag.y-e.clientY)*.35);});
 el.addEventListener('pointerup',e=>{if(modelDrag?.id!==id)return;e.stopPropagation();const d=modelDrag;modelDrag=null;sendModel(id,d.generation);});
 ['pointercancel','lostpointercapture'].forEach(evt=>el.addEventListener(evt,()=>{if(modelDrag?.id===id)modelDrag=null;}));
 el.addEventListener('keydown',e=>{if(!['ArrowUp','ArrowDown'].includes(e.key))return;e.preventDefault();e.stopPropagation();if(busy||moving||state?.cameraFollow)return;modelValue(id,Number($('servo'+id).value)+(e.key==='ArrowUp'?1:-1));});
 el.addEventListener('keyup',e=>{if(['ArrowUp','ArrowDown'].includes(e.key)){e.stopPropagation();sendModel(id,op);}});
});
for(let i=1;i<=2;i++)$('servo'+i).addEventListener('input',paintModel);

preview(0);render();paintModel();
})();
</script></body></html>
)ROBOTPAGE";
