Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
210 lines (209 loc) · 99.3 KB
/
Copy pathapp.js
File metadata and controls
210 lines (209 loc) · 99.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
(() => {
const KEY = 'gridshift-planner-v1';
const {APP_VERSION,CALC_VERSION,MAX_STATE_CHARS,calc,parseCsv,csvValue,validateBackup,migrateLegacyFactor,migrateLegacyCosts}=GridshiftCore;
const FACTOR = { value: 24300, horizon: '100-year', source: 'IPCC AR6 WGI Supplementary Material, Table 7.SM.7 (SF₆)', version: 'AR6 WGI 2021' };
const MODEL_REVIEW_STATUS = 'Not independently reviewed';
const app = document.querySelector('#app'), dialog = document.querySelector('#dialog'), toastEl = document.querySelector('#toast');
let toastTimer, dialogOpener=null, workerRegistration=null, applyWorkerUpdate=false;
dialog.addEventListener('close',()=>{
if(dialog.open)return;
const target=dialogOpener;dialogOpener=null;
if(target?.isConnected&&!target.disabled){target.focus();if(document.activeElement===target)return}
const heading=document.querySelector('#view h1, #view h2');
if(heading){heading.tabIndex=-1;heading.focus({preventScroll:true})}
});
const uid = () => crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const yearNow = new Date().getFullYear();
const blankState = () => ({ version: 1, projects: [], activeProjectId: null, updatedAt: null });
let state, storageCorruptRaw=null, storageUnavailable=false;
try { const raw=localStorage.getItem(KEY);state=raw?JSON.parse(raw):blankState();if(!state||state.version!==1||!Array.isArray(state.projects)||state.projects.some(p=>!p||!Array.isArray(p.assets)||!Array.isArray(p.sites)||!Array.isArray(p.technologies)||!Array.isArray(p.scenarios)))throw new Error('Stored workspace has an unsupported structure.');try{validateBackup({format:'gridshift-backup',version:1,data:state})}catch{throw new Error('Stored workspace has an unsupported structure.')} }
catch(e){state=blankState();if(e instanceof SyntaxError||e.message==='Stored workspace has an unsupported structure.')storageCorruptRaw=(()=>{try{return localStorage.getItem(KEY)}catch{return null}})();else storageUnavailable=true;}
const legacyFactorSource='IPCC Sixth Assessment Report, WG I, Table 7.15 (SF₆)';
const migratedFactorProjects=storageCorruptRaw?0:migrateLegacyFactor(state,legacyFactorSource,FACTOR);
const migratedCostProjects=storageCorruptRaw?0:migrateLegacyCosts(state);
let page = 'dashboard', searchText = '', filterCategory = 'All categories';
const current = () => state.projects.find(p => p.id === state.activeProjectId) || state.projects[0] || null;
const activeScenario = p => p?.scenarios.find(s => s.id === p.activeScenarioId) || p?.scenarios[0] || null;
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const money = (v, currency='USD', digits=0) => Number.isFinite(v) ? new Intl.NumberFormat(undefined,{style:'currency',currency,maximumFractionDigits:digits,minimumFractionDigits:digits}).format(v) : 'Unavailable';
const num = (v,d=1) => Number.isFinite(v) ? new Intl.NumberFormat(undefined,{maximumFractionDigits:d}).format(v) : '—';
const fmtDate = v => v ? new Date(v).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}) : 'Not saved';
const fitsLocalDataLimit=value=>JSON.stringify(value).length<=MAX_STATE_CHARS;
function save(message='Changes saved locally') {
if(storageCorruptRaw!==null){toast('Existing browser data may be damaged. Export a recovery copy and reset local data before saving.',true);return}
const priorUpdatedAt=state.updatedAt;
state.updatedAt = new Date().toISOString();
try { const payload=JSON.stringify(state);if(payload.length>MAX_STATE_CHARS){const error=new Error('Gridshift local-data limit exceeded.');error.name='QuotaExceededError';throw error}localStorage.setItem(KEY,payload);renderTop();if(message)toast(message); }
catch (e) { state.updatedAt=priorUpdatedAt;renderTop();toast(`Save failed: ${e.name === 'QuotaExceededError' ? 'browser storage is full. Export a JSON backup, then free browser space.' : 'browser storage is unavailable. Export a JSON backup before leaving this tab.'} Your current edits remain visible in this tab.`, true); }
}
function toast(message, error=false) { toastEl.textContent=message;toastEl.style.background=error?'#8c352c':'#173f35';toastEl.classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>toastEl.classList.remove('show'),3200); }
function mkProject(name, description='', horizon=10) { return {id:uid(),name,description,baseYear:yearNow,horizon:Number(horizon),currency:'USD',priceYear:yearNow,discountRate:0.04,gwp:FACTOR.value,gwpHorizon:FACTOR.horizon,gwpSource:FACTOR.source,factorVersion:FACTOR.version,sites:[],assets:[],technologies:[],scenarios:[],activeScenarioId:null,weights:{age:35,emissions:40,condition:25},createdAt:new Date().toISOString()}; }
function renderTop() {
const p=current();
const selector=document.querySelector('#project-select'); if(selector) selector.textContent=p?.name||'Select a project ⌄';
const count=document.querySelector('#asset-count'); if(count)count.textContent=p?.assets.length||0;
const scount=document.querySelector('#scenario-count'); if(scount)scount.textContent=p?.scenarios.length||0;
renderStatus();
}
function syncUpdateButton(){const button=document.querySelector('#update-app');if(!button)return;const waiting=workerRegistration?.waiting,controlled='serviceWorker'in navigator&&navigator.serviceWorker.controller;if(!waiting||!controlled){button.hidden=true;return}button.hidden=false;button.disabled=false;button.textContent='Update ready · Reload';button.onclick=()=>{const worker=workerRegistration?.waiting;if(!worker)return;applyWorkerUpdate=true;button.disabled=true;button.textContent='Updating…';worker.postMessage({type:'SKIP_WAITING'})}}
const navItems=[['dashboard','◫','Overview'],['inventory','▤','Asset inventory'],['technology','⌘','Technology library'],['scenarios','◷','Scenarios'],['roadmap','↗','Roadmap'],['reports','▧','Reports & export']];
function shell() {
app.innerHTML=`<div class="shell"><aside class="sidebar"><div class="brand"><img class="brand-mark" src="assets/gridshift-mark.svg" alt="Gridshift" width="88" height="88"></div><div class="project-select-label">Workspace</div><button class="project-select" id="project-select" aria-label="Choose active project"></button><div class="nav-group"><div class="nav-label">Planning</div>${navItems.slice(0,5).map(([id,icon,label])=>`<button class="nav-link ${page===id?'active':''}" data-page="${id}" ${page===id?'aria-current="page"':''}><span class="nav-icon">${icon}</span>${label}${id==='inventory'?'<span class="nav-count" id="asset-count">0</span>':''}${id==='scenarios'?'<span class="nav-count" id="scenario-count">0</span>':''}</button>`).join('')}</div><div class="nav-group"><div class="nav-label">Workspace</div>${navItems.slice(5).map(([id,icon,label])=>`<button class="nav-link ${page===id?'active':''}" data-page="${id}" ${page===id?'aria-current="page"':''}><span class="nav-icon">${icon}</span>${label}</button>`).join('')}<button class="nav-link ${page==='settings'?'active':''}" data-page="settings" ${page==='settings'?'aria-current="page"':''}><span class="nav-icon">⚙</span>Settings & data</button></div><div class="sidebar-bottom"><div class="status" id="connection-status"><span class="dot"></span> Online</div><div class="local-note">Your planning data stays in this browser. No account or cloud sync required.</div></div></aside><main class="main"><header class="topbar"><div class="crumbs">PLANNING WORKSPACE <span> / </span> <span id="crumb-project"></span></div><button class="btn small" id="update-app" type="button" hidden>Update ready · Reload</button></header><section class="content" id="view"></section></main><aside class="mobile-nav" aria-label="Primary navigation">${navItems.filter(([id])=>['dashboard','inventory','technology','scenarios','roadmap','reports'].includes(id)).map(([id,icon,label])=>`<button class="nav-link ${page===id?'active':''}" data-page="${id}" ${page===id?'aria-current="page"':''} aria-label="${esc(label)}"><span class="nav-icon">${icon}</span>${({dashboard:'Home',inventory:'Assets',technology:'Tech',scenarios:'Plan',roadmap:'Roadmap',reports:'Reports'})[id]}</button>`).join('')}<button class="nav-link" data-action="mobile-menu" aria-label="More workspace options"><span class="nav-icon">⋯</span>More</button></aside></div>`;
document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>{page=b.dataset.page;searchText='';render()});
document.querySelector('#project-select').onclick=projectMenu;
document.querySelector('#crumb-project').textContent=current()?.name||'No project';
renderTop(); renderPage(); setOnline(); syncUpdateButton();
}
function render(){shell()}
function pageHead(title,sub,actions=''){return `<div class="page-head"><div><div class="eyebrow">${current()?esc(current().name):'LOCAL PLANNING WORKSPACE'}</div><h1>${title}</h1><p>${sub}</p></div><div class="head-actions">${actions}</div></div>`}
function factorNotice(c){return `${c?.factorReviewRequired?`<div class="notice factor-review-notice"><strong>Review saved emissions factor.</strong> This scenario keeps the previous 25,200 value for reproducibility. New projects use 24,300 from IPCC AR6 WGI Supplementary Material Table 7.SM.7. Edit and save the scenario to recalculate with the current project assumption.</div>`:''}${c?.legacyCostReviewRequired?`<div class="notice factor-review-notice"><strong>Review legacy cost inputs.</strong> Some zero costs in this saved scenario may have been blank fields stored as zero by an older Gridshift version. Review the asset and technology costs, then edit and save the scenario to refresh its inputs.</div>`:''}`}
function reviewStatusNotice(){return `<div class="notice review-status-notice" role="note" aria-label="Independent model review status"><strong>Independent review status: ${MODEL_REVIEW_STATUS}.</strong> No independent qualified power-system engineering or climate/accounting review has been completed. Treat outputs as exploratory estimates; verify assumptions and obtain qualified review before operational, investment, or regulatory decisions.</div>`}
function renderPage(){const el=document.querySelector('#view');if(!el)return;const p=current();if(!p){el.innerHTML=reviewStatusNotice()+welcome();wireEmpty();return}const views={dashboard:dashboard,inventory:inventory,technology:technology,scenarios:scenarios,roadmap:roadmap,reports:reports,settings:settings};el.innerHTML=reviewStatusNotice()+(views[page]||dashboard)(p);if(journeyStages.some(([id])=>id===page))el.insertAdjacentHTML('beforeend',screenTransition());wirePage();}
const journeyStages=[['dashboard','Project'],['inventory','Inventory'],['technology','Technologies'],['scenarios','Scenarios'],['roadmap','Roadmap'],['reports','Reports']];
function screenTransition(){const index=journeyStages.findIndex(([id])=>id===page),next=index<journeyStages.length-1?journeyStages[index+1]:journeyStages[3],label=index===journeyStages.length-1?'Return to Scenarios':`Continue to ${next[1]}`;return `<div class="screen-transition"><button class="btn primary" data-page="${next[0]}">${label} →</button></div>`}
function welcome(){return `${pageHead('Make the shift, with a plan.','Build a clear, reviewable path from SF₆ assets to lower-impact alternatives.')}<div class="empty"><div class="empty-icon">⌁</div><h2>Your planning workspace is ready</h2><p>Create a project to organize sites, inventory SF₆ equipment, compare preliminary technology profiles, and model a phased transition. Data is stored locally in this browser.</p><button class="btn primary" data-action="new-project">+ Create your first project</button><button class="btn" data-action="demo-project" style="margin-left:7px">Load sample workspace</button></div><p class="disclaimer welcome-disclaimer">Planning estimates only. Compatibility screening does not constitute engineering approval.</p>`}
function wireEmpty(){document.querySelector('[data-action="new-project"]')?.addEventListener('click',()=>projectForm());document.querySelector('[data-action="demo-project"]')?.addEventListener('click',seedDemo)}
function snapshotScenario(p){return {assets:structuredClone(p.assets),technologies:structuredClone(p.technologies),factor:{gwp:Number(p.gwp),horizon:p.gwpHorizon,source:p.gwpSource,version:p.factorVersion},currency:p.currency,priceYear:p.priceYear}}
function cumulativeChart(c,scenarioName='Transition scenario'){
let base=0,scenario=0;
const points=c.annual.map((r,i)=>{base+=r.baseline;scenario+=r.scenario;const x=c.annual.length<2?0:i*880/(c.annual.length-1);return {x,base,scenario,year:r.year}});
const max=Math.max(1,...points.flatMap(q=>[q.base,q.scenario]));const axisWidth=Math.max(34,Math.max(num(max/1000,1).length,num(max/2000,1).length)*6+4);
const y=value=>220-value/max*180;
const path=k=>points.map((q,i)=>`${i?'L':'M'} ${q.x.toFixed(1)} ${y(q[k]).toFixed(1)}`).join(' ');
const ticks=[0,.5,1].map(f=>`<line class="chart-grid" x1="0" x2="880" y1="${220-f*180}" y2="${220-f*180}"/>`).join('');
const years=[points[0],points[Math.floor(points.length/2)],points.at(-1)].filter((q,i,a)=>q&&a.findIndex(x=>x?.year===q.year)===i);
const avoided=c.avoided/1000;
return `<div class="trajectory-summary"><div><span>Baseline total</span><strong>${num(c.baselineTotal/1000)} <small>t CO₂e</small></strong></div><div><span>${esc(scenarioName)} total</span><strong>${num(c.scenarioTotal/1000)} <small>t CO₂e</small></strong></div><div class="trajectory-avoided"><span>${avoided>=0?'Avoided by scenario':'Above baseline'}</span><strong>${num(Math.abs(avoided))} <small>t CO₂e</small></strong></div></div><div class="trajectory-chart"><div class="trajectory-unit">Cumulative emissions · t CO₂e</div><div class="trajectory-plot" style="--trajectory-axis-width:${axisWidth}px"><div class="trajectory-ylabels"><span>${num(max/1000,1)}</span><span>${num(max/2000,1)}</span><span>0</span></div><svg class="chart-svg trajectory-svg" viewBox="0 0 880 270" preserveAspectRatio="none" role="img" aria-label="Cumulative emissions comparison in tonnes of CO₂ equivalent; baseline ${num(c.baselineTotal/1000)} tonnes and scenario ${num(c.scenarioTotal/1000)} tonnes.">${ticks}<path class="chart-series chart-series-baseline" d="${path('base')}"/><path class="chart-series chart-series-scenario" d="${path('scenario')}"/></svg></div><div class="trajectory-xlabels">${years.map(q=>`<span>${esc(q.year)}</span>`).join('')}</div></div><div class="legend trajectory-legend"><span><i></i> Baseline</span><span><i class="b"></i> ${esc(scenarioName)}</span></div>`
}
function annualAvoidedView(c){
const values=c.annual.map(r=>({year:r.year,avoided:r.baseline-r.scenario}));
const max=Math.max(1,...values.map(r=>Math.abs(r.avoided)));
return `<div class="annual-avoided-view" role="group" aria-label="Annual emissions avoided compared with baseline"><div class="annual-avoided-guide"><span>Annual change · baseline minus scenario</span><span>t CO₂e</span></div>${values.map(r=>{const positive=r.avoided>=0,width=Math.abs(r.avoided)/max*50;return `<div class="annual-avoided-row"><span class="annual-avoided-year">${esc(r.year)}</span><div class="annual-avoided-track" aria-hidden="true"><span class="annual-avoided-fill ${positive?'positive':'negative'}" style="${positive?'left':'right'}:50%;width:${width}%"></span></div><span class="annual-avoided-value ${positive?'positive':'negative'}">${r.avoided>0?'+':''}${num(r.avoided/1000,2)}</span></div>`}).join('')}<div class="annual-avoided-legend"><span><i class="positive"></i> Avoided</span><span><i class="negative"></i> Increase</span></div></div>`
}
function dashboard(p){
const s=activeScenario(p), c=calc(p,s), count=p.assets.length, upcoming=p.assets.filter(a=>Number(a.retirementYear)<=p.baseYear+3).length, sites=p.sites.length, reduction=c.baselineAnnual?Math.max(-100,Math.round(c.avoided/c.baselineAnnual*100)):0;
const bars=c.annual.slice(0,Math.min(10,c.annual.length));const max=Math.max(1,...bars.flatMap(r=>[r.baseline,r.scenario]));
return `${pageHead('Transition overview','A portfolio view of SF₆ assets, project timing, and scenario outcomes.',`<button class="btn" data-action="edit-project">Edit project</button><button class="btn primary" data-action="new-asset">+ Add asset</button>`)}${factorNotice(c)}<div class="cards"><div class="metric"><div class="metric-label">SF₆ assets <span class="metric-icon">▤</span></div><div class="metric-value">${count}</div><div class="metric-foot">Across ${sites} ${sites===1?'site':'sites'}</div></div><div class="metric"><div class="metric-label">Annual baseline emissions <span class="metric-icon">⌁</span></div><div class="metric-value">${c.baselineAnnual?num(c.baselineAnnual/1000):'—'} <span style="font:12px var(--sans)">t CO₂e</span></div><div class="metric-foot">Estimated from recorded annual losses</div></div><div class="metric"><div class="metric-label">Scenario reduction <span class="metric-icon">↘</span></div><div class="metric-value">${c.baselineAnnual?`${reduction}%`:'—'}</div><div class="metric-foot">${s?esc(s.name):'Create a scenario to compare'}</div></div><div class="metric"><div class="metric-label">Near-term retirements <span class="metric-icon">◷</span></div><div class="metric-value">${upcoming}</div><div class="metric-foot">Expected by ${p.baseYear+3}</div></div></div><div class="split"><section class="panel"><div class="panel-head"><div><div class="panel-title">Emissions trajectory</div><div class="panel-sub">Baseline vs. scenario · kg CO₂e · ${p.baseYear}–${p.baseYear+p.horizon-1}</div></div></div><div class="panel-body"><div class="bar-chart" role="img" aria-label="Annual baseline and scenario emissions comparison">${bars.map((r,i)=>`<div class="bar-col"><div class="bar" title="Baseline ${num(r.baseline,0)} kg CO₂e" style="height:${Math.max(2,r.baseline/max*100)}%"></div><div class="bar transition" title="Scenario ${num(r.scenario,0)} kg CO₂e" style="height:${Math.max(2,r.scenario/max*100)}%;margin-top:2px"></div><div class="bar-label">${r.year.toString().slice(-2)}</div></div>`).join('')}</div><div class="legend"><span><i></i> Baseline</span><span><i class="b"></i> ${esc(s?.name||'Transition scenario')}</span></div>${c.incomplete.length?`<div class="callout"><strong>Calculation needs attention.</strong> ${esc(c.incomplete.length)} unresolved input${c.incomplete.length===1?'':'s'}: ${esc(c.incomplete.slice(0,2).join('; '))}${c.incomplete.length>2?'…':''}</div>`:''}<p class="disclaimer">Annual loss is treated as a full-year estimate until the year before replacement. In the replacement year, annual leakage is excluded and explicitly modeled end-of-life loss is included. Manufacturing and construction emissions are not included.</p></div></section><section class="panel"><div class="panel-head"><div><div class="panel-title">Priority candidates</div><div class="panel-sub">Ranked by age, emissions, and condition</div></div><button class="btn small panel-shortcut" data-page="roadmap">Full ranking</button></div><div class="panel-body">${p.assets.length?`<div class="portfolio-list">${ranked(p).slice(0,4).map((a,i)=>`<div class="portfolio-row"><div class="portfolio-number">${i+1}</div><div class="portfolio-info"><strong>${esc(a.assetId)} · ${esc(a.category)}</strong><span>${esc(a.site)} · ${Number(a.voltageKv)||'Voltage ?'} kV</span></div><div class="portfolio-value">${num(assetLoss(a,p)*Number(p.gwp)/1000,1)}<small>t CO₂e / yr</small></div></div>`).join('')}</div><div class="callout"><strong>Preliminary screening only.</strong> Ranked candidates require qualified engineering review before any operational decision.</div>`:`<div class="empty" style="padding:26px 12px;border:0"><div class="empty-icon">+</div><h2>Start with your inventory</h2><p>Add an SF₆ asset to see portfolio emissions and replacement candidates.</p><button class="btn primary" data-action="new-asset">Add an asset</button></div>`}</div></section></div><div class="panel" style="margin-top:15px"><div class="panel-head"><div><div class="panel-title">Workspace details</div><div class="panel-sub">Planning assumptions and factor provenance</div></div><button class="btn small panel-shortcut" data-page="settings">Review assumptions</button></div><div class="panel-body"><dl class="workspace-details"><div><dt>Planning horizon</dt><dd>${p.baseYear}–${p.baseYear+p.horizon-1}</dd></div><div><dt>Reporting currency</dt><dd>${p.currency}</dd></div><div><dt>Discount rate</dt><dd>${num(p.discountRate*100)}%</dd></div><div><dt>SF₆ GWP · ${esc(p.gwpHorizon)}</dt><dd>${num(p.gwp,0)}</dd></div><div><dt>Factor source</dt><dd>${esc(p.factorVersion)}</dd></div><div><dt>Calculation version</dt><dd>v${c.version}</dd></div></dl></div></div>`;
}
function assetLoss(a,p){return a.lossMode==='measured'?Number(a.measuredLoss)||0:(Number(a.capacityKg)||0)*(Number(a.lossRate)||0)}
function ranked(p){return [...p.assets].map(a=>{const age=Math.max(0,p.baseYear-Number(a.installYear)), ageScore=Math.min(1,age/40), emission=Math.min(1,assetLoss(a,p)*Number(p.gwp)/100000), condition=({'Poor':1,'Fair':.65,'Good':.3,'Unknown':.5}[a.condition]||.5);const w=p.weights||{age:35,emissions:40,condition:25};return {...a,score:(ageScore*w.age+emission*w.emissions+condition*w.condition)/Math.max(1,w.age+w.emissions+w.condition),annual:assetLoss(a,p)}}).sort((a,b)=>b.score-a.score)}
function inventory(p){const all=p.assets.filter(a=>(filterCategory==='All categories'||a.category===filterCategory)&&(!searchText||`${a.assetId} ${a.site} ${a.category} ${a.manufacturer||''}`.toLowerCase().includes(searchText.toLowerCase())));const incomplete=p.assets.filter(a=>!a.assetId||!a.site||!a.category||!Number.isFinite(Number(a.voltageKv))||!Number.isFinite(Number(a.capacityKg))||!Number.isFinite(Number(a.installYear))||!Number.isFinite(Number(a.retirementYear))||!Number.isFinite(a.lossMode==='measured'?Number(a.measuredLoss):Number(a.lossRate))).length;const mobileRows=all.map(a=>`<article class="inventory-mobile-card"><div class="inventory-mobile-top"><div class="inventory-mobile-identity"><strong>${esc(a.assetId)}</strong><span>${esc(a.site)} · ${esc(a.category)}</span></div><div class="inventory-mobile-rating"><strong>${num(Number(a.voltageKv),0)} kV</strong><span class="badge ${a.condition==='Poor'?'red':a.condition==='Fair'?'orange':'green'}">${esc(a.condition||'Unknown')}</span></div></div><div class="inventory-mobile-stats"><div><small>SF₆ capacity</small><strong>${num(Number(a.capacityKg),1)} kg</strong></div><div><small>Annual loss</small><strong>${a.lossMode==='measured'?`${num(Number(a.measuredLoss),2)} kg`:`${num(Number(a.lossRate)*100,2)}% / yr`}</strong></div><div><small>Installed / retire</small><strong>${a.installYear||'—'} / ${a.retirementYear||'—'}</strong></div></div><div class="inventory-mobile-actions"><button class="row-action" data-action="edit-asset" data-id="${a.id}" aria-label="Edit ${esc(a.assetId)}">Edit</button><button class="row-action delete" data-action="delete-asset" data-id="${a.id}" aria-label="Remove ${esc(a.assetId)}">Remove</button></div></article>`).join('');
return `${pageHead('Asset inventory',`${p.assets.length} equipment records · ${p.sites.length} sites`, `<button class="btn" data-action="import-csv">↑ Import CSV</button><button class="btn" data-action="export-assets">↓ Export CSV</button><button class="btn primary" data-action="new-asset">+ Add asset</button>`)}<div class="toolbar"><input class="search" id="asset-search" type="search" placeholder="Search assets, sites…" value="${esc(searchText)}" aria-label="Search assets"><select id="category-filter" class="select" aria-label="Filter by category"><option>All categories</option>${[...new Set(p.assets.map(a=>a.category))].filter(Boolean).map(c=>`<option ${filterCategory===c?'selected':''}>${esc(c)}</option>`).join('')}</select><span class="table-tools">${all.length} shown${incomplete?` · <span style="color:#ffb879">${incomplete} missing required inputs</span>`:''}</span></div>${all.length?`<section class="panel"><div class="table-wrap inventory-table-wrap"><table class="data-table inventory-table"><thead><tr><th>Asset</th><th>Site / type</th><th><abbr title="Rated voltage in kilovolts">kV</abbr></th><th><abbr title="SF₆ nameplate capacity in kilograms">SF₆ (kg)</abbr></th><th>Loss / year</th><th>Install / retire</th><th>Condition</th><th>Actions</th></tr></thead><tbody>${all.map(a=>`<tr><td><span class="asset-name">${esc(a.assetId)}</span><div class="subcell">${esc(a.manufacturer||'Manufacturer not recorded')}</div></td><td>${esc(a.site)}<div class="subcell">${esc(a.category)}</div></td><td>${num(Number(a.voltageKv),0)} kV<div class="subcell">${esc(a.characteristics||'Ratings not detailed')}</div></td><td>${num(Number(a.capacityKg),1)} kg</td><td>${a.lossMode==='measured'?`${num(Number(a.measuredLoss),2)} kg`:`${num(Number(a.lossRate)*100,2)}% / yr`}<div class="subcell">${a.lossMode==='measured'?'Measured':'Estimated'} · ${esc(a.lossSource||'source not recorded')}</div></td><td>${a.installYear||'—'} / ${a.retirementYear||'—'}</td><td><span class="badge ${a.condition==='Poor'?'red':a.condition==='Fair'?'orange':'green'}">${esc(a.condition||'Unknown')}</span></td><td><div class="asset-actions"><button class="row-action" data-action="edit-asset" data-id="${a.id}" aria-label="Edit ${esc(a.assetId)}">Edit</button><button class="row-action delete" data-action="delete-asset" data-id="${a.id}" aria-label="Remove ${esc(a.assetId)}">Remove</button></div></td></tr>`).join('')}</tbody></table></div><div class="inventory-mobile-list">${mobileRows}</div></section>`:`<div class="empty"><div class="empty-icon">▤</div><h2>${p.assets.length?'No matching assets':'Your inventory is empty'}</h2><p>${p.assets.length?'Try a different search or category filter.':'Add equipment individually or import a CSV inventory. Required data and units are validated before it is saved.'}</p>${p.assets.length?'':`<button class="btn primary" data-action="new-asset">+ Add first asset</button> <button class="btn" data-action="import-csv">Import CSV</button>`}</div>`}<div class="callout"><strong>Input provenance matters.</strong> Measured annual losses and estimated loss rates are tracked separately. Missing values remain unavailable and are flagged before scenario use.</div>`;
}
function technology(p){return `${pageHead('Technology library','Maintain candidate profiles and compare their stated electrical characteristics.',`${p.technologies.length>1?'<button class="btn" data-action="compare-profiles">Compare profiles</button>':''}<button class="btn primary" data-action="new-tech">+ Add profile</button>`)}<div class="notice" style="margin-bottom:15px"><strong>Screening boundary.</strong> These user-maintained profiles support preliminary comparison only. A match does not certify compatibility or replace manufacturer documentation and qualified engineering review.</div>${p.technologies.length?`<div class="tech-grid">${p.technologies.map(t=>`<article class="tech-card"><div style="display:flex;justify-content:space-between;gap:8px"><h3>${esc(t.name)}</h3><span class="badge orange">${esc(t.status==='Engineering reviewed'?'Legacy engineering-review label · verify':t.status||'Unverified')}</span></div><p>${esc(t.description||'No profile notes recorded.')}</p><div class="tech-meta"><div><span>Insulation</span><br><strong>${esc(t.insulation||'Not recorded')}</strong></div><div><span>Gas composition</span><br><strong>${esc(t.gasComposition||'Not recorded')}</strong></div><div><span>Voltage class</span><br><strong>${esc(t.voltageClass||'Not recorded')}</strong></div><div><span>Rated voltage</span><br><strong>${t.voltageKv?`${num(Number(t.voltageKv),0)} kV`:'Not recorded'}</strong></div><div><span>Interrupting rating</span><br><strong>${esc(t.interrupting||'Not recorded')}</strong></div><div><span>Alt. emissions</span><br><strong>${t.altAnnualCO2e?`${num(Number(t.altAnnualCO2e),1)} kg CO₂e/yr`:'Unavailable'}</strong></div></div><p><strong>Source:</strong> ${esc(t.source||'No reference supplied')}</p><div style="display:flex;gap:7px"><button class="btn small" data-action="edit-tech" data-id="${t.id}">Edit</button><button class="btn small" data-action="compare-tech" data-id="${t.id}">Compare with asset</button><button class="btn small" data-action="delete-tech" data-id="${t.id}">Remove</button></div></article>`).join('')}</div>`:`<div class="empty"><div class="empty-icon">⌘</div><h2>No technology profiles yet</h2><p>Add user-maintained alternatives with insulation type, voltage ratings, gas composition, and source references. Missing specifications stay visible.</p><button class="btn primary" data-action="new-tech">+ Create technology profile</button></div>`}`}
function scenarios(p){return `${pageHead('Scenarios','Compare continue-operation and phased replacement plans against the same inventory.',`<div class="scenario-head-actions"><button class="btn primary" data-action="new-scenario">+ New scenario</button><button class="btn" data-page="reports">Emissions & lifecycle costs ↗</button></div>`)}${p.scenarios.length?`<div class="scenario-grid">${p.scenarios.map(s=>{const c=calc(p,s);const isActive=s.id===p.activeScenarioId;const replacements=Object.keys(s.replacements||{}).length;return `<article class="scenario-card"><div class="scenario-card-head"><h3>${esc(s.name)}</h3>${isActive?'<span class="badge blue">Selected</span>':''}${c.factorReviewRequired?'<span class="badge orange">Review factor</span>':''}${c.legacyCostReviewRequired?'<span class="badge orange">Review costs</span>':''}</div><p>${esc(s.description||'No description recorded')} · ${esc(s.mode||'Phased transition')}</p><div class="scenario-stats"><div><span>Assets replaced</span><strong>${replacements}</strong></div><div><span>NPC</span><strong>${money(c.npc,c.currency)}</strong></div><div><span>CO₂e avoided</span><strong>${c.incomplete.length?'Partial':`${num(c.avoided/1000)} t`}</strong></div></div><div class="scenario-footer"><span>Budget ${Number(s.budget)>0?money(Number(s.budget),p.currency)+'/yr':'not set'} · Calc v${c.version}</span><div style="display:flex;gap:6px"><button class="btn small" data-action="select-scenario" data-id="${s.id}">${isActive?'Selected':'Select'}</button><button class="btn small" data-action="edit-scenario" data-id="${s.id}">Edit</button><button class="btn small" data-action="duplicate-scenario" data-id="${s.id}">Duplicate</button><button class="btn small danger" data-action="delete-scenario" data-id="${s.id}">Delete</button></div></div></article>`}).join('')}</div>`:`<div class="empty"><div class="empty-icon">◷</div><h2>Build your first transition scenario</h2><p>Assign candidate technologies and replacement years, set an annual capital budget, then compare costs and modeled emissions with continued operation.</p><button class="btn primary" data-action="new-scenario">+ Create scenario</button></div>`}<div class="callout scenario-repro"><strong>Reproducibility.</strong> Scenarios retain a snapshot of project assumptions and calculation version ${CALC_VERSION}. Updating shared assumptions will not overwrite saved scenario factors.</div>`}
function roadmap(p){const s=activeScenario(p), c=calc(p,s), rankedAssets=ranked(p),mobileRanking=rankedAssets.map((a,i)=>{const linked=s?.replacements?.[a.id],tech=p.technologies.find(t=>t.id===linked?.technologyId),missing=!a.voltageKv||!a.characteristics||!tech?.voltageKv;return `<article class="ranking-mobile-card"><div class="ranking-mobile-main"><div class="ranking-mobile-identity"><span class="ranking-mobile-position">${i+1}</span><div><strong>${esc(a.assetId)}</strong><small>${esc(a.site)} · ${esc(a.category)}</small></div></div><div class="ranking-mobile-score"><strong>${num(a.score*100,0)}</strong><small>Score</small></div></div><div class="ranking-mobile-meta"><div><small>Retire</small><strong>${a.retirementYear||'Unknown'}</strong></div><div><small>Emissions</small><strong>${num(a.annual*Number(p.gwp)/1000,1)} t/yr</strong></div><div><small>Condition</small><strong>${esc(a.condition||'Unknown')}</strong></div><div><small>Screening</small><span class="badge ${missing?'orange':'green'}">${missing?'Review':'Linked'}</span></div></div></article>`}).join('');return `${pageHead('Prioritization & roadmap','Transparent candidate ranking with editable weights and a year-by-year capital view.',`<button class="btn" data-action="export-results">↓ Export roadmap CSV</button>`)}${factorNotice(c)}<div class="split"><section class="panel"><div class="panel-head"><div><div class="panel-title">Candidate ranking</div><div class="panel-sub">Weighted score uses asset age, annual emissions, and condition</div></div><button class="btn small" data-action="weights">Adjust weights</button></div>${rankedAssets.length?`<div class="table-wrap candidate-ranking-table"><table class="data-table"><thead><tr><th>Rank / asset</th><th>Score</th><th>Retirement</th><th>Emissions</th><th>Condition</th><th>Screening</th></tr></thead><tbody>${rankedAssets.map((a,i)=>{const linked=s?.replacements?.[a.id],tech=p.technologies.find(t=>t.id===linked?.technologyId);const missing=!a.voltageKv||!a.characteristics||!tech?.voltageKv;return `<tr><td><strong>${i+1}. ${esc(a.assetId)}</strong><div class="subcell">${esc(a.site)} · ${esc(a.category)}</div></td><td>${num(a.score*100,0)}</td><td>${a.retirementYear||'Unknown'}</td><td>${num(a.annual*Number(p.gwp)/1000,1)} t/yr</td><td>${esc(a.condition||'Unknown')}</td><td><span class="badge ${missing?'orange':'green'}">${missing?'Review required':'Profile linked'}</span></td></tr>`}).join('')}</tbody></table></div><div class="ranking-mobile-list">${mobileRanking}</div>`:`<div class="empty" style="border:0"><p>Add assets to rank candidates.</p></div>`}<div class="panel-body disclaimer">Weights: age ${p.weights.age}% · emissions ${p.weights.emissions}% · condition ${p.weights.condition}%. Scores sort candidates for review; they are not technology approvals.</div></section><section class="panel"><div class="panel-head"><div><div class="panel-title">Annual replacement budget</div><div class="panel-sub">${esc(s?.name||'No scenario selected')} · annual capital expenditure in ${p.currency}</div></div></div><div class="panel-body">${s?c.costsByYear.map(r=>`<div style="margin-bottom:15px"><div style="display:flex;justify-content:space-between;font-size:11px"><strong>${r.year}${r.over?' · Over budget':''}</strong><span>${money(r.cost,p.currency)}${r.budget?` / ${money(r.budget,p.currency)}`:''}</span></div>${r.budget?`<div class="budget-track"><div class="budget-fill ${r.over?'over':''}" style="width:${Math.min(100,r.cost/r.budget*100)}%"></div></div>`:''}</div>`).join(''):`<p class="disclaimer">Create a scenario to see planned capital expenditure against the annual budget.</p>`}${s&&c.costsByYear.some(r=>r.over)?'<div class="callout"><strong>Budget exceedance.</strong> One or more annual plans exceed the scenario budget. Adjust asset timing in scenario settings.</div>':''}</div></section></div><section class="panel" style="margin-top:15px"><div class="panel-head"><div><div class="panel-title">Replacement roadmap</div><div class="panel-sub">Selected scenario assignments</div></div><button class="btn small" data-action="edit-scenario">Edit schedule</button></div><div class="panel-body">${s?roadmapTimeline(p,s):'<p class="disclaimer">Create a scenario to assign replacement projects to years.</p>'}</div></section>`}
function roadmapTimeline(p,s){const entries=Object.entries(s.replacements||{}).map(([assetId,plan])=>({a:p.assets.find(a=>a.id===assetId),...plan})).filter(x=>x.a).sort((a,b)=>a.year-b.year);if(!entries.length)return '<p class="disclaimer">No replacements assigned. Edit the scenario to schedule selected assets.</p>';return `<div class="roadmap">${[...new Set(entries.map(e=>e.year))].map(y=>`<div class="roadmap-year"><h3>${y}</h3>${entries.filter(e=>e.year===y).map(e=>`<div class="roadmap-item"><span><strong>${esc(e.a.assetId)}</strong> · ${esc(e.a.site)} · ${esc(p.technologies.find(t=>t.id===e.technologyId)?.name||'Technology not selected')}</span><span class="roadmap-cost">${money((Number(e.a.capex)||0)+(Number(e.a.installCost)||0)+(Number(e.a.decommissionCost)||0)+(Number(e.a.recoveryCost)||0),p.currency)}</span></div>`).join('')}</div>`).join('')}</div>`}
function reports(p){const s=activeScenario(p),c=calc(p,s);return `${pageHead('Reports & assumptions','Review calculation inputs, emissions and cost comparisons, then export a reproducible planning record.',`<button class="btn" data-action="print">▧ Print report</button><button class="btn" data-action="export-results">↓ Scenario CSV</button><button class="btn primary" data-action="backup">↓ JSON backup</button>`)}<div class="toolbar"><label for="report-scenario" class="disclaimer">Scenario</label><select class="select" id="report-scenario">${p.scenarios.map(x=>`<option value="${x.id}" ${x.id===s?.id?'selected':''}>${esc(x.name)}</option>`).join('')}</select><span class="table-tools">Calculation v${c.version} · Factor ${esc(c.factor.version)}</span></div>${factorNotice(c)}${s?`<div class="cards report-metrics"><div class="metric"><div class="metric-label">Baseline emissions</div><div class="metric-value">${num(c.baselineTotal/1000)} <span style="font:12px var(--sans)">t CO₂e</span></div><div class="metric-foot">Cumulative · ${p.horizon} years</div></div><div class="metric"><div class="metric-label">Scenario emissions</div><div class="metric-value">${num(c.scenarioTotal/1000)} <span style="font:12px var(--sans)">t CO₂e</span></div><div class="metric-foot">Cumulative · ${p.horizon} years</div></div><div class="metric"><div class="metric-label">Avoided vs. baseline</div><div class="metric-value">${num(c.avoided/1000)} <span style="font:12px var(--sans)">t CO₂e</span></div><div class="metric-foot">Negative values indicate an increase</div></div><div class="metric"><div class="metric-label">Lifecycle NPC</div><div class="metric-value" style="font-size:22px">${money(c.npc,c.currency)}</div><div class="metric-foot">Incremental vs. continued operation</div></div></div><section class="panel trajectory-panel"><div class="panel-head"><div><div class="panel-title">Cumulative emissions trajectory</div><div class="panel-sub">See how the selected plan changes total emissions over ${p.horizon} years</div></div></div><div class="panel-body">${cumulativeChart(c,s.name)}</div></section><div class="report-grid"><section class="panel"><div class="panel-head"><div><div class="panel-title">Annual emissions comparison</div><div class="panel-sub">Annual comparison · baseline and scenario emissions</div></div></div><div class="annual-view-switch" role="group" aria-label="Annual emissions view"><button type="button" class="annual-view-tab active" aria-pressed="true" aria-controls="annual-panel-chart" data-annual-view="chart">Avoided emissions</button><button type="button" class="annual-view-tab" aria-pressed="false" aria-controls="annual-panel-table" data-annual-view="table">Annual values</button></div><div id="annual-panel-chart" class="annual-view-panel" role="region" aria-label="Avoided emissions chart" data-annual-panel="chart">${annualAvoidedView(c)}</div><div id="annual-panel-table" class="annual-view-panel" role="region" aria-label="Annual emissions values" data-annual-panel="table" hidden><div class="table-wrap"><table class="data-table"><thead><tr><th>Year</th><th>Baseline</th><th>Scenario</th><th>Avoided / (increase)</th></tr></thead><tbody>${c.annual.map(r=>`<tr><td>${esc(r.year)}</td><td>${num(r.baseline,1)} kg</td><td>${num(r.scenario,1)} kg</td><td>${num(r.baseline-r.scenario,1)} kg</td></tr>`).join('')}</tbody></table></div></div></section><section class="panel"><div class="panel-head"><div><div class="panel-title">Lifecycle cost summary</div><div class="panel-sub">User-entered estimates and calculated values · ${c.currency} ${esc(c.priceYear)}</div></div></div><div class="panel-body"><div class="setting-row"><div><strong>Net present cost</strong><p>Discount rate ${num(p.discountRate*100)}%</p></div><strong>${money(c.npc,c.currency)}</strong></div><div class="setting-row"><div><strong>Incremental NPC</strong><p>Compared with continued-operation baseline</p></div><strong>${money(c.incrementalNpc,c.currency)}</strong></div><div class="setting-row"><div><strong>Baseline NPC</strong><p>Continued operation using recorded asset costs</p></div><strong>${money(c.baselineNpc,c.currency)}</strong></div><div class="setting-row"><div><strong>Cost per tonne avoided</strong><p>Only available when cumulative avoided emissions are positive</p></div><strong>${c.costPerTonne===null?'Unavailable':money(c.costPerTonne,c.currency)}</strong></div><div class="setting-row"><div><strong>Undiscounted scenario cost</strong><p>Capital, installation, recovery, operating, and maintenance</p></div><strong>${money(c.annual.reduce((sum,r)=>sum+r.cost,0),c.currency)}</strong></div><p class="disclaimer">Baseline NPC includes the recorded annual operating and maintenance costs for continuing assets. Replacement scenario NPC uses the technology profile operating and maintenance costs after replacement.</p></div></section></div><section class="panel" style="margin-top:15px"><div class="panel-head"><div><div class="panel-title">Assumption register</div><div class="panel-sub">Inputs, sources, scope, and unresolved data</div></div><button class="btn small" data-page="settings">Edit assumptions ↗</button></div><div class="panel-body"><div class="setting-row"><div><strong>SF₆ GWP factor</strong><p>${esc(c.factor.source)} · ${esc(c.factor.horizon)} horizon · reference ${esc(c.factor.version)}</p></div><strong>${num(c.factor.gwp,0)}</strong></div><div class="setting-row"><div><strong>Loss methodology</strong><p>Measured annual loss or capacity × estimated annual loss rate, per asset</p></div><strong>Mixed provenance</strong></div><div class="setting-row"><div><strong>Replacement year convention</strong><p>Full year leakage before replacement; replacement year uses remaining gas × (1 − recovery efficiency)</p></div><strong>v${c.version}</strong></div><div class="setting-row"><div><strong>Manufacturing emissions</strong><p>Excluded; results do not represent complete lifecycle climate impact</p></div><strong>Out of scope</strong></div>${c.incomplete.length?`<div class="callout"><strong>Incomplete inputs (${c.incomplete.length}).</strong> ${c.incomplete.map(esc).join(' · ')}</div>`:'<div class="callout"><strong>Inputs available for this calculation.</strong> Review provenance and engineering assumptions before relying on the scenario.</div>'}<p class="disclaimer" style="margin-top:14px">Planning estimates only. No emissions result represents measured leakage unless the source asset input was recorded as measured. Factors and reporting requirements vary by jurisdiction; this tool does not certify regulatory compliance or equipment compatibility.</p></div></section>`:`<div class="empty"><div class="empty-icon">▧</div><h2>Create a scenario report</h2><p>Once you create a scenario, this page will show emissions, lifecycle costs, assumptions, and export actions.</p><button class="btn primary" data-action="new-scenario">+ Create scenario</button></div>`}`}
function settings(p){return `${pageHead('Settings & data','Manage project assumptions, sites, local storage, and portable backups.',`<button class="btn" data-action="edit-project">Edit project details</button><button class="btn primary" data-action="new-site">+ Add site</button>`)}<div class="split"><section class="panel"><div class="panel-head"><div><div class="panel-title">Planning assumptions</div><div class="panel-sub">Scenario snapshots preserve the factor values and calculation version in use</div></div><button class="btn small" data-action="edit-assumptions">Edit</button></div><div class="panel-body"><div class="setting-row"><div><strong>Base year & horizon</strong><p>${p.baseYear} · ${p.horizon} years (${p.baseYear}–${p.baseYear+p.horizon-1})</p></div></div><div class="setting-row"><div><strong>Currency & price year</strong><p>${esc(p.currency)} · ${p.priceYear}</p></div></div><div class="setting-row"><div><strong>Discount rate</strong><p>${num(p.discountRate*100)}% annual</p></div></div><div class="setting-row"><div><strong>SF₆ factor</strong><p>${num(p.gwp,0)} GWP · ${esc(p.gwpHorizon)} · ${esc(p.factorVersion)}</p></div></div><div class="setting-row"><div><strong>Factor source</strong><p>${esc(p.gwpSource)}${p.gwpSource===FACTOR.source?` · <a href="https://www.ipcc.ch/report/ar6/wg1/downloads/report/IPCC_AR6_WGI_Chapter07_SM.pdf" target="_blank" rel="noreferrer">Open IPCC AR6 table ↗</a>`:''}</p></div></div></div></section><section class="panel"><div class="panel-head"><div><div class="panel-title">Sites</div><div class="panel-sub">${p.sites.length} locations in this project</div></div><button class="btn small" data-action="new-site">+ Add</button></div><div class="panel-body">${p.sites.length?p.sites.map(s=>`<div class="setting-row"><div><strong>${esc(s.name)}</strong><p>${esc(s.region||'Region not recorded')} · ${p.assets.filter(a=>a.site===s.name).length} assets ${s.notes?`· ${esc(s.notes)}`:''}</p></div><div style="display:flex;gap:4px"><button class="row-action" data-action="edit-site" data-id="${s.id}">Edit</button><button class="row-action delete" data-action="delete-site" data-id="${s.id}">Remove</button></div></div>`).join(''):'<p class="disclaimer">No sites yet. Add sites to organize your inventory.</p>'}</div></section></div><section class="panel" style="margin-top:15px"><div class="panel-head"><div><div class="panel-title">Local data controls</div><div class="panel-sub">This browser is the authoritative workspace. There is no cloud sync.</div></div></div><div class="panel-body"><div class="setting-row"><div><strong>App version</strong><p>Gridshift ${APP_VERSION} · calculation ${CALC_VERSION}</p></div></div><div class="setting-row"><div><strong>Install this app</strong><p>Use an install prompt when supported, or follow your browser’s Add to Home Screen option.</p></div><button class="btn" data-action="install-app">Install guidance</button></div><div class="setting-row"><div><strong>Check reference updates</strong><p>No live factor feed is configured; review your source and version when policy changes.</p></div><button class="btn" data-action="reference-check">Review reference status</button></div><div class="setting-row"><div><strong>Export full backup</strong><p>Versioned JSON with projects, sites, assets, profiles, and scenarios. Store it somewhere safe.</p></div><button class="btn" data-action="backup">Download JSON</button></div><div class="setting-row"><div><strong>Restore from backup</strong><p>Validates the file before changing anything. Existing project IDs prompt for cancel, replace, or separate copy.</p></div><button class="btn" data-action="restore">Import JSON</button></div><div class="setting-row"><div><strong>Storage status</strong><p id="storage-status">Checking browser storage usage…</p></div><button class="btn" data-action="storage-check">Refresh</button></div><div class="setting-row"><div><strong>Delete all local projects</strong><p>Deletes every project saved by this planner from this browser. This cannot be undone.</p></div><button class="btn danger" data-action="delete-all">Delete all data</button></div><p class="disclaimer">Browser-local storage is convenient for offline planning, but it does not provide enterprise access control or encryption. Shared devices and browser storage eviction can expose or remove project data. Browser extensions with permission to access this site may inspect or change site data or displayed records. The planned GitHub Pages URL is on boredpolymath.github.io; any other page on that exact host shares this storage origin and can read, change, or delete Gridshift data if opened in this profile. Do not store confidential utility records there unless every publisher on the host is trusted; a dedicated hostname is required for isolation. Downloaded JSON backups contain readable project data, are not encrypted by Gridshift, and must be protected or deleted separately. See README for more information.</p></div></section>`}
function wirePage(){document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>{page=b.dataset.page;render()});document.querySelectorAll('[data-action]').forEach(b=>b.addEventListener('click',()=>action(b.dataset.action,b.dataset.id)));const search=document.querySelector('#asset-search');if(search)search.oninput=()=>{searchText=search.value;const pos=search.selectionStart;renderPage();const n=document.querySelector('#asset-search');n.focus();n.setSelectionRange(pos,pos);wirePage()};const filter=document.querySelector('#category-filter');if(filter)filter.onchange=()=>{filterCategory=filter.value;renderPage();wirePage()};document.querySelector('#report-scenario')?.addEventListener('change',e=>{const p=current();p.activeScenarioId=e.target.value;save();renderPage();wirePage()});document.querySelectorAll('[data-annual-view]').forEach(tab=>tab.addEventListener('click',()=>{const mode=tab.dataset.annualView,panel=tab.closest('.panel');panel.querySelectorAll('[data-annual-view]').forEach(button=>{const active=button.dataset.annualView===mode;button.classList.toggle('active',active);button.setAttribute('aria-pressed',String(active))});panel.querySelectorAll('[data-annual-panel]').forEach(view=>{view.hidden=view.dataset.annualPanel!==mode})}));if(page==='settings')storageEstimate();}
function action(type,id){const p=current();switch(type){case'mobile-menu':return mobileMenu();case'new-project':return projectForm();case'demo-project':return seedDemo();case'edit-project':return projectForm(p);case'new-asset':return assetForm();case'edit-asset':return assetForm(p.assets.find(a=>a.id===id));case'delete-site':{const site=p.sites.find(x=>x.id===id);return confirmDialog('Remove site?',`Assets at ${site.name} will be moved to Unassigned. This site’s notes will be deleted.`,()=>{p.assets.forEach(a=>{if(a.site===site.name)a.site='Unassigned'});p.sites=p.sites.filter(x=>x.id!==id);save('Site removed');render()})}case'delete-scenario':return confirmDialog('Delete scenario?','This permanently removes this scenario and its saved assumptions. Other scenarios and project data remain.',()=>{p.scenarios=p.scenarios.filter(x=>x.id!==id);if(p.activeScenarioId===id)p.activeScenarioId=p.scenarios[0]?.id||null;save('Scenario deleted');render()});case'delete-asset':return confirmDialog('Delete asset?','This removes the equipment record and its scenario assignments.',()=>{p.assets=p.assets.filter(a=>a.id!==id);p.scenarios.forEach(s=>delete s.replacements[id]);save('Asset deleted');render()});case'import-csv':return csvPicker();case'export-assets':return exportAssets(p);case'new-tech':return techForm();case'edit-tech':return techForm(p.technologies.find(t=>t.id===id));case'delete-tech':return confirmDialog('Remove technology profile?','Existing scenario assignments will remain but show the missing profile.',()=>{p.technologies=p.technologies.filter(t=>t.id!==id);save('Profile removed');render()});case'compare-tech':return compareTech(id);case'compare-profiles':return compareProfiles();case'install-app':return installApp();case'reference-check':return referenceCheck();case'new-scenario':return scenarioForm();case'edit-scenario':return scenarioForm(p.scenarios.find(x=>x.id===id)||activeScenario(p));case'duplicate-scenario':return duplicateScenario(id);case'select-scenario':p.activeScenarioId=id;save('Scenario selected');render();return;case'weights':return weightsForm();case'new-site':return siteForm();case'edit-site':return siteForm(p.sites.find(s=>s.id===id));case'edit-assumptions':return assumptionsForm();case'backup':return backup();case'restore':return restorePicker();case'delete-all':return confirmDialog('Delete all local data?','All projects, assets, profiles, and scenarios in this browser will be permanently deleted.',()=>{try{localStorage.removeItem(KEY);state=blankState();page='dashboard';render();toast('All local project data deleted')}catch{toast('Browser storage could not be cleared.',true)}});case'export-results':return exportResults(p);case'print':return window.print();case'storage-check':return storageEstimate(true);}}
function mobileMenu(){showDialog('Workspace options','Project switching and data tools are available here on small screens.',`<div class="mobile-menu-actions"><button class="btn" id="mobile-projects">Switch or manage projects</button><button class="btn" id="mobile-settings">Settings & data</button><button class="btn" id="mobile-install">Install app</button><button class="btn" id="mobile-backup">Download full backup</button><button class="btn" id="mobile-restore">Restore from backup</button></div>`);dialog.querySelector('#mobile-projects').onclick=()=>{closeDialog();projectMenu()};dialog.querySelector('#mobile-settings').onclick=()=>{closeDialog();page='settings';render()};dialog.querySelector('#mobile-install').onclick=installApp;dialog.querySelector('#mobile-backup').onclick=backup;dialog.querySelector('#mobile-restore').onclick=restorePicker}
function projectMenu(){const options=state.projects.map(p=>`<button class="nav-link ${p.id===state.activeProjectId?'active':''}" data-project-id="${p.id}">▧ ${esc(p.name)}</button>`).join('');showDialog('Project workspace','Switch projects, create a workspace, or duplicate an existing plan.',`<div>${options||'<p class="disclaimer">No project exists yet.</p>'}</div><div style="display:flex;gap:8px;margin-top:13px;flex-wrap:wrap"><button class="btn primary" id="dialog-new-project">+ New project</button>${current()?'<button class="btn" id="dialog-duplicate-project">Duplicate project</button><button class="btn danger" id="dialog-delete-project">Delete project</button>':''}</div>`);dialog.querySelectorAll('[data-project-id]').forEach(b=>b.onclick=()=>{state.activeProjectId=b.dataset.projectId;page='dashboard';save('Project opened');closeDialog();render()});dialog.querySelector('#dialog-new-project').onclick=()=>{closeDialog();projectForm()};dialog.querySelector('#dialog-duplicate-project')?.addEventListener('click',()=>duplicateProject());dialog.querySelector('#dialog-delete-project')?.addEventListener('click',()=>deleteProject());}
function showDialog(title,sub,body){dialogOpener=document.activeElement;dialog.innerHTML=`<div class="dialog-head"><div><h2 id="dialog-title">${esc(title)}</h2><p>${esc(sub||'')}</p></div><button class="close" aria-label="Close dialog">×</button></div><div class="dialog-body">${body}</div>`;dialog.querySelector('.close').onclick=closeDialog;dialog.showModal()}
function closeDialog(){if(dialog.open)dialog.close()}
function showRecoveryDialog(){showDialog('Local workspace needs recovery','Gridshift found data it cannot read. Keep a copy before clearing it; this file may need manual repair and is not a validated Gridshift backup.',`<p class="disclaimer">Project data remains in this browser until you choose to clear it. Do not close this page before downloading the recovery copy.</p><div class="form-actions"><button class="btn primary" id="download-recovery">Download recovery copy</button><button class="btn danger" id="reset-recovery">Clear damaged local data</button></div>`);dialog.querySelector('#download-recovery').onclick=()=>{download(`gridshift-local-recovery-${new Date().toISOString().slice(0,10)}.json`,storageCorruptRaw||'','application/json');toast('Recovery copy downloaded')};dialog.querySelector('#reset-recovery').onclick=()=>{closeDialog();confirmDialog('Clear damaged local data?','This deletes the unreadable workspace from this browser. Download a recovery copy first if you may need it.',()=>{try{localStorage.removeItem(KEY);storageCorruptRaw=null;state=blankState();page='dashboard';render();toast('Damaged local data cleared')}catch{toast('Browser storage could not be cleared. Your recovery copy remains available.',true)}})}}
function confirmDialog(title,text,fn){showDialog(title,text,`<div class="form-actions" style="margin-top:0"><button class="btn" id="cancel">Cancel</button><button class="btn danger" id="confirm">Confirm</button></div>`);dialog.querySelector('#cancel').onclick=closeDialog;dialog.querySelector('#confirm').onclick=()=>{closeDialog();fn()}}
function form(title,sub,fields,submitLabel,handler){showDialog(title,sub,`<form id="form"><div class="form-grid">${fields}</div><div class="form-actions"><button class="btn" type="button" id="cancel-form">Cancel</button><button class="btn primary" type="submit">${submitLabel}</button></div></form>`);dialog.querySelector('#cancel-form').onclick=closeDialog;dialog.querySelector('#form').onsubmit=e=>{e.preventDefault();const fd=new FormData(e.currentTarget),data=Object.fromEntries(fd.entries());const invalid=e.currentTarget.querySelector(':invalid');if(invalid){invalid.focus();invalid.reportValidity();return}try{handler(data,e.currentTarget)}catch(err){toast(err.message||'Could not save changes',true)}};return dialog.querySelector('#form')}
function field(label,name,value='',type='text',opts={}){const req=opts.required?'required':'';const min=opts.min!==undefined?`min="${opts.min}"`:'';const max=opts.max!==undefined?`max="${opts.max}"`:'';const step=opts.step?`step="${opts.step}"`:'';const hint=opts.hint?`<small>${esc(opts.hint)}</small>`:'';const cls=opts.full?'full':'';if(opts.options)return `<div class="field ${cls}"><label for="${name}">${label}</label><select id="${name}" name="${name}" ${req}>${opts.options.map(v=>`<option value="${esc(v)}" ${String(value)===String(v)?'selected':''}>${esc(v)}</option>`).join('')}</select>${hint}</div>`;if(type==='textarea')return `<div class="field ${cls}"><label for="${name}">${label}</label><textarea id="${name}" name="${name}" ${req} placeholder="${esc(opts.placeholder||'')}">${esc(value)}</textarea>${hint}</div>`;return `<div class="field ${cls}"><label for="${name}">${label}</label><input id="${name}" name="${name}" type="${type}" value="${esc(value)}" ${req} ${min} ${max} ${step} ${opts.placeholder?`placeholder="${esc(opts.placeholder)}"`:''}>${hint}</div>`}
function projectForm(existing){const p=existing||{};form(existing?'Project settings':'Create a transition project','Set the planning context and reporting conventions.',field('Project name','name',p.name||'','text',{required:true,full:true,placeholder:'e.g. North network SF₆ transition'})+field('Description','description',p.description||'','textarea',{full:true})+field('Base year','baseYear',p.baseYear||yearNow,'number',{required:true,min:2000,max:2200})+field('Planning horizon (years)','horizon',p.horizon||10,'number',{required:true,min:1,max:50})+field('Reporting currency','currency',p.currency||'USD','text',{required:true,hint:'ISO 4217 currency code, e.g. USD, EUR, GBP'})+field('Price year','priceYear',p.priceYear||yearNow,'number',{required:true,min:2000,max:2200}),existing?'Save project':'Create project',d=>{const base=mkProject(d.name,d.description,d.horizon);if(!/^[A-Za-z]{3}$/.test(d.currency))throw Error('Enter a three-letter currency code such as USD.');if(existing){Object.assign(existing,{name:d.name,description:d.description,baseYear:Number(d.baseYear),horizon:Number(d.horizon),currency:d.currency.toUpperCase(),priceYear:Number(d.priceYear)});}else{Object.assign(base,{baseYear:Number(d.baseYear),currency:d.currency.toUpperCase(),priceYear:Number(d.priceYear)});state.projects.push(base);state.activeProjectId=base.id;page='dashboard'}save(existing?'Project updated':'Project created');closeDialog();render()})}
function deleteProject(){const p=current();closeDialog();confirmDialog('Delete project?','This permanently deletes this project and all of its sites, assets, profiles, and scenarios.',()=>{state.projects=state.projects.filter(x=>x.id!==p.id);state.activeProjectId=state.projects[0]?.id||null;page='dashboard';save('Project deleted');render()})}
function duplicateProject(){const p=current();const copy=structuredClone(p);copy.id=uid();copy.name=`${p.name} (copy)`;copy.createdAt=new Date().toISOString();copy.assets.forEach(a=>{const old=a.id;a.id=uid();copy.scenarios.forEach(s=>{if(s.replacements[old])s.replacements[a.id]=s.replacements[old];delete s.replacements[old]})});copy.technologies.forEach(t=>t.id=uid());copy.scenarios.forEach(s=>{s.id=uid();s.technologies=undefined;s.replacements=Object.fromEntries(Object.entries(s.replacements).map(([aid,r])=>[aid,{...r,technologyId:copy.technologies.find(t=>t.name===p.technologies.find(x=>x.id===r.technologyId)?.name)?.id||r.technologyId}])) ;s.inputSnapshot=snapshotScenario(copy)});copy.sites.forEach(x=>x.id=uid());state.projects.push(copy);state.activeProjectId=copy.id;page='dashboard';save('Project duplicated');closeDialog();render()}
function assetForm(existing){
const p=current(),a=existing||{};
const siteOptions=[...new Set([...p.sites.map(s=>s.name),...p.assets.map(x=>x.site)])];
if(!siteOptions.length)siteOptions.push('Unassigned');
const lossMode=a.lossMode||'estimated';
const basics=`${field('Asset identifier','assetId',a.assetId||'','text',{required:true,placeholder:'e.g. CB-104'})}${field('Site','site',a.site||siteOptions[0],'text',{required:true,hint:'Add/manage sites in Settings.'})}${field('Equipment category','category',a.category||'Circuit breaker','select',{required:true,options:['Circuit breaker','Gas-insulated switchgear','Instrument transformer','Gas-insulated line','Other']})}${field('Rated voltage (kV)','voltageKv',a.voltageKv??'','number',{required:true,min:0,max:2000,step:'any'})}${field('SF₆ nameplate capacity (kg)','capacityKg',a.capacityKg??'','number',{required:true,min:0,step:'any'})}${field('Installation year','installYear',a.installYear??'','number',{required:true,min:1900,max:2200})}${field('Expected retirement year','retirementYear',a.retirementYear??'','number',{required:true,min:1900,max:2300})}`;
const lossFields=`${field('Annual loss input type','lossMode',lossMode,'select',{options:['estimated','measured']})}${field('Estimated annual loss rate (fraction/year)','lossRate',a.lossRate??'','number',{min:0,max:1,step:'any',hint:'A value of 0.01 means 1% per year.'})}${field('Measured annual loss (kg/year)','measuredLoss',a.measuredLoss??'','number',{min:0,step:'any',hint:'Enter the recorded annual mass loss.'})}${field('Loss source / provenance','lossSource',a.lossSource||'','text',{full:true,placeholder:'Metered record, maintenance log, engineering estimate…'})}`;
const technical=`${field('Manufacturer / model','manufacturer',a.manufacturer||'')}${field('Electrical characteristics','characteristics',a.characteristics||'','text',{placeholder:'e.g. 50 kA interrupting, 60 Hz',full:true})}${field('Asset condition','condition',a.condition||'Unknown','select',{options:['Unknown','Good','Fair','Poor']})}${field('Maintenance notes','maintenanceNotes',a.maintenanceNotes||'','textarea',{full:true})}${field('Custom attributes (JSON)','customAttributesText',a.customAttributes?JSON.stringify(a.customAttributes,null,2):'','textarea',{full:true,hint:'Optional equipment-specific fields as a JSON object.'})}`;
const costs=`${field('Estimated remaining gas at end-of-life (kg)','remainingGasKg',a.remainingGasKg??'','number',{min:0,step:'any',hint:'Used for end-of-life emissions when the asset is replaced.'})}${field('SF₆ recovery efficiency (fraction)','recoveryEfficiency',a.recoveryEfficiency??'','number',{min:0,max:1,step:'any',hint:'Enter a value from 0 to 1.'})}${field('Annual operating cost','annualOpex',a.annualOpex??'','number',{min:0,step:'any'})}${field('Annual maintenance cost','annualMaintenance',a.annualMaintenance??'','number',{min:0,step:'any'})}${field('Replacement equipment capital cost','capex',a.capex??'','number',{min:0,step:'any'})}${field('Installation & commissioning cost','installCost',a.installCost??'','number',{min:0,step:'any'})}${field('Decommissioning cost','decommissionCost',a.decommissionCost??'','number',{min:0,step:'any'})}${field('Gas recovery cost','recoveryCost',a.recoveryCost??'','number',{min:0,step:'any'})}`;
const section=(title,description,content,open=false)=>`<details class="field full form-section" ${open?'open':''}><summary>${title}</summary><p class="section-note">${description}</p><div class="form-grid">${content}</div></details>`;
const fields=section('Equipment basics','Start with the asset identifier, location, rating, and planned retirement.',basics,true)+section('Annual SF₆ loss','Optional during inventory setup; add a measured value or estimate before calculating emissions.',lossFields,Boolean(a.lossSource||a.lossRate!==undefined||a.measuredLoss!==undefined))+section('Technical and maintenance details','Optional. Fill these in as the information becomes available.',technical)+section('Recovery and cost assumptions','Optional for inventory entry; needed for complete replacement emissions and cost estimates.',costs);
const formNode=form(existing?'Edit equipment asset':'Add asset',existing?'Update the core record; optional details can stay collapsed.':'Start with the essentials. Add optional details as you have them.',fields,existing?'Save asset':'Add asset',d=>{
if(p.assets.some(x=>x.assetId.toLowerCase()===d.assetId.toLowerCase()&&x.id!==a.id))throw Error('Asset identifier must be unique within this project.');
const mode=dialog.querySelector('#lossMode').value;
const customAttributes=(()=>{try{return d.customAttributesText?JSON.parse(d.customAttributesText):{}}catch{throw Error('Custom attributes must be valid JSON.')}})();
if(customAttributes===null||typeof customAttributes!=='object'||Array.isArray(customAttributes))throw Error('Custom attributes must be a JSON object.');
const item={...a,id:a.id||uid(),assetId:d.assetId.trim(),site:d.site.trim(),category:d.category,manufacturer:d.manufacturer,voltageKv:Number(d.voltageKv),characteristics:d.characteristics,capacityKg:Number(d.capacityKg),installYear:Number(d.installYear),retirementYear:Number(d.retirementYear),lossMode:mode,lossSource:d.lossSource,condition:d.condition,maintenanceNotes:d.maintenanceNotes,customAttributes,remainingGasKg:d.remainingGasKg===''||d.remainingGasKg===undefined?null:Number(d.remainingGasKg),recoveryEfficiency:d.recoveryEfficiency===''||d.recoveryEfficiency===undefined?null:Number(d.recoveryEfficiency),annualOpex:d.annualOpex===''?null:Number(d.annualOpex),annualMaintenance:d.annualMaintenance===''?null:Number(d.annualMaintenance),capex:d.capex===''?null:Number(d.capex),installCost:d.installCost===''?null:Number(d.installCost),decommissionCost:d.decommissionCost===''?null:Number(d.decommissionCost),recoveryCost:d.recoveryCost===''?null:Number(d.recoveryCost)};
if(item.retirementYear<item.installYear)throw Error('Retirement year must be on or after installation year.');
if(item.remainingGasKg!==null&&item.remainingGasKg>item.capacityKg)throw Error('Remaining end-of-life gas cannot exceed nameplate capacity in this planning model.');
if(mode==='measured'){delete item.lossRate;if(d.measuredLoss!==''&&d.measuredLoss!==undefined){item.measuredLoss=Number(d.measuredLoss);if(!d.lossSource.trim())throw Error('Add the source for this measured loss value.')}else delete item.measuredLoss}
else{delete item.measuredLoss;if(d.lossRate!==''&&d.lossRate!==undefined){item.lossRate=Number(d.lossRate);if(!d.lossSource.trim())throw Error('Add the source for this estimated loss rate.')}else delete item.lossRate}
if(existing)Object.assign(a,item);else p.assets.push(item);
save(existing?'Asset updated':'Asset added');closeDialog();render()
});
const lossSection=dialog.querySelector('#lossMode').closest('details');const updateLossFields=()=>{const selected=dialog.querySelector('#lossMode').value;for(const [id,show] of [['lossRate',selected==='estimated'],['measuredLoss',selected==='measured']]){const input=dialog.querySelector(`#${id}`),wrap=input.closest('.field');wrap.hidden=!show;input.disabled=!show;input.required=show&&lossSection.open}};
formNode.querySelector('#lossMode').addEventListener('change',updateLossFields);lossSection.addEventListener('toggle',updateLossFields);updateLossFields();
}
function techForm(existing){const t=existing||{};form(existing?'Edit technology profile':'Create technology profile','Record evidence and rated characteristics. Blank or unverified fields remain visible.',field('Profile name','name',t.name||'','text',{required:true})+field('Insulation technology','insulation',t.insulation||'','text',{required:true,placeholder:'e.g. vacuum, clean air, fluoronitrile blend'})+field('Gas composition','gasComposition',t.gasComposition||'','text',{required:true,hint:'List components and concentrations when available.'})+field('Voltage class','voltageClass',t.voltageClass||'')+field('Rated voltage (kV)','voltageKv',t.voltageKv??'','number',{min:0,max:2000,step:'any'})+field('Interrupting rating','interrupting',t.interrupting||'')+field('Vendor / evidence source','source',t.source||'','text',{required:true,full:true,placeholder:'Specification title, URL, document identifier'})+field('Screening status','status',t.status||'Unverified','select',{options:['Unverified','Preliminary review','Review recorded by project team']})+field('Annual alternative gas emissions (kg CO₂e/year)','altAnnualCO2e',t.altAnnualCO2e??'','number',{min:0,step:'any',hint:'Leave blank when unsupported; blank is never treated as zero.'})+field('Annual operating cost','annualOpex',t.annualOpex??'','number',{min:0,step:'any'})+field('Annual maintenance cost','annualMaintenance',t.annualMaintenance??'','number',{min:0,step:'any'})+field('Residual value at end of planning horizon','residualValue',t.residualValue??'','number',{min:0,step:'any',hint:'Enter 0 if there is no residual value. Leave blank if it is unknown.'})+field('Profile notes','description',t.description||'','textarea',{full:true}),existing?'Save profile':'Add profile',d=>{const item={...t,id:t.id||uid(),name:d.name.trim(),insulation:d.insulation,gasComposition:d.gasComposition,voltageClass:d.voltageClass,voltageKv:d.voltageKv===''?null:Number(d.voltageKv),interrupting:d.interrupting,source:d.source,status:d.status,altAnnualCO2e:d.altAnnualCO2e===''?null:Number(d.altAnnualCO2e),annualOpex:d.annualOpex===''?null:Number(d.annualOpex),annualMaintenance:d.annualMaintenance===''?null:Number(d.annualMaintenance),residualValue:d.residualValue===''?null:Number(d.residualValue),description:d.description};if(existing)Object.assign(t,item);else current().technologies.push(item);save(existing?'Profile updated':'Technology profile added');closeDialog();render()})}
function compareProfiles(){const p=current(),profiles=p.technologies;if(profiles.length<2){toast('Add at least two profiles to compare.',true);return}const options=profiles.map(t=>`<option value="${t.id}">${esc(t.name)}</option>`).join('');const body=`<div class="form-grid"><div class="field"><label for="profile-a">Profile A</label><select id="profile-a">${options}</select></div><div class="field"><label for="profile-b">Profile B</label><select id="profile-b">${options}</select></div></div><div id="profile-compare" style="margin-top:14px"></div><div class="form-actions"><button class="btn" id="compare-close">Close</button></div>`;showDialog('Compare technology profiles','Profile comparison is informational and does not certify suitability.',body);dialog.querySelector('#compare-close').onclick=closeDialog;const update=()=>{const a=profiles.find(t=>t.id===dialog.querySelector('#profile-a').value),b=profiles.find(t=>t.id===dialog.querySelector('#profile-b').value);const props=[['Insulation',a.insulation,b.insulation],['Gas composition',a.gasComposition,b.gasComposition],['Voltage class',a.voltageClass,b.voltageClass],['Rated voltage (kV)',a.voltageKv,b.voltageKv],['Interrupting rating',a.interrupting,b.interrupting],['Annual gas emissions (kg CO₂e)',a.altAnnualCO2e,b.altAnnualCO2e],['Annual operating cost',a.annualOpex,b.annualOpex],['Annual maintenance cost',a.annualMaintenance,b.annualMaintenance],['Residual value',a.residualValue,b.residualValue],['Evidence source',a.source,b.source],['Screening status',a.status,b.status]];dialog.querySelector('#profile-compare').innerHTML=`<div class="table-wrap"><table class="data-table" style="min-width:0"><thead><tr><th>Specification</th><th>${esc(a.name)}</th><th>${esc(b.name)}</th></tr></thead><tbody>${props.map(r=>`<tr><td>${r[0]}</td><td>${esc(r[1]??'Not recorded')}</td><td>${esc(r[2]??'Not recorded')}</td></tr>`).join('')}</tbody></table></div><div class="notice" style="margin-top:12px">Review source documents, all operating constraints, and engineering requirements before selecting a replacement.</div>`};dialog.querySelector('#profile-a').onchange=update;dialog.querySelector('#profile-b').onchange=update;update()}
function installApp(){if(window.installPrompt){window.installPrompt.prompt();window.installPrompt.userChoice.then(()=>{window.installPrompt=null})}else toast('To install, use your browser’s Add to Home Screen or Install app option when this site is served over HTTPS or localhost.')}
function referenceCheck(){toast('No online reference feed is configured. Verify factor sources manually; saved scenario factors will not change.')}
function compareTech(id){const p=current(),t=p.technologies.find(x=>x.id===id);if(!p.assets.length){toast('Add at least one asset before screening a profile',true);return}showDialog(`Preliminary screen · ${t.name}`,'This comparison identifies recorded mismatches and missing values; it is not an engineering approval.',`<div class="field"><label for="screen-asset">Asset to compare</label><select id="screen-asset">${p.assets.map(a=>`<option value="${a.id}">${esc(a.assetId)} · ${esc(a.category)} · ${a.voltageKv} kV</option>`).join('')}</select></div><div id="screen-result" style="margin-top:14px"></div><div class="form-actions"><button class="btn" id="screen-close">Close</button></div>`);dialog.querySelector('#screen-close').onclick=closeDialog;const renderCompare=()=>{const a=p.assets.find(x=>x.id===dialog.querySelector('#screen-asset').value);const checks=[['Rated voltage',a.voltageKv,t.voltageKv,t.voltageKv?`${a.voltageKv} kV asset / ${t.voltageKv} kV profile`:null],['Voltage class',a.category,t.voltageClass,t.voltageClass?`${a.category} / ${t.voltageClass}`:null],['Electrical characteristics',a.characteristics,t.interrupting,t.interrupting?`${a.characteristics||'not recorded'} / ${t.interrupting}`:null]];dialog.querySelector('#screen-result').innerHTML=`<div class="table-wrap"><table class="data-table" style="min-width:0"><thead><tr><th>Criterion</th><th>Asset</th><th>Profile</th><th>Result</th></tr></thead><tbody>${checks.map(([label,av,tv])=>{const missing=!av||!tv;const mismatch=!missing&&label==='Rated voltage'&&Number(av)>Number(tv);return `<tr><td>${label}</td><td>${esc(av||'Missing')}</td><td>${esc(tv||'Missing')}</td><td><span class="badge ${missing||mismatch?'orange':'green'}">${missing?'Information missing':mismatch?'Potential mismatch':'Recorded'}</span></td></tr>`}).join('')}</tbody></table></div><div class="notice" style="margin-top:12px">${t.source?`Evidence: ${esc(t.source)}.`:'No supporting evidence source recorded.'} This preliminary screen does not verify technical suitability. Have a qualified engineer review manufacturer specifications and operating requirements.</div><div class="field" style="margin-top:12px"><label for="candidate-year">Proposed replacement year</label><input id="candidate-year" type="number" min="${p.baseYear}" max="${p.baseYear+p.horizon-1}" value="${a.retirementYear||p.baseYear+5}"></div><button class="btn primary" id="save-candidate" style="margin-top:10px">Save as scenario candidate</button>`;dialog.querySelector('#save-candidate').onclick=()=>{const candidateYear=Number(dialog.querySelector('#candidate-year')?.value)||a.retirementYear;closeDialog();let s=activeScenario(p);if(!s){s={id:uid(),name:'Initial transition plan',description:'Candidate assignments from technology screening',mode:'Phased transition',budget:0,replacements:{},calcVersion:CALC_VERSION,gwpSnapshot:p.gwp,factorVersion:p.factorVersion,inputSnapshot:snapshotScenario(p)};p.scenarios.push(s);p.activeScenarioId=s.id} s.replacements[a.id]={year:candidateYear,technologyId:t.id};s.inputSnapshot=snapshotScenario(p);s.discountSnapshot=Number(s.discountSnapshot??p.discountRate);s.baseYearSnapshot=Number(s.baseYearSnapshot??p.baseYear);s.horizonSnapshot=Number(s.horizonSnapshot??p.horizon);save('Candidate saved to selected scenario');render()}};dialog.querySelector('#screen-asset').onchange=renderCompare;renderCompare()}
function scenarioForm(existing){const p=current(),s=existing||{name:'',description:'',mode:'Phased transition',budget:0,replacements:{}};const assigned=s.replacements||{};const choices=p.assets.map(a=>{const r=assigned[a.id]||{};return `<div style="border-top:1px solid #4f4f4f;padding:11px 0;display:grid;grid-template-columns:minmax(120px,1fr) 120px minmax(130px,1fr);gap:8px;align-items:center"><label style="display:flex;gap:7px;font-size:11px"><input type="checkbox" name="select-${a.id}" ${assigned[a.id]?'checked':''}> <span><strong>${esc(a.assetId)}</strong><br><small style="color:#bbb">${esc(a.site)} · retire ${a.retirementYear}</small></span></label><div class="field"><label for="year-${a.id}">Replace in</label><input id="year-${a.id}" name="year-${a.id}" type="number" min="${p.baseYear}" max="${p.baseYear+p.horizon-1}" value="${r.year||a.retirementYear||p.baseYear+5}"></div><div class="field"><label for="tech-${a.id}">Technology</label><select id="tech-${a.id}" name="tech-${a.id}"><option value="">Choose profile</option>${p.technologies.map(t=>`<option value="${t.id}" ${r.technologyId===t.id?'selected':''}>${esc(t.name)}</option>`).join('')}</select></div></div>`}).join('');form(existing?'Edit transition scenario':'Create transition scenario','Assignments, budget, and calculation version are saved with this scenario.',field('Scenario name','name',s.name,'text',{required:true,full:true})+field('Description','description',s.description||'','textarea',{full:true})+field('Scenario mode','mode',s.mode||'Phased transition','select',{options:['Continue operation','Replace at end of planned life','Early replacement','Phased transition']})+field('Annual capital budget','budget',s.budget||0,'number',{min:0,step:'any',hint:'Use 0 for no budget constraint.'})+`<div class="field full"><label>Asset replacements</label><small>Tick assets to include. For each selected asset, set the year and technology profile. Unticked assets continue operating.</small><div style="margin-top:8px">${choices||'<p class="disclaimer">Add assets to build assignments.</p>'}</div></div>`,'Save scenario',d=>{const replacements={};for(const a of p.assets){if(dialog.querySelector(`[name="select-${CSS.escape(a.id)}"]`)?.checked){const year=Number(d[`year-${a.id}`]),techId=d[`tech-${a.id}`]||null;if(year<p.baseYear||year>p.baseYear+p.horizon-1)throw Error(`Replacement year for ${a.assetId} falls outside the project horizon.`);replacements[a.id]={year,technologyId:techId}}}if(d.mode==='Continue operation')Object.keys(replacements).forEach(k=>delete replacements[k]);const obj={...s,id:s.id||uid(),name:d.name.trim(),description:d.description,mode:d.mode,budget:Number(d.budget)||0,replacements,calcVersion:CALC_VERSION,gwpSnapshot:Number(p.gwp),factorVersion:p.factorVersion,factorReviewRequired:false,legacyCostReviewRequired:false,discountSnapshot:Number(p.discountRate),baseYearSnapshot:Number(p.baseYear),horizonSnapshot:Number(p.horizon),inputSnapshot:snapshotScenario(p)};if(existing)Object.assign(existing,obj);else{p.scenarios.push(obj);p.activeScenarioId=obj.id}save(existing?'Scenario updated':'Scenario created');closeDialog();render()})}
function duplicateScenario(id){const p=current(),s=p.scenarios.find(x=>x.id===id),copy=structuredClone(s);copy.id=uid();copy.name=`${s.name} (copy)`;p.scenarios.push(copy);p.activeScenarioId=copy.id;save('Scenario duplicated');render()}
function weightsForm(){const w=current().weights||{age:35,emissions:40,condition:25};form('Prioritization weights','Weights are normalized to their total when scores are calculated.',field('Asset age (%)','age',w.age,'number',{required:true,min:0,max:100})+field('Estimated annual emissions (%)','emissions',w.emissions,'number',{required:true,min:0,max:100})+field('Condition (%)','condition',w.condition,'number',{required:true,min:0,max:100}), 'Save weights',d=>{const vals=[Number(d.age),Number(d.emissions),Number(d.condition)];if(vals.reduce((a,b)=>a+b,0)===0)throw Error('At least one weight must be greater than zero.');current().weights={age:vals[0],emissions:vals[1],condition:vals[2]};save('Ranking weights updated');closeDialog();render()})}
function siteForm(existing){const s=existing||{};form(existing?'Edit site':'Add a site','Sites organize assets within this project.',field('Site name','name',s.name||'','text',{required:true})+field('Region / district','region',s.region||'')+field('Site notes','notes',s.notes||'','textarea',{full:true}),existing?'Save site':'Add site',d=>{const p=current();if(p.sites.some(x=>x.name.toLowerCase()===d.name.toLowerCase()&&x.id!==s.id))throw Error('A site with this name already exists.');const item={...s,id:s.id||uid(),name:d.name.trim(),region:d.region,notes:d.notes};if(existing){const old=s.name;Object.assign(s,item);p.assets.forEach(a=>{if(a.site===old)a.site=s.name})}else p.sites.push(item);save(existing?'Site updated':'Site added');closeDialog();render()})}
function assumptionsForm(){const p=current();form('Edit calculation assumptions','Factor values are explicit and versioned. Existing saved scenarios preserve their original snapshots.',field('Discount rate (fraction)','discountRate',p.discountRate,'number',{required:true,min:0,max:1,step:'any'})+field('SF₆ GWP factor','gwp',p.gwp,'number',{required:true,min:0,step:'any'})+field('Assessment time horizon','gwpHorizon',p.gwpHorizon,'text',{required:true})+field('Factor version','factorVersion',p.factorVersion,'text',{required:true})+field('Factor source / citation','gwpSource',p.gwpSource,'text',{required:true,full:true}), 'Save assumptions',d=>{p.discountRate=Number(d.discountRate);p.gwp=Number(d.gwp);p.gwpHorizon=d.gwpHorizon;p.factorVersion=d.factorVersion;p.gwpSource=d.gwpSource;save('Assumptions updated; saved scenario snapshots are preserved');closeDialog();render()})}
function csvPicker(){const input=document.createElement('input');input.type='file';input.accept='.csv,text/csv';input.onchange=()=>{const f=input.files?.[0];if(!f)return;if(f.size>5*1024*1024){toast('CSV exceeds 5 MB. Split the file and retry.',true);return}const reader=new FileReader();reader.onload=()=>importCsv(String(reader.result||''));reader.onerror=()=>toast('Could not read this file. Check permissions and retry.',true);reader.readAsText(f)};input.click()}
function importCsv(text){const p=current();try{
const rows=parseCsv(text),required=['assetId','site','category','voltageKv','capacityKg','installYear','retirementYear','lossMode','lossSource'],headers=Object.keys(rows[0]||{}),missing=required.filter(x=>!headers.includes(x));
if(missing.length)throw Error(`Missing required columns: ${missing.join(', ')}.`);
const ids=new Set(p.assets.map(a=>String(a.assetId).toLowerCase())),errors=[],incoming=[];
rows.forEach((r,i)=>{
const line=i+2,id=r.assetId?.trim(),site=r.site?.trim(),category=r.category?.trim();
if(!id)errors.push(`Row ${line}: assetId is blank.`);else if(id.length>200)errors.push(`Row ${line}: assetId exceeds 200 characters.`);else if(ids.has(id.toLowerCase()))errors.push(`Row ${line}: duplicate assetId “${id}”.`);else ids.add(id.toLowerCase());
if(!site)errors.push(`Row ${line}: site is blank.`);if(!category)errors.push(`Row ${line}: category is blank.`);
const requiredNumbers=['voltageKv','capacityKg','installYear','retirementYear'];
for(const k of requiredNumbers)if(!r[k]?.trim()||!Number.isFinite(Number(r[k])))errors.push(`Row ${line}: ${k} must be numeric.`);
if(Number(r.capacityKg)<0||Number(r.voltageKv)<0)errors.push(`Row ${line}: voltage and gas capacity cannot be negative.`);
if(Number(r.installYear)<1900||Number(r.installYear)>2200||Number(r.retirementYear)<1900||Number(r.retirementYear)>2300||Number(r.retirementYear)<Number(r.installYear))errors.push(`Row ${line}: installation/retirement years are outside the supported range or reversed.`);
if(!['measured','estimated'].includes(r.lossMode))errors.push(`Row ${line}: lossMode must be measured or estimated.`);
const lossKey=r.lossMode==='measured'?'measuredLoss':'lossRate';
if(!r[lossKey]?.trim()||!Number.isFinite(Number(r[lossKey]))||Number(r[lossKey])<0||(lossKey==='lossRate'&&Number(r[lossKey])>1))errors.push(`Row ${line}: ${lossKey} must be a valid non-negative number${lossKey==='lossRate'?' no greater than 1':''}.`);
if(!r.lossSource?.trim())errors.push(`Row ${line}: lossSource is required.`);
for(const k of ['remainingGasKg','recoveryEfficiency','annualOpex','annualMaintenance','capex','installCost','decommissionCost','recoveryCost'])if(r[k]?.trim()&&(!Number.isFinite(Number(r[k]))||Number(r[k])<0))errors.push(`Row ${line}: ${k} must be a non-negative number.`);
if(r.recoveryEfficiency?.trim()&&Number(r.recoveryEfficiency)>1)errors.push(`Row ${line}: recoveryEfficiency must be between 0 and 1.`);
if(r.remainingGasKg?.trim()&&Number(r.remainingGasKg)>Number(r.capacityKg))errors.push(`Row ${line}: remainingGasKg cannot exceed capacityKg.`);
let customAttributes={};try{customAttributes=r.customAttributes?JSON.parse(r.customAttributes):{}}catch{errors.push(`Row ${line}: customAttributes must contain valid JSON.`)}
if(!customAttributes||typeof customAttributes!=='object'||Array.isArray(customAttributes))errors.push(`Row ${line}: customAttributes must be a JSON object.`);
const optionalNumber=k=>r[k]?.trim()?Number(r[k]):null;
incoming.push({...r,id:uid(),assetId:id,site,category,voltageKv:Number(r.voltageKv),capacityKg:Number(r.capacityKg),installYear:Number(r.installYear),retirementYear:Number(r.retirementYear),lossRate:r.lossMode==='estimated'?Number(r.lossRate):null,measuredLoss:r.lossMode==='measured'?Number(r.measuredLoss):null,remainingGasKg:optionalNumber('remainingGasKg'),recoveryEfficiency:optionalNumber('recoveryEfficiency'),annualOpex:optionalNumber('annualOpex'),annualMaintenance:optionalNumber('annualMaintenance'),capex:Number(r.capex)||0,installCost:Number(r.installCost)||0,decommissionCost:Number(r.decommissionCost)||0,recoveryCost:Number(r.recoveryCost)||0,condition:r.condition||'Unknown',maintenanceNotes:r.maintenanceNotes||'',customAttributes});
});
if(errors.length)throw Error(`Nothing was imported; existing inventory is unchanged. ${errors.slice(0,7).join(' ')}${errors.length>7?` And ${errors.length-7} more error(s).`:''}`);
const candidate=structuredClone(state),candidateProject=candidate.projects.find(x=>x.id===p.id);candidateProject.assets.push(...incoming);if(!fitsLocalDataLimit(candidate))throw Error('Nothing was imported; this workspace would exceed Gridshift’s 3 MB local-data limit. Split the inventory or remove unused records.');p.assets.push(...incoming);save(`${incoming.length} asset${incoming.length===1?'':'s'} imported`);render();
}catch(e){toast(e.message||'CSV import failed; no records changed.',true)}}
function download(name,content,type){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([content],{type}));a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(a.href),1000)}
function exportAssets(p){const headers=['assetId','site','category','manufacturer','voltageKv','characteristics','capacityKg','installYear','retirementYear','lossMode','lossRate','measuredLoss','lossSource','condition','maintenanceNotes','customAttributes','remainingGasKg','recoveryEfficiency','annualOpex','annualMaintenance','capex','installCost','decommissionCost','recoveryCost'];download(`${slug(p.name)}-inventory.csv`,[headers.join(','),...p.assets.map(a=>headers.map(k=>csvValue(a[k])).join(','))].join('\r\n'),'text/csv');toast('Inventory CSV exported')}
function exportResults(p){const s=activeScenario(p);if(!s){toast('Create a scenario before exporting results.',true);return}const c=calc(p,s),rows=[['type','year','assetId','value','unit','provenance']];rows.push(['model review status','','independent domain review',MODEL_REVIEW_STATUS,'status','No independent qualified power-system engineering or climate/accounting review has been completed; exploratory estimates only.'],['scenario assumption','','name',s.name,'text','Saved scenario'],['scenario assumption','','annual budget',s.budget,c.currency,'User-entered; price year '+c.priceYear],['scenario assumption','','discount rate',s.discountSnapshot??p.discountRate,'fraction/year','Scenario snapshot'],['model boundary','','lifecycle emissions','Manufacturing, construction, and other unmodeled lifecycle emissions are excluded','text','Results cover modeled operational leakage and recorded replacement/recovery terms only'],['emissions factor','','SF6 GWP',c.factor.gwp,'kg CO2e/kg SF6',`${c.factor.version}; ${c.factor.horizon}; ${c.factor.source}`],['scenario review','','legacy factor',c.factorReviewRequired?'Review required':'No','status',c.factorReviewRequired?'Saved factor retained for reproducibility; verify before use':'Not flagged'],['scenario review','','legacy costs',c.legacyCostReviewRequired?'Review required':'No','status',c.legacyCostReviewRequired?'Older saved zero values may represent missing costs':'Not flagged'],['calculation','','version',c.version,'version','Deterministic local calculation']);for(const [assetId,plan] of Object.entries(s.replacements||{}))rows.push(['replacement assignment',plan.year,assetId,plan.technologyId||'Unavailable','technology profile ID','Scenario snapshot']);for(const r of c.annual){rows.push(['baseline emissions',r.year,'',r.baseline,'kg CO2e',`${s.factorVersion??p.factorVersion}; GWP ${s.gwpSnapshot??p.gwp}`],['scenario emissions',r.year,'',r.scenario,'kg CO2e',`Scenario ${s.name}; calculation v${c.version}`],['scenario cost',r.year,'',r.cost,c.currency,`User-entered asset costs; price year ${c.priceYear}`]);}for(const a of p.assets)rows.push(['asset input',a.assetId,a.assetId,a.lossMode==='measured'?a.measuredLoss:a.lossRate,a.lossMode==='measured'?'kg/year':'fraction/year',`${a.lossMode}; ${a.lossSource}`]);download(`${slug(p.name)}-${slug(s.name)}-results.csv`,rows.map(r=>r.map(csvValue).join(',')).join('\r\n'),'text/csv');toast('Scenario results CSV exported')}
function slug(s){return String(s||'project').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')}
function backup(){const payload={format:'gridshift-backup',version:1,exportedAt:new Date().toISOString(),data:state};download(`gridshift-backup-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(payload,null,2),'application/json');toast('JSON backup downloaded')}
function restorePicker(){const input=document.createElement('input');input.type='file';input.accept='.json,application/json';input.onchange=()=>{const f=input.files?.[0];if(!f)return;if(f.size>15*1024*1024){toast('Backup exceeds 15 MB.',true);return}const r=new FileReader();r.onload=()=>restoreJson(String(r.result||''));r.onerror=()=>toast('Could not read backup file.',true);r.readAsText(f)};input.click()}
function restoreJson(text){try{
const incoming=validateBackup(JSON.parse(text)),conflicts=incoming.projects.filter(p=>state.projects.some(x=>x.id===p.id));
const counts={projects:incoming.projects.length,sites:incoming.projects.reduce((n,p)=>n+p.sites.length,0),assets:incoming.projects.reduce((n,p)=>n+p.assets.length,0),profiles:incoming.projects.reduce((n,p)=>n+p.technologies.length,0),scenarios:incoming.projects.reduce((n,p)=>n+p.scenarios.length,0)};
showDialog('Review backup contents','No data changes until you choose an import action.',`<dl class="workspace-details"><div><dt>Projects</dt><dd>${counts.projects}</dd></div><div><dt>Sites</dt><dd>${counts.sites}</dd></div><div><dt>Assets</dt><dd>${counts.assets}</dd></div><div><dt>Technology profiles</dt><dd>${counts.profiles}</dd></div><div><dt>Scenarios</dt><dd>${counts.scenarios}</dd></div></dl>${conflicts.length?`<p class="disclaimer">Matching local projects: ${conflicts.map(p=>esc(p.name)).join(', ')}. You can import separate copies or replace those projects.</p>`:'<p class="disclaimer">No project identifiers conflict with this browser’s saved projects.</p>'}<div class="form-actions"><button class="btn" id="import-cancel">Cancel</button><button class="btn primary" id="import-continue">${conflicts.length?'Choose import action':'Import backup'}</button></div>`);
dialog.querySelector('#import-cancel').onclick=closeDialog;
dialog.querySelector('#import-continue').onclick=()=>{closeDialog();if(!conflicts.length){merge('add');return}showDialog('Project IDs already exist','Choose how to handle matching project identifiers.',`<p class="disclaimer">${conflicts.map(p=>esc(p.name)).join(', ')}</p><div class="form-actions"><button class="btn" id="import-cancel-conflicts">Cancel</button><button class="btn" id="import-separate">Import as separate</button><button class="btn danger" id="import-replace">Replace existing</button></div>`);dialog.querySelector('#import-cancel-conflicts').onclick=closeDialog;dialog.querySelector('#import-separate').onclick=()=>{closeDialog();merge('separate')};dialog.querySelector('#import-replace').onclick=()=>{closeDialog();confirmDialog('Replace existing projects?','Matching local project IDs and all their data will be replaced by the backup.',()=>merge('replace'))}};
function merge(mode){const next=structuredClone(state);for(const source of incoming.projects){const project=structuredClone(source),i=next.projects.findIndex(x=>x.id===project.id);if(i>=0){if(mode==='replace')next.projects[i]=project;else if(mode==='separate'){project.id=uid();project.name+=` (imported)`;next.projects.push(project)}}else next.projects.push(project)}if(!fitsLocalDataLimit(next)){toast('Backup not restored; the combined workspace exceeds Gridshift’s 3 MB local-data limit. Export current data and restore into a separate empty browser workspace.',true);return}state=next;state.activeProjectId=incoming.activeProjectId&&state.projects.some(p=>p.id===incoming.activeProjectId)?incoming.activeProjectId:state.projects[0]?.id||null;save('Backup restored');render()}
}catch(e){toast(`Backup not imported: ${e.message}`,true)}}
function storageEstimate(force=false){const x=document.querySelector('#storage-status');const chars=JSON.stringify(state).length;if(x)x.textContent=`Gridshift data: ${(chars*2/1024).toFixed(0)} KB of 2,930 KB local-data limit. This is a single-browser workspace; export a backup before approaching the limit.`;if(chars>MAX_STATE_CHARS*0.85)toast('Gridshift local data is approaching its 3 MB limit. Export a backup and split large workspaces.',true);if(!navigator.storage?.estimate)return;if(force&&x)x.textContent+=` Browser quota estimate is also being checked.`;navigator.storage.estimate().then(({usage=0,quota=0})=>{const target=document.querySelector('#storage-status');if(target)target.textContent+=` Browser origin usage: ${(usage/1024/1024).toFixed(2)} MB of ${(quota/1024/1024).toFixed(0)} MB; this is shared with other site data.`}).catch(()=>{const target=document.querySelector('#storage-status');if(target)target.textContent+=' Browser quota estimate is unavailable.'})}
function seedDemo(){const p=mkProject('North Valley Grid Transition','Illustrative sample workspace · replace with verified utility records.',10);p.sites=[{id:uid(),name:'Cedar Ridge',region:'North District'},{id:uid(),name:'Lake Junction',region:'Central District'},{id:uid(),name:'Summit East',region:'East District'}];p.technologies=[{id:uid(),name:'Clean air GIS — 145 kV',insulation:'Dry air / vacuum interruption',gasComposition:'Clean dry air; composition reference required',voltageClass:'145 kV',voltageKv:145,interrupting:'31.5 kA',source:'Illustrative profile; replace with manufacturer specification',status:'Unverified',altAnnualCO2e:null,description:'User-maintained example profile for preliminary screening.'},{id:uid(),name:'Vacuum breaker — 72.5 kV',insulation:'Vacuum interruption / clean air insulation',gasComposition:'No fluorinated insulation gas specified in this example',voltageClass:'72.5 kV',voltageKv:72.5,interrupting:'25 kA',source:'Illustrative profile; replace with manufacturer specification',status:'Unverified',altAnnualCO2e:null,description:'User-maintained example profile; alternative lifecycle impacts not quantified.'}];p.assets=[['CB-114','Cedar Ridge','Circuit breaker',145,18,2008,2033,.006,'Fair'],['GIS-042','Lake Junction','Gas-insulated switchgear',72.5,32,2011,2036,.004,'Good'],['CB-208','Summit East','Circuit breaker',145,21,2002,2029,.009,'Poor'],['GIS-105','Cedar Ridge','Gas-insulated switchgear',72.5,26,2015,2040,.003,'Good'],['CB-311','Lake Junction','Circuit breaker',145,17,2006,2031,.007,'Fair']].map(([assetId,site,category,voltageKv,capacityKg,installYear,retirementYear,lossRate,condition])=>({id:uid(),assetId,site,category,manufacturer:'Example — verify',voltageKv,characteristics:'Interrupting rating requires verification',capacityKg,installYear,retirementYear,lossMode:'estimated',lossRate,lossSource:'Illustrative assumed annual loss rate — replace with utility data',condition,maintenanceNotes:'Sample data only',remainingGasKg:capacityKg*.45,recoveryEfficiency:.95,annualOpex:1500,annualMaintenance:2600,capex:category==='Circuit breaker'?320000:480000,installCost:80000,decommissionCost:19000,recoveryCost:6000}));const s={id:uid(),name:'Steady transition · 2027–2035',description:'Illustrative phased replacement for demonstration.',mode:'Phased transition',budget:600000,replacements:{},calcVersion:CALC_VERSION,gwpSnapshot:p.gwp,factorVersion:p.factorVersion,discountSnapshot:p.discountRate,baseYearSnapshot:p.baseYear,horizonSnapshot:p.horizon,inputSnapshot:snapshotScenario(p)};s.replacements[p.assets[2].id]={year:p.baseYear+2,technologyId:p.technologies[1].id};s.replacements[p.assets[0].id]={year:p.baseYear+4,technologyId:p.technologies[0].id};s.replacements[p.assets[1].id]={year:p.baseYear+6,technologyId:p.technologies[1].id};p.scenarios.push(s);p.activeScenarioId=s.id;state.projects.push(p);state.activeProjectId=p.id;page='dashboard';save('Sample workspace loaded. Replace illustrative inputs with verified data.');render()}
function renderStatus(){const el=document.querySelector('#connection-status');if(!el)return;const online=navigator.onLine,saved=state.updatedAt?`Saved · ${fmtDate(state.updatedAt)}`:state.projects.length?'Saved locally':'Nothing saved yet';el.innerHTML=`<span class="dot ${online?'':'offline'}"></span><span>${online?'Online':'Offline · local mode'} · ${esc(saved)}</span>`}
function setOnline(){renderStatus()}
window.addEventListener('online',setOnline);window.addEventListener('offline',setOnline);
window.addEventListener('storage',event=>{if(event.key!==KEY)return;try{const next=event.newValue?JSON.parse(event.newValue):blankState();if(!next||next.version!==1||!Array.isArray(next.projects))throw new Error('Invalid shared workspace');validateBackup({format:'gridshift-backup',version:1,data:next});state=next;if(dialog.open)closeDialog();render();toast('Workspace updated from another open tab.')}catch{storageCorruptRaw=event.newValue||'null';showRecoveryDialog()}});
window.addEventListener('beforeinstallprompt',e=>{e.preventDefault();window.installPrompt=e;});
shell();
if((migratedFactorProjects||migratedCostProjects)&&!storageCorruptRaw){save(null);const notes=[];if(migratedFactorProjects)notes.push(`updated the AR6 SF₆ factor in ${migratedFactorProjects} project${migratedFactorProjects===1?'':'s'}`);if(migratedCostProjects)notes.push(`marked older zero cost entries for review in ${migratedCostProjects} project${migratedCostProjects===1?'':'s'}`);toast(`Gridshift ${notes.join(' and ')}. Saved scenarios were preserved and flagged where needed.`,true)}
if(storageCorruptRaw!==null)showRecoveryDialog();else if(storageUnavailable)toast('Browser storage is unavailable. Changes can be exported from this tab but will not persist after it closes.',true);
if('serviceWorker' in navigator && location.protocol!=='file:')navigator.serviceWorker.register('./sw.js').then(registration=>{
workerRegistration=registration;
const revealUpdate=()=>syncUpdateButton();
if(registration.waiting&&navigator.serviceWorker.controller)revealUpdate();
registration.addEventListener('updatefound',()=>{const worker=registration.installing;worker?.addEventListener('statechange',()=>{if(worker.state==='installed'&&navigator.serviceWorker.controller)revealUpdate()})});
navigator.serviceWorker.addEventListener('controllerchange',()=>{if(applyWorkerUpdate)location.reload()});
registration.update().catch(()=>{});
}).catch(()=>{});
})();