Spaces:
Running

File size: 48,285 Bytes
8b1628d
628ab0d
 
d7dbd19
684a9cc
ce65d97
afb6251
684a9cc
628ab0d
8b1628d
afb6251
628ab0d
 
 
 
 
 
 
 
8b1628d
 
 
667eed0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b1628d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667eed0
8b1628d
667eed0
8b1628d
 
 
 
 
667eed0
8b1628d
667eed0
8b1628d
 
 
 
 
 
 
 
 
667eed0
8b1628d
 
 
 
 
 
667eed0
8b1628d
 
667eed0
8b1628d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667eed0
8b1628d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667eed0
8b1628d
 
 
 
 
667eed0
 
 
 
 
 
 
 
 
8b1628d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667eed0
 
8b1628d
667eed0
 
 
 
 
 
 
 
8b1628d
 
667eed0
8b1628d
 
 
667eed0
 
 
 
 
 
 
 
8b1628d
 
667eed0
 
 
 
 
 
8b1628d
 
667eed0
 
 
8b1628d
 
 
628ab0d
8b1628d
684a9cc
628ab0d
684a9cc
ce65d97
 
684a9cc
628ab0d
684a9cc
 
 
628ab0d
d7dbd19
628ab0d
684a9cc
628ab0d
 
684a9cc
8b1628d
628ab0d
8b1628d
628ab0d
8b1628d
684a9cc
 
 
 
d7dbd19
8b1628d
628ab0d
afb6251
d7dbd19
afb6251
684a9cc
 
628ab0d
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import React,{useState,useEffect,useRef,useMemo} from 'react';
import {Zap,Activity,BarChart3,ReceiptText,Network,FileJson,ArrowUpRight,Upload,ArrowRight,Play,CheckCircle2,AlertCircle,Download,RefreshCw,ChevronRight,Info} from 'lucide-react';
import Papa from 'papaparse';
import AnalysisPanel,{AuditDatasets} from './AnalysisPanel.jsx';
import LiveWorkspace from './LiveWorkspace.jsx';
import EnergyIntro from './EnergyIntro.jsx';
import ChallengePanel from './ChallengePanel.jsx';
import './live.css';
const markets={PT:{name:'Portugal',scope:'Mainland grid',currency:'EUR',region:'PT-mainland',flag:'🇵🇹'},DE:{name:'Germany',scope:'National grid load',currency:'EUR',region:'DE-local-grid',flag:'🇩🇪'},AU:{name:'Australia',scope:'NEM · five regions',currency:'AUD',region:'NSW1',flag:'🇦🇺'}};
const nav=[['live','Analyze now',Zap],['atlas','Grid Atlas',Activity],['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['analysis','Import bills & swaps',Network],['benchmark','Forecast lab',Activity],['challenge','LLM challenge',BarChart3],['models','Model evidence',BarChart3],['sources','Official feeds',Network],['api','API & methods',FileJson]];
async function request(path,payload){let r=await fetch(path,{signal:AbortSignal.timeout(path==='/api/benchmark'?240000:120000),method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});if(!r.headers.get('content-type')?.includes('application/json'))throw Error(`Service returned HTTP ${r.status} instead of JSON. Retry the connection.`);let data=await r.json();if(!r.ok)throw Error(data.detail||'Request failed');return data;}
const num=(n,d=0)=>Number(n).toLocaleString(undefined,{maximumFractionDigits:d});
function Json({value}){return <pre className="json">{JSON.stringify(value,null,2)}</pre>}
function Notice({children}){return <div className="notice"><Info size={17}/><div>{children}</div></div>}
function Table({rows,columns}){if(!rows?.length)return <div className="empty">No records to show yet.</div>;return <div className="table-wrap"><table><thead><tr>{columns.map(([key,label])=><th key={key}>{label}</th>)}</tr></thead><tbody>{rows.map((row,i)=><tr key={i}>{columns.map(([key])=><td key={key}>{typeof row[key]==='number'?num(row[key],2):typeof row[key]==='boolean'?(row[key]?'Yes':'—'):String(row[key]??'—')}</td>)}</tr>)}</tbody></table></div>}
function Chart({series,unit='GWh',labels=[]}){let arrays=series.filter(s=>s.values?.length);let all=arrays.flatMap(s=>s.values);if(!all.length)return null;let lo=Math.min(...all),hi=Math.max(...all);let pad=(hi-lo)*.15||1;lo-=pad;hi+=pad;const w=780,h=220,left=55,right=18,top=12,bottom=36;const xy=(v,i,n)=>[left+i*(w-left-right)/Math.max(n-1,1),h-bottom-(v-lo)/(hi-lo)*(h-top-bottom)];return <div className="chart"><svg viewBox={`0 0 ${w} ${h}`} role="img" aria-label={`Line chart in ${unit}`}><defs><linearGradient id="fill" x1="0" y1="0" x2="0" y2="1"><stop stopColor="#20a585" stopOpacity=".2"/><stop offset="1" stopColor="#20a585" stopOpacity="0"/></linearGradient></defs>{[0,1,2,3].map(i=>{let y=top+i*(h-top-bottom)/3;return <g key={i}><line x1={left} y1={y} x2={w-right} y2={y} stroke="#e7ecec" strokeDasharray="3 4"/><text x={left-9} y={y+4} textAnchor="end" fontSize="11" fill="#899295">{num(hi-i*(hi-lo)/3)}</text></g>})}{arrays.map((s,k)=>{let pts=s.values.map((v,i)=>xy(v,i,s.values.length).join(',')).join(' ');return <g key={s.name}>{k===0&&arrays.length===1&&<polygon points={`${left},${h-bottom} ${pts} ${w-right},${h-bottom}`} fill="url(#fill)"/>}<polyline points={pts} fill="none" stroke={s.color||'#199e80'} strokeWidth={k===0?2.6:2} strokeDasharray={s.dashed?'5 4':undefined} strokeLinejoin="round"/></g>})}{[0,Math.floor(labels.length/2),labels.length-1].filter((x,i,a)=>x>=0&&a.indexOf(x)===i).map(i=><text key={i} x={xy(0,i,labels.length)[0]} y={h-10} textAnchor={i===0?'start':i===labels.length-1?'end':'middle'} fill="#899295" fontSize="11">{String(labels[i]||'').slice(0,7)}</text>)}</svg><div className="legend">{arrays.map(s=><span key={s.name}><i style={{background:s.color||'#199e80'}}/>{s.name}</span>)}<span className="unit">{unit}</span></div></div>}
function CsvUpload({label,onData,onError,help}){return <label className="upload"><Upload size={20}/><b>{label}</b><span>{help||'CSV · maximum 2 MB'}</span><input type="file" accept=".csv" aria-label={label} onChange={e=>{let f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('CSV limit is 2 MB.');return;}Papa.parse(f,{header:true,skipEmptyLines:true,complete:r=>{if(r.errors.length){onError(r.errors[0].message);return;}onData(r.data);},error:e=>onError(e.message)});e.target.value='';}}/></label>}
function Field({label,children}){return <label className="field"><span>{label}</span>{children}</label>}
function download(value,name){let url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));let a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}
const atlasMonthLabels = Array.from({length: 12}, (_, month) =>
  new Intl.DateTimeFormat('en', {month: 'short', timeZone: 'UTC'}).format(Date.UTC(2024, month))
);
const gridDemandStops = [
  [69, 184, 126],
  [240, 211, 94],
  [248, 160, 76],
  [231, 98, 91]
];

