<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Plane Tracker Wi-Fi Setup</title>
<style>
:root{
  --navy:#00205b;--blue:#005587;--cyan:#0085ad;--steel:#6399ae;
  --mist:#b7c9d3;--silver:#d6d9dc;--white:#fff;--black:#000;
}
*{box-sizing:border-box;letter-spacing:0}
body{
  margin:0;min-height:100vh;background:var(--navy);color:var(--white);
  font-family:Consolas,"Courier New",monospace;display:flex;flex-direction:column;
}
header{
  background:var(--cyan);color:var(--white);padding:18px 20px;
  border-bottom:1px solid var(--mist);
}
h1{font-size:24px;margin:0;font-weight:600}
header p{margin:5px 0 0;color:var(--silver);font-size:14px}
main{width:min(680px,100%);margin:0 auto;padding:22px 16px 40px}
.step{color:var(--mist);font-size:13px;text-transform:uppercase;margin-bottom:8px}
.panel{background:var(--blue);border:1px solid var(--steel);padding:16px;margin-bottom:14px}
.status{min-height:24px;color:var(--mist);font-size:14px;line-height:1.45}
.networks{display:flex;flex-direction:column;gap:7px;margin-top:12px}
.network{
  width:100%;display:flex;align-items:center;gap:12px;text-align:left;
  background:rgba(0,32,91,.7);color:var(--white);border:1px solid var(--steel);
  padding:12px;cursor:pointer;font:inherit;
}
.network:hover,.network.selected{background:var(--cyan);border-color:var(--white)}
.network-name{font-size:17px;flex:1;overflow-wrap:anywhere}
.network-meta{font-size:12px;color:var(--mist);white-space:nowrap}
.network.selected .network-meta{color:var(--white)}
label{display:block;color:var(--mist);font-size:12px;text-transform:uppercase;margin:12px 0 5px}
input{
  width:100%;background:var(--black);color:var(--white);border:1px solid var(--steel);
  padding:11px;font:inherit;font-size:16px;
}
input:focus{outline:2px solid var(--mist);outline-offset:1px}
.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px}
button.action{
  border:1px solid var(--mist);background:var(--cyan);color:var(--white);
  padding:10px 15px;font:inherit;cursor:pointer;
}
button.secondary{background:transparent}
button:disabled{opacity:.45;cursor:not-allowed}
.hidden{display:none}
.notice{font-size:13px;line-height:1.5;color:var(--silver);margin-top:12px}
.success{border-color:var(--white);background:var(--cyan)}
.error{color:var(--white);border-color:var(--silver)}
@media(max-width:520px){
  main{padding:14px 10px 28px}
  .panel{padding:13px}
  .network{align-items:flex-start}
  .network-meta{white-space:normal;text-align:right}
}
</style>
</head>
<body>
<header>
  <h1>Plane Tracker Wi-Fi Setup</h1>
  <p>Connect this display to your home network</p>
</header>
<main>
  <section class="panel">
    <div class="step">1. Choose a network</div>
    <div id="scan-status" class="status">Scanning for Wi-Fi networks...</div>
    <div id="networks" class="networks"></div>
    <div class="actions">
      <button class="action secondary" type="button" id="scan-button">Scan Again</button>
    </div>
  </section>

  <section class="panel">
    <div class="step">2. Enter Wi-Fi details</div>
    <label for="ssid">Network name</label>
    <input id="ssid" autocomplete="off" placeholder="Select above or enter a hidden network">
    <label for="password">Wi-Fi password</label>
    <input id="password" type="password" autocomplete="current-password" placeholder="Leave blank for an open network">
    <div class="actions">
      <button class="action" type="button" id="connect-button">Connect</button>
    </div>
    <div class="notice">
      The setup network will disappear while the tracker connects. Rejoin your home Wi-Fi on this device, then open
      <strong>http://tracker-fr24-unof.local:8080</strong>. If connection fails, the PlaneTracker setup network will return.
    </div>
  </section>

  <section id="result-panel" class="panel hidden">
    <div class="step">Connection status</div>
    <div id="result" class="status"></div>
  </section>
</main>
<script>
const state={selected:''};
const esc=value=>String(value??'').replace(/[&<>"']/g,char=>({
  '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
}[char]));

async function loadResult(){
  try{
    const data=await fetch('/api/wifi/connect-result',{cache:'no-store'}).then(response=>response.json());
    if(data.state==='failed'){
      const panel=document.getElementById('result-panel');
      panel.classList.remove('hidden');
      panel.classList.add('error');
      document.getElementById('result').textContent=`Could not connect to ${data.ssid||'the selected network'}: ${data.message||'Unknown error'}`;
    }
  }catch(error){}
}

function chooseNetwork(ssid,button){
  state.selected=ssid;
  document.getElementById('ssid').value=ssid;
  document.querySelectorAll('.network').forEach(item=>item.classList.remove('selected'));
  if(button)button.classList.add('selected');
  document.getElementById('password').focus();
}

async function scan(){
  const status=document.getElementById('scan-status');
  const list=document.getElementById('networks');
  const button=document.getElementById('scan-button');
  button.disabled=true;
  status.textContent='Scanning for Wi-Fi networks...';
  list.innerHTML='';
  try{
    const data=await fetch('/api/wifi/scan',{cache:'no-store'}).then(response=>response.json());
    const networks=(data.networks||[]).filter(network=>!String(network.ssid||'').startsWith('PlaneTracker-Setup'));
    status.textContent=networks.length?`${networks.length} networks found`:(data.message||'No networks found. Try scanning again.');
    list.innerHTML=networks.map(network=>`
      <button class="network" type="button" data-ssid="${esc(network.ssid)}">
        <span class="network-name">${esc(network.ssid)}</span>
        <span class="network-meta">${Number(network.signal)||0}% &nbsp; ${esc(network.security||'Open')}</span>
      </button>`).join('');
    document.querySelectorAll('.network').forEach(item=>{
      item.onclick=()=>chooseNetwork(item.dataset.ssid||'',item);
    });
  }catch(error){
    status.textContent=`Scan failed: ${error.message}`;
  }finally{
    button.disabled=false;
  }
}

async function connect(){
  const ssid=document.getElementById('ssid').value.trim();
  const password=document.getElementById('password').value;
  const button=document.getElementById('connect-button');
  const panel=document.getElementById('result-panel');
  const result=document.getElementById('result');
  if(!ssid){
    panel.classList.remove('hidden');
    result.textContent='Choose or enter a Wi-Fi network first.';
    return;
  }
  button.disabled=true;
  panel.classList.remove('hidden','error');
  panel.classList.add('success');
  result.textContent=`Connecting to ${ssid}. This page will disconnect shortly...`;
  try{
    const response=await fetch('/api/wifi/connect',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({ssid,password})
    });
    const data=await response.json();
    result.textContent=data.message||(data.ok?'Connection started.':'Connection failed.');
    if(!data.ok)button.disabled=false;
  }catch(error){
    result.textContent='The setup network disconnected. Rejoin your home Wi-Fi, or wait for the setup network to return.';
  }
}

document.getElementById('scan-button').onclick=scan;
document.getElementById('connect-button').onclick=connect;
loadResult();
scan();
</script>
</body>
</html>
