(function(){
const REGIONS=["","Europe","North America","Oceania","Asia","Latin America","Africa"];
const STATUSES=["Candidate","Shortlisted","Invited","Accepted","Declined"];
const COCHAIR=new Set(["Shortlisted","Invited","Accepted"]);
const FIELDS=["name","affiliation","region","status","note"];
const KEY="its2027-board-code";
let code="",me="",roles=[],cands=[],logs=[],filter=null,structureKey="",busy=0;
const rowEls=new Map();
const $=id=>document.getElementById(id);
function setStatus(t){$("status").textContent=t||"";}
function getCode(){try{return localStorage.getItem(KEY)||"";}catch(e){return "";}}
function setCode(v){try{v?localStorage.setItem(KEY,v):localStorage.removeItem(KEY);}catch(e){}}
function fmt(iso){if(!iso)return "";try{const d=new Date(iso);return d.toLocaleDateString(undefined,{day:"2-digit",month:"short"})+" "+d.toLocaleTimeString(undefined,{hour:"2-digit",minute:"2-digit"});}catch(e){return "";}}
function el(tag,attrs,kids){const e=document.createElement(tag);if(attrs)for(const k in attrs){if(k==="text")e.textContent=attrs[k];else if(k==="cls")e.className=attrs[k];else e.setAttribute(k,attrs[k]);}(kids||[]).forEach(c=>c&&e.appendChild(c));return e;}
async function api(action,body){
let r;
try{r=await fetch("api.php?action="+action,{method:body?"POST":"GET",headers:{"X-Access-Code":code,"Content-Type":"application/json"},body:body?JSON.stringify(body):undefined,cache:"no-store"});}
catch(e){throw new Error("The server cannot be reached (network error).");}
const text=await r.text();let data=null;
try{data=JSON.parse(text);}catch(e){}
if(r.status===401){logout("This access code is not valid.");throw new Error("auth");}
if(r.status===404)throw new Error("api.php was not found next to index.html (error 404). Check that all files are in the same folder.");
if(data===null){
if(text.indexOf("<?php")!==-1)throw new Error("PHP does not run on this server: api.php is sent as plain text. PHP must be enabled for this folder.");
throw new Error("The server returned an unexpected answer (HTTP "+r.status+"). Open api.php directly in the browser to see the message.");
}
if(!r.ok)throw new Error(data.error||("The server refused the request (HTTP "+r.status+")."));
return data;
}
let lastError="";
async function load(){
try{const d=await api("state");
if(!d||!Array.isArray(d.roles)||!Array.isArray(d.candidates))throw new Error("The data files could not be read. Check that the data folder was uploaded with board.php and log.php.");
me=d.me;roles=d.roles.slice().sort((a,b)=>a.order-b.order);cands=d.candidates;logs=d.log||[];
$("who").textContent="Signed in as "+me+".";if(!busy)setStatus("");lastError="";render();return true;}
catch(e){lastError=e.message;if(e.message!=="auth")setStatus(e.message);return false;}
}
function render(){
const byRole={};cands.forEach(c=>{(byRole[c.roleId]=byRole[c.roleId]||[]).push(c);});
Object.values(byRole).forEach(a=>a.sort((x,y)=>(x.order||0)-(y.order||0)));
const key=roles.map(r=>r.id+":"+(byRole[r.id]||[]).map(c=>c.id).join(",")).join("|");
if(key!==structureKey){structureKey=key;buildRoles(byRole);}
roles.forEach(r=>{
const list=byRole[r.id]||[];const n=list.filter(c=>COCHAIR.has(c.status)).length;
const b=document.querySelector('[data-badge="'+r.id+'"]');
if(b){b.textContent=n+" / 2 co-chairs";b.className="badge"+(n>2?" over":n===2?" full":"");}
list.forEach(c=>{const row=rowEls.get(c.id);if(!row)return;
FIELDS.forEach(f=>{const inp=row.inputs[f];if(inp&&document.activeElement!==inp)inp.value=c[f]||(f==="status"?"Candidate":"");});
row.tr.classList.toggle("sel",COCHAIR.has(c.status));
row.meta.textContent=c.updatedBy?(c.updatedBy+" · "+fmt(c.updatedAt)):"Initial proposal";});
});
renderRegions();renderPeople();renderLog();
}
function buildRoles(byRole){
const root=$("roles");root.replaceChildren();rowEls.clear();
roles.forEach(r=>{
const h=el("h2",{},[el("span",{text:r.title.toUpperCase()}),el("span",{cls:"badge","data-badge":r.id})]);
const thead=el("thead",{},[el("tr",{},["Potential chair","Affiliation (to verify)","Region","Status","Note","Last change",""].map(t=>el("th",{text:t})))]);
const tbody=el("tbody");(byRole[r.id]||[]).forEach(c=>tbody.appendChild(buildRow(r,c)));
const add=el("button",{cls:"add",text:"+ Add a candidate"});add.onclick=()=>act("add",{roleId:r.id});
root.appendChild(el("div",{cls:"panel"},[h,el("div",{cls:"body"},[el("p",{cls:"mission",text:r.mission||""}),el("div",{cls:"scroll"},[el("table",{},[thead,tbody])]),add])]));
});
}
function buildRow(r,c){
const inputs={};
const mkIn=(f,ph)=>{const i=el("input",{type:"text",placeholder:ph});i.addEventListener("change",()=>edit(c.id,f,i.value.trim(),i));inputs[f]=i;return i;};
const mkSel=(f,opts)=>{const s=el("select");opts.forEach(o=>s.appendChild(el("option",{value:o,text:o||"–"})));s.addEventListener("change",()=>edit(c.id,f,s.value,s));inputs[f]=s;return s;};
const meta=el("div",{cls:"meta"});
const del=el("button",{cls:"del",title:"Remove this candidate",text:"✕"});
del.onclick=()=>{const cur=cands.find(x=>x.id===c.id);if(confirm("Remove "+((cur&&cur.name)||"this candidate")+" from "+r.title+"?"))act("delete",{id:c.id});};
const tr=el("tr",{},[el("td",{cls:"name"},[mkIn("name","Name")]),el("td",{},[mkIn("affiliation","Affiliation")]),el("td",{},[mkSel("region",REGIONS)]),el("td",{},[mkSel("status",STATUSES)]),el("td",{},[mkIn("note","Comment")]),el("td",{},[meta]),el("td",{},[del])]);
rowEls.set(c.id,{tr,inputs,meta});return tr;
}
async function edit(id,field,value,input){
const c=cands.find(x=>x.id===id);const before=c?(c[field]||""):"";
if(field==="status"&&COCHAIR.has(value)&&!COCHAIR.has(before)){
const n=cands.filter(x=>c&&x.roleId===c.roleId&&COCHAIR.has(x.status)).length;
if(n>=2){alert("This role already has two co-chairs. Set one of them back to Candidate or Declined first.");input.value=before||"Candidate";return;}
}
await act("update",{id,field,value},()=>{input.value=before;});
}
async function act(action,body,onFail){
busy++;try{await api(action,body);setStatus("");}catch(e){if(e.message!=="auth"){setStatus(e.message);if(onFail)onFail();}}
finally{busy--;await load();}
}
function renderRegions(){
const counts={};REGIONS.filter(Boolean).forEach(x=>counts[x]=0);let none=0;
cands.filter(c=>COCHAIR.has(c.status)).forEach(c=>{if(counts[c.region]!==undefined)counts[c.region]++;else none++;});
const tb=$("regions");tb.replaceChildren();
Object.entries(counts).forEach(([k,v])=>tb.appendChild(el("tr",{},[el("td",{text:k}),el("td",{text:String(v)})])));
if(none)tb.appendChild(el("tr",{},[el("td",{text:"Region not set"}),el("td",{text:String(none)})]));
}
function renderPeople(){
const counts={};logs.forEach(l=>{if(l.by)counts[l.by]=(counts[l.by]||0)+1;});
const box=$("people");box.replaceChildren();const ids=Object.keys(counts);
if(!ids.length){box.appendChild(el("span",{cls:"legend",text:"No changes yet."}));return;}
const all=el("button",{cls:"chip"+(filter===null?" on":""),text:"Everyone"});all.style.paddingLeft="10px";all.onclick=()=>{filter=null;render();};box.appendChild(all);
ids.sort((a,b)=>counts[b]-counts[a]).forEach(n=>{const ch=el("button",{cls:"chip"+(filter===n?" on":""),text:n+" ("+counts[n]+")"});ch.style.paddingLeft="10px";ch.onclick=()=>{filter=filter===n?null:n;render();};box.appendChild(ch);});
}
function renderLog(){
const box=$("log");box.replaceChildren();const list=logs.filter(l=>!filter||l.by===filter);
$("logcount").textContent=list.length+" changes";
if(!list.length){box.appendChild(el("div",{cls:"legend",text:"No changes recorded yet."}));return;}
list.forEach(l=>{
const head=el("div",{},[el("span",{cls:"w",text:l.by}),el("span",{cls:"t",text:" · "+fmt(l.at)})]);
let line;
if(l.action==="edit")line=el("div",{},[el("span",{text:"Changed the "+l.field+" of "+(l.candidate||"a candidate")+" ("+l.role+"): "}),el("span",{cls:"old",text:l.before||"empty"}),el("span",{text:" → "}),el("span",{cls:"new",text:l.after||"empty"})]);
else if(l.action==="add")line=el("div",{text:"Added a candidate to "+l.role+"."});
else line=el("div",{text:"Removed "+l.candidate+" from "+l.role+"."});
box.appendChild(el("div",{cls:"e"},[el("div",{},[head,line])]));
});
}
function csv(){
const q=v=>'"'+String(v==null?"":v).replace(/"/g,'""')+'"';
const lines=[["Role","Name","Affiliation","Region","Status","Note","Last change by","Last change at"].map(q).join(",")];
roles.forEach(r=>cands.filter(c=>c.roleId===r.id).sort((a,b)=>a.order-b.order).forEach(c=>lines.push([r.title,c.name,c.affiliation,c.region,c.status,c.note,c.updatedBy,c.updatedAt].map(q).join(","))));
const a=document.createElement("a");a.href=URL.createObjectURL(new Blob(["\ufeff"+lines.join("\r\n")],{type:"text/csv;charset=utf-8"}));a.download="ITS2027-committee.csv";a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000);
}
function logout(msg){setCode("");code="";$("login").style.display="flex";$("err").textContent=msg||"";}
async function login(){
code=$("code").value.trim().toUpperCase();if(!code)return;$("err").textContent="";
$("go").disabled=true;$("err").textContent="Checking…";
const ok=await load();$("go").disabled=false;
if(ok){setCode(code);$("login").style.display="none";$("err").textContent="";}
else if(lastError!=="auth"){$("err").textContent=lastError;code="";}
}
$("go").onclick=login;$("code").addEventListener("keydown",e=>{if(e.key==="Enter")login();});
$("out").onclick=()=>logout("");$("csv").onclick=csv;
code=getCode();
if(code){load().then(ok=>{if(!ok&&!code)return;});}else{$("login").style.display="flex";setStatus("");}
setInterval(()=>{if(code&&!busy&&!document.hidden)load();},15000);
document.addEventListener("visibilitychange",()=>{if(!document.hidden&&code)load();});
})();