function gridDemandColor(fraction) {
  const position = Math.max(0, Math.min(1, fraction)) * (gridDemandStops.length - 1);
  const lower = Math.floor(position);
  const mix = position - lower;
  const start = gridDemandStops[lower];
  const end = gridDemandStops[Math.ceil(position)];
  return `rgb(${start.map((value, index) => Math.round(value + (end[index] - value) * mix)).join(', ')})`;
}

function AtlasWheel({points, selection, onSelect, low, high}) {
  const canvas = useRef(null);
  const hitTargets = useRef([]);
  const drag = useRef(null);
  const [angle, setAngle] = useState(-0.52);
  useEffect(() => {
    const element = canvas.current;
    function draw() {
      const width = element.clientWidth;
      const height = element.clientHeight;
      if (!width || !height) return;
      const scale = window.devicePixelRatio || 1;
      element.width = Math.round(width * scale);
      element.height = Math.round(height * scale);
      const ctx = element.getContext('2d');
      ctx.scale(scale, scale);
      const radius = Math.min(width * .31, height * .40);
      const firstYear = points[0].year;
      const lastYear = points.at(-1).year;
      const vertical = height * .52;
      function project(month, year, factor) {
        const phase = angle + month * Math.PI / 6;
        const depth = Math.sin(phase) * radius * factor;
        const level = (year - firstYear) / Math.max(lastYear - firstYear, 1);
        return {
          x: width / 2 + Math.cos(phase) * radius * factor,
          y: height * .76 - (lastYear === firstYear ? .5 : level) * vertical + depth * .40,
          depth
        };
      }
      function line(nodes, color, weight = 1) {
        ctx.beginPath();
        nodes.forEach((p, index) => index ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));
        ctx.strokeStyle = color;
        ctx.lineWidth = weight;
        ctx.stroke();
      }
      const yearStep = Math.max(1, Math.ceil((lastYear - firstYear) / 7));
      for (let year = firstYear; year <= lastYear; year += yearStep) {
        const ring = Array.from({length: 73}, (_, index) => project(index / 6, year, 1.08));
        line(ring, '#b5ced23b');
        ctx.font = '11px system-ui';
        ctx.fillStyle = '#b9cbd0';
        ctx.fillText(year, Math.min(width - 33, width / 2 + radius * 1.12), ring[0].y);
      }
      for (let month = 0; month < 12; month += 3) {
        const start = project(month, firstYear, 1.08);
        const end = project(month, lastYear, 1.08);
        line([start, end], '#b5ced23b');
        ctx.font = '11px system-ui';
        ctx.fillStyle = '#b9cbd0';
        ctx.fillText(atlasMonthLabels[month], start.x - 9, start.y + 20 + (lastYear === firstYear ? 4 : 0));
      }
      const nodes = points.map(point => {
        const fraction = (point.value - low) / (high - low || 1);
        return {...project(point.month, point.year, .31 + .69 * fraction), point, fraction};
      });
      for (let i = 1; i < nodes.length; i++) {
        const before = nodes[i - 1];
        const after = nodes[i];
        if (after.point.index - before.point.index === 1) line([before, after], '#90b7ba78', 1.6);
      }
      hitTargets.current = [...nodes].sort((a, b) => a.depth - b.depth);
      for (const node of hitTargets.current) {
        const active = node.point.key === selection;
        ctx.beginPath();
        ctx.arc(node.x, node.y, active ? 8 : 3.4 + node.fraction * 1.2, 0, Math.PI * 2);
        ctx.fillStyle = gridDemandColor(node.fraction);
        ctx.fill();
        if (active) {
          ctx.strokeStyle = '#ffffff';
          ctx.lineWidth = 2.5;
          ctx.stroke();
        }
      }
    }
    const observer = new ResizeObserver(draw);
    observer.observe(element);
    draw();
    return () => observer.disconnect();
  }, [points, selection, angle, low, high]);

  function endDrag(event) {
    const start = drag.current;
    drag.current = null;
    if (!start || start.moved) return;
    const bounds = event.currentTarget.getBoundingClientRect();
    const x = event.clientX - bounds.left;
    const y = event.clientY - bounds.top;
    const nearest = hitTargets.current.reduce((best, point) => {
      const distance = Math.hypot(point.x - x, point.y - y);
      return distance <= best.distance ? {distance, point} : best;
    }, {distance: 16});
    if (nearest.point) onSelect(nearest.point.point.key);
  }
  return <div className="atlas-wheel">
    <canvas ref={canvas} aria-label="Seasonal grid demand in 3D. Use the month selector to inspect exact values."
      onPointerDown={event => {
        drag.current = {x: event.clientX, angle, moved: false};
        event.currentTarget.setPointerCapture(event.pointerId);
      }}
      onPointerMove={event => {
        if (!drag.current) return;
        const delta = event.clientX - drag.current.x;
        drag.current.moved ||= Math.abs(delta) > 5;
        if (drag.current.moved) setAngle(drag.current.angle + delta / 115);
      }}
      onPointerUp={endDrag} onPointerCancel={() => {drag.current = null;}} />
    <div className="atlas-camera" aria-label="View rotation">
      <button type="button" aria-label="Rotate left" onClick={() => setAngle(value => value - .45)}>←</button>
      <button type="button" onClick={() => setAngle(-.52)}>Reset view</button>
      <button type="button" aria-label="Rotate right" onClick={() => setAngle(value => value + .45)}>→</button>
    </div>
  </div>;
}

