-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2194 lines (1984 loc) · 100 KB
/
app.js
File metadata and controls
2194 lines (1984 loc) · 100 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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================
VISION STACK — App State Machine + Multiplayer Layer
============================================================ */
// ============================================================
// SESSION (multiplayer context — separate from workshop state)
// ============================================================
const session = {
mode: null, // null (lobby) | 'solo' | 'host' | 'participant'
socket: null,
roomCode: null,
myId: null, // socket.id
myName: '',
myColor: '#5b5bd6',
presence: [], // [{ id, name, color, isFacilitator }]
// Participant-side live state (populated from server events)
live: {
phase: 'principles',
teamName: '',
ideas: {
principles: [],
purpose: { who: [], struggle: [], change: [] },
mission: [],
strategy: { ux: [], technical: [], process: [], custom: [] },
customLabel: 'Culture & People',
okrs: { objectives: ['', ''], metrics: [] }
},
aiResults: { principles: null, purpose: null, mission: null, strategy: null, okrs: null },
selections: { principles: [], purpose: null, mission: null, strategy: [], okrs: [[], []] },
stack: { principles: [], purpose: null, mission: null, strategy: [], okrs: [] },
status: 'idle' // 'synthesizing' | 'idle'
}
};
// ============================================================
// WORKSHOP STATE (source of truth for solo + host facilitator)
// ============================================================
const state = {
phase: 'principles',
teamName: '',
facilitator: '',
stack: {
principles: [],
purpose: null,
mission: null,
strategy: [],
okrs: []
},
principles: { ideas: [''], aiResult: null, selected: new Set() },
purpose: { who: [''], struggle: [''], change: [''], aiResult: null, selectedIdx: null },
mission: { drafts: [{ solution: '', audience: '', outcome: '' }], aiResult: null, selectedIdx: null },
strategy: { clusters: { ux: [''], technical: [''], process: [''], custom: [''] }, customLabel: 'Culture & People', aiResult: null, selected: new Set() },
okrs: { objectives: ['', ''], metricIdeas: [''], aiResult: null, selected: [new Set(), new Set()] }
};
const PHASES = ['setup', 'principles', 'purpose', 'mission', 'strategy', 'okrs', 'output'];
// ============================================================
// IDEA HELPERS (handle both string (solo) and object (mp))
// ============================================================
function ideaValue(item) { return typeof item === 'string' ? item : (item?.value ?? ''); }
function ideaId(item, idx) { return typeof item === 'object' && item?.id ? item.id : String(idx); }
function ideaColor(item) { return typeof item === 'object' ? item?.ownerColor : null; }
function ideaOwnerName(item) { return typeof item === 'object' ? item?.ownerName : null; }
function ideaOwnerId(item) { return typeof item === 'object' ? item?.ownerSocketId : null; }
function isMineOrSolo(item) {
if (session.mode === 'solo' || session.mode === 'host') return true;
if (session.mode === 'participant') return ideaOwnerId(item) === session.myId;
return true;
}
// Get the ideas array for a given phase+slot from state (host/solo)
function getStateIdeasArray(phase, slot) {
if (phase === 'principles') return state.principles.ideas;
if (phase === 'purpose') return state.purpose[slot];
if (phase === 'strategy') return state.strategy.clusters[slot];
if (phase === 'okrs') return state.okrs.metricIdeas;
if (phase === 'mission') return state.mission.ideas; // not used currently
return null;
}
// Get the ideas array for participant live state
function getLiveIdeasArray(phase, slot) {
const l = session.live.ideas;
if (phase === 'principles') return l.principles;
if (phase === 'purpose') return l.purpose[slot];
if (phase === 'strategy') return l.strategy[slot];
if (phase === 'okrs') return l.okrs.metrics;
if (phase === 'mission') return l.mission;
return null;
}
// ============================================================
// MOCK AI
// ============================================================
function mockAISynthesis(phase) {
switch (phase) {
case 'principles':
return [
{ title: 'Assume Positive Intent', description: 'Default to curiosity over judgment — treat every interaction as an opportunity to understand, not to win.' },
{ title: 'Own It End-to-End', description: 'Take full responsibility for outcomes, not just outputs. Follow through until the problem is actually solved.' },
{ title: 'Clarity Over Cleverness', description: 'Favor clear, simple communication over impressive-sounding complexity in both code and conversation.' },
{ title: 'Move With Purpose', description: 'Bias toward action, but not at the cost of direction — know why you\'re moving fast before you accelerate.' },
{ title: 'Make the Invisible Visible', description: 'Surface blockers, risks, and context early and often. Hidden problems compound; shared problems shrink.' }
];
case 'purpose':
return [
'To empower the people who build the future by making the hardest design decisions feel effortless.',
'To create the clarity and tools that let passionate teams do the most meaningful work of their careers.',
'To bridge the gap between imagination and reality — so that great ideas actually ship.',
'To be the steady foundation that ambitious teams build on when everything else feels uncertain.',
'To make strategic design leadership accessible to every team, not just those with the biggest budgets.',
'To ensure no brilliant product idea fails because the team behind it lacked alignment.',
'To accelerate human progress by helping the builders within it move with conviction and speed.'
];
case 'mission':
return [
'We build a structured facilitation platform for design and product teams so they can align on strategy in hours, not months.',
'We build AI-powered workshop tools for cross-functional leaders so they can transform ambiguity into actionable team identity.',
'We build collaborative clarity frameworks for forward-thinking organizations so they can move faster with less friction and more focus.',
'We build intelligent alignment experiences for high-growth teams so they can establish a shared vision that actually guides daily decisions.'
];
case 'strategy':
return {
pillars: [
{ title: 'AI-First Facilitation', description: 'Embed AI synthesis at every step to compress decision-making from days to minutes without sacrificing depth or quality.' },
{ title: 'Opinionated Simplicity', description: 'Design every interaction with radical constraints — fewer inputs, clearer outputs, zero cognitive overhead for the facilitator.' },
{ title: 'Artifact-Driven Outcomes', description: 'Every session produces a polished, shareable document that outlives the meeting and can be socialized across the org instantly.' }
],
critique: 'Strong instincts, but these pillars risk being output-focused rather than capability-focused. "AI-First Facilitation" may over-index on the tool vs. the outcome — what\'s the plan when AI is wrong? There\'s no pillar for trust or validation loops. "Opinionated Simplicity" will polarize early adopters; be intentional about who you\'re willing to lose. Critically, none of these pillars address distribution or growth. You can build the best alignment tool in the world and have it die quietly. Consider adding a "Community & Champions" growth pillar.'
};
case 'okrs': {
const obj0 = state.okrs.objectives[0] || session.live.ideas.okrs.objectives[0] || 'Objective 1';
const obj1 = state.okrs.objectives[1] || session.live.ideas.okrs.objectives[1];
const results = [{ objective: obj0, keyResults: [
'Increase workshop completion rate from baseline to 80% within Q2.',
'Achieve average post-session NPS of 50+ across 10 pilot workshops.',
'Reduce average time-to-aligned-output from 4 hours to under 2.5 hours by end of quarter.',
'Onboard 3 enterprise pilot teams with at least 1 repeat session each.'
]}];
if (obj1 && obj1.trim()) {
results.push({ objective: obj1, keyResults: [
'Ship AI synthesis integration with live API for 2 phases by end of month.',
'Reduce facilitator session prep time from 60 minutes to under 15 minutes.',
'Achieve a Lighthouse performance score of 90+ on the application.',
'Pass a WCAG 2.1 AA accessibility audit with zero critical failures before launch.'
]});
}
return results;
}
default: return [];
}
}
// ============================================================
// RENDER ENGINE
// ============================================================
function render() {
renderBreadcrumb();
renderPresenceBar();
renderSidebar();
renderPhaseContent();
}
// Focus-safe render for socket-triggered updates
function renderFromSocket() {
const active = document.activeElement;
const ref = active?.dataset?.ideaRef;
const selStart = active?.selectionStart;
render();
if (ref) {
requestAnimationFrame(() => {
const el = document.querySelector(`[data-idea-ref="${ref}"]`);
if (el) { el.focus(); try { el.setSelectionRange(selStart, selStart); } catch(e) {} }
});
}
}
function renderBreadcrumb() {
if (session.mode === null || session.mode === 'participant') return;
const items = document.querySelectorAll('.breadcrumb-item');
const currentIdx = PHASES.indexOf(state.phase);
items.forEach((el, i) => {
el.classList.remove('active', 'completed');
if (i === currentIdx) {
el.classList.add('active');
el.style.cursor = '';
el.onclick = null;
} else if (i < currentIdx) {
el.classList.add('completed');
el.style.cursor = 'pointer';
el.onclick = () => goToPhase(el.dataset.phase);
} else {
el.style.cursor = '';
el.onclick = null;
}
});
}
function renderPresenceBar() {
const bar = document.getElementById('presenceBar');
if (!bar) return;
if ((session.mode !== 'host' && session.mode !== 'participant') || session.presence.length === 0) {
bar.style.display = 'none';
return;
}
bar.style.display = 'flex';
const avatars = session.presence.map(p => `
<div class="presence-avatar" style="--avatar-color:${p.color}" title="${escapeHtml(p.name)}${p.isFacilitator ? ' (facilitator)' : ''}">
${escapeHtml(p.name.charAt(0).toUpperCase())}
${p.isFacilitator ? '<span class="presence-host-dot"></span>' : ''}
</div>`).join('');
bar.innerHTML = `
<div class="presence-room-code" id="copyRoomCode" title="Click to copy room code" style="cursor:pointer">
<span class="presence-code-label">Room</span>
<span class="presence-code-value" id="roomCodeDisplay">${session.roomCode}</span>
</div>
<div class="presence-divider"></div>
<div class="presence-avatars">${avatars}</div>
<span class="presence-count">${session.presence.length} online</span>`;
document.getElementById('copyRoomCode')?.addEventListener('click', () => {
navigator.clipboard.writeText(session.roomCode).then(() => {
const el = document.getElementById('roomCodeDisplay');
if (!el) return;
const orig = el.textContent;
el.textContent = 'Copied!';
el.style.letterSpacing = '0';
setTimeout(() => { el.textContent = orig; el.style.letterSpacing = ''; }, 1500);
});
});
}
function renderSidebar() {
// In participant mode, drive sidebar from live state
const stackData = session.mode === 'participant' ? session.live.stack : state.stack;
const layers = ['principles', 'purpose', 'mission', 'strategy', 'okrs'];
let count = 0;
layers.forEach(key => {
const layer = document.getElementById(`layer-${key}`);
const content = document.getElementById(`layer-${key}-content`);
if (!layer || !content) return;
const data = stackData[key];
const has = Array.isArray(data) ? data.length > 0 : !!data;
if (has) {
count++;
layer.classList.add('populated');
content.classList.remove('empty');
content.innerHTML = renderSidebarLayer(key, data);
// Inject edit button (solo/host only, not participant)
if (session.mode !== 'participant') {
const label = layer.querySelector('.layer-label');
if (label && !label.querySelector('.layer-edit-btn')) {
const btn = document.createElement('button');
btn.className = 'layer-edit-btn';
btn.textContent = 'Edit';
btn.addEventListener('click', e => { e.stopPropagation(); goToPhase(key); });
label.appendChild(btn);
}
}
} else {
layer.classList.remove('populated');
content.classList.add('empty');
content.innerHTML = '<p class="layer-empty-text">Not yet defined</p>';
layer.querySelector('.layer-edit-btn')?.remove();
}
});
document.getElementById('progressBar').style.width = Math.round(count / 5 * 100) + '%';
document.getElementById('progressLabel').textContent =
`${count} of 5 layer${count !== 1 ? 's' : ''} complete`;
}
function renderSidebarLayer(key, data) {
if (key === 'principles' || key === 'strategy') {
return data.map(p => `<span class="layer-principle-chip">${escapeHtml(p.title)}</span>`).join('');
}
if (key === 'purpose' || key === 'mission') {
return `<p class="layer-statement-text">${escapeHtml(data)}</p>`;
}
if (key === 'okrs') {
return data.map(o => `
<div class="layer-okr-item">
<p class="layer-okr-obj">${escapeHtml(o.objective)}</p>
<p class="layer-okr-krs">${o.keyResults.length} KR${o.keyResults.length !== 1 ? 's' : ''}</p>
</div>`).join('');
}
return '';
}
function renderPhaseContent() {
const el = document.getElementById('phaseContent');
if (!el) return;
// LOBBY
if (session.mode === null) {
el.innerHTML = renderLobby();
attachLobbyListeners();
return;
}
// PARTICIPANT VIEW
if (session.mode === 'participant') {
el.innerHTML = renderParticipantView();
attachParticipantListeners();
return;
}
// FACILITATOR (solo or host) — full workshop flow
const map = {
setup: renderSetup,
principles: renderPrinciples,
purpose: renderPurpose,
mission: renderMission,
strategy: renderStrategy,
okrs: renderOKRs,
output: renderOutput
};
el.innerHTML = (map[state.phase] || renderSetup)();
attachEventListeners();
}
// ============================================================
// LOBBY
// ============================================================
function renderLobby() {
const isOnServer = window.location.protocol !== 'file:';
const noServerNote = !isOnServer
? `<div class="lobby-server-note">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
<span>
<strong>Multiplayer & AI require the Node server.</strong><br/>
Open a terminal in this folder and run:<br/>
<code>ANTHROPIC_API_KEY=sk-ant-… npm start</code><br/>
Then visit <code>http://localhost:3000</code>
</span>
</div>`
: `<div id="lobbyAiStatus" style="display:inline-flex;align-items:center;gap:7px;padding:5px 13px;border-radius:99px;border:1px solid #e4e4e7;background:#fafafa;font-size:12px;color:#71717a;margin-top:6px;transition:all .3s">
<span id="lobbyAiDot" style="width:7px;height:7px;border-radius:50%;background:#d4d4d8;flex-shrink:0;transition:background .4s"></span>
<span id="lobbyAiStatusText">Checking AI status…</span>
</div>`;
return `
<div class="lobby-view">
<div class="lobby-hero">
<div class="setup-logo-mark" style="margin-bottom:28px">
<div class="setup-logo-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>
</svg>
</div>
<div class="setup-logo-wordmark">Vision Stack</div>
<span class="setup-logo-version">Workshop</span>
</div>
<h1 class="phase-title" style="margin-bottom:10px">Your workshop,<br/>your room.</h1>
<p class="phase-description">Host a live session for your team or run through it solo. No FigJam required.</p>
${noServerNote}
</div>
<div class="lobby-cards">
<!-- HOST -->
<div class="lobby-card lobby-card-host">
<div class="lobby-card-icon" style="background:linear-gradient(135deg,var(--accent),#a78bfa)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
</div>
<h3 class="lobby-card-title">Host a Workshop</h3>
<p class="lobby-card-desc">Start a live session. Share a 4-letter room code and your team joins in real time.</p>
<div class="lobby-fields">
<input class="field-input" id="lobbyTeamName" type="text" placeholder="Team name" value="${escapeHtml(state.teamName)}" autocomplete="off" ${!isOnServer ? 'disabled' : ''} />
<input class="field-input" id="lobbyFacilitator" type="text" placeholder="Your name (facilitator)" value="${escapeHtml(state.facilitator)}" autocomplete="off" ${!isOnServer ? 'disabled' : ''} />
</div>
<button class="btn btn-primary" id="createSessionBtn" ${!isOnServer ? 'disabled' : ''} style="width:100%;justify-content:center;margin-top:4px">
Create Session
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
</button>
<p id="createError" class="lobby-error" style="display:none"></p>
</div>
<!-- JOIN -->
<div class="lobby-card">
<div class="lobby-card-icon" style="background:linear-gradient(135deg,#16a34a,#4ade80)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
</div>
<h3 class="lobby-card-title">Join a Session</h3>
<p class="lobby-card-desc">Enter the room code your facilitator shared and contribute in real time.</p>
<div class="lobby-fields">
<input class="field-input lobby-code-input" id="lobbyCode" type="text" placeholder="Room code (e.g. A3K9)" maxlength="4" autocomplete="off" autocapitalize="characters" ${!isOnServer ? 'disabled' : ''} />
<input class="field-input" id="lobbyParticipantName" type="text" placeholder="Your name" autocomplete="off" ${!isOnServer ? 'disabled' : ''} />
</div>
<button class="btn btn-primary" id="joinSessionBtn" ${!isOnServer ? 'disabled' : ''} style="width:100%;justify-content:center;background:var(--success);box-shadow:0 1px 3px rgba(22,163,74,.3),0 4px 12px rgba(22,163,74,.2)">
Join Session
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
</button>
<p id="joinError" class="lobby-error" style="display:none"></p>
</div>
</div>
<div class="lobby-solo">
<div class="lobby-solo-divider"><span>or</span></div>
<button class="btn btn-ghost" id="soloModeBtn" style="width:100%;justify-content:center">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
Continue in Solo Mode
</button>
<p class="lobby-solo-hint">No server needed. Run the full workshop yourself.</p>
</div>
</div>`;
}
function attachLobbyListeners() {
bindInput('lobbyTeamName', v => state.teamName = v);
bindInput('lobbyFacilitator', v => state.facilitator = v);
bindInput('lobbyCode', v => {
const el = document.getElementById('lobbyCode');
if (el) el.value = v.toUpperCase();
});
on('createSessionBtn', 'click', e => {
addRipple(e);
const teamName = document.getElementById('lobbyTeamName')?.value.trim() || 'Our Team';
const facilitator = document.getElementById('lobbyFacilitator')?.value.trim() || 'Facilitator';
state.teamName = teamName;
state.facilitator = facilitator;
connectAsHost(teamName, facilitator);
});
on('joinSessionBtn', 'click', e => {
addRipple(e);
const code = document.getElementById('lobbyCode')?.value.trim().toUpperCase();
const name = document.getElementById('lobbyParticipantName')?.value.trim();
if (!code) { showLobbyError('joinError', 'Enter a room code.'); return; }
if (!name) { showLobbyError('joinError', 'Enter your name.'); return; }
connectAsParticipant(code, name);
});
on('soloModeBtn', 'click', e => {
addRipple(e);
session.mode = 'solo';
state.phase = 'setup';
render();
});
// Auto-uppercase room code input
const codeInput = document.getElementById('lobbyCode');
if (codeInput) {
codeInput.addEventListener('input', () => {
const pos = codeInput.selectionStart;
codeInput.value = codeInput.value.toUpperCase();
codeInput.setSelectionRange(pos, pos);
});
}
// Check AI availability and update status badge
if (window.location.protocol !== 'file:') {
fetch('/api/health')
.then(r => r.json())
.then(({ aiEnabled }) => {
const dot = document.getElementById('lobbyAiDot');
const txt = document.getElementById('lobbyAiStatusText');
const badge = document.getElementById('lobbyAiStatus');
if (!dot || !txt || !badge) return;
if (aiEnabled) {
dot.style.background = '#16a34a';
txt.textContent = 'AI synthesis ready';
badge.style.background = '#f0fdf4';
badge.style.borderColor = '#bbf7d0';
badge.style.color = '#15803d';
} else {
dot.style.background = '#d97706';
txt.innerHTML = 'AI not configured — set <code style="background:#fef3c7;padding:1px 5px;border-radius:3px;font-size:11px">ANTHROPIC_API_KEY</code> and restart';
badge.style.background = '#fffbeb';
badge.style.borderColor = '#fde68a';
badge.style.color = '#92400e';
}
})
.catch(() => {
const badge = document.getElementById('lobbyAiStatus');
if (badge) badge.style.display = 'none';
});
}
}
function showLobbyError(id, msg) {
const el = document.getElementById(id);
if (el) { el.textContent = msg; el.style.display = 'block'; }
}
// ============================================================
// PARTICIPANT VIEW
// ============================================================
function renderParticipantView() {
const live = session.live;
const phase = live.phase;
const ai = live.aiResults[phase];
const sel = live.selections[phase];
const status = live.status;
const phaseInfo = {
principles: { num: '1 of 5', name: 'Principles', desc: 'What specific behaviors do you value most in your colleagues?', slots: [{ key: 'principles', slot: null, placeholder: 'e.g. Always assume the user is confused…' }] },
purpose: { num: '2 of 5', name: 'Purpose', desc: 'Contribute ideas to each of the three prompts below.', slots: [
{ key: 'who', slot: 'who', label: 'Who do we help?', placeholder: 'e.g. Early-stage startup founders…' },
{ key: 'struggle', slot: 'struggle', label: 'What is their biggest struggle?', placeholder: 'e.g. They can\'t align their team…' },
{ key: 'change', slot: 'change', label: 'How does our work change their lives?', placeholder: 'e.g. They ship with confidence…' }
]},
mission: { num: '3 of 5', name: 'Mission', desc: 'Drop any mission draft ideas — phrases, fragments, or full sentences.', slots: [{ key: 'mission', slot: null, placeholder: 'e.g. We build tools that help teams…' }] },
strategy: { num: '4 of 5', name: 'Strategy', desc: 'Add focus areas to any of the four clusters.', slots: [
{ key: 'ux', slot: 'ux', label: 'User Experience', placeholder: 'Key UX focus area…' },
{ key: 'technical', slot: 'technical', label: 'Technical Foundation', placeholder: 'Technical priority…' },
{ key: 'process', slot: 'process', label: 'Process & Operations', placeholder: 'Process improvement…' },
{ key: 'custom', slot: 'custom', label: live.ideas.customLabel || 'Custom', placeholder: 'Another focus area…' }
]},
okrs: { num: '5 of 5', name: 'OKRs', desc: 'Brainstorm raw metric ideas — anything that could measure success.', slots: [{ key: 'metrics', slot: null, placeholder: 'e.g. fewer bugs, faster handoff, more signups…' }] },
output: { num: 'Done', name: 'Output', desc: 'The workshop is complete. View your Vision Stack below.', slots: [] }
};
const info = phaseInfo[phase] || phaseInfo.principles;
const isOutput = phase === 'output';
// Collect all ideas for live feed
const allIdeas = collectAllLiveIdeas(phase);
// Render AI results for participant (read-only)
let aiSection = '';
if (ai && !isOutput) {
aiSection = renderParticipantAISection(phase, ai, sel);
}
// Build input sections
let inputSections = '';
if (!isOutput && status !== 'selecting') {
inputSections = info.slots.map(s => {
const slot = s.slot || s.key;
const arr = getLiveIdeasArray(phase === 'okrs' ? 'okrs' : phase, slot === 'metrics' ? null : slot) || getLiveIdeasArray('okrs', null);
const myIdeas = (slot === 'metrics' ? getLiveIdeasArray('okrs', null) : getLiveIdeasArray(phase, slot) || [])
.filter(i => ideaOwnerId(i) === session.myId);
const areaId = `pArea-${s.key}`;
return `
<div class="participant-input-section">
${s.label ? `<div class="purpose-section-label" style="margin-bottom:10px"><span class="purpose-section-dot" style="background:var(--accent)"></span>${s.label}</div>` : ''}
<div class="participant-idea-input">
<textarea class="sticky-input participant-sticky" id="pInput-${s.key}" placeholder="${s.placeholder}" rows="1"></textarea>
<button class="btn btn-primary participant-add-btn" data-phase="${phase}" data-slot="${slot}" data-input-id="pInput-${s.key}">Add</button>
</div>
${myIdeas.length > 0 ? `
<div class="participant-my-ideas">
${myIdeas.map(idea => `
<div class="participant-my-idea">
<span>${escapeHtml(ideaValue(idea))}</span>
<button class="sticky-delete" data-phase="${phase}" data-slot="${slot}" data-idea-id="${idea.id}">×</button>
</div>`).join('')}
</div>` : ''}
</div>`;
}).join('');
}
// Live feed
const liveFeedHtml = allIdeas.length > 0 ? `
<div class="live-feed">
<p class="live-feed-label">
<span class="live-dot"></span>
Live from the room (${allIdeas.length} idea${allIdeas.length !== 1 ? 's' : ''})
</p>
<div class="live-feed-ideas">
${allIdeas.map(idea => `
<div class="live-idea-card" style="--owner-color:${ideaColor(idea) || 'var(--accent)'}">
<span class="live-idea-owner-dot"></span>
<span class="live-idea-text">${escapeHtml(ideaValue(idea))}</span>
<span class="live-idea-name">${escapeHtml(ideaOwnerName(idea) || '')}</span>
</div>`).join('')}
</div>
</div>` : '';
// Status bar
const statusHtml = `
<div class="participant-status-bar ${status}">
${status === 'synthesizing'
? `<span class="loading-dots"><span></span><span></span><span></span></span> Facilitator is synthesizing with AI…`
: status === 'selecting'
? `<span class="participant-status-icon">👁</span> Facilitator is reviewing options…`
: `<span class="participant-status-icon" style="opacity:.5">⬤</span> Brainstorming in progress. Add your ideas above.`}
</div>`;
return `
<div class="participant-view">
<div class="phase-eyebrow"><div class="phase-eyebrow-dot"></div>Phase ${info.num}</div>
<h1 class="phase-title" style="font-size:26px;margin-bottom:8px">${info.name}</h1>
${!isOutput ? `<div class="step-prompt" style="margin-bottom:24px">${info.desc}</div>` : ''}
${inputSections}
${liveFeedHtml}
${statusHtml}
${aiSection}
${isOutput ? `
<div class="output-artifact" style="margin-top:24px">
${renderOutputArtifactBody(session.live.stack)}
</div>` : ''}
</div>`;
}
function collectAllLiveIdeas(phase) {
const l = session.live.ideas;
if (phase === 'principles') return l.principles;
if (phase === 'purpose') return [...l.purpose.who, ...l.purpose.struggle, ...l.purpose.change];
if (phase === 'strategy') return [...l.strategy.ux, ...l.strategy.technical, ...l.strategy.process, ...l.strategy.custom];
if (phase === 'okrs') return l.okrs.metrics;
if (phase === 'mission') return l.mission;
return [];
}
function renderParticipantAISection(phase, ai, sel) {
if (phase === 'principles' && Array.isArray(ai)) {
const selSet = new Set(Array.isArray(sel) ? sel : []);
return `
<div class="step-card ai-results-section" style="margin-top:16px">
<div class="ai-results-header">
<div class="ai-results-badge">
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>
AI Synthesized
</div>
<span class="ai-results-hint">Facilitator is selecting</span>
</div>
<div class="option-cards-grid">
${ai.map((opt, i) => `
<div class="option-card ${selSet.has(i) ? 'selected' : ''}" style="cursor:default;pointer-events:none">
<div class="option-card-check">${selSet.has(i) ? '✓' : ''}</div>
<div class="option-card-title">${escapeHtml(opt.title)}</div>
<div class="option-card-desc">${escapeHtml(opt.description)}</div>
</div>`).join('')}
</div>
</div>`;
}
if ((phase === 'purpose' || phase === 'mission') && Array.isArray(ai)) {
const selectedIdx = typeof sel === 'number' ? sel : null;
return `
<div class="step-card ai-results-section" style="margin-top:16px">
<div class="ai-results-header"><div class="ai-results-badge">AI Synthesized</div><span class="ai-results-hint">Facilitator is selecting</span></div>
<div class="option-cards-grid">
${ai.map((opt, i) => `
<div class="option-card ${selectedIdx === i ? 'selected' : ''}" style="cursor:default;pointer-events:none">
<div class="option-card-check">${selectedIdx === i ? '✓' : ''}</div>
<div class="option-card-title">${escapeHtml(typeof opt === 'string' ? opt : opt.title)}</div>
</div>`).join('')}
</div>
</div>`;
}
return '';
}
function attachParticipantListeners() {
// Add idea buttons
document.querySelectorAll('.participant-add-btn').forEach(btn => {
btn.addEventListener('click', () => {
const phase = btn.dataset.phase;
const slot = btn.dataset.slot;
const inputId = btn.dataset.inputId;
const input = document.getElementById(inputId);
const value = input?.value.trim();
if (!value || !session.socket) return;
const id = crypto.randomUUID?.() || `${Date.now()}-${Math.random()}`;
// Optimistic update
const ideaObj = { id, value, ownerSocketId: session.myId, ownerName: session.myName, ownerColor: session.myColor };
const arr = getLiveIdeasArray(phase, slot === 'metrics' ? null : (slot !== phase ? slot : null)) || getLiveIdeasArrayBySlot(phase, slot);
if (arr) arr.push(ideaObj);
if (input) { input.value = ''; input.style.height = 'auto'; }
renderFromSocket();
session.socket.emit('idea:add', { phase, slot, value, id });
});
});
// Remove own idea
document.querySelectorAll('.sticky-delete[data-idea-id]').forEach(btn => {
btn.addEventListener('click', () => {
const phase = btn.dataset.phase;
const slot = btn.dataset.slot;
const id = btn.dataset.ideaId;
// Optimistic remove
const arr = getLiveIdeasArrayBySlot(phase, slot);
if (arr) { const idx = arr.findIndex(i => i.id === id); if (idx !== -1) arr.splice(idx, 1); }
renderFromSocket();
if (session.socket) session.socket.emit('idea:remove', { phase, slot, id });
});
});
// Auto-resize participant textareas
document.querySelectorAll('.participant-sticky').forEach(el => {
autoResizeTextarea(el);
el.addEventListener('input', () => autoResizeTextarea(el));
el.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
const addBtn = document.querySelector(`.participant-add-btn[data-input-id="${el.id}"]`);
if (addBtn) addBtn.click();
}
});
});
}
// Helper to route phase+slot to live ideas array
function getLiveIdeasArrayBySlot(phase, slot) {
const l = session.live.ideas;
if (phase === 'principles') return l.principles;
if (phase === 'purpose') return l.purpose[slot] || l.purpose.who;
if (phase === 'mission') return l.mission;
if (phase === 'strategy') return l.strategy[slot] || l.strategy.ux;
if (phase === 'okrs') return l.okrs.metrics;
return null;
}
// ============================================================
// SHARED COMPONENT HELPERS
// ============================================================
function renderStickyRow(item, idx, placeholder = '') {
const value = ideaValue(item);
const ref = ideaId(item, idx);
const color = ideaColor(item);
const ownerName = ideaOwnerName(item);
const mine = isMineOrSolo(item);
return `
<div class="sticky-row ${color ? 'mp-sticky' : ''}" data-sticky-idx="${idx}" data-idea-ref="${ref}"
${color ? `style="--owner-color:${color}"` : ''}>
<textarea class="sticky-input" data-sticky-idx="${idx}" data-idea-ref="${ref}"
placeholder="${placeholder}" rows="1"
${!mine ? 'readonly' : ''}>${escapeHtml(value)}</textarea>
${mine ? `<button class="sticky-delete" data-sticky-idx="${idx}" data-idea-ref="${ref}" title="Remove">×</button>` : ''}
${color ? `<span class="sticky-owner-badge" title="${escapeHtml(ownerName || '')}" style="background:${color}">${escapeHtml((ownerName || '?').charAt(0))}</span>` : ''}
</div>`;
}
function renderAddStickyBtn(id, label = 'Add idea') {
return `
<button class="add-sticky-btn" id="${id}">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
${label}
</button>`;
}
function aiSparkIcon() {
return `<svg class="ai-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/>
</svg>`;
}
function renderAIBar(btnId, hint, disabled, hasResult) {
return `
<div class="ai-action-bar">
<p class="ai-hint">${hint}</p>
<div class="ai-action-btns">
<button class="btn btn-ghost btn-copy-prompt" id="copyPromptBtn" ${disabled ? 'disabled' : ''}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
Copy Prompt
</button>
<button class="btn btn-ai" id="${btnId}" ${disabled ? 'disabled' : ''}>
${aiSparkIcon()}
${hasResult ? 'Re-synthesize' : 'AI Synthesize'}
</button>
</div>
</div>
<div class="copy-prompt-panel" id="copyPromptPanel">
<div class="cpp-inner">
<div class="cpp-header">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
Prompt copied — open any AI assistant, paste it in, then paste the response below
</div>
<div class="cpp-links">
<a href="https://claude.ai/new" target="_blank" rel="noopener" class="cpp-link cpp-claude">Claude.ai ↗</a>
<a href="https://chatgpt.com/" target="_blank" rel="noopener" class="cpp-link cpp-chatgpt">ChatGPT ↗</a>
<a href="https://gemini.google.com/" target="_blank" rel="noopener" class="cpp-link cpp-gemini">Gemini ↗</a>
</div>
<textarea class="cpp-textarea" id="pasteArea" placeholder="Paste the AI's response here — results appear automatically…" rows="4"></textarea>
<p class="cpp-parse-status" id="parseStatus"></p>
</div>
</div>`;
}
function renderAIBadge() {
return `
<div class="ai-results-header">
<div class="ai-results-badge">
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>
AI Synthesized
</div>
<span class="ai-results-hint">Click to select · Click text to edit</span>
</div>`;
}
function renderFinalizeBar(id, countText, disabled, label = 'Commit to Stack') {
return `
<div class="finalize-bar">
<p class="finalize-count">${countText}</p>
<button class="btn btn-success" id="${id}" ${disabled ? 'disabled' : ''}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
${label}
</button>
</div>`;
}
// ============================================================
// FACILITATOR PHASE RENDERS (solo + host)
// ============================================================
function renderSetup() {
return `
<div class="phase-view">
<div class="setup-hero">
<div class="setup-logo-mark">
<div class="setup-logo-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>
</svg>
</div>
<div><div class="setup-logo-wordmark">Vision Stack</div></div>
<span class="setup-logo-version">Workshop</span>
</div>
<div class="phase-eyebrow"><div class="phase-eyebrow-dot"></div>Getting Started</div>
<h1 class="phase-title">Build your team's<br/>north star.</h1>
<p class="phase-description">
In under four hours, your team will align on <strong>Principles, Purpose, Mission, Strategy,</strong> and <strong>OKRs</strong> —
the five layers that define how you work, why you exist, and how you measure success.
</p>
<div id="setupAiNote" style="display:none;margin-top:12px;padding:10px 14px;border-radius:10px;border:1px solid #fde68a;background:#fffbeb;font-size:13px;color:#92400e;line-height:1.5">
<strong>AI synthesis is not configured.</strong> You can still run the full workshop — the AI step will return example output instead of real synthesis.
To enable AI: restart the server with <code style="background:#fef3c7;padding:1px 5px;border-radius:3px">ANTHROPIC_API_KEY=sk-ant-…</code> set.
</div>
</div>
<div class="setup-fields">
<div class="field-group">
<label class="field-label" for="teamNameInput">Team Name</label>
<p class="field-hint">This will appear on your final Vision Stack artifact.</p>
<input class="field-input" id="teamNameInput" type="text" placeholder="e.g. Antigravity Design Team" value="${escapeHtml(state.teamName)}" autocomplete="off" />
</div>
<div class="field-group">
<label class="field-label" for="facilitatorInput">Facilitator Name</label>
<p class="field-hint">Who is running today's workshop?</p>
<input class="field-input" id="facilitatorInput" type="text" placeholder="e.g. Sarah Kim" value="${escapeHtml(state.facilitator)}" autocomplete="off" />
</div>
</div>
<div class="agenda-card">
<p class="agenda-title">Workshop Agenda</p>
<ul class="agenda-list">
${[['1','Principles','45 min'],['2','Purpose','30 min'],['3','Mission','40 min']].map(([n,name,t]) => `
<li class="agenda-item"><span class="agenda-num">${n}</span><span class="agenda-phase-name">${name}</span><span class="agenda-time">${t}</span></li>`).join('')}
<li class="agenda-item"><span class="agenda-num" style="background:var(--warn-soft);color:var(--warn);">⏸</span><span class="agenda-phase-name">Break</span><span class="agenda-time">20 min</span></li>
${[['4','Strategy','50 min'],['5','OKRs','40 min']].map(([n,name,t]) => `
<li class="agenda-item"><span class="agenda-num">${n}</span><span class="agenda-phase-name">${name}</span><span class="agenda-time">${t}</span></li>`).join('')}
<li class="agenda-item"><span class="agenda-num" style="background:var(--success-soft);color:var(--success);">✓</span><span class="agenda-phase-name">Wrap-up & Output</span><span class="agenda-time">15 min</span></li>
</ul>
</div>
<div class="phase-nav">
<div></div>
<button class="btn btn-primary" id="startWorkshopBtn">
Begin Workshop
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
</button>
</div>
</div>`;
}
function renderPrinciples() {
const p = state.principles;
const hasIdeas = p.ideas.some(s => ideaValue(s).trim());
const hasResults = p.aiResult && p.aiResult.length > 0;
const selCount = p.selected.size;
return `
<div class="phase-view">
<div class="phase-eyebrow"><div class="phase-eyebrow-dot"></div>Phase 1 of 5 · 45 min</div>
<h1 class="phase-title">Principles</h1>
<p class="phase-description">Principles are the <strong>behaviors and beliefs</strong> that define your team's culture. Think specific actions — <em>"Always assume the user is confused"</em> beats <em>"Integrity."</em></p>
<div class="step-card">
<div class="step-card-header"><span class="step-num">Step 1 · 7 min</span></div>
<h3 class="step-title">Silent Brainstorm</h3>
<p class="step-desc">Each team member independently writes down specific behaviors they value in great colleagues.</p>
<div class="step-prompt">"What specific behaviors do you value most in your colleagues?"</div>
<div class="stickies-area" id="stickiesArea">
${p.ideas.map((v, i) => renderStickyRow(v, i, 'e.g. Always question assumptions before writing a single line of code…')).join('')}
</div>
${renderAddStickyBtn('addStickyBtn')}
${renderAIBar('synthesizeBtn',
hasIdeas ? `${p.ideas.filter(s=>ideaValue(s).trim()).length} idea${p.ideas.filter(s=>ideaValue(s).trim()).length !== 1 ? 's' : ''} ready.` : 'Add at least one idea.',
!hasIdeas, !!p.aiResult)}
</div>
${hasResults ? `
<div class="step-card ai-results-section">
<div class="step-card-header"><span class="step-num">Step 2–3 · 33 min</span></div>
<h3 class="step-title">Vote & Refine</h3>
<p class="step-desc">Select themes that resonate. Click text to edit. Aim for 4–5 principles.</p>
${renderAIBadge()}
<div class="option-cards-grid" id="optionCardsGrid">
${p.aiResult.map((opt, i) => `
<div class="option-card ${p.selected.has(i) ? 'selected' : ''}" data-option-idx="${i}">
<div class="option-card-check">${p.selected.has(i) ? '✓' : ''}</div>
<div class="option-card-title" contenteditable="${p.selected.has(i)}" data-field="title" data-option-idx="${i}">${escapeHtml(opt.title)}</div>
<div class="option-card-desc" contenteditable="${p.selected.has(i)}" data-field="desc" data-option-idx="${i}">${escapeHtml(opt.description)}</div>
<p class="option-card-edit-hint">Click text above to edit wording.</p>
</div>`).join('')}
</div>
${renderFinalizeBar('finalizeBtn', selCount === 0 ? 'Select the principles that resonate.' : `<strong>${selCount} principle${selCount !== 1 ? 's' : ''}</strong> selected.`, selCount === 0)}
</div>` : ''}
<div class="phase-nav"><button class="btn btn-ghost" id="backBtn">← Back</button><div></div></div>
</div>`;
}
function renderPurpose() {
const p = state.purpose;
const totalIdeas = [...p.who, ...p.struggle, ...p.change].filter(s => ideaValue(s).trim()).length;
const hasResults = p.aiResult && p.aiResult.length > 0;
const sections = [
{ key: 'who', dotClass: 'who', label: 'Who do we help?', placeholder: 'e.g. Early-stage startup founders who…' },
{ key: 'struggle', dotClass: 'struggle', label: 'What is their biggest struggle?', placeholder: 'e.g. They struggle to align their team…' },
{ key: 'change', dotClass: 'change', label: 'How does our work change their lives?', placeholder: 'e.g. They can finally ship with confidence…' }
];
return `
<div class="phase-view">
<div class="phase-eyebrow"><div class="phase-eyebrow-dot"></div>Phase 2 of 5 · 30 min</div>
<h1 class="phase-title">Purpose</h1>
<p class="phase-description">Purpose is your team's <strong>"why"</strong> — the fundamental reason you exist beyond the work itself.</p>
<div class="step-card">
<div class="step-card-header"><span class="step-num">Step 1 · 8 min</span></div>
<h3 class="step-title">The "Why" Prompts</h3>
<p class="step-desc">Add sticky notes in each area. Short phrases are fine — the AI will weave them into statements.</p>
<div class="purpose-sections">
${sections.map(s => `
<div class="purpose-section">
<div class="purpose-section-label"><span class="purpose-section-dot ${s.dotClass}"></span>${s.label}</div>
<div class="stickies-area" id="stickiesArea-${s.key}">
${p[s.key].map((v, i) => renderStickyRow(v, i, s.placeholder)).join('')}
</div>
${renderAddStickyBtn(`addStickyBtn-${s.key}`)}
</div>`).join('')}
</div>
${renderAIBar('synthesizeBtn',
totalIdeas > 0 ? `${totalIdeas} idea${totalIdeas !== 1 ? 's' : ''} across all prompts.` : 'Fill in at least one area.',
totalIdeas === 0, !!p.aiResult)}
</div>
${hasResults ? `
<div class="step-card ai-results-section">
<div class="step-card-header"><span class="step-num">Step 2 · 22 min</span></div>
<h3 class="step-title">Select Your Purpose</h3>
<p class="step-desc">Pick the statement that resonates most — one only. Click text to edit.</p>
${renderAIBadge()}
<div class="option-cards-grid" id="purposeCardsGrid">
${p.aiResult.map((stmt, i) => `
<div class="purpose-statement-card ${p.selectedIdx === i ? 'selected' : ''}" data-option-idx="${i}">
<div class="option-card-check">${p.selectedIdx === i ? '✓' : ''}</div>
<span contenteditable="${p.selectedIdx === i}" data-option-idx="${i}">${escapeHtml(stmt)}</span>
</div>`).join('')}
</div>
${renderFinalizeBar('finalizeBtn', p.selectedIdx === null ? 'Select one purpose statement.' : '<strong>1 statement</strong> selected.', p.selectedIdx === null)}
</div>` : ''}
<div class="phase-nav"><button class="btn btn-ghost" id="backBtn">← Back</button><div></div></div>
</div>`;
}
function renderMission() {
const m = state.mission;
const hasContent = m.drafts.some(d => d.solution.trim() || d.audience.trim() || d.outcome.trim());
const hasResults = m.aiResult && m.aiResult.length > 0;
return `
<div class="phase-view">
<div class="phase-eyebrow"><div class="phase-eyebrow-dot"></div>Phase 3 of 5 · 40 min</div>
<h1 class="phase-title">Mission</h1>
<p class="phase-description">Mission is your team's <strong>"what"</strong> — the concrete objective you're working to achieve over the next 1–3 years.</p>
<div class="step-card">
<div class="step-card-header"><span class="step-num">Step 1 · 10 min</span></div>
<h3 class="step-title">Mad-Libs Framework</h3>
<p class="step-desc">Fill in the blanks. Write 2–3 variations to explore different framings of your mission.</p>
<div class="madlibs-drafts" id="madlibsDrafts">
${m.drafts.map((d, i) => `
<div class="madlibs-draft" data-draft-idx="${i}">