@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,523 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Full-pane EditorHostView (`krusch:plumbing:schedule`) that opens beside the 3D/2D scene:
5
+ * 6 Tabs: Fixtures | Loads & Electrical | IPC/IFGC Audit | Framing Drill List | Priced BOM | 3D Manifold Cutaway.
6
+ */
7
+
8
+ import { useScene, useViewer } from '@pascal-app/editor'
9
+ import { useEffect, useMemo, useRef, useState } from 'react'
10
+ import type { ManifoldPortAssignment } from '../cad/manifold-interior'
11
+ import { auditScenePlumbing } from '../ipc/audit'
12
+ import {
13
+ type FramingPenetration,
14
+ type SceneNodeLike,
15
+ type Vec3,
16
+ computePipeFramingPenetrations,
17
+ extractBonesPlumbingContext,
18
+ resolveNodeLevelId,
19
+ } from '../ipc/framing-interop'
20
+ import { buildPlumbingBom, formatPlumbingBomCsv } from '../ipc/pricing'
21
+ import { extractWallSegments } from '../ipc/routing'
22
+ import { buildPlumbingSchedule, formatPlumbingScheduleCsv } from '../ipc/schedule'
23
+ import { METERS_TO_INCHES, type ManifoldKind, type PipeMaterial, type PipeNominalSize } from '../ipc/tables'
24
+ import ManifoldCutawayView from './manifold-cutaway-view'
25
+ import { type PlumbingScheduleTab, usePlumbingUi } from './store'
26
+
27
+ function clampNumericInput(raw: string, max: number): number {
28
+ const v = Number(raw)
29
+ if (!Number.isFinite(v)) return 0
30
+ return Math.max(0, Math.min(max, v))
31
+ }
32
+
33
+ export default function PlumbingScheduleView() {
34
+ const nodes = useScene((s) => s.nodes)
35
+ const setSelection = useViewer((s) => s.setSelection)
36
+ const {
37
+ codeEdition,
38
+ occupancy,
39
+ supplyMaterial,
40
+ activeTab,
41
+ setActiveTab,
42
+ selectedManifoldId,
43
+ setSelectedManifoldId,
44
+ manifoldViewMode,
45
+ setManifoldViewMode,
46
+ } = usePlumbingUi()
47
+
48
+ const [laborRateUsd, setLaborRateUsd] = useState(115)
49
+ const [materialMarkupPct, setMaterialMarkupPct] = useState(0)
50
+ const [salesTaxPct, setSalesTaxPct] = useState(0)
51
+ const [copiedMsg, setCopiedMsg] = useState<string | null>(null)
52
+ const [copiedIsError, setCopiedIsError] = useState(false)
53
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
54
+ const mountedRef = useRef(true)
55
+ const copyReqIdRef = useRef(0)
56
+
57
+ useEffect(() => {
58
+ mountedRef.current = true
59
+ return () => {
60
+ mountedRef.current = false
61
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current)
62
+ }
63
+ }, [])
64
+
65
+ const record = nodes as unknown as Readonly<Record<string, SceneNodeLike>>
66
+ const codePrefix = codeEdition.startsWith('UPC') ? 'UPC' : 'IPC'
67
+
68
+ const selectNodesWithLevel = (ids: string[]) => {
69
+ if (ids.length === 0) return
70
+ const firstNode = record[ids[0]!]
71
+ const targetLevelId = firstNode ? resolveNodeLevelId(record, firstNode) : null
72
+ setSelection({
73
+ ...(targetLevelId ? { levelId: targetLevelId as never } : {}),
74
+ selectedIds: ids as never,
75
+ })
76
+ }
77
+
78
+ const schedule = useMemo(
79
+ () => buildPlumbingSchedule(record, { codeEdition, occupancy, supplyMaterial }),
80
+ [record, codeEdition, occupancy, supplyMaterial],
81
+ )
82
+ const audit = useMemo(
83
+ () => auditScenePlumbing(record, { codeEdition, occupancy }),
84
+ [record, codeEdition, occupancy],
85
+ )
86
+ const bom = useMemo(
87
+ () =>
88
+ buildPlumbingBom(record, {
89
+ codeEdition,
90
+ occupancy,
91
+ supplyMaterial,
92
+ laborRateUsd,
93
+ materialMarkupPct,
94
+ salesTaxPct,
95
+ schedule,
96
+ }),
97
+ [record, codeEdition, occupancy, supplyMaterial, laborRateUsd, materialMarkupPct, salesTaxPct, schedule],
98
+ )
99
+
100
+ const penetrations = useMemo<FramingPenetration[]>(() => {
101
+ if (activeTab !== 'penetrations') return []
102
+ const out: FramingPenetration[] = []
103
+ const wallsByLevel = new Map<string, ReturnType<typeof extractWallSegments>>()
104
+ const bonesByLevel = new Map<string, ReturnType<typeof extractBonesPlumbingContext>>()
105
+ for (const n of Object.values(record)) {
106
+ if (n.type !== 'plumbing:pipe-run' || !Array.isArray(n.path)) continue
107
+ const lvlId = resolveNodeLevelId(record, n)
108
+ const cacheKey = lvlId ?? '__root__'
109
+ let walls = wallsByLevel.get(cacheKey)
110
+ if (!walls) {
111
+ walls = extractWallSegments(record, lvlId)
112
+ wallsByLevel.set(cacheKey, walls)
113
+ }
114
+ let bones = bonesByLevel.get(cacheKey)
115
+ if (!bones) {
116
+ bones = extractBonesPlumbingContext(record, lvlId)
117
+ bonesByLevel.set(cacheKey, bones)
118
+ }
119
+ out.push(
120
+ ...computePipeFramingPenetrations({
121
+ pipeRunId: n.id,
122
+ path: n.path as ReadonlyArray<Vec3>,
123
+ pipeSize: (n.nominalSize as PipeNominalSize) || '1/2"',
124
+ material: (n.material as PipeMaterial) || 'pex-a',
125
+ walls,
126
+ bonesContext: bones,
127
+ }),
128
+ )
129
+ }
130
+ return out
131
+ }, [record, activeTab])
132
+
133
+ const manifolds = useMemo(
134
+ () => Object.values(record).filter((n) => n.type === 'plumbing:manifold'),
135
+ [record],
136
+ )
137
+ const activeManifold = useMemo(
138
+ () => (selectedManifoldId ? manifolds.find((m) => m.id === selectedManifoldId) : undefined) ?? manifolds[0] ?? null,
139
+ [manifolds, selectedManifoldId],
140
+ )
141
+ const activeManifoldPorts = useMemo<ManifoldPortAssignment[]>(() => {
142
+ if (!activeManifold || activeTab !== 'manifold') return []
143
+ const isGasManifold = activeManifold.manifoldKind === 'gas-csst'
144
+ // Include only outgoing branch circuits fed from this manifold (never incoming main headers targeting it)
145
+ const connectedRuns = Object.values(record).filter((n) => {
146
+ if (n.type !== 'plumbing:pipe-run' || n.sourceNodeId !== activeManifold.id) return false
147
+ const sys = String(n.system ?? '')
148
+ if (isGasManifold) return sys === 'fuel-gas'
149
+ return sys === 'cold-water' || sys === 'hot-water' || sys === 'hot-recirc'
150
+ })
151
+ const ports: ManifoldPortAssignment[] = []
152
+ let hotIdx = 0
153
+ let coldIdx = 0
154
+ let gasIdx = 0
155
+ for (const r of connectedRuns) {
156
+ const sys = String(r.system ?? '')
157
+ const side: 'hot' | 'cold' | 'gas' =
158
+ sys === 'hot-water' || sys === 'hot-recirc' ? 'hot' : sys === 'fuel-gas' ? 'gas' : 'cold'
159
+ const portIndex = side === 'hot' ? hotIdx++ : side === 'gas' ? gasIdx++ : coldIdx++
160
+ ports.push({
161
+ portIndex,
162
+ side,
163
+ label: typeof r.name === 'string' && r.name ? r.name : r.id,
164
+ pipeSize: String(r.nominalSize ?? '1/2"'),
165
+ active: true,
166
+ })
167
+ }
168
+ return ports
169
+ }, [record, activeManifold, activeTab])
170
+
171
+ const copyCsv = async (label: string, csv: string) => {
172
+ const reqId = ++copyReqIdRef.current
173
+ if (copyTimerRef.current) {
174
+ clearTimeout(copyTimerRef.current)
175
+ copyTimerRef.current = null
176
+ }
177
+ if (!navigator.clipboard?.writeText) {
178
+ setCopiedIsError(true)
179
+ setCopiedMsg(`Clipboard unavailable for ${label} CSV`)
180
+ } else {
181
+ try {
182
+ await navigator.clipboard.writeText(csv)
183
+ if (!mountedRef.current || reqId !== copyReqIdRef.current) return
184
+ setCopiedIsError(false)
185
+ setCopiedMsg(`Copied ${label} CSV`)
186
+ } catch {
187
+ if (!mountedRef.current || reqId !== copyReqIdRef.current) return
188
+ setCopiedIsError(true)
189
+ setCopiedMsg(`Failed to copy ${label} CSV`)
190
+ }
191
+ }
192
+ if (!mountedRef.current || reqId !== copyReqIdRef.current) return
193
+ copyTimerRef.current = setTimeout(() => {
194
+ if (!mountedRef.current) return
195
+ setCopiedMsg(null)
196
+ copyTimerRef.current = null
197
+ }, 2000)
198
+ }
199
+
200
+ const tabs: ReadonlyArray<[PlumbingScheduleTab, string]> = [
201
+ ['fixtures', `Fixtures (${schedule.fixtures.length})`],
202
+ ['loads', 'Loads & Power'],
203
+ ['audit', `${codePrefix} Audit (${audit.errorCount}/${audit.warningCount})`],
204
+ ['penetrations', activeTab === 'penetrations' ? `Drill List (${penetrations.length})` : 'Drill List'],
205
+ ['bom', `BOM ($${Math.round(bom.grandTotalUsd).toLocaleString()})`],
206
+ ['manifold', '3D Manifold Cutaway'],
207
+ ]
208
+
209
+ return (
210
+ <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12, fontSize: 12, height: '100%', overflow: 'auto' }}>
211
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
212
+ <div>
213
+ <strong style={{ fontSize: 15 }}>Plumbing Engineering Schedule ({codeEdition})</strong>
214
+ <div style={{ fontSize: 11, opacity: 0.75 }}>
215
+ {schedule.loads.totalDfu} DFU · {schedule.loads.totalWsfu} WSFU ({schedule.loads.peakDemandGpm} GPM Peak) · Main Drain{' '}
216
+ {schedule.loads.recommendedBuildingDrain} · Vent Stack {schedule.loads.recommendedVentStack}
217
+ </div>
218
+ </div>
219
+ {copiedMsg && (
220
+ <span style={{ color: copiedIsError ? '#ef4444' : '#22c55e', fontSize: 11 }}>{copiedMsg}</span>
221
+ )}
222
+ </div>
223
+
224
+ {/* Tabs */}
225
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', borderBottom: '1px solid var(--border, rgba(255,255,255,0.14))', paddingBottom: 8 }}>
226
+ {tabs.map(([id, label]) => (
227
+ <button
228
+ key={id}
229
+ type="button"
230
+ onClick={() => setActiveTab(id)}
231
+ style={{
232
+ padding: '5px 10px',
233
+ borderRadius: 6,
234
+ border: '1px solid var(--border, rgba(255,255,255,0.18))',
235
+ background: activeTab === id ? 'rgba(37,99,235,0.28)' : 'transparent',
236
+ color: 'inherit',
237
+ cursor: 'pointer',
238
+ fontSize: 11,
239
+ fontWeight: activeTab === id ? 600 : 400,
240
+ }}
241
+ >
242
+ {label}
243
+ </button>
244
+ ))}
245
+ </div>
246
+
247
+ {/* Tab 1: Fixture Schedule */}
248
+ {activeTab === 'fixtures' && (
249
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
250
+ <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
251
+ <button type="button" onClick={() => copyCsv('Fixture Schedule', formatPlumbingScheduleCsv(schedule))} style={btnStyle}>
252
+ Copy CSV
253
+ </button>
254
+ </div>
255
+ <table style={tableStyle}>
256
+ <thead>
257
+ <tr>
258
+ <th style={thStyle}>Fixture</th>
259
+ <th style={thStyle}>Room</th>
260
+ <th style={thStyle}>DFU</th>
261
+ <th style={thStyle}>WSFU (C/H)</th>
262
+ <th style={thStyle}>Drain / Vent</th>
263
+ <th style={thStyle}>Supply</th>
264
+ </tr>
265
+ </thead>
266
+ <tbody>
267
+ {schedule.fixtures.map((f) => (
268
+ <tr key={f.nodeId} onClick={() => selectNodesWithLevel([f.nodeId])} style={{ cursor: 'pointer' }}>
269
+ <td style={tdStyle}>{f.name}</td>
270
+ <td style={tdStyle}>{f.roomName}</td>
271
+ <td style={tdStyle}>{f.dfu}</td>
272
+ <td style={tdStyle}>{f.wsfuCold} / {f.wsfuHot}</td>
273
+ <td style={tdStyle}>{f.drainSize ?? '-'} / {f.ventSize ?? '-'}</td>
274
+ <td style={tdStyle}>{f.supplySize ?? '-'}</td>
275
+ </tr>
276
+ ))}
277
+ </tbody>
278
+ </table>
279
+ </div>
280
+ )}
281
+
282
+ {/* Tab 2: Loads & Cross-Trade Electrical Coordination */}
283
+ {activeTab === 'loads' && (
284
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
285
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 8 }}>
286
+ <MetricCard title="Building Drain" value={schedule.loads.recommendedBuildingDrain} sub={`${schedule.loads.totalDfu} DFU @ 1/4"/ft`} />
287
+ <MetricCard title="Peak Water Demand" value={`${schedule.loads.peakDemandGpm} GPM`} sub={`${schedule.loads.totalWsfu} WSFU · Cold ${schedule.loads.recommendedColdMain}`} />
288
+ <MetricCard title="Water Heater Rec" value={`${schedule.loads.waterHeaterRecommendation.recommendedTankGal} gal`} sub={`or ${schedule.loads.waterHeaterRecommendation.recommendedTanklessGpm} GPM Tankless`} />
289
+ <MetricCard title="Fuel Gas Load" value={schedule.loads.totalGasBtuh > 0 ? `${Math.round(schedule.loads.totalGasBtuh / 1000)} kBTU/h` : 'All-Electric'} sub={schedule.loads.recommendedGasMain ? `Main: ${schedule.loads.recommendedGasMain}` : 'No gas appliances'} />
290
+ </div>
291
+
292
+ <strong>Cross-Trade Electrical Power Coordination (Auto-Breaker Handoff)</strong>
293
+ <table style={tableStyle}>
294
+ <thead>
295
+ <tr>
296
+ <th style={thStyle}>Powered Plumbing Unit</th>
297
+ <th style={thStyle}>Circuit</th>
298
+ <th style={thStyle}>Load</th>
299
+ <th style={thStyle}>Protection</th>
300
+ <th style={thStyle}>Electrical Status</th>
301
+ </tr>
302
+ </thead>
303
+ <tbody>
304
+ {schedule.electricalCoordination.map((c) => (
305
+ <tr key={c.sourceNodeId} onClick={() => selectNodesWithLevel([c.sourceNodeId])} style={{ cursor: 'pointer' }}>
306
+ <td style={tdStyle}>{c.label}</td>
307
+ <td style={tdStyle}>{c.voltage}V {c.poles}P {c.breakerAmps}A</td>
308
+ <td style={tdStyle}>{c.loadVa} VA</td>
309
+ <td style={tdStyle}>{[c.dedicatedCircuit ? 'Dedicated' : 'Shared', c.gfciRequired ? 'GFCI' : ''].filter(Boolean).join(' · ')}</td>
310
+ <td style={{ ...tdStyle, color: c.wired ? '#22c55e' : '#f59e0b', fontWeight: 600 }}>
311
+ {c.wired ? `WIRED (CKT-${c.matchedCircuitNumber ?? '?'})` : 'NEEDS BREAKER'}
312
+ </td>
313
+ </tr>
314
+ ))}
315
+ </tbody>
316
+ </table>
317
+ </div>
318
+ )}
319
+
320
+ {/* Tab 3: IPC / UPC / IFGC / NEC 110.26(E) Audit */}
321
+ {activeTab === 'audit' && (
322
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
323
+ {audit.findings.length === 0 && (
324
+ <div style={{ padding: 12, borderRadius: 8, background: 'rgba(34,197,94,0.14)', border: '1px solid #22c55e' }}>
325
+ 0 Errors · 0 Warnings. All IPC/UPC/IFGC/IRC &amp; NEC 110.26(E) checks passed!
326
+ </div>
327
+ )}
328
+ {audit.findings.map((f) => (
329
+ <div
330
+ key={f.id}
331
+ onClick={() => f.nodeIds.length > 0 && selectNodesWithLevel(f.nodeIds)}
332
+ style={{
333
+ padding: 10,
334
+ borderRadius: 8,
335
+ cursor: f.nodeIds.length > 0 ? 'pointer' : 'default',
336
+ border: `1px solid ${f.severity === 'error' ? '#ef4444' : '#f59e0b'}`,
337
+ background: f.severity === 'error' ? 'rgba(239,68,68,0.12)' : 'rgba(245,158,11,0.12)',
338
+ }}
339
+ >
340
+ <div style={{ fontWeight: 600 }}>
341
+ [{f.codeRef}] {f.title}
342
+ </div>
343
+ <div style={{ fontSize: 11, opacity: 0.85, marginTop: 2 }}>{f.detail}</div>
344
+ <div style={{ fontSize: 11, color: '#38bdf8', marginTop: 4 }}>Fix: {f.suggestedFix}</div>
345
+ </div>
346
+ ))}
347
+ </div>
348
+ )}
349
+
350
+ {/* Tab 4: Bones Framing Penetration & Drill Schedule */}
351
+ {activeTab === 'penetrations' && (
352
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
353
+ <div style={{ fontSize: 11, opacity: 0.8 }}>
354
+ Exact stud, sole-plate, and top-plate drill coordinates synced to <code>@pascal-app/plugin-bones</code> framing geometry (IRC R602.6).
355
+ </div>
356
+ <table style={tableStyle}>
357
+ <thead>
358
+ <tr>
359
+ <th style={thStyle}>Member</th>
360
+ <th style={thStyle}>Height AFF</th>
361
+ <th style={thStyle}>Pipe</th>
362
+ <th style={thStyle}>Hole Saw</th>
363
+ <th style={thStyle}>Bore %</th>
364
+ <th style={thStyle}>Nail Plate</th>
365
+ <th style={thStyle}>IRC R602.6</th>
366
+ </tr>
367
+ </thead>
368
+ <tbody>
369
+ {penetrations.map((p) => (
370
+ <tr key={p.id} onClick={() => selectNodesWithLevel([p.pipeRunId])} style={{ cursor: 'pointer' }}>
371
+ <td style={tdStyle}>{p.memberLabel}</td>
372
+ <td style={tdStyle}>{Math.round(p.position[1] * METERS_TO_INCHES)}&quot;</td>
373
+ <td style={tdStyle}>{p.pipeSize} {p.material}</td>
374
+ <td style={tdStyle}><strong>{p.holeSawIn}&quot;</strong></td>
375
+ <td style={tdStyle}>{p.borePctOfStud}%</td>
376
+ <td style={tdStyle}>{p.needsNailPlate ? 'Required' : 'No'}</td>
377
+ <td style={{ ...tdStyle, color: p.codeCompliant ? '#22c55e' : '#ef4444', fontWeight: 600 }}>
378
+ {p.codeCompliant ? 'PASS' : 'OVERSIZE'}
379
+ </td>
380
+ </tr>
381
+ ))}
382
+ </tbody>
383
+ </table>
384
+ </div>
385
+ )}
386
+
387
+ {/* Tab 5: Priced BOM Takeoff */}
388
+ {activeTab === 'bom' && (
389
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
390
+ <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
391
+ <label>
392
+ Labor $/hr:{' '}
393
+ <input
394
+ type="number"
395
+ min={0}
396
+ max={1000}
397
+ value={laborRateUsd}
398
+ onChange={(e) => setLaborRateUsd(clampNumericInput(e.target.value, 1000))}
399
+ style={numInputStyle}
400
+ />
401
+ </label>
402
+ <label>
403
+ Markup %:{' '}
404
+ <input
405
+ type="number"
406
+ min={0}
407
+ max={500}
408
+ value={materialMarkupPct}
409
+ onChange={(e) => setMaterialMarkupPct(clampNumericInput(e.target.value, 500))}
410
+ style={numInputStyle}
411
+ />
412
+ </label>
413
+ <label>
414
+ Tax %:{' '}
415
+ <input
416
+ type="number"
417
+ min={0}
418
+ max={50}
419
+ value={salesTaxPct}
420
+ onChange={(e) => setSalesTaxPct(clampNumericInput(e.target.value, 50))}
421
+ style={numInputStyle}
422
+ />
423
+ </label>
424
+ <button type="button" onClick={() => copyCsv('BOM', formatPlumbingBomCsv(bom))} style={btnStyle}>
425
+ Copy BOM CSV
426
+ </button>
427
+ </div>
428
+ <table style={tableStyle}>
429
+ <thead>
430
+ <tr>
431
+ <th style={thStyle}>Category</th>
432
+ <th style={thStyle}>Item</th>
433
+ <th style={thStyle}>Qty</th>
434
+ <th style={thStyle}>Material</th>
435
+ <th style={thStyle}>Labor</th>
436
+ <th style={thStyle}>Total</th>
437
+ </tr>
438
+ </thead>
439
+ <tbody>
440
+ {bom.lines.map((l, idx) => (
441
+ <tr key={`${l.item}_${idx}`}>
442
+ <td style={tdStyle}>{l.category}</td>
443
+ <td style={tdStyle}>{l.item}</td>
444
+ <td style={tdStyle}>{l.quantity} {l.unit}</td>
445
+ <td style={tdStyle}>${l.materialUsd.toFixed(2)}</td>
446
+ <td style={tdStyle}>${l.laborUsd.toFixed(2)} ({l.laborHours}h)</td>
447
+ <td style={tdStyle}><strong>${l.totalUsd.toFixed(2)}</strong></td>
448
+ </tr>
449
+ ))}
450
+ </tbody>
451
+ </table>
452
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, fontSize: 12 }}>
453
+ <div>
454
+ Material Subtotal: <strong>${bom.subtotalMaterialUsd.toLocaleString(undefined, { minimumFractionDigits: 2 })}</strong>
455
+ </div>
456
+ {bom.markupUsd > 0 && (
457
+ <div>
458
+ Markup ({materialMarkupPct}%): <strong>${bom.markupUsd.toLocaleString(undefined, { minimumFractionDigits: 2 })}</strong>
459
+ </div>
460
+ )}
461
+ {bom.taxUsd > 0 && (
462
+ <div>
463
+ Sales Tax ({salesTaxPct}%): <strong>${bom.taxUsd.toLocaleString(undefined, { minimumFractionDigits: 2 })}</strong>
464
+ </div>
465
+ )}
466
+ <div>
467
+ Labor Subtotal ({bom.totalLaborHours}h):{' '}
468
+ <strong>${bom.subtotalLaborUsd.toLocaleString(undefined, { minimumFractionDigits: 2 })}</strong>
469
+ </div>
470
+ <div style={{ fontSize: 14, fontWeight: 700, marginTop: 4 }}>
471
+ Grand Total: ${bom.grandTotalUsd.toLocaleString(undefined, { minimumFractionDigits: 2 })}
472
+ </div>
473
+ </div>
474
+ </div>
475
+ )}
476
+
477
+ {/* Tab 6: 3D PEX Manifold & Wet-Wall Cutaway */}
478
+ {activeTab === 'manifold' && (
479
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
480
+ {manifolds.length > 1 && (
481
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 11 }}>
482
+ <strong>Manifold:</strong>
483
+ <select
484
+ value={activeManifold?.id ?? ''}
485
+ onChange={(e) => setSelectedManifoldId(e.target.value || null)}
486
+ style={{ padding: '3px 6px', borderRadius: 5, border: '1px solid rgba(255,255,255,0.2)', background: 'transparent', color: 'inherit', fontSize: 11 }}
487
+ >
488
+ {manifolds.map((m) => (
489
+ <option key={m.id} value={m.id}>
490
+ {String(m.name ?? m.id)} ({String(m.manifoldKind ?? 'pex-homerun')})
491
+ </option>
492
+ ))}
493
+ </select>
494
+ </div>
495
+ )}
496
+ <ManifoldCutawayView
497
+ manifoldKind={((activeManifold?.manifoldKind as ManifoldKind) || 'pex-homerun')}
498
+ portCount={typeof activeManifold?.portCount === 'number' ? activeManifold.portCount : 12}
499
+ viewMode={manifoldViewMode}
500
+ ports={activeManifoldPorts}
501
+ onChangeViewMode={setManifoldViewMode}
502
+ />
503
+ </div>
504
+ )}
505
+ </div>
506
+ )
507
+ }
508
+
509
+ function MetricCard({ title, value, sub }: { title: string; value: string; sub: string }) {
510
+ return (
511
+ <div style={{ padding: 10, borderRadius: 8, border: '1px solid var(--border, rgba(255,255,255,0.14))' }}>
512
+ <div style={{ fontSize: 10, opacity: 0.72 }}>{title}</div>
513
+ <div style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>{value}</div>
514
+ <div style={{ fontSize: 11, opacity: 0.8 }}>{sub}</div>
515
+ </div>
516
+ )
517
+ }
518
+
519
+ const tableStyle = { width: '100%', borderCollapse: 'collapse' as const, fontSize: 11 }
520
+ const thStyle = { textAlign: 'left' as const, padding: '6px 8px', borderBottom: '1px solid rgba(255,255,255,0.16)', opacity: 0.8 }
521
+ const tdStyle = { padding: '6px 8px', borderBottom: '1px solid rgba(255,255,255,0.08)' }
522
+ const btnStyle = { padding: '4px 9px', borderRadius: 6, border: '1px solid rgba(56,189,248,0.5)', background: 'rgba(56,189,248,0.16)', color: 'inherit', cursor: 'pointer', fontSize: 11 }
523
+ const numInputStyle = { width: 58, padding: '3px 5px', borderRadius: 5, border: '1px solid rgba(255,255,255,0.2)', background: 'transparent', color: 'inherit', fontSize: 11 }
@@ -0,0 +1,115 @@
1
+ 'use client'
2
+
3
+ /**
4
+ * Isolated Zustand UI state store for `krusch:plumbing`.
5
+ * Never mutates or extends Pascal's `useScene`, `useEditor`, or `useViewer` stores.
6
+ */
7
+
8
+ import { create } from 'zustand'
9
+ import type { ManifoldCutawayViewMode } from '../cad/manifold-interior'
10
+ import type {
11
+ CodeEdition,
12
+ FoundationType,
13
+ OccupancyType,
14
+ PlumbingSystem,
15
+ SupplyTopology,
16
+ } from '../ipc/tables'
17
+
18
+ export type PlumbingScheduleTab =
19
+ | 'fixtures'
20
+ | 'loads'
21
+ | 'audit'
22
+ | 'penetrations'
23
+ | 'bom'
24
+ | 'manifold'
25
+
26
+ type PlumbingUiState = {
27
+ occupancy: OccupancyType
28
+ codeEdition: CodeEdition
29
+ supplyTopology: SupplyTopology
30
+ supplyMaterial: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
31
+ dwvMaterial: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
32
+ foundationType: FoundationType
33
+ waterHeaterKind:
34
+ | 'water-heater-tank-electric'
35
+ | 'water-heater-tank-gas'
36
+ | 'water-heater-tankless-gas'
37
+ | 'water-heater-hpwh'
38
+ includeFuelGas: boolean
39
+ includeDryerVent: boolean
40
+ includeHotRecirc: boolean
41
+ activeTab: PlumbingScheduleTab
42
+ manifoldViewMode: ManifoldCutawayViewMode
43
+ selectedManifoldId: string | null
44
+ hiddenSystems: Readonly<Record<PlumbingSystem, boolean>>
45
+ setOccupancy: (v: OccupancyType) => void
46
+ setCodeEdition: (v: CodeEdition) => void
47
+ setSupplyTopology: (v: SupplyTopology) => void
48
+ setSupplyMaterial: (v: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc') => void
49
+ setDwvMaterial: (v: 'pvc-dwv' | 'abs-dwv' | 'cast-iron') => void
50
+ setFoundationType: (v: FoundationType) => void
51
+ setWaterHeaterKind: (
52
+ v:
53
+ | 'water-heater-tank-electric'
54
+ | 'water-heater-tank-gas'
55
+ | 'water-heater-tankless-gas'
56
+ | 'water-heater-hpwh',
57
+ ) => void
58
+ setIncludeFuelGas: (v: boolean) => void
59
+ setIncludeDryerVent: (v: boolean) => void
60
+ setIncludeHotRecirc: (v: boolean) => void
61
+ setActiveTab: (v: PlumbingScheduleTab) => void
62
+ setManifoldViewMode: (v: ManifoldCutawayViewMode) => void
63
+ setSelectedManifoldId: (id: string | null) => void
64
+ toggleSystemVisibility: (sys: PlumbingSystem) => void
65
+ }
66
+
67
+ export const usePlumbingUi = create<PlumbingUiState>((set) => ({
68
+ occupancy: 'residential',
69
+ codeEdition: 'IPC-2021',
70
+ supplyTopology: 'manifold',
71
+ supplyMaterial: 'pex-a',
72
+ dwvMaterial: 'pvc-dwv',
73
+ foundationType: 'crawlspace',
74
+ waterHeaterKind: 'water-heater-tank-electric',
75
+ includeFuelGas: false,
76
+ includeDryerVent: true,
77
+ includeHotRecirc: false,
78
+ activeTab: 'fixtures',
79
+ manifoldViewMode: 'wet-wall-cutaway',
80
+ selectedManifoldId: null,
81
+ hiddenSystems: {
82
+ 'cold-water': false,
83
+ 'hot-water': false,
84
+ 'hot-recirc': false,
85
+ 'dwv-drain': false,
86
+ 'dwv-vent': false,
87
+ 'fuel-gas': false,
88
+ condensate: false,
89
+ 'dryer-vent': false,
90
+ },
91
+ setOccupancy: (occupancy) => set({ occupancy }),
92
+ setCodeEdition: (codeEdition) => set({ codeEdition }),
93
+ setSupplyTopology: (supplyTopology) => set({ supplyTopology }),
94
+ setSupplyMaterial: (supplyMaterial) => set({ supplyMaterial }),
95
+ setDwvMaterial: (dwvMaterial) => set({ dwvMaterial }),
96
+ setFoundationType: (foundationType) => set({ foundationType }),
97
+ setWaterHeaterKind: (waterHeaterKind) =>
98
+ set((s) => ({
99
+ waterHeaterKind,
100
+ includeFuelGas:
101
+ waterHeaterKind === 'water-heater-tank-gas' || waterHeaterKind === 'water-heater-tankless-gas'
102
+ ? true
103
+ : s.includeFuelGas,
104
+ })),
105
+ setIncludeFuelGas: (includeFuelGas) => set({ includeFuelGas }),
106
+ setIncludeDryerVent: (includeDryerVent) => set({ includeDryerVent }),
107
+ setIncludeHotRecirc: (includeHotRecirc) => set({ includeHotRecirc }),
108
+ setActiveTab: (activeTab) => set({ activeTab }),
109
+ setManifoldViewMode: (manifoldViewMode) => set({ manifoldViewMode }),
110
+ setSelectedManifoldId: (selectedManifoldId) => set({ selectedManifoldId }),
111
+ toggleSystemVisibility: (sys) =>
112
+ set((s) => ({
113
+ hiddenSystems: { ...s.hiddenSystems, [sys]: !s.hiddenSystems[sys] },
114
+ })),
115
+ }))