function GridAtlas({history, market, source, loaded}) {
  const [mode, setMode] = useState('wheel');
  const [windowSize, setWindowSize] = useState('5');
  const [selectedKey, setSelectedKey] = useState(null);
  const all = useMemo(() => {
    const unique = new Map();
    for (const row of history) {
      const stamp = typeof row.timestamp === 'string' ? row.timestamp : '';
      const match = /^(\d{4})-(0[1-9]|1[0-2])/.exec(stamp || '');
      if (!match || row.value == null || !Number.isFinite(Number(row.value))) continue;
      const year = Number(match[1]);
      const month = Number(match[2]) - 1;
      const key = match[0];
      unique.set(key, {year, month, key, index: year * 12 + month, value: Number(row.value), coverage: row.coverage});
    }
    return [...unique.values()].sort((a, b) => a.index - b.index);
  }, [history]);
  const latest = all.at(-1);
  const points = useMemo(() => {
    if (!latest || windowSize === 'all') return all;
    return all.filter(point => point.year > latest.year - Number(windowSize));
  }, [all, latest, windowSize]);
  if (!latest) return <section className="panel"><p role="status">{loaded ? 'No published monthly grid data for this market.' : 'Loading the published grid snapshot…'}</p></section>;
  const selected = points.find(point => point.key === selectedKey) || latest;
  const previous = all.find(point => point.index === selected.index - 12);
  const delta = previous?.value ? (selected.value - previous.value) / previous.value * 100 : null;
  const low = Math.min(...points.map(point => point.value));
  const high = Math.max(...points.map(point => point.value));
  const years = [...new Set(points.map(point => point.year))].reverse();
  const byDate = new Map(points.map(point => [point.year * 12 + point.month, point]));
  const position = points.indexOf(selected);
  const publisher = source?.publisher || 'Published';
  return <section className="panel grid-atlas" aria-label="Grid Atlas">
    <style>{gridAtlasStyles}</style>
    <div className="atlas-heading">
      <div><p className="atlas-kicker">{publisher} grid history</p><h2>Grid Atlas</h2><p>{market.scope} · {points[0].key} to {latest.key}</p></div>
      <div className="atlas-modes" role="group" aria-label="Visualization">
        <button type="button" aria-pressed={mode === 'wheel'} onClick={() => setMode('wheel')}>Seasonal orbit</button>
        <button type="button" aria-pressed={mode === 'calendar'} onClick={() => setMode('calendar')}>Calendar</button>
      </div>
    </div>
    <div className="atlas-body">
      <div className="atlas-visual">
        {mode === 'wheel' ? <AtlasWheel points={points} selection={selected.key} onSelect={setSelectedKey} low={low} high={high}/> :
          <div className="atlas-calendar" tabIndex={0} role="region" aria-label="Scrollable calendar of monthly grid energy">
            <div className="atlas-calendar-row"><span>Year</span>{atlasMonthLabels.map(label => <span key={label}>{label}</span>)}</div>
            {years.map(year => <div className="atlas-calendar-row" key={year}>
              <strong>{year}</strong>
              {atlasMonthLabels.map((label, month) => {
                const point = byDate.get(year * 12 + month);
                const amount = point ? (point.value - low) / (high - low || 1) : 0;
                return point ? <button type="button" key={label} aria-pressed={point.key === selected.key}
                  aria-label={`${label} ${year}, ${num(point.value, 1)} GWh`}
                  title={`${label} ${year} · ${num(point.value, 1)} GWh`}
                  style={{backgroundColor: gridDemandColor(amount)}}
                  onClick={() => setSelectedKey(point.key)} /> :
                  <span key={label} className="atlas-gap" title={`${label} ${year} · no record`}>—</span>;
              })}
            </div>)}
          </div>}
        <div className="atlas-scale">
          <p>{mode === 'wheel' ? 'One turn per year. Distance from the centre shows demand. Drag to rotate.' : 'Select a month to inspect demand. A dash marks a gap in the record.'}</p>
          <div className="atlas-demand-key" aria-label={`Grid demand from ${num(low)} to ${num(high)} GWh`}>
            <span>{num(low)}</span>
            <span className="atlas-demand-ramp" aria-hidden="true"
              style={{background: `linear-gradient(90deg, ${gridDemandStops.map((_, index) => gridDemandColor(index / (gridDemandStops.length - 1))).join(', ')})`}} />
            <span>{num(high)} GWh</span>
          </div>
        </div>
      </div>
      <div className="atlas-detail">
        <label>History range<select value={windowSize} onChange={event => setWindowSize(event.target.value)}>
          <option value="3">Last 3 calendar years</option><option value="5">Last 5 calendar years</option><option value="all">All available years</option>
        </select></label>
        <div className="atlas-readout" aria-live="polite">
          <span>{atlasMonthLabels[selected.month]} {selected.year}</span>
          <strong>{num(selected.value, 1)} <small>GWh</small></strong>
          {Number.isFinite(selected.coverage)&&selected.coverage<1&&<p>{num(selected.coverage*100,1)}% source coverage</p>}
          <p>{delta === null ? 'Same month last year unavailable' : `${delta > 0 ? '+' : ''}${num(delta, 1)}% vs the same month last year`}</p>
        </div>
        <label>Month<input type="range" min="0" max={points.length - 1} value={position}
          aria-valuetext={`${atlasMonthLabels[selected.month]} ${selected.year}`}
          onChange={event => setSelectedKey(points[Number(event.target.value)].key)} /></label>
        {source?.link&&<a href={source.link} target="_blank" rel="noreferrer">Open {publisher} source ↗</a>}
      </div>
    </div>
  </section>;
}

