-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
899 lines (746 loc) · 39.3 KB
/
index.html
File metadata and controls
899 lines (746 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🌟 Quannex Coherence Engine - University Demo</title>
<link rel="icon" href="data:,"><!-- Suppress favicon 404 -->
<link rel="stylesheet" href="css/dashboard.css">
<link rel="stylesheet" href="css/data-integrity.css">
</head>
<body>
<div class="container">
<div class="header">
<div class="title">🌟 QUANNEX COHERENCE ENGINE</div>
<div class="subtitle">Organizational DNA • 12 Faces • Real-time Coherence Analysis</div>
<div class="global-coherence tooltip" id="globalCoherence"
data-tooltip="Average energy across all 12 organizational faces - Higher is better!">—</div>
<div class="status" id="globalStatus">Initializing...</div>
<!-- Data Integrity Indicator - Per-Face Quality Badges -->
<div class="data-integrity-header" id="dataIntegrityHeader" style="display: none;">
<div class="data-integrity-header__summary" id="faceQualitySummary">
<!-- Face quality summary badges will be inserted here by FaceQualityBadge.js -->
</div>
</div>
</div>
<!-- Company Selector -->
<div class="company-selector" id="companySelector">
<div class="selector-title">Select Organization</div>
<div class="company-cards" id="companyCards">
<!-- Company cards will be inserted here -->
</div>
</div>
<!-- Breath Analysis Section -->
<div class="breath-section" id="breathSection" style="display: none;">
<div class="section-header">
<h2>🫁 Organizational Respiration</h2>
<p class="section-subtitle">The 6 Breath Axes • Reception ↔ Projection Balance</p>
</div>
<div class="breath-overall" id="breathOverall">
<!-- Overall breath health will be inserted here -->
</div>
<div class="breath-axes" id="breathAxes">
<!-- Breath axis cards will be inserted here -->
</div>
</div>
<!-- Spectral Analysis Section (New) -->
<div class="spectral-section" id="spectralSection" style="display: none;">
<div class="section-header">
<h2>🎵 System Resonance</h2>
<p class="section-subtitle">Spectral Analysis • Eigenvector Decomposition • Hidden Harmonics</p>
</div>
<div class="spectral-grid" id="spectralContent">
<!-- Spectral content will be inserted here -->
</div>
</div>
<div id="loading" class="loading">
<div class="spinner"></div>
<div>Initializing Coherence Engine...</div>
</div>
<div id="dashboard" class="dashboard" style="display: none;">
<!-- Face cards will be inserted here -->
</div>
<div class="controls" style="display: none;" id="controls">
<button class="btn" onclick="refreshData()">🔄 Refresh Data</button>
<button class="btn" onclick="window.location.href='calculations.html'">🔬 Calculations View</button>
<button class="btn" onclick="window.location.href='breath-analysis.html'">🌊 Breath Analysis View</button>
<button class="btn" onclick="window.location.href='octave-dna.html'">🧬 View DNA Visualization</button>
</div>
<div class="footer">
<p>© 2025 Quannex • Organizational Coherence Engine</p>
<p>University Demo • Serverless Edition</p>
</div>
</div>
<!-- Load Logger Utility -->
<script src="./js/utils/logger.js"></script>
<!-- Load company loader first -->
<script type="module" src="./js/company-loader.js"></script>
<!-- Load breath analyzer -->
<script src="./js/breath-analyzer.js"></script>
<!-- Load spectral analyzer -->
<script src="./js/spectral-analyzer.js"></script>
<!-- Load data integrity components -->
<script src="./js/data-system/face-quality-badge.js"></script>
<!-- Load JSON data loader (enables JSON-first loading with CSV fallback) -->
<script src="./js/data-system/json-data-loader.js"></script>
<!-- Dodecahedron topology SSOT (12 faces, 30 edges, 20 vertices) -->
<script src="./js/geometry/dodecahedron-topology.js"></script>
<!-- Load the serverless engine (ES Module) -->
<script type="module" src="./js/main.js"></script>
<script>
// ============================================
// IFRAME DETECTION: Hide header if embedded
// ============================================
// Prevents header overlap when loaded inside demo.html iframe
if (window.self !== window.top) {
document.addEventListener('DOMContentLoaded', () => {
const header = document.querySelector('.header');
const companySelector = document.querySelector('.company-selector');
if (header) {
header.style.display = 'none';
Logger.info('Index', '📐 Iframe mode: Header hidden to prevent overlap');
}
if (companySelector) {
companySelector.style.display = 'none';
}
});
}
/**
* Populate company selector cards
*/
function populateCompanySelector() {
const container = document.getElementById('companyCards');
const companies = window.CompanyLoader.getAvailableCompanies();
companies.forEach((company, index) => {
const card = document.createElement('div');
card.className = 'company-card';
card.id = `company-${company.id}`;
card.style.setProperty('--company-color', company.color);
card.style.setProperty('--company-color-alpha', company.color + '33');
// Set first company as active by default
if (index === 0) {
card.classList.add('active');
}
card.innerHTML = `
<div class="company-name">${company.name}</div>
<div class="company-tagline">${company.tagline}</div>
<div class="company-stage">${company.stage}</div>
<div class="company-octaves">
<span style="opacity: 0.7;">Octave Range:</span>
<span class="octave-badge">${company.octaveRange}</span>
</div>
<div class="company-description">${company.description}</div>
`;
// Add click handler
card.addEventListener('click', () => selectCompany(company.id));
container.appendChild(card);
});
}
/**
* Select a company and reinitialize dashboard
*/
async function selectCompany(companyId) {
try {
Logger.info('Index', `🏢 Switching to company: ${companyId}`);
// ✅ Store selected company in sessionStorage for navigation to other pages
sessionStorage.setItem('selectedCompanyId', companyId);
// Update UI to show active company
document.querySelectorAll('.company-card').forEach(card => {
card.classList.remove('active');
});
document.getElementById(`company-${companyId}`).classList.add('active');
// Show loading state
document.getElementById('loading').style.display = 'block';
document.getElementById('dashboard').style.display = 'none';
document.getElementById('breathSection').style.display = 'none';
document.getElementById('controls').style.display = 'none';
// Load company and reinitialize
const company = await window.CompanyLoader.switchCompany(companyId);
if (company) {
// Get updated state and display
const state = window.Quannex.getState();
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
displayState(state);
Logger.info('Index', `✅ Switched to ${company.name}`);
} else {
throw new Error('Failed to load company data');
}
} catch (error) {
Logger.error('Index', '❌ Failed to switch company:', error);
alert(`Failed to load company: ${error.message}`);
}
}
/**
* Initialize and display the dashboard
*/
async function initDashboard() {
try {
Logger.info('Index', '🚀 Initializing Quannex Dashboard...');
// Populate company selector
populateCompanySelector();
// Load first company by default
const companies = window.CompanyLoader.getAvailableCompanies();
const firstCompany = companies[0];
// ✅ Store in sessionStorage for navigation to other pages
sessionStorage.setItem('selectedCompanyId', firstCompany.id);
Logger.info('Index', `📦 Loading default company: ${firstCompany.name}`);
const company = await window.CompanyLoader.loadCompany(firstCompany.id);
// Initialize the engine with company data
const state = await window.Quannex.initWithCompany(company);
Logger.info('Index', '✅ Engine initialized:', state);
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
// Display data
displayState(state);
} catch (error) {
Logger.error('Index', '❌ Failed to initialize:', error);
document.getElementById('loading').innerHTML = `
<div class="spinner"></div>
<div>Error: ${error.message}</div>
<div style="margin-top: 20px; font-size: 14px;">
Please check the console for details.
</div>
`;
}
}
/**
* Display system state
*/
function displayState(state) {
// Update global coherence
const coherence = state.globalCoherence;
const coherencePercent = (coherence * 100).toFixed(1);
document.getElementById('globalCoherence').textContent = `${coherencePercent}%`;
// Update global status
const statusEl = document.getElementById('globalStatus');
if (coherence >= 0.7) {
statusEl.textContent = '✅ HEALTHY SYSTEM';
statusEl.className = 'status healthy';
} else if (coherence >= 0.5) {
statusEl.textContent = '⚠️ DIMMING';
statusEl.className = 'status dimming';
} else {
statusEl.textContent = '🚨 CRITICAL';
statusEl.className = 'status critical';
}
// Display face cards
const dashboard = document.getElementById('dashboard');
dashboard.innerHTML = '';
state.faces.forEach(face => {
dashboard.appendChild(createFaceCard(face));
});
// Display breath analysis
displayBreathAnalysis();
// Display spectral analysis
displaySpectralAnalysis();
// Update face quality badges
refreshFaceQuality();
}
/**
* Create a face card
*/
function createFaceCard(face) {
const card = document.createElement('div');
card.className = 'face-card';
card.style.borderColor = face.color;
const energyPercent = (face.faceEnergy * 100).toFixed(1);
card.innerHTML = `
<div class="face-header">
<div>
<div class="face-name tooltip" data-tooltip="Organizational domain - one of 12 pentagonal faces">${face.name}</div>
<div class="face-id">Face ${face.id}</div>
</div>
<div style="font-size: 24px;">${getHealthIcon(face.status)}</div>
</div>
<div class="energy-display tooltip" style="color: ${face.color};"
data-tooltip="Face energy: Base KPI average + harmonic resonance boost (up to 30%)">${energyPercent}%</div>
<div class="energy-bar">
<div class="energy-fill" style="width: ${energyPercent}%; background: linear-gradient(90deg, ${face.color}, ${face.color}88);"></div>
</div>
<div style="text-align: center; margin-top: 10px; padding: 8px; background: rgba(0,0,0,0.2); border-radius: 6px;">
<strong>Status:</strong> ${face.status}
</div>
<div class="kpi-list" id="kpis-${face.id}">
<!-- KPIs will be loaded here -->
</div>
`;
// Load KPIs for this face
loadFaceKPIs(face.id);
return card;
}
/**
* Load KPIs for a specific face
*/
function loadFaceKPIs(faceId) {
const faces = window.Quannex.getFaces();
const face = faces.find(f => f.id === faceId);
if (!face || !face.kpis || face.kpis.length === 0) {
return;
}
const container = document.getElementById(`kpis-${faceId}`);
if (!container) return;
let html = '<div style="margin-top: 15px; font-size: 13px; font-weight: bold; opacity: 0.8;">Elemental KPIs:</div>';
face.kpis.forEach((kpi, index) => {
const elements = [
{ icon: '🜃', name: 'Earth', tooltip: 'Earth - Grounding, stability, material resources' },
{ icon: '💧', name: 'Water', tooltip: 'Water - Flow, adaptability, emotional intelligence' },
{ icon: '🔥', name: 'Fire', tooltip: 'Fire - Energy, passion, transformation' },
{ icon: '💨', name: 'Air', tooltip: 'Air - Communication, intellect, movement' },
{ icon: '🜀', name: 'Ether', tooltip: 'Ether - Space, potential, integration' }
];
const element = elements[index] || { icon: '⚡', name: 'Element', tooltip: 'Elemental KPI' };
html += `
<div class="kpi-item">
<div class="kpi-name tooltip" data-tooltip="${element.tooltip}">${element.icon} ${kpi.name}</div>
<div class="kpi-value">
<span class="tooltip" data-tooltip="Normalized score (0-100%) based on KPI direction">Score: ${(kpi.normalizedScore * 100).toFixed(1)}%</span>
<span>Value: ${kpi.value.toFixed(2)}</span>
</div>
</div>
`;
});
container.innerHTML = html;
}
/**
* Get health status icon
*/
function getHealthIcon(status) {
const icons = {
'Radiant': '✨',
'Healthy': '✅',
'Dimming': '⚠️',
'Struggling': '🔴',
'Critical': '🚨'
};
return icons[status] || '●';
}
/**
* Refresh data
*/
function refreshData() {
const state = window.Quannex.getState();
displayState(state);
Logger.info('Index', '🔄 Data refreshed');
}
/**
* Display breath analysis
*/
function displayBreathAnalysis() {
const breathAnalysis = window.Quannex.getBreathAnalysis();
if (!breathAnalysis) {
Logger.warn('Index', '⚠️ No breath analysis available - breath analyzer may not be loaded');
// Hide breath section if no data
document.getElementById('breathSection').style.display = 'none';
return;
}
Logger.info('Index', '🌊 Displaying breath analysis:', breathAnalysis);
// Show breath section
document.getElementById('breathSection').style.display = 'block';
// Check if we should auto-scroll to breath section (hash navigation)
if (window.location.hash === '#breath') {
setTimeout(() => {
document.getElementById('breathSection').scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}, 500); // Delay to ensure section is rendered
}
// Display overall breath health
const overallContainer = document.getElementById('breathOverall');
const overall = breathAnalysis.overall;
const statusClass = overall.status.toLowerCase().replace(' ', '-');
overallContainer.innerHTML = `
<div class="breath-overall-score tooltip" style="color: ${getBreathHealthColor(overall.breathHealth)}"
data-tooltip="Overall breath health across 6 harmonic axes (Reception ↔ Projection balance)">
${overall.breathHealthPercentage.toFixed(1)}%
</div>
<div class="breath-overall-status breath-status-${overall.dominantTendency}">
${overall.status} • ${overall.dominantTendency.replace('-', ' ').toUpperCase()}
</div>
<div class="breath-overall-message">${overall.message}</div>
<div style="font-size: 13px; margin-top: 15px; opacity: 0.8;">
<span class="tooltip" data-tooltip="Breath ratio between 0.8-1.2 (balanced breathing)">${overall.balancedAxes} of 6 axes balanced</span> •
<span class="tooltip" data-tooltip="Ratio > 1.2 - Doing too much, burnout risk">${overall.overExhalingCount} over-exhaling</span> •
<span class="tooltip" data-tooltip="Ratio < 0.8 - Not expressing enough, stagnation risk">${overall.overInhalingCount} over-inhaling</span>
</div>
`;
// Display individual breath axes
const axesContainer = document.getElementById('breathAxes');
axesContainer.innerHTML = '';
breathAnalysis.axes.forEach(axis => {
axesContainer.appendChild(createBreathAxisCard(axis));
});
}
/**
* Create a breath axis card
*/
function createBreathAxisCard(axis) {
const card = document.createElement('div');
card.className = 'breath-axis-card';
const statusClass = axis.direction === 'balanced' ? 'balanced' :
axis.direction === 'over-exhaling' ? 'over-exhaling' : 'over-inhaling';
const ratioColor = axis.direction === 'balanced' ? '#00ff66' :
axis.direction === 'over-exhaling' ? '#ff6666' : '#66b2ff';
card.innerHTML = `
<div class="breath-axis-header">
<div class="breath-axis-name tooltip" data-tooltip="One of 6 harmonic breath axes connecting opposite dodecahedron faces">${axis.emoji} ${axis.axis}</div>
</div>
<div class="breath-axis-story">${axis.story}</div>
<div class="breath-axis-energies">
<div class="breath-energy">
<div class="breath-energy-label tooltip" data-tooltip="Reception / Inhale: Being, receiving, gathering energy">← Reception (Inhale)</div>
<div class="breath-energy-value">${(axis.receptionEnergy * 100).toFixed(1)}%</div>
</div>
<div class="breath-arrow">⟷</div>
<div class="breath-energy">
<div class="breath-energy-label tooltip" data-tooltip="Projection / Exhale: Doing, expressing, releasing energy">Projection (Exhale) →</div>
<div class="breath-energy-value">${(axis.projectionEnergy * 100).toFixed(1)}%</div>
</div>
</div>
<div class="breath-ratio-container">
<div class="breath-ratio-label">Breath Ratio</div>
<div class="breath-ratio-value tooltip" style="color: ${ratioColor}"
data-tooltip="Projection / Reception ratio - Balanced: 0.8-1.2 | > 1.2: Over-exhaling | < 0.8: Over-inhaling">
${axis.breathRatio.toFixed(2)}
</div>
<div class="breath-status-badge breath-status-${statusClass}">
${axis.direction.replace('-', ' ').toUpperCase()}
${axis.severity !== 'none' ? ' • ' + axis.severity.toUpperCase() : ''}
</div>
</div>
<div class="breath-recommendation">
<div class="breath-recommendation-label">💡 Recommendation</div>
<div>${axis.recommendation}</div>
</div>
`;
return card;
}
/**
* Get color based on breath health — φ-derived thresholds
* Excellent ≥ ψ₄ (0.854), Good ≥ φ⁻¹ (0.618), Concerning ≥ φ⁻² (0.382)
*/
function getBreathHealthColor(breathHealth) {
const PH = window.PhiHarmonics || {};
const PHI = PH.PHI || 1.618033988749895;
const PSI_4 = PH.PSI_4 || (1 - Math.pow(PHI, -4)); // 0.854
const PHI_1 = PH.PHI_1 || (1 / PHI); // 0.618
const PHI_2 = PH.PHI_2 || (1 / (PHI * PHI)); // 0.382
if (breathHealth >= PSI_4) return '#00ff66';
if (breathHealth >= PHI_1) return '#ffff00';
if (breathHealth >= PHI_2) return '#ff9900';
return '#ff6666';
}
/**
* Display Spectral Analysis
*/
function displaySpectralAnalysis() {
const analysis = window.Quannex.getSpectralAnalysis();
const section = document.getElementById('spectralSection');
if (!analysis) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
const container = document.getElementById('spectralContent');
// Format dissonance
const dissonance = analysis.diagnostics.dissonanceIndex;
const dissonanceColor = dissonance.percentage < 10 ? '#00ff66' : dissonance.percentage < 25 ? '#ffff00' : '#ff6666';
container.innerHTML = `
<!-- Dominant Mode -->
<div class="spectral-card">
<div class="spectral-label">Dominant Pattern</div>
<div class="spectral-value-large" style="font-size: 24px; color: #e0ccff;">
${analysis.summary.pattern}
</div>
<div style="font-size: 13px; opacity: 0.8; margin-top: 5px;">
Mode ${analysis.dominantMode.mode} (λ = ${analysis.dominantMode.eigenvalue})
</div>
<div style="font-size: 12px; opacity: 0.6; margin-top: 5px;">
${analysis.dominantMode.interpretation}
</div>
</div>
<!-- System Dissonance -->
<div class="spectral-card">
<div class="spectral-label">Dissonance Index</div>
<div class="spectral-value-large" style="color: ${dissonanceColor}">
${dissonance.percentage.toFixed(1)}%
</div>
<div class="spectral-bar-bg">
<div class="spectral-bar-fill" style="width: ${Math.min(dissonance.percentage, 100)}%; background: ${dissonanceColor}"></div>
</div>
<div style="font-size: 12px; margin-top: 8px;">
${dissonance.interpretation}
</div>
</div>
<!-- Strategic Recommendation -->
<div class="spectral-card" style="grid-column: 1 / -1;">
<div class="spectral-label">✨ Strategic Harmonic Correction</div>
<div style="font-size: 16px; line-height: 1.6; margin-top: 12px; color: #fff;">
${analysis.summary.recommendation}
</div>
</div>
`;
Logger.info('Index', '🎵 Displayed spectral analysis');
}
// Track currently loaded company to prevent double-loading
let currentLoadedCompanyId = null;
/**
* Listen for company data from parent window (when embedded in iframe)
*/
window.addEventListener('message', async (event) => {
// Security: verify origin if needed
// if (event.origin !== 'expected-origin') return;
const { type, companyId, companyData } = event.data;
if (type === 'LOAD_COMPANY') {
Logger.info('Index', `📨 Received company load request from parent: ${companyId}`);
// Check if this company is already loaded
if (currentLoadedCompanyId === companyId) {
Logger.info('Index', `ℹ️ Company "${companyId}" is already loaded, skipping duplicate load`);
return;
}
try {
// Show loading
document.getElementById('loading').style.display = 'flex';
document.getElementById('dashboard').style.display = 'none';
document.getElementById('breathSection').style.display = 'none';
// Load the specified company
if (companyId && window.CompanyLoader) {
const company = await window.CompanyLoader.loadCompany(companyId);
const state = await window.Quannex.initWithCompany(company);
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
// Display data
displayState(state);
// Mark as loaded
currentLoadedCompanyId = companyId;
Logger.info('Index', `✅ Loaded company from parent: ${company.name}`);
} else if (companyData) {
// Use provided company data directly
const state = await window.Quannex.initWithCompany(companyData);
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
displayState(state);
// Mark as loaded (use ID from data if available)
currentLoadedCompanyId = companyData.id || 'custom';
Logger.info('Index', `✅ Loaded company data from parent`);
} else {
Logger.warn('Index', '⚠️ CompanyLoader not available');
}
} catch (error) {
Logger.error('Index', '❌ Failed to load company from parent:', error);
}
}
});
/**
* Check if running in iframe
*/
function isInIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
/**
* Initialize based on context
*/
async function init() {
if (isInIframe()) {
Logger.info('Index', '📺 Running in iframe - checking for company selection...');
// Check sessionStorage for company ID (fallback mechanism)
const selectedCompanyId = sessionStorage.getItem('selectedCompanyId');
if (selectedCompanyId) {
Logger.info('Index', `💾 Found company ID in sessionStorage: ${selectedCompanyId}`);
// Check if this is custom data from the orchestrator
const customDataJson = sessionStorage.getItem('customCompanyData');
if (selectedCompanyId === 'custom' && customDataJson) {
try {
Logger.info('Index', `🎨 Loading CUSTOM data from orchestrator`);
const customData = JSON.parse(customDataJson);
// Transform custom data to company format
const company = {
id: 'custom',
name: customData.name || 'Custom Analysis',
description: customData.description || 'User-generated data',
kpis: customData.kpis || []
};
Logger.info('Index', `📊 Custom company has ${company.kpis.length} KPIs`);
// Initialize Quannex with custom data
const state = await window.Quannex.initWithCompany(company);
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
// Display data
displayState(state);
// Force breath analysis refresh after a brief delay (ensure breath analyzer is loaded)
setTimeout(() => {
Logger.info('Index', '🔄 Force refreshing breath analysis for custom data...');
displayBreathAnalysis();
}, 300);
// Mark as loaded
currentLoadedCompanyId = 'custom';
Logger.info('Index', `✅ Successfully loaded custom data with ${company.kpis.length} KPIs`);
} catch (error) {
Logger.error('Index', '❌ Failed to load custom data:', error);
showWaitingMessage();
}
} else {
// Regular company data - wait for CompanyLoader
let attempts = 0;
const maxAttempts = 10;
while (!window.CompanyLoader && attempts < maxAttempts) {
Logger.info('Index', `⏳ Waiting for CompanyLoader... (attempt ${attempts + 1}/${maxAttempts})`);
await new Promise(resolve => setTimeout(resolve, 200));
attempts++;
}
if (window.CompanyLoader) {
try {
Logger.info('Index', `🔄 Loading company from sessionStorage: ${selectedCompanyId}`);
const company = await window.CompanyLoader.loadCompany(selectedCompanyId);
const state = await window.Quannex.initWithCompany(company);
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
// Display data
displayState(state);
// Mark as loaded to prevent duplicate loading from postMessage
currentLoadedCompanyId = selectedCompanyId;
Logger.info('Index', `✅ Successfully loaded ${company.name} from sessionStorage`);
} catch (error) {
Logger.error('Index', '❌ Failed to load from sessionStorage:', error);
showWaitingMessage();
}
} else {
Logger.warn('Index', '⚠️ CompanyLoader not available after waiting');
showWaitingMessage();
}
}
} else {
Logger.info('Index', '📭 No company ID in sessionStorage, waiting for postMessage...');
showWaitingMessage();
}
} else {
// Running standalone - check for custom data first
const selectedCompanyId = sessionStorage.getItem('selectedCompanyId');
const customDataJson = sessionStorage.getItem('customCompanyData');
if (selectedCompanyId === 'custom' && customDataJson) {
Logger.info('Index', '🎨 Standalone mode - found custom data in sessionStorage!');
try {
const customData = JSON.parse(customDataJson);
// Transform custom data to company format
const company = {
id: 'custom',
name: customData.name || 'Custom Analysis',
description: customData.description || 'User-generated data',
kpis: customData.kpis || []
};
Logger.info('Index', `📊 Loading custom company with ${company.kpis.length} KPIs`);
// Initialize Quannex with custom data
const state = await window.Quannex.initWithCompany(company);
// Hide loading, show dashboard
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'grid';
document.getElementById('controls').style.display = 'block';
// Hide company selector (since we're showing custom data)
document.getElementById('companySelector').style.display = 'none';
// Display data
displayState(state);
// Force breath analysis refresh
setTimeout(() => {
Logger.info('Index', '🔄 Force refreshing breath analysis for custom data...');
displayBreathAnalysis();
}, 300);
Logger.info('Index', `✅ Successfully loaded custom data in standalone mode`);
} catch (error) {
Logger.error('Index', '❌ Failed to load custom data:', error);
// Fall back to default
await initDashboard();
}
} else {
Logger.info('Index', '🖥️ Running standalone - auto-loading default company...');
// Running standalone, load default company
await initDashboard();
}
}
}
/**
* Show waiting message in loading screen
*/
function showWaitingMessage() {
document.getElementById('loading').innerHTML = `
<div class="spinner"></div>
<div>Waiting for company selection...</div>
`;
}
// ============================================
// DATA INTEGRITY: Face Quality Badges
// ============================================
/**
* Initialize Face Quality Badge system
*/
function initFaceQualityBadges() {
if (window.FaceQualityBadge) {
window.FaceQualityBadge.init();
console.log('🏷️ FaceQualityBadge initialized');
// Listen for quality updates
document.addEventListener('quannex:face-quality-updated', updateFaceQualityDisplay);
} else {
console.log('⏳ FaceQualityBadge not loaded yet');
}
}
/**
* Update face quality display in header
*/
function updateFaceQualityDisplay(event) {
const headerContainer = document.getElementById('dataIntegrityHeader');
const summaryContainer = document.getElementById('faceQualitySummary');
if (!headerContainer || !summaryContainer) return;
const summary = event ? event.detail.summary : window.FaceQualityBadge.getSummary();
// Show header if there are any issues
if (summary.warning > 0 || summary.critical > 0) {
headerContainer.style.display = 'block';
summaryContainer.innerHTML = window.FaceQualityBadge.getSummaryHTML();
console.log('🏷️ Face quality: ', summary);
} else {
// All healthy - optionally show or hide
headerContainer.style.display = 'block';
summaryContainer.innerHTML = window.FaceQualityBadge.getSummaryHTML();
}
}
/**
* Manually trigger face quality update (after data load)
* Shows header even if DataValidator isn't available (all healthy state)
*/
function refreshFaceQuality() {
if (window.FaceQualityBadge) {
// Ensure FaceQualityBadge is initialized (idempotent)
window.FaceQualityBadge.init();
if (window.DataValidator) {
// DataValidator available - get real corruption report
const report = window.DataValidator.getCorruptionReport();
window.FaceQualityBadge.updateFromReport(report);
} else {
// No DataValidator - show all-healthy state directly
updateFaceQualityDisplay(null);
}
}
}
// Initialize when page loads
window.addEventListener('load', () => {
init();
// Init badges after a short delay to ensure modules are loaded
setTimeout(initFaceQualityBadges, 500);
});
</script>
</body>
</html>