import {SCENARIOS,round,sigmoid,baselineValues,contributions,logit,predict,demoRows,metrics,groups,permutationImportance,pdp,solveCounterfactual,importCsv,exportCsv,buildReport,clamp} from './core.mjs';
const $=id=>document.getElementById(id);
const START={logistics:{demand:64,distance:470,weather:4,utilization:79,buffer:4,supplier:78},customer:{tickets:8,resolution:39,adoption:55,tenure:20,satisfaction:6,outages:3},equipment:{temperature:70,vibration:7,hours:520,maintenance:65,spares:55,load:74}};
const state={scenario:'logistics',model:SCENARIOS.logistics,values:{...START.logistics},rows:demoRows(SCENARIOS.logistics),source:'synthetic',view:'overview',target:.35,threshold:.5,counter:null};
let memoGlobal=null;
const esc=x=>String(x).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll("'",''');
const pct=(x,d=1)=>x==null||!Number.isFinite(x)?'N/A':`${(x*100).toFixed(d)}%`;
const num=(x,d=3)=>x==null||!Number.isFinite(x)?'N/A':Number(x).toFixed(d);
const fmt=(x,unit='')=>`${Number(x).toLocaleString('en-US',{maximumFractionDigits:2})}${unit&&unit.startsWith('/')?' ':' '}${unit}`.trim();
function message(text,isError=false){const n=$('notice');n.textContent=text;n.hidden=false;n.classList.toggle('error',isError);if(message.timer)clearTimeout(message.timer);message.timer=setTimeout(()=>n.hidden=true,6500)}
function download(name,type,content){const blob=new Blob([content],{type});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=name;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1800)}
function riskLevel(p){return p>=.7?'HIGH RISK':p>=.4?'ELEVATED':'LOWER RISK'}
function buildSelectors(){for(const id of ['localFeature','globalFeature']){$(id).innerHTML=state.model.features.map(f=>``).join('')}}
function navigate(view){if(!$("view-"+view))return;state.view=view;document.querySelectorAll('.nav-item').forEach(b=>{const active=b.dataset.view===view;b.classList.toggle('active',active);if(active)b.setAttribute('aria-current','page');else b.removeAttribute('aria-current')});document.querySelectorAll('.view').forEach(v=>v.classList.toggle('active',v.id===`view-${view}`));const navTitle=document.querySelector(`.nav-item[data-view="${view}"]`)?.textContent.trim()||view;$('breadcrumb').textContent=navTitle;$('sidebar').classList.remove('open');renderView();}
function setScenario(id){if(!SCENARIOS[id])return;state.scenario=id;state.model=SCENARIOS[id];state.values={...START[id]};state.rows=demoRows(state.model);state.source='synthetic';state.counter=null;memoGlobal=null;$('scenario').value=id;buildSelectors();$('contextDesc').textContent=state.model.description;renderView();message('Model changed. Demo dataset restored. All results have been recalculated.');}
function renderView(){ $('datasetBadge').textContent=`${state.rows.length.toLocaleString()} ${state.source} records`;switch(state.view){case'overview':renderOverview();break;case'local':renderLocal();break;case'global':renderGlobal();break;case'counterfactual':renderCounter();break;case'groups':renderGroups();break;case'data':renderData();break;}}
function barRows(items,type='signed'){let max=Math.max(.05,...items.map(x=>Math.abs(x.contribution??x.delta??0)));return items.map(x=>{const v=type==='signed'?x.contribution:x.delta;const label=x.label;const sign=v>=0;let width=type==='signed'?Math.min(48,Math.abs(v)/max*48):Math.min(100,Math.max(0,v)/max*100);const bar=type==='signed'?`
`}).join('');}
function sliders(container){container.innerHTML=state.model.features.map(f=>`
${esc(f.label)} ${f.mutable?'':'· fixed in planner'}${esc(fmt(state.values[f.key],f.unit))}
${f.min} ${esc(f.unit)}${f.max} ${esc(f.unit)}
`).join('');container.querySelectorAll('[data-feature]').forEach(input=>input.addEventListener('input',()=>{state.values[input.dataset.feature]=Number(input.value);state.counter=null;const f=state.model.features.find(f=>f.key===input.dataset.feature);document.getElementById(`val-${input.dataset.feature}`).textContent=fmt(state.values[input.dataset.feature],f.unit);renderOverview(false);}));}
function renderOverview(updateSliders=true){const p=predict(state.model,state.values);const m=metrics(state.rows,state.model,state.threshold);$('riskNumber').textContent=pct(p);$('baselineNumber').textContent=pct(sigmoid(state.model.bias));$('aucNumber').textContent=num(m.auc);$('brierNumber').textContent=num(m.brier);$('riskTag').textContent=riskLevel(p);$('outcomeLabel').textContent=state.model.outcome;$('riskBar').style.width=`${(p*100).toFixed(2)}%`;$('overviewContrib').innerHTML=barRows(contributions(state.model,state.values).sort((a,b)=>Math.abs(b.contribution)-Math.abs(a.contribution)));if(updateSliders)sliders($('overviewSliders'));}
const svgWidth=660,svgHeight=268;
function curveSvg(xs,ys,{currentX=null,currentY=null,ice=[]}={}){const pad={left:48,right:18,top:18,bottom:42};let xMin=Math.min(...xs),xMax=Math.max(...xs);if(xMax<=xMin)xMax=xMin+1;const X=x=>pad.left+(x-xMin)/(xMax-xMin)*(svgWidth-pad.left-pad.right);const Y=y=>svgHeight-pad.bottom-clamp(y,0,1)*(svgHeight-pad.top-pad.bottom);const points=(data)=>data.map((v,i)=>`${X(xs[i]).toFixed(2)},${Y(v).toFixed(2)}`).join(' ');let svg=`'}
function renderLocal(){const cs=contributions(state.model,state.values).sort((a,b)=>Math.abs(b.contribution)-Math.abs(a.contribution));$('localContrib').innerHTML=barRows(cs);const total=logit(state.model,state.values),prob=predict(state.model,state.values);$('identityProof').textContent=`Identity check: bias ${num(state.model.bias)} + contributions ${num(total-state.model.bias)} = total ${num(total)} log-odds → ${pct(prob)} probability.`;$('formula').textContent='P(outcome = 1 | x) = σ[ bias + Σᵢ weightᵢ × (xᵢ − centerᵢ) / scaleᵢ ]';renderLocalChart();}
function renderLocalChart(){const feature=state.model.features.find(f=>f.key===$('localFeature').value)||state.model.features[0];const xs=Array.from({length:26},(_,i)=>feature.min+(feature.max-feature.min)*i/25);const ys=xs.map(x=>predict(state.model,{...state.values,[feature.key]:x}));$('localChart').innerHTML=curveSvg(xs,ys,{currentX:state.values[feature.key],currentY:predict(state.model,state.values)});}
function globalScores(){if(!memoGlobal)memoGlobal=permutationImportance(state.model,state.rows,4,106);return memoGlobal}
function renderGlobal(){$('globalBars').innerHTML=barRows(globalScores(),'importance');renderGlobalChart();}
function renderGlobalChart(){const result=pdp(state.model,state.rows,$('globalFeature').value,23,9);$('pdpChart').innerHTML=curveSvg(result.xs,result.avg,{ice:result.ice});}
function renderCounter(){state.counter=null;$('targetValue').textContent=pct(state.target,0);$('targetRange').value=state.target*100;$('counterStatus').textContent='Current risk: '+pct(predict(state.model,state.values))+'. Select a target and compute a possible scenario.';$('counterResult').innerHTML='
No plan computed yet. Click “Find minimum-change scenario” to run the search.
';}
function computeCounter(){try{const result=solveCounterfactual(state.model,state.values,state.target,2);state.counter=result;const p=predict(state.model,state.values);if(result.already){$('counterStatus').textContent='This case already meets the requested risk target.';$('counterResult').innerHTML=`
${pct(p)}
Target already satisfied. No changes required.
`;return}if(!result){$('counterResult').textContent='No available editable change found.';return}const color=result.met?'#59edc1':'#ffc978';$('counterStatus').textContent=result.met?'A feasible candidate was found on the search grid.':'No candidate reached the target; showing the lowest-risk candidate found.';$('counterResult').innerHTML=`
${pct(result.probability)}
Current ${pct(p)} → Candidate ${pct(result.probability)} · ${result.met?'MEETS TARGET':'DOES NOT MEET TARGET'}
`;$('applyCandidate').addEventListener('click',()=>{state.values={...result.values};state.counter=null;computeCounter();message('Candidate applied. Command Center now reflects the new inputs.')});}catch(err){message(err.message,true)}}
function renderGroups(){const gs=groups(state.rows,state.model,state.threshold),overall=metrics(state.rows,state.model,state.threshold);$('thresholdValue').textContent=pct(state.threshold,0);$('thresholdRange').value=state.threshold*100;$('groupRows').innerHTML=gs.map(g=>`
${esc(g.name)}
${g.n}
${pct(g.actualRate)}
${pct(g.meanPred)}
${num(g.brier)}
${num(g.auc)}
${pct(g.recall)}
`).join('');const enough=gs.filter(g=>g.n>=20),gap=enough.length>=2?Math.max(...enough.map(g=>g.meanPred))-Math.min(...enough.map(g=>g.meanPred)):null;$('groupCallout').textContent=gap==null?'Insufficient groups with at least 20 records for a stable descriptive comparison.':`Mean predicted risk gap across groups with ≥20 records: ${pct(gap)}. Inspect possible composition effects before interpreting disparities.`;$('confusionStats').innerHTML=[['TRUE POS',overall.tp],['FALSE POS',overall.fp],['TRUE NEG',overall.tn],['FALSE NEG',overall.fn]].map(([n,v])=>`
${v}${n}
`).join('');}
function renderData(){$('dataStatus').textContent=`Dataset: ${state.rows.length} ${state.source} records · ${state.model.features.length} features · outcome ∈ {0,1} · segment label.`;}
function reportMarkdown(){const m=metrics(state.rows,state.model,state.threshold),p=predict(state.model,state.values),cf=solveCounterfactual(state.model,state.values,state.target,2);return `# ClarityXAI Research Report\n\n- Model: ${state.model.title}\n- Evaluation records: ${state.rows.length} (${state.source})\n- Risk estimate: ${pct(p)}\n- Reference risk: ${pct(sigmoid(state.model.bias))}\n- ROC AUC (labeled sample): ${num(m.auc)}\n- Brier score: ${num(m.brier)}\n- Prediction threshold: ${pct(state.threshold,0)}\n\n## Feature contributions (log-odds)\n\n${contributions(state.model,state.values).map(c=>`- ${c.label}: ${num(c.contribution)}`).join('\n')}\n\n## Counterfactual (${pct(state.target,0)} target)\n\n- Target reached on discrete grid: ${cf?.met?'yes':'no'}\n- Candidate risk: ${cf?pct(cf.probability):'N/A'}\n${(cf?.changes||[]).map(c=>`- ${c.label}: ${c.from} → ${c.to} ${c.unit}`).join('\n')}\n\n## Model assumptions and limitations\n\nThis educational scoring model uses fixed, synthetic coefficients and synthetic evaluation labels unless user-authorized data have been imported. Local attribution measures mathematical contribution, not causal influence. Counterfactuals search a discrete space and do not guarantee feasibility in real operations. Subgroup comparisons are descriptive only. This application is not suitable for live high-stakes decisions.\n`}
function init(){document.querySelectorAll('.nav-item').forEach(b=>b.addEventListener('click',()=>navigate(b.dataset.view)));$('mobileMenu').addEventListener('click',()=> $('sidebar').classList.toggle('open'));$('scenario').addEventListener('change',e=>setScenario(e.target.value));$('resetValues').addEventListener('click',()=>{state.values=baselineValues(state.model);renderView();message('Inputs restored to published reference values.')});$('localFeature').addEventListener('change',renderLocalChart);$('globalFeature').addEventListener('change',renderGlobalChart);$('targetRange').addEventListener('input',e=>{state.target=Number(e.target.value)/100;$('targetValue').textContent=pct(state.target,0);state.counter=null;$('counterResult').innerHTML='
Target changed. Run the search again.
';});$('solveButton').addEventListener('click',computeCounter);$('thresholdRange').addEventListener('input',e=>{state.threshold=Number(e.target.value)/100;renderGroups();});$('restoreDemo').addEventListener('click',()=>{state.rows=demoRows(state.model);state.source='synthetic';memoGlobal=null;renderView();message('Original synthetic evaluation dataset restored.')});$('csvFile').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;try{if(file.size>2000000)throw Error('CSV exceeds 2 MB.');const rows=importCsv(await file.text(),state.model);state.rows=rows;state.source='imported';memoGlobal=null;renderView();message(`Imported ${rows.length} labeled records successfully. Nothing was sent to a server.`)}catch(err){message(err.message,true)}finally{e.target.value=''}});$('downloadTemplate').addEventListener('click',()=>{const names=[...state.model.features.map(f=>f.key),'outcome','segment'];const sample=state.rows.slice(0,8);const text=[names.join(','),...sample.map(r=>names.map(n=>r[n]).join(','))].join('\n')+'\n';download('clarityxai_import_template.csv','text/csv;charset=utf-8',text)});$('downloadReport').addEventListener('click',exportReport);$('topExport').addEventListener('click',exportReport);$('downloadCsv').addEventListener('click',()=>download('clarityxai_predictions.csv','text/csv;charset=utf-8',exportCsv(state.rows,state.model)));$('downloadMarkdown').addEventListener('click',()=>download('clarityxai_readable_report.md','text/markdown;charset=utf-8',reportMarkdown()));buildSelectors();renderView()}
function exportReport(){const obj=buildReport(state.model,state.values,state.rows,state.threshold,state.target,state.scenario);obj.data_source=state.source;download('clarityxai_audit_report.json','application/json;charset=utf-8',JSON.stringify(obj,null,2)+'\n');}
init();