forked from johanzander/bess-manager-beta
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetupWizardPage.tsx
More file actions
696 lines (645 loc) · 33.9 KB
/
Copy pathSetupWizardPage.tsx
File metadata and controls
696 lines (645 loc) · 33.9 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { CheckCircle, ChevronRight, ChevronLeft, Zap, Eye } from 'lucide-react';
import api from '../lib/api';
import { INTEGRATIONS, INVERTER_INTEGRATION_IDS, SHARED_INTEGRATION_IDS, emptyPerPlatformSensors, getActiveSensorsFlat } from '../lib/sensorDefinitions';
import type { PerPlatformSensors } from '../lib/sensorDefinitions';
import { HomeFormSection } from '../components/settings/HomeFormSection';
import type { HomeForm } from '../components/settings/HomeFormSection';
import { PricingFormSection } from '../components/settings/PricingFormSection';
import type { PricingForm } from '../components/settings/PricingFormSection';
import { BatteryFormSection } from '../components/settings/BatteryFormSection';
import type { BatteryForm } from '../components/settings/BatteryFormSection';
import { SensorConfigSection } from '../components/settings/SensorConfigSection';
import type { DiscoveryResult, InverterForm } from '../components/settings/SensorConfigSection';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const STEPS = ['Scan', 'Review Sensors', 'Electricity Pricing', 'Battery', 'Home', 'Control Mode', 'Done'];
// Battery cycle cost approximates wear cost per kWh cycled, so the SEK
// default (0.40) is wrong for other currencies. Mirrors
// core.bess.settings.CYCLE_COST_BY_CURRENCY.
const CYCLE_COST_BY_CURRENCY: Record<string, number> = { SEK: 0.40, EUR: 0.035, GBP: 0.031 };
// Placeholder values (bootstrap SEK default, initial form default) treated as
// "not yet user-configured" so a detected currency can safely replace them.
const UNSET_CYCLE_COST_DEFAULTS = new Set([0.40, 0.50]);
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
const SetupWizardPage: React.FC = () => {
const navigate = useNavigate();
const [step, setStep] = useState(0);
const [scanning, setScanning] = useState(false);
const [scanError, setScanError] = useState<string | null>(null);
const [discovery, setDiscovery] = useState<DiscoveryResult | null>(null);
const [sensors, setSensors] = useState<PerPlatformSensors>(emptyPerPlatformSensors());
const [completing, setCompleting] = useState(false);
const [completeError, setCompleteError] = useState<string | null>(null);
const [controlMode, setControlMode] = useState<'demo' | 'live' | null>(null);
const existingSensorsRef = useRef<PerPlatformSensors>(emptyPerPlatformSensors());
const [batteryForm, setBatteryForm] = useState<BatteryForm>({
totalCapacity: 30.0,
minSoc: 15,
maxSoc: 95,
maxChargeDischargePowerKw: 15.0,
cycleCostPerKwh: 0.50,
efficiencyCharge: 97,
efficiencyDischarge: 97,
temperatureDeratingEnabled: false,
minActionProfit: 8.0,
});
const [inverterForm, setInverterForm] = useState<InverterForm>({
inverterPlatform: 'growatt_server_min',
deviceId: '',
controlMode: 'tou',
});
const [homeForm, setHomeForm] = useState<HomeForm>({
consumption: 3.5,
consumptionStrategy: 'sensor',
maxFuseCurrent: 25,
voltage: 230,
safetyMarginFactor: 1.0,
phaseCount: 3,
powerMonitoringEnabled: true,
});
const [pricingForm, setPricingForm] = useState<PricingForm>({
provider: 'nordpool_official',
currency: 'SEK',
area: '',
nordpoolConfigEntryId: '',
nordpoolEntity: '',
octopusImportTodayEntity: '',
octopusImportTomorrowEntity: '',
octopusExportTodayEntity: '',
octopusExportTomorrowEntity: '',
entsoeEntity: '',
markupRate: 0.08,
vatMultiplier: 1.25,
additionalCosts: 0.77,
taxReduction: 0.2,
spotMultiplier: 1.0,
exportSpotMultiplier: 1.0,
sellPriceEqualsBuyPrice: false,
});
const handleScan = useCallback(async () => {
setScanning(true);
setScanError(null);
setDiscovery(null);
try {
const res = await api.post('/api/setup/discover');
const d: DiscoveryResult = res.data;
setDiscovery(d);
// Seed form defaults from auto-detected hints
if (d.detectedPhaseCount) {
setHomeForm(f => ({ ...f, phaseCount: d.detectedPhaseCount! }));
}
// Auto-select pricing provider based on discovered integrations.
// When the official HA Nordpool integration is present (has a
// config_entry_id), prefer it. Otherwise fall back to HACS custom.
const hasOfficialNordpool = !!d.nordpoolConfigEntryId;
const hasCustomNordpool = !!d.nordpoolCustomArea;
const autoProvider = d.octopusFound && !d.nordpoolFound
? 'octopus' as const
: d.entsoeFound && !d.nordpoolFound
? 'entsoe' as const
: hasOfficialNordpool
? 'nordpool_official' as const
: hasCustomNordpool
? 'nordpool_hacs' as const
: undefined;
// Use area from the matching integration — not mixed
const autoArea = hasOfficialNordpool ? d.nordpoolArea : d.nordpoolCustomArea;
setPricingForm(f => ({
...f,
// Only seed spot-multiplier defaults when the provider is newly
// auto-detected (changing) — never on a re-scan of an already
// configured provider, or this would clobber a saved custom
// contract-specific value (e.g. a real Luminus vs. non-Luminus
// ENTSO-e multiplier) every time the wizard mounts or rescans.
...(autoProvider && autoProvider !== f.provider ? (d.pricingDefaults ?? {}) : {}),
...(autoProvider ? { provider: autoProvider } : {}),
...(d.currency ? { currency: d.currency } : {}),
...(autoArea ? { area: autoArea } : {}),
...(d.vatMultiplier ? { vatMultiplier: d.vatMultiplier } : {}),
...(d.nordpoolConfigEntryId ? { nordpoolConfigEntryId: d.nordpoolConfigEntryId } : {}),
...(d.nordpoolCustomEntity ? { nordpoolEntity: d.nordpoolCustomEntity } : {}),
...(d.octopusEntities?.importToday ? { octopusImportTodayEntity: d.octopusEntities.importToday } : {}),
...(d.octopusEntities?.importTomorrow ? { octopusImportTomorrowEntity: d.octopusEntities.importTomorrow } : {}),
...(d.octopusEntities?.exportToday ? { octopusExportTodayEntity: d.octopusEntities.exportToday } : {}),
...(d.octopusEntities?.exportTomorrow ? { octopusExportTomorrowEntity: d.octopusEntities.exportTomorrow } : {}),
...(d.entsoeEntity ? { entsoeEntity: d.entsoeEntity } : {}),
}));
if (d.currency && CYCLE_COST_BY_CURRENCY[d.currency] !== undefined) {
const cycleCost = CYCLE_COST_BY_CURRENCY[d.currency];
setBatteryForm(f => (
UNSET_CYCLE_COST_DEFAULTS.has(f.cycleCostPerKwh)
? { ...f, cycleCostPerKwh: cycleCost }
: f
));
}
// Auto-select the first detected platform; user can switch if multiple
const detected = d.detectedInverterPlatforms ?? [];
const detectedPlatform = detected[0] ?? null;
if (detectedPlatform) {
setInverterForm(f => ({ ...f, inverterPlatform: detectedPlatform }));
}
if (d.growattDeviceId) {
setInverterForm(f => ({ ...f, deviceId: d.growattDeviceId! }));
}
// Build per-platform sensor structure from discovery results.
// platformSensors has per-platform dicts; shared sensors come from d.sensors.
const platform = detectedPlatform ?? inverterForm.inverterPlatform ?? '';
const newSensors: PerPlatformSensors = emptyPerPlatformSensors(platform);
const existing = existingSensorsRef.current;
// Populate each platform's sub-dict from discovered platformSensors
if (d.platformSensors) {
for (const [platId, platMap] of Object.entries(d.platformSensors)) {
if (platId in newSensors && platId !== 'platform' && platId !== 'shared') {
(newSensors as Record<string, Record<string, string>>)[platId] = { ...platMap };
}
}
}
// Populate shared sensors from discovery, falling back to existing config
const sharedSensors: Record<string, string> = {};
for (const intg of INTEGRATIONS) {
if (!SHARED_INTEGRATION_IDS.has(intg.id)) continue;
for (const group of intg.sensorGroups) {
for (const s of group.sensors) {
sharedSensors[s.key] = d.sensors[s.key] || (existing.shared ?? {})[s.key] || '';
}
}
}
newSensors.shared = sharedSensors;
// For each platform, merge with existing config (fill gaps)
for (const platId of Object.keys(INVERTER_INTEGRATION_IDS)) {
const disc = (newSensors as Record<string, Record<string, string>>)[platId] ?? {};
const prev = (existing as Record<string, Record<string, string>>)[platId] ?? {};
const merged: Record<string, string> = { ...prev };
for (const [k, v] of Object.entries(disc)) {
if (v) merged[k] = v;
}
(newSensors as Record<string, Record<string, string>>)[platId] = merged;
}
setSensors(newSensors);
setStep(1);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Discovery failed';
setScanError(message);
} finally {
setScanning(false);
}
}, []);
useEffect(() => {
// Load existing settings so re-running the wizard preserves user config,
// then run the sensor scan. Sequencing via .finally() ensures the scan
// never overwrites the loaded values (scan seeds only auto-detected hints).
api.get('/api/settings').then(res => {
const s = res.data;
const bat = s.battery ?? {};
const home = s.home ?? {};
const elec = s.electricityPrice ?? {};
const ep = s.energyProvider ?? {};
const inv = s.growatt ?? {};
// Cache existing sensors (per-platform structure) so handleScan can
// use them as fallback when auto-discovery fails.
if (s.sensors && typeof s.sensors === 'object' && 'platform' in s.sensors) {
existingSensorsRef.current = s.sensors as PerPlatformSensors;
}
setBatteryForm(f => ({
...f,
totalCapacity: bat.totalCapacity ?? f.totalCapacity,
minSoc: bat.minSoc ?? f.minSoc,
maxSoc: bat.maxSoc ?? f.maxSoc,
maxChargeDischargePowerKw: bat.maxChargePowerKw ?? f.maxChargeDischargePowerKw,
cycleCostPerKwh: bat.cycleCostPerKwh ?? f.cycleCostPerKwh,
minActionProfit: bat.minActionProfitThreshold ?? f.minActionProfit,
efficiencyCharge: bat.efficiencyCharge ?? f.efficiencyCharge,
efficiencyDischarge: bat.efficiencyDischarge ?? f.efficiencyDischarge,
temperatureDeratingEnabled: bat.temperatureDeratingEnabled ?? f.temperatureDeratingEnabled,
}));
setHomeForm(f => ({
...f,
consumption: home.defaultHourly ?? f.consumption,
consumptionStrategy: home.consumptionStrategy ?? f.consumptionStrategy,
maxFuseCurrent: home.maxFuseCurrent ?? f.maxFuseCurrent,
voltage: home.voltage ?? f.voltage,
safetyMarginFactor: home.safetyMargin ?? f.safetyMarginFactor,
phaseCount: home.phaseCount ?? f.phaseCount,
powerMonitoringEnabled: home.powerMonitoringEnabled ?? f.powerMonitoringEnabled,
}));
setPricingForm(f => ({
...f,
provider: ep.provider ?? f.provider,
currency: home.currency ?? f.currency,
// area is read-only / auto-detected — never restore from saved settings;
// discovery (handleScan) is the single source of truth for price area.
markupRate: elec.markupRate ?? f.markupRate,
vatMultiplier: elec.vatMultiplier ?? f.vatMultiplier,
additionalCosts: elec.additionalCosts ?? f.additionalCosts,
taxReduction: elec.taxReduction ?? f.taxReduction,
spotMultiplier: elec.spotMultiplier ?? f.spotMultiplier,
exportSpotMultiplier: elec.exportSpotMultiplier ?? f.exportSpotMultiplier,
sellPriceEqualsBuyPrice: elec.sellPriceEqualsBuyPrice ?? f.sellPriceEqualsBuyPrice,
// Restore saved config entry IDs so manual entries survive a wizard re-run
nordpoolConfigEntryId: ep.nordpoolOfficial?.configEntryId ?? f.nordpoolConfigEntryId,
nordpoolEntity: ep.nordpoolHacs?.entity ?? f.nordpoolEntity,
// Restore Octopus Energy entity IDs
octopusImportTodayEntity: ep.octopus?.importTodayEntity ?? f.octopusImportTodayEntity,
octopusImportTomorrowEntity: ep.octopus?.importTomorrowEntity ?? f.octopusImportTomorrowEntity,
octopusExportTodayEntity: ep.octopus?.exportTodayEntity ?? f.octopusExportTodayEntity,
octopusExportTomorrowEntity: ep.octopus?.exportTomorrowEntity ?? f.octopusExportTomorrowEntity,
// Restore ENTSO-e entity
entsoeEntity: ep.entsoe?.entity ?? f.entsoeEntity,
}));
const invNew = s.inverter ?? {};
if (invNew.platform) {
setInverterForm(f => ({ ...f, inverterPlatform: invNew.platform }));
}
if (invNew.controlMode) {
setInverterForm(f => ({ ...f, controlMode: invNew.controlMode }));
}
if (inv.deviceId) setInverterForm(f => ({ ...f, deviceId: inv.deviceId }));
}).catch((err: unknown) => {
const status = (err as { response?: { status?: number } })?.response?.status;
if (status !== 404) {
console.error('Failed to load existing settings:', err);
}
}).finally(() => {
handleScan();
});
}, [handleScan]);
const handleConfirm = () => {
if (!discovery) return;
setStep(2);
};
const handleComplete = async () => {
if (!discovery) return;
setCompleting(true);
setCompleteError(null);
try {
await api.post('/api/setup/complete', {
sensors,
// Area is read-only / auto-detected — prefer discovery over stale saved value
nordpoolArea: discovery.nordpoolArea || discovery.nordpoolCustomArea || pricingForm.area,
// Prefer the user-entered form value; fall back to auto-detected value
nordpoolConfigEntryId: pricingForm.nordpoolConfigEntryId || discovery.nordpoolConfigEntryId,
growattDeviceId: inverterForm.deviceId || discovery.growattDeviceId,
// Battery
totalCapacity: batteryForm.totalCapacity,
minSoc: batteryForm.minSoc,
maxSoc: batteryForm.maxSoc,
maxChargeDischargePower: batteryForm.maxChargeDischargePowerKw,
cycleCost: batteryForm.cycleCostPerKwh,
minActionProfitThreshold: batteryForm.minActionProfit,
// Home
currency: pricingForm.currency,
consumption: homeForm.consumption,
consumptionStrategy: homeForm.consumptionStrategy,
maxFuseCurrent: homeForm.maxFuseCurrent,
voltage: homeForm.voltage,
safetyMarginFactor: homeForm.safetyMarginFactor,
phaseCount: homeForm.phaseCount,
powerMonitoringEnabled: homeForm.powerMonitoringEnabled,
// Electricity
area: discovery.nordpoolArea || discovery.nordpoolCustomArea || pricingForm.area,
provider: pricingForm.provider,
markupRate: pricingForm.markupRate,
vatMultiplier: pricingForm.vatMultiplier,
additionalCosts: pricingForm.additionalCosts,
taxReduction: pricingForm.taxReduction,
spotMultiplier: pricingForm.spotMultiplier,
exportSpotMultiplier: pricingForm.exportSpotMultiplier,
sellPriceEqualsBuyPrice: pricingForm.sellPriceEqualsBuyPrice,
// Nordpool HACS entity
nordpoolEntity: pricingForm.nordpoolEntity || undefined,
// Octopus Energy entity IDs
octopusImportTodayEntity: pricingForm.octopusImportTodayEntity || undefined,
octopusImportTomorrowEntity: pricingForm.octopusImportTomorrowEntity || undefined,
octopusExportTodayEntity: pricingForm.octopusExportTodayEntity || undefined,
octopusExportTomorrowEntity: pricingForm.octopusExportTomorrowEntity || undefined,
// ENTSO-e entity
entsoeEntity: pricingForm.entsoeEntity || undefined,
// Inverter
inverterPlatform: inverterForm.inverterPlatform,
inverterControlMode: inverterForm.controlMode ?? 'tou',
// Control mode
demoMode: controlMode === 'demo',
});
window.dispatchEvent(new Event('bess:demo-mode-changed'));
setStep(6);
} catch (err: unknown) {
setCompleteError(err instanceof Error ? err.message : 'Setup failed');
} finally {
setCompleting(false);
}
};
// When the user switches inverter platform, just update inverterForm.
// The SensorConfigSection handles updating sensors.platform via onChange.
const handleInverterChange = (newForm: InverterForm) => {
setInverterForm(newForm);
};
const activeInverterIntegrationId = INVERTER_INTEGRATION_IDS[inverterForm.inverterPlatform] ?? 'growatt_server_min';
const inverterIntegrationIds = new Set(Object.values(INVERTER_INTEGRATION_IDS));
// Check that all required sensors are filled using the flat merged view
const activeSensorsFlat = getActiveSensorsFlat(sensors);
const allRequiredFilled = INTEGRATIONS.every(integration => {
// Skip inverter integrations that don't match the selected inverter type
if (inverterIntegrationIds.has(integration.id) && integration.id !== activeInverterIntegrationId) return true;
return integration.sensorGroups.every(group =>
group.sensors.every(s => !s.required || !!activeSensorsFlat[s.key]),
);
});
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col items-center justify-center p-6">
<div className="w-full max-w-3xl">
{/* Header */}
<div className="text-center mb-8">
<div className="flex justify-center mb-3">
<Zap className="h-10 w-10 text-blue-500" />
</div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">BESS Auto-Configuration</h1>
<p className="mt-2 text-gray-600 dark:text-gray-400">
Detecting integrations and mapping sensor entity IDs
</p>
</div>
{/* Step indicator */}
<div className="flex items-center justify-center mb-8 space-x-2">
{STEPS.map((label, idx) => (
<React.Fragment key={label}>
<div className="flex items-center space-x-1">
<div className={`w-7 h-7 rounded-full flex items-center justify-center text-sm font-semibold
${idx < step ? 'bg-green-500 text-white' :
idx === step ? 'bg-blue-500 text-white' :
'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'}`}>
{idx < step ? <CheckCircle className="h-4 w-4" /> : idx + 1}
</div>
<span className={`hidden sm:inline text-sm ${idx === step ? 'font-semibold text-gray-900 dark:text-white' : 'text-gray-500 dark:text-gray-400'}`}>
{label}
</span>
</div>
{idx < STEPS.length - 1 && (
<ChevronRight className="h-4 w-4 text-gray-400 flex-shrink-0" />
)}
</React.Fragment>
))}
</div>
{/* ── Step 0: Scanning ── */}
{step === 0 && (
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<div className="text-center py-8">
{scanning ? (
<>
<div className="h-12 w-12 border-2 border-blue-500 rounded-full border-t-transparent animate-spin mx-auto mb-4" />
<p className="text-lg font-medium text-gray-900 dark:text-white">Scanning Home Assistant…</p>
<p className="text-gray-500 dark:text-gray-400 mt-1">Querying REST API and WebSocket for integrations</p>
</>
) : scanError ? (
<>
<p className="text-lg font-medium text-gray-900 dark:text-white">Discovery failed</p>
<p className="text-red-500 mt-1 text-sm">{scanError}</p>
<button onClick={handleScan} className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 font-medium">
Retry
</button>
</>
) : null}
</div>
</div>
)}
{/* ── Step 1: Review Sensors ── */}
{step === 1 && discovery && (
<div className="space-y-3">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">Review Sensors</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Confirm the detected sensor entity IDs. Expand each integration to view or correct individual sensors.
Fields marked <span className="font-semibold text-orange-500">*</span> are required.
</p>
</div>
{discovery.vatMultiplier != null && (
<div className="rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 px-4 py-2 text-xs text-green-800 dark:text-green-300">
Sensors and settings pre-filled from detected integrations. Review and correct as needed.
</div>
)}
<SensorConfigSection
sensors={sensors}
onChange={setSensors}
inverterForm={inverterForm}
onInverterChange={handleInverterChange}
discovery={discovery}
/>
{!allRequiredFilled && (
<div className="p-3 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg text-sm text-orange-700 dark:text-orange-300">
Some required sensors (marked with <span className="font-semibold">*</span>) are missing. Expand the integration to configure them manually.
</div>
)}
<div className="flex justify-between pt-2">
<button
onClick={handleScan}
className="flex items-center space-x-1 px-4 py-2 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
>
<ChevronLeft className="h-4 w-4" />
<span>Re-scan</span>
</button>
<button
onClick={handleConfirm}
disabled={!allRequiredFilled}
className="flex items-center space-x-2 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 font-medium disabled:opacity-60"
>
<span>Next: Electricity Pricing</span>
<ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
)}
{/* ── Step 2: Electricity Pricing ── */}
{step === 2 && (
<div className="space-y-3">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">Electricity Pricing</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
How the optimizer calculates the real cost of buying and selling electricity. Getting this right is essential for accurate savings calculations.
</p>
</div>
{discovery?.vatMultiplier != null && (
<div className="rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 px-4 py-2 text-xs text-green-800 dark:text-green-300">
Currency, VAT multiplier and price area pre-filled from detected Nord Pool integration.
</div>
)}
<PricingFormSection form={pricingForm} onChange={setPricingForm} />
<div className="flex justify-between pt-2">
<button onClick={() => setStep(1)}
className="flex items-center space-x-1 px-4 py-2 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700">
<ChevronLeft className="h-4 w-4" /><span>Back</span>
</button>
<button onClick={() => setStep(3)}
className="flex items-center space-x-2 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 font-medium">
<span>Next: Battery</span><ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
)}
{/* ── Step 3: Battery ── */}
{step === 3 && (
<div className="space-y-3">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">Battery</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Battery hardware specifications. These values are used by the optimizer to plan charge and discharge schedules.
</p>
</div>
<BatteryFormSection
form={batteryForm}
onChange={setBatteryForm}
currency={pricingForm.currency}
weatherEntity={sensors.shared?.['weather_entity']}
hideAdvanced
/>
<div className="flex justify-between pt-2">
<button onClick={() => setStep(2)}
className="flex items-center space-x-1 px-4 py-2 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700">
<ChevronLeft className="h-4 w-4" /><span>Back</span>
</button>
<button onClick={() => setStep(4)}
className="flex items-center space-x-2 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 font-medium">
<span>Next: Home</span><ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
)}
{/* ── Step 4: Home ── */}
{step === 4 && (
<div className="space-y-3">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">Home</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Fuse protection prevents the main fuse from blowing when the battery charges at the same time as other high loads. Recommended if your home does not have hardware power limiting.
</p>
</div>
<HomeFormSection form={homeForm} onChange={setHomeForm} sensors={getActiveSensorsFlat(sensors)} />
<div className="flex justify-between pt-2">
<button onClick={() => setStep(3)}
className="flex items-center space-x-1 px-4 py-2 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700">
<ChevronLeft className="h-4 w-4" /><span>Back</span>
</button>
<button
onClick={() => setStep(5)}
className="flex items-center space-x-2 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 font-medium"
>
<span>Next: Control Mode</span><ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
)}
{/* ── Step 5: Control Mode ── */}
{step === 5 && (
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
{/* Config summary */}
<div className="rounded-lg bg-gray-50 dark:bg-gray-700 p-4 space-y-2 text-sm mb-6">
<div className="flex justify-between">
<span className="text-gray-500 dark:text-gray-400">Battery capacity</span>
<span className="font-medium text-gray-900 dark:text-white">{batteryForm.totalCapacity} kWh</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500 dark:text-gray-400">SOC range</span>
<span className="font-medium text-gray-900 dark:text-white">{batteryForm.minSoc}% – {batteryForm.maxSoc}%</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500 dark:text-gray-400">Max power</span>
<span className="font-medium text-gray-900 dark:text-white">{batteryForm.maxChargeDischargePowerKw} kW</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500 dark:text-gray-400">Inverter type</span>
<span className="font-medium text-gray-900 dark:text-white">{inverterForm.inverterPlatform}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500 dark:text-gray-400">Price provider</span>
<span className="font-medium text-gray-900 dark:text-white">{pricingForm.provider}</span>
</div>
</div>
{/* Control mode choice */}
<h2 className="text-lg font-bold text-gray-900 dark:text-white">How would you like to start?</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1 mb-4">You can change this anytime in Settings.</p>
<div className="space-y-3">
<button
onClick={() => setControlMode('demo')}
className={`w-full text-left rounded-lg border-2 p-4 flex items-start gap-3 transition-colors ${
controlMode === 'demo'
? 'border-blue-500 bg-blue-900/10'
: 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
}`}
>
<div className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
controlMode === 'demo' ? 'border-blue-500 bg-blue-500' : 'border-gray-400 dark:border-gray-500'
}`}>
{controlMode === 'demo' && <CheckCircle className="h-3 w-3 text-white" />}
</div>
<div>
<div className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Eye className="h-4 w-4" /> Demo Mode
</div>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Watch how the system would optimize your battery. No commands sent to inverter.
</p>
</div>
</button>
<button
onClick={() => setControlMode('live')}
className={`w-full text-left rounded-lg border-2 p-4 flex items-start gap-3 transition-colors ${
controlMode === 'live'
? 'border-green-500 bg-green-900/10'
: 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
}`}
>
<div className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
controlMode === 'live' ? 'border-green-500 bg-green-500' : 'border-gray-400 dark:border-gray-500'
}`}>
{controlMode === 'live' && <CheckCircle className="h-3 w-3 text-white" />}
</div>
<div>
<div className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Zap className="h-4 w-4" /> Live Control
</div>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Start optimizing immediately. Sends charge/discharge commands to your inverter.
</p>
</div>
</button>
</div>
<button
onClick={handleComplete}
disabled={controlMode === null || completing}
className="mt-6 w-full px-8 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 font-semibold text-base disabled:opacity-40 disabled:cursor-not-allowed"
>
{completing ? 'Completing...' : controlMode === null ? 'Select a mode to continue' : 'Complete Setup'}
</button>
{completeError && (
<p className="mt-2 text-sm text-red-500">{completeError}</p>
)}
</div>
)}
{/* ── Step 6: Done ── */}
{step === 6 && (
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 text-center py-8">
<CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
<h2 className="text-xl font-bold text-gray-900 dark:text-white">Setup Complete!</h2>
<p className="text-gray-600 dark:text-gray-400 mt-2">
{controlMode === 'demo'
? 'BESS Manager is running in demo mode. You can switch to live control anytime in Settings.'
: 'BESS Manager is configured and ready to optimize your battery.'}
</p>
<button
onClick={() => navigate('/', { replace: true })}
className="mt-6 w-full px-8 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 font-semibold text-base"
>
Go to Dashboard
</button>
</div>
)}
<p className="text-center mt-4 text-xs text-gray-400 dark:text-gray-500">
Settings can be updated at any time via the Settings page.
</p>
</div>
</div>
);
};
export default SetupWizardPage;