const gridAtlasStyles = `
.grid-atlas{color:#1b2e37}
.atlas-heading,.atlas-modes,.atlas-camera,.atlas-scale{display:flex;align-items:center;gap:8px}
.atlas-heading{justify-content:space-between;flex-wrap:wrap;margin-bottom:18px}
.atlas-heading h2{font-size:clamp(23px,3.6vw,33px);letter-spacing:-.045em;margin:0;line-height:1.08}
.atlas-heading p{margin:6px 0 0;color:#52666a;font-size:12px}
.atlas-heading .atlas-kicker{color:#306f5e;font-size:10px;font-weight:700;letter-spacing:.13em;text-transform:uppercase;margin:0 0 6px}
.atlas-modes{padding:4px;gap:3px;border-radius:9px;background:#e9efec}
.atlas-modes button,.atlas-camera button{border-radius:6px;padding:7px 11px;cursor:pointer;font-size:11px;font-weight:700}
.atlas-modes button{color:#526761;background:transparent}
.atlas-modes button[aria-pressed=true]{background:#fff;color:#234d3d;box-shadow:0 2px 6px #18332b14}
.atlas-modes button:hover{color:#1b4f41}
.atlas-body{display:grid;grid-template-columns:minmax(0,1fr) minmax(175px,.36fr);gap:16px}
.atlas-visual{min-width:0}
.atlas-wheel{overflow:hidden;position:relative;border-radius:10px;background:radial-gradient(ellipse at 47% 43%,#203947,#13212e 78%);border:1px solid #233746}
.atlas-wheel canvas{display:block;width:100%;height:clamp(285px,43vw,430px);touch-action:pan-y;cursor:grab}
.atlas-wheel canvas:active{cursor:grabbing}
.atlas-camera{position:absolute;bottom:10px;left:50%;transform:translateX(-50%);white-space:nowrap}
.atlas-camera button{background:#1f3540;color:#e3eeef;border:1px solid #55717a}
.atlas-camera button:hover{background:#2c4b52}
.atlas-detail{display:grid;align-content:start;gap:17px;background:#f5f8f7;border:1px solid #e2e9e6;border-radius:10px;padding:15px}
.atlas-detail label{display:grid;gap:6px;font-size:12px;font-weight:700;color:#3b5651}
.atlas-detail select{width:100%;border-radius:7px;padding:7px;background:#fff;color:#1b2e37;border:1px solid #ccdad5}
.atlas-detail input{width:100%;min-width:0;accent-color:#238b70}
.atlas-detail a{font-size:12px;font-weight:700;color:#176653;text-underline-offset:3px}
.atlas-readout span,.atlas-readout p{font-size:12px;color:#52666a;margin:4px 0}
.atlas-readout strong{display:block;font-size:clamp(25px,4vw,38px);letter-spacing:-.05em;line-height:1.15;overflow-wrap:anywhere}
.atlas-readout small{font-size:13px;letter-spacing:0}
.atlas-scale{justify-content:space-between;flex-wrap:wrap;color:#52666a;font-size:12px;margin:8px 0 0}
.atlas-scale p{margin:0}
.atlas-demand-key{display:flex;align-items:center;gap:6px;white-space:nowrap;font-variant-numeric:tabular-nums}
.atlas-demand-ramp{display:block;width:clamp(66px,10vw,108px);height:7px;border-radius:99px}
.atlas-calendar{overflow:auto;max-height:430px;border:1px solid #e2e9e6;border-radius:10px;padding:10px;background:#f5f8f7}
.atlas-calendar-row{min-width:430px;display:grid;grid-template-columns:45px repeat(12,minmax(25px,1fr));gap:4px;align-items:center;text-align:center;color:#42595a;font-size:10px;padding:3px 0}
.atlas-calendar-row button,.atlas-gap{height:23px;border:1px solid transparent;border-radius:4px}
.atlas-calendar-row button{cursor:pointer}
.atlas-calendar-row button[aria-pressed=true]{border:2px solid #13212e;box-shadow:inset 0 0 0 1px #fff}
.grid-atlas button:focus-visible,.grid-atlas select:focus-visible,.grid-atlas input:focus-visible,.grid-atlas a:focus-visible{outline:2px solid #1b7d65;outline-offset:2px}
.atlas-camera button:focus-visible{outline-color:#d9efea}
@media(max-width:820px){.atlas-body{grid-template-columns:minmax(0,1fr)}}
`;

export default function App(){
 const [boot,setBoot]=useState(null),[country,setCountry]=useState('PT'),[tab,setTab]=useState(()=>nav.find(([id])=>window.location.hash==='#'+id)?.[0]||'live'),[error,setError]=useState(''),[busy,setBusy]=useState(false);
 const [usage,setUsage]=useState(''),[bill,setBill]=useState(''),[region,setRegion]=useState('PT-mainland'),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(.5),[powerKva,setPowerKva]=useState(''),[profileSource,setProfileSource]=useState('annual_user_input'),[demo,setDemo]=useState(false),[quotes,setQuotes]=useState(null),[bills,setBills]=useState(null),[accepted,setAccepted]=useState(''),[comparison,setComparison]=useState(null);
 const [kind,setKind]=useState('demand'),[monthly,setMonthly]=useState(null),[provider,setProvider]=useState(''),[bench,setBench]=useState(null),[evidence,setEvidence]=useState(null);
 const [runtime,setRuntime]=useState(null),[runtimeError,setRuntimeError]=useState(''),[liveBusy,setLiveBusy]=useState(false);
 const analysisStartRef=useRef(null);
 const focusAnalysis=()=>requestAnimationFrame(()=>{analysisStartRef.current?.focus({preventScroll:true});analysisStartRef.current?.scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});});
 const [month,setMonth]=useState(''),[nemRegion,setNemRegion]=useState('NSW1'),[live,setLive]=useState(null),[brand,setBrand]=useState('agl'),[postcode,setPostcode]=useState(''),[plans,setPlans]=useState(null),[planId,setPlanId]=useState(''),[plan,setPlan]=useState(null);
 const [jsonInput,setJsonInput]=useState(''),[apiType,setApiType]=useState('consumer_compare'),[apiOutput,setApiOutput]=useState(null);
 useEffect(()=>{let cancelled=false;request('/api/runtime').then(d=>{if(!cancelled){setRuntime(d);setMonth(d.latest_complete_month||d.latest_month||'')}}).catch(e=>{if(!cancelled)setRuntimeError(e.message)});return()=>{cancelled=true}},[]);
 useEffect(()=>{if(tab==='live'||boot)return;let cancelled=false;request('/api/bootstrap').then(d=>{if(!cancelled){setBoot(d);setMonth(d.latest_month)}}).catch(e=>{if(!cancelled)setError(e.message)});return()=>{cancelled=true}},[tab,boot]);
 useEffect(()=>{if(tab!=='models')return;setEvidence(null);let cancel=false;request('/api/model_evidence',{country}).then(d=>{if(!cancel)setEvidence(d)}).catch(e=>setError(e.message));return()=>{cancel=true}},[country,tab]);
 const market=markets[country];const history=boot?.histories[country]||[];
 const payload=()=>{let p={country,region,profile_source:profileSource,meter_type:meter,peak_share:Number(peak),allow_illustrative:demo,offers:quotes||(demo?boot.example_quotes.filter(q=>q.country===country):[]),accepted_conditions:accepted.split(',').map(x=>x.trim()).filter(Boolean)};if(powerKva)p.contracted_power_kva=Number(powerKva);if(bills){p.billing_months=bills;if(bills.every(x=>'peak_kwh'in x))delete p.peak_share;}else{p.annual_kwh=Number(usage);p.current_annual_bill=Number(bill)}return p};
 const run=async(fn)=>{setError('');setBusy(true);try{await fn()}catch(e){setError(e.message)}finally{setBusy(false)}};
 const changeMarket=c=>{if(liveBusy)return;setCountry(c);setRegion(markets[c].region);setComparison(null);setBench(null);setBills(null);setPowerKva('');setProfileSource('annual_user_input');setQuotes(null);setLive(null);setError('')};
 const best=comparison?.ranked_offers?.[0];
 let billingUsage=bills?bills.reduce((s,r)=>s+Number(r.kwh||0),0):Number(usage);let billingTotal=bills?bills.reduce((s,r)=>s+Number(r.billed_total||0),0):Number(bill);

 return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('live');window.history.replaceState(null,'','#live')}}><div className="brand-symbol"><Zap size={23} fill="currentColor"/></div><div><strong>XenoWAttz</strong><small>WITH BHOR BOHR</small></div></a><div className="side-divider"/><div className="side-label">ELECTROCHEAP WORKSPACE</div><nav>{nav.map(([id,label,Icon])=><button key={id} aria-current={id===tab?'page':undefined} onClick={()=>{setTab(id);window.history.replaceState(null,'','#'+id);setError('')}} className={tab===id?'nav-item active':'nav-item'}><Icon size={19}/>{label}{id===tab&&<ChevronRight size={15} className="nav-arrow"/>}</button>)}</nav><div className="side-character"><img src="/brand/xenowattz-poster.png" alt="Bhor Bohr, the XenoWAttz energy rebel" loading="lazy"/><div><span className="tiny-dot"/>Bhor Bohr is in the grid.</div></div><div className="side-foot"><span className="status-dot"/>CPU research space<small>Source first. Estimate second.</small></div></aside>
 <main><header className="topbar"><div className="crumb">XenoWAttz <ChevronRight size={13}/><b>Electrocheap</b></div><div className="top-links"><span className="research-badge">RESEARCH PREVIEW</span><a href="/docs" target="_blank" rel="noreferrer">API docs <ArrowUpRight size={14}/></a></div></header>
 <div className="page"><div hidden={tab!=='live'}><EnergyIntro active={tab==='live'} onStart={focusAnalysis}/></div><div className="page-heading" ref={analysisStartRef} tabIndex={-1}><div><div className="eyebrow">ELECTRICITY, WITH THE EVIDENCE ATTACHED</div><h1>{tab==='live'?'Your data. A fresh analysis.':tab==='atlas'?'Explore grid demand.':tab==='quotes'?'More clarity. Less bill shock.':tab==='bills'?'Your year, in kilowatt-hours.':tab==='analysis'?'From billing archive to scenario.':tab==='benchmark'?'Challenge the forecast.':tab==='challenge'?'Put our model to the test.':tab==='models'?'Every model earns its place.':tab==='sources'?'Go straight to the source.':'The engine behind XenoWAttz.'}</h1><p>{tab==='live'?'Run a forecast, compare supplied offers, and check the market when you need it.':tab==='atlas'?'Follow seasonal demand through the published monthly series for Portugal, Germany and Australia.':tab==='quotes'?'Compare the offers you can actually use, with every supplied cost included.':tab==='bills'?'A complete bill profile makes a better starting point than a national average.':tab==='analysis'?'Import compressed bills, inspect tariffs, and compare constrained provider plans.':tab==='benchmark'?'Chronological calibration, validation and test. Complexity gets no free pass.':tab==='challenge'?'Portable prompts, matched predictions and fine-tuning files.':tab==='models'?'TSF, transformers and Astra — inspect the versions and the measured evidence.':tab==='sources'?'Published demand, wholesale prices and Australian retailer plan data.':'React on the surface. Reproducible Python underneath.'}</p></div><div className="market-switch">{Object.entries(markets).map(([c,m])=><button key={c} className={c===country?'selected':''} disabled={liveBusy} title={liveBusy?'Wait for the current analysis before changing markets':undefined} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>
 {error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}
 {tab!=='live'&&tab!=='atlas'&&<div className="stats-row"><div><span>SELECTED MARKET</span><strong>{market.name}<small>{market.flag}</small></strong><p>{market.scope}</p></div><div><span>YOUR CONSUMPTION SCENARIO</span><strong>{bills||usage!==''?num(billingUsage):'—'}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':profileSource==='annual_user_input'?(usage!==''?'From your annual input':'Enter your consumption'):'Reviewed annualized invoice estimate'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{bills||bill!==''?num(billingTotal,2):'—'}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:bill!==''?'Full electricity cost, tax included':'Enter your electricity cost'}</p></div></div>}
 <div hidden={tab!=='live'}><LiveWorkspace key={country} country={country} market={market} runtime={runtime} runtimeError={runtimeError} onPendingChange={setLiveBusy} onOpenBills={()=>setTab('analysis')}/></div>
 {tab!=='live'&&!boot&&<section className="panel" role="status"><h2>Loading this workspace</h2><p>{error||'Retrieving the archive and source registry…'}</p>{error&&<button className="secondary" onClick={()=>{setError('');request('/api/bootstrap').then(setBoot).catch(e=>setError(e.message))}}>Retry</button>}</section>}
 {boot&&<><div hidden={tab!=='analysis'}><AnalysisPanel country={country} quotes={quotes} onError={setError} onProfile={p=>{setCountry(p.country);setRegion(p.region);setUsage(p.annual_kwh);setBill(p.current_annual_bill);setMeter(p.meter_type);setPowerKva(p.contracted_power_kva??'');setProfileSource(p.profile_source);setBills(null);setComparison(null);setTab('quotes')}}/></div>
 {tab==='quotes'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><Zap size={18}/></span><div><h2>Build your comparison</h2><p>Complete quotes. One consistent usage scenario.</p></div><span className="step">01</span></div><div className="form-grid"><Field label="Annual usage · kWh"><input type="number" min="1" value={bills?billingUsage:usage} disabled={!!bills} onChange={e=>setUsage(e.target.value)}/></Field><Field label={`Current annual cost · ${market.currency}`}><input type="number" min="0" value={bills?billingTotal:bill} disabled={!!bills} onChange={e=>setBill(e.target.value)}/></Field><Field label="Eligibility region / grid"><input value={region} onChange={e=>setRegion(e.target.value)}/></Field><Field label="Contracted power · kVA (when applicable)"><input type="number" value={powerKva} placeholder="e.g. 3.45" min="0.1" step="0.05" onChange={e=>setPowerKva(e.target.value)}/></Field><Field label="Meter type"><select value={meter} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label={`Peak usage share · ${Math.round(peak*100)}%`}><input type="range" min="0" max="1" step=".01" value={peak} onChange={e=>setPeak(e.target.value)}/></Field>}<CsvUpload label={quotes?`${quotes.length} supplied quotes loaded`:'Add your provider quotes'} onData={d=>{setQuotes(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/quote_template.csv" download>Get the empty template <Download size={13}/></a><button onClick={()=>setTab('bills')}>{bills?'Edit bill profile':'Use monthly bills'} <ArrowRight size={13}/></button></div><Field label="Acknowledged offer condition IDs · optional"><input value={accepted} placeholder="Comma-separated IDs" onChange={e=>setAccepted(e.target.value)}/></Field><label className="check-row"><input type="checkbox" checked={demo} onChange={e=>{setDemo(e.target.checked);setComparison(null)}}/><span>Try fictional example quotes<small>Illustrative sandbox · explicitly enabled</small></span></label><button className="primary full" disabled={busy} onClick={()=>run(async()=>setComparison(await request('/api/consumer_compare',payload())))}>{busy?<RefreshCw size={16}/>:<Zap size={16}/>}Compare eligible quotes<ArrowRight size={16}/></button></section><div className="right-stack"><section className="panel grid-card"><div className="section-title"><div><div className="eyebrow">ARCHIVED MARKET CONTEXT</div><h2>{market.name} · grid demand</h2></div><span className="source-pill">{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'}</span></div><Chart series={[{name:'Published monthly grid energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/><div className="chart-caption">{history.length} archived monthly records · {String(history[0]?.timestamp||'').slice(0,7)}–{String(history.at(-1)?.timestamp||'').slice(0,7)}<span>GWh</span></div><p className="subtle">Grid demand provides context. It does not describe an individual retailer or predict your bill.</p></section><section className="how-card"><span className="icon-box"><CheckCircle2 size={19}/></span><h3>The whole quoted cost.</h3><p>Energy + supply charges + annual fees + switching costs − guaranteed credits.</p><div className="how-tags"><span>Tax included</span><span>Eligibility checked</span><span>Dated evidence</span></div></section></div></div>{comparison&&<section className="panel result-panel"><div className="section-title"><div><div className="eyebrow">{demo?'ILLUSTRATIVE SCENARIO':'SUPPLIED QUOTE SCENARIO'}</div><h2>{best?`${best.provider} · lowest supplied first-year cost`:'No eligible quotes'}</h2></div>{best&&<strong className="result-cost">{num(best.first_year_cost,2)} <small>{market.currency}</small></strong>}</div>{best&&<p>Estimated difference from your supplied annual bill: <b>{num(best.estimated_saving,2)} {market.currency}</b>. {best.price_basis}.</p>}<Table rows={comparison.ranked_offers} columns={[["provider","Provider"],["first_year_cost","First-year cost"],["recurring_annual_cost","Recurring cost"],["estimated_saving","Estimated saving"],["evidence","Evidence"]]}/>{comparison.excluded_offers.length>0&&<details><summary>Excluded quotes and reasons ({comparison.excluded_offers.length})</summary><Table rows={comparison.excluded_offers} columns={[["offer_id","Offer"],["reason","Reason"]]}/></details>}<details><summary>Calculation evidence</summary><Json value={comparison}/></details></section>}<Notice>Quotes must be complete and tax inclusive. The comparison covers eligible supplied offers; it is not a whole-market promise. Complex indexed, tiered, demand-charge or export tariffs need a complete scoped quote.</Notice></>}
 {tab==='bills'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><ReceiptText size={18}/></span><div><h2>A complete latest-year profile</h2><p>Twelve complete months before the current month.</p></div></div><button className="secondary full" onClick={()=>setTab('analysis')}><Upload size={16}/>Import ZIP / PDF billing archives</button><CsvUpload label="Upload anonymous monthly bills" help="month, kwh, billed_total, currency · optional peak_kwh" onData={d=>{setBills(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/example_billing_months.csv" download>Download fictional EUR sample <Download size={13}/></a>{country==='PT'&&<button onClick={()=>{setBills(boot.example_bills);setComparison(null)}}>Load fictional sample</button>}</div><Notice>Use actual tax-inclusive electricity charges, not bank-payment instalments. Remove names, addresses and account numbers. Each month must appear once, in the selected market currency.</Notice><button className="primary full" onClick={()=>setTab('quotes')}>Compare using this profile <ArrowRight size={16}/></button>{bills&&<button className="text-button" onClick={()=>{setBills(null);setComparison(null)}}>Clear monthly profile</button>}</section><section className="panel"><h2>What your data can tell us</h2><div className="explain-row"><span>01</span><div><b>Consumption and current cost</b><p>Your latest-year totals replace the manual annual fields.</p></div></div><div className="explain-row"><span>02</span><div><b>Peak and off-peak allocation</b><p>Supply peak_kwh for every month, or supply your measured peak share separately.</p></div></div><div className="explain-row"><span>03</span><div><b>A starting scenario, not a model winner</b><p>Twelve monthly bills cover only one annual cycle. The grid-model leaderboard cannot select a reliable household forecaster.</p></div></div></section></div>{bills&&<section className="panel"><h2>Supplied monthly profile</h2><Chart series={[{name:'Monthly consumption',values:bills.map(x=>Number(x.kwh))}]} labels={bills.map(x=>x.month)} unit="kWh"/><Table rows={bills} columns={[["month","Month"],["kwh","Consumption · kWh"],["billed_total","Billed electricity cost"],["currency","Currency"]]}/></section>}</>}
 {tab==='atlas'&&<GridAtlas key={country} history={history} market={market} source={boot?.sources?.find(entry=>entry.market===market.name)} loaded={!!boot}/>}
 {tab==='benchmark'&&<><section className="panel"><div className="section-title"><div><h2>The forecast laboratory</h2><p>Same series. Same origins. Validation chooses; test measures.</p></div><span className="source-pill">PROTOCOL V2</span></div><div className="form-grid three"><Field label="Forecast target"><select value={kind} onChange={e=>{setKind(e.target.value);setBench(null)}}><option value="demand">Monthly grid energy · GWh</option><option value="price">Monthly wholesale price · {market.currency}/MWh</option></select></Field><Field label="Provider label · uploaded data only"><input value={provider} placeholder="Exact provider column value" onChange={e=>setProvider(e.target.value)}/></Field><div className="worker-note"><span className="status-dot"/>Single CPU benchmark worker<br/><small>No paid model calls</small></div></div><CsvUpload label={monthly?`${monthly.length} monthly records loaded`:'Use an optional monthly series'} help="timestamp,value,unit,coverage · ≥72 complete months" onData={d=>{setMonthly(d);setBench(null)}} onError={setError}/>{monthly&&<button className="text-button" onClick={()=>{setMonthly(null);setBench(null)}}>Use bundled grid snapshot instead</button>}<div className="protocol-strip"><span><b>1.</b> Training prefix</span><ArrowRight size={14}/><span><b>2.</b> Calibration</span><ArrowRight size={14}/><span><b>3.</b> Validation</span><ArrowRight size={14}/><span><b>4.</b> Test</span></div><div className="button-row"><button className="primary" disabled={busy} onClick={()=>run(async()=>setBench(await request('/api/benchmark',{country,kind,records:monthly,provider})))}>{busy?<RefreshCw size={16}/>:<Play size={16}/>}Run CPU benchmark</button><span className="subtle">Seasonal baselines · SARIMA · Grokked · SARIMAX · GARCH</span></div></section>{!bench&&<section className="panel"><div className="section-title"><h2>Published historical context</h2><span className="source-pill">{market.scope}</span></div>{kind==='demand'?<Chart series={[{name:'Monthly energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/>:<div className="empty">Wholesale history is not bundled. Upload a complete monthly price series to run a pricing benchmark.</div>}</section>}{bench&&<section className="panel"><div className="section-title"><div><div className="eyebrow">VALIDATION-SELECTED</div><h2>{bench.selected_model}</h2><p>{bench.series_scope} · held-out test starts {bench.test_start}</p></div><button className="secondary" onClick={()=>download(bench,'electrocheap-benchmark.json')}><Download size={15}/>Evidence JSON</button></div><Chart unit={bench.unit} labels={bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.timestamp)} series={[{name:'Actual',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.actual),color:'#243344'},{name:bench.selected_model,values:bench.predictions.filter(p=>p.split==='test'&&p.model===bench.selected_model).map(p=>p.forecast),color:'#18a184'},{name:'Seasonal naive',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.forecast),color:'#e59b39',dashed:true}]}/><Table rows={bench.scores.filter(s=>s.split==='test')} columns={[["model","Model"],["MAE","MAE"],["RMSE","RMSE"],["MASE","MASE"],["selected_on_validation","Selected"]]}/><details><summary>Residual GARCH volatility and protocol</summary><Json value={{volatility:bench.residual_volatility,claim:bench.claim,input_sha256:bench.input_sha256,implementation_sha256:bench.implementation_sha256}}/></details></section>}<Notice>At least 72 consecutive complete months. No interpolation. Bias is frozen after calibration; a candidate needs 5% better validation MAE to replace the baseline. GARCH estimates residual volatility and keeps the SARIMAX mean unchanged. Tests are retrospective and descriptive.</Notice></>}
 {tab==='challenge'&&<ChallengePanel key={country} country={country}/>}
 {tab==='models'&&<><AuditDatasets/><section className="panel"><div className="section-title"><div><h2>The full recorded model family</h2><p>Archived grid-demand evidence · 24 test targets · six-month forecasts</p></div><span className="source-pill">2026-10-09 ARCHIVE</span></div><Table rows={evidence?.scores} columns={[["model","Model / variant"],["mae_gwh","MAE · GWh"],["mase","MASE"],["skill_vs_seasonal_naive_pct","Skill vs baseline · %"],["selected_on_validation","Selected"]]}/></section><div className="model-cards"><section className="panel"><div className="eyebrow">LIVE CPU CANDIDATES</div><h2>Statistical & Grokked</h2><p>Seasonal baselines, SARIMA, the explicit 80/20 Grokked blend, calendar SARIMAX and residual GARCH.</p><span className="availability live"><CheckCircle2 size={14}/>Runnable in Forecast lab</span></section><section className="panel"><div className="eyebrow">PINNED TRANSFORMERS</div><h2>TimesFM 2.5 · Chronos-2</h2><p>Exact checkpoint revisions and Python package versions preserved from the measured archived runs.</p><span className="availability"><BarChart3 size={14}/>Cached measured evidence</span></section><section className="panel"><div className="eyebrow">HOSTED MODEL DIAGNOSTICS</div><h2>Astra · Sol</h2><p>Archived delegated test diagnostics. No separately authenticated customer inference API is configured.</p><span className="availability"><BarChart3 size={14}/>Diagnostic only</span></section></div><Notice>A separate Super Grokked implementation and the original KMLAIOps SARIMAX-GARCHX source are unavailable. Newly written adapters are not presented under those identities. Grid scores do not establish household accuracy or bill savings.</Notice><section className="panel"><details><summary>Inspect exact versions, source commits and availability</summary><Json value={evidence}/></details></section></>}
 {tab==='sources'&&<><div className="two-column"><section className="panel"><h2>Official grid & wholesale feed</h2><p className="subtle">Fetch only on request. Freshness and completeness travel with the response.</p><div className="form-grid"><Field label="Complete month · YYYY-MM"><input value={month} onChange={e=>setMonth(e.target.value)}/></Field><Field label="Australian NEM region"><select value={nemRegion} onChange={e=>setNemRegion(e.target.value)}>{boot.au_regions.map(r=><option key={r}>{r}</option>)}</select></Field></div><button className="primary" disabled={busy} onClick={()=>run(async()=>setLive(await request('/api/live_market',{country,region:nemRegion,month})))}><RefreshCw size={15}/>Fetch official data</button></section><section className="panel"><h2>Australian retailer plans</h2><p className="subtle">AER Product Reference Data. Full plan pricing is inspected before any normalization.</p><div className="form-grid"><Field label="Retailer"><select value={brand} onChange={e=>setBrand(e.target.value)}>{boot.aer_brands.map(b=><option key={b}>{b}</option>)}</select></Field><Field label="Postcode · optional"><input value={postcode} placeholder="2000" onChange={e=>setPostcode(e.target.value)}/></Field></div><button className="secondary" disabled={busy} onClick={()=>run(async()=>setPlans(await request('/api/aer_plans',{brand,postcode})))}>Read retailer plans <ArrowRight size={15}/></button></section></div>{live&&<section className="panel"><h2>Fetched market data</h2><Table rows={live.records.slice(0,100)} columns={Object.keys(live.records[0]||{}).map(k=>[k,k])}/><p className="subtle">Showing up to 100 of {live.records.length} source records.</p><details><summary>Source, retrieval time and completeness</summary><Json value={live.metadata}/></details><button className="secondary" onClick={()=>download(live,'electrocheap-live-feed.json')}><Download size={14}/>Download full response</button></section>}{plans&&<section className="panel"><h2>Published retailer plans</h2><Table rows={plans.records} columns={Object.keys(plans.records[0]||{}).map(k=>[k,k])}/><div className="button-row"><Field label="Plan ID"><input value={planId} onChange={e=>setPlanId(e.target.value)} placeholder="Copy from the plan table"/></Field><button className="secondary" disabled={busy||!planId} onClick={()=>run(async()=>setPlan(await request('/api/aer_detail',{brand,plan_id:planId})))}>Inspect full plan</button></div><details><summary>Plan list metadata</summary><Json value={plans.metadata}/></details>{plan&&<Json value={plan}/>}</section>}<section className="panel"><h2>Source registry</h2><Table rows={boot.sources} columns={Object.keys(boot.sources[0]||{}).map(k=>[k,k])}/></section><Notice>Australia covers the NEM, excluding WA and NT. Portugal is mainland only. German live data validates every hourly observation across the complete local month, including daylight-saving changes. Wholesale prices are not retail bills; national grids do not reveal retailer-level customer demand.</Notice></>}
 {tab==='api'&&<><section className="panel"><div className="section-title"><div><h2>On-demand analysis and audit APIs.</h2><p>Anonymous profiles, dated quotes and explicit evidence.</p></div><a className="secondary" href="/docs" target="_blank" rel="noreferrer">Open REST documentation <ArrowUpRight size={14}/></a></div><div className="api-cards"><div><code>live_analysis</code><p>Run customer or NGO forecasts with dated market and news context.</p></div><div><code>market_news</code><p>Read SerpApi electricity news with source dates and cache metadata.</p></div><div><code>consumer_compare</code><p>One household or site. Annual totals or the latest 12 monthly bills.</p></div><div><code>ngo_compare</code><p>Up to 100 anonymous profiles. Totals stay separate by currency.</p></div><div><code>model_evidence</code><p>Archived grid-demand scores and exact implementation versions.</p></div></div><div className="form-grid"><Field label="REST endpoint"><select value={apiType} onChange={e=>setApiType(e.target.value)}><option>live_analysis</option><option>market_news</option><option>consumer_compare</option><option>ngo_compare</option><option>model_evidence</option></select></Field><div className="button-row"><button className="secondary" onClick={()=>{let p=payload();if(['model_evidence','market_news'].includes(apiType))p={country};if(apiType==='live_analysis')p={role:'customer',country,include_news:true,include_market:true,series:[],horizon_months:12,models:['seasonal_naive']};if(apiType==='ngo_compare')p={offers:p.offers,allow_illustrative:p.allow_illustrative,profiles:[{...p,profile_id:'anonymous-001'}]};setJsonInput(JSON.stringify(p,null,2))}}>Use current profile</button></div></div><Field label="JSON request · editable"><textarea rows="14" spellCheck="false" value={jsonInput} onChange={e=>setJsonInput(e.target.value)} placeholder={'{"country":"PT"}'}/></Field><button className="primary" disabled={busy||!jsonInput} onClick={()=>run(async()=>setApiOutput(await request('/api/'+apiType,JSON.parse(jsonInput))))}>Run API request <ArrowRight size={15}/></button>{apiOutput&&<Json value={apiOutput}/>}<details><summary>MCP connection for XenoWAttz</summary><Json value={{mcpServers:{xenowattz:{type:'streamable-http',url:location.origin+'/mcp-server/mcp'}}}}/></details></section><section className="panel"><h2>Keep the decision honest</h2><p>First-year quote cost = annual kWh × rate + 365 × daily charge + annual fees + switching cost − guaranteed credit. A two-period tariff uses the supplied peak/off-peak allocation. The quote must include taxes and all mandatory fees.</p><p>Unknown eligibility, incomplete tariff structures and stale quotes are excluded. Model selection is separate from tariff arithmetic. Forecast accuracy alone does not demonstrate financial savings.</p><Notice>This public research API has no customer billing, tenant isolation, contracting or automatic switching. Inputs are processed in memory. Do not submit personal identifiers. React uploads are parsed in your browser; the normalized data is sent to the API only when you run a request.</Notice></section></>}
 </>}
 <footer><span><Zap size={13}/>Electrocheap · XenoWAttz × Bhor Bohr</span><span>Evidence before savings. Always.</span></footer></div></main></div>;
}