/***************************************************************
   INTEGRATION HELPER FUNCTIONS
****************************************************************/
function getArchetypePhaseIntegration(arch, phase) {
  const patterns = {
    'Builder-3': 'You build in rapid iteration cycles, not continuous construction. Your structures emerge through successive 3-beat refinement: design → test → revise. This creates "burst architecture"—fast structural insight followed by integration pauses.',
    'Builder-6': 'You build with balanced pacing: foundation → peak construction → completion. Your 6-beat rhythm allows for measured development with clear phases. Patient, thorough, sustainable construction.',
    'Builder-9': 'You build for deep mastery and completion. Your 9-beat cycle means slow, thorough transformation. Foundations laid once, correctly. Your structures are generational, not iterative.',
    'Visionary-3': 'You receive visions in rapid bursts—3-beat cycles of inspiration → integration → release. Your gift is quick pattern recognition in future timelines. Sprint visioning.',
    'Visionary-6': 'Your visions unfold in balanced waves: receive → develop → dissolve → receive. You see the future in measured phases, building probability maps over time.',
    'Visionary-9': 'Deep, slow visioning cycles. Your sight extends far into timeline architecture. You perceive futures others can\'t yet imagine. Generational foresight.'
  };
  
  return patterns[`${arch}-${phase}`] || `Your ${arch} archetype operates within a ${phase}-beat temporal rhythm, creating a unique expression of your core pattern.`;
}

function getPhaseScalarIntegration(phase, scalar) {
  const patterns = {
    '3-Restoration': 'Rapid 3-beat cycles paired with restoration need creates a burst-rest pattern. You cannot sustain continuous output. Your tempo: initiate fast → rest deeply → iterate. Honor both the speed AND the recovery.',
    '3-Action': 'Rapid 3-beat cycles with action orientation creates relentless momentum. Your tempo: initiate → stabilize → release → repeat. Risk: burnout. Strategy: build rest into the 3rd beat.',
    '3-Reflection': 'Rapid 3-beat cycles with reflective processing creates quick pattern recognition. Your tempo: observe → synthesize → apply. You iterate through understanding faster than most.',
    '6-Restoration': 'Balanced 6-beat cycles with restoration mode creates sustainable rhythm. You build → peak → rest → rebuild naturally. Your cycles include recovery by design.',
    '6-Action': 'Balanced 6-beat cycles with action drive creates sustained output. You can maintain effort through all phases without depletion. Marathon capacity.',
    '6-Reflection': 'Balanced 6-beat cycles with reflective processing creates deep integration. You process thoroughly at each phase. Quality over speed.',
    '9-Restoration': 'Deep 9-beat cycles with restoration mode creates profound integration periods. You work in long arcs with extensive rest between. Seasonal rhythm.',
    '9-Action': 'Deep 9-beat cycles with action orientation creates sustained campaigns. You can maintain effort through long transformations. Epic projects.',
    '9-Reflection': 'Deep 9-beat cycles with reflective processing creates mastery-level integration. You think in decades, not days. Wisdom accumulation.'
  };
  
  return patterns[`${phase}-${scalar}`] || `Phase ${phase} combined with ${scalar} mode creates your unique temporal operating system.`;
}

function getMasterNumberIntegration(lp, arch) {
  if (lp === 11) {
    return `Master Number 11 adds high-sensitivity spiritual reception to your ${arch} archetype. You don't just work as a ${arch.toLowerCase()}—you channel higher patterns through your work. Your ${arch} function serves collective awakening. The challenge: grounding high-frequency insight into practical application.`;
  }
  if (lp === 22) {
    return `Master Number 22 adds master manifestation capacity to your ${arch} archetype. You don't just work as a ${arch.toLowerCase()}—you materialize spiritual ideals into concrete reality. Your ${arch} function builds the new paradigm. The challenge: staying grounded while holding vast vision.`;
  }
  if (lp === 33) {
    return `Master Number 33 adds master teacher energy to your ${arch} archetype. You don't just work as a ${arch.toLowerCase()}—you uplift humanity through your work. Your ${arch} function serves collective evolution. The challenge: sustainable service without self-abandonment.`;
  }
  return '';
}

function getCognitiveFlowIntegration(profile) {
  const phase = profile.thdPhase;
  const scalar = profile.scalarMod;
  const gid = profile.archetype;
  
  return `Your cognitive architecture (${gid.gid_in} → ${gid.gid_proc} → ${gid.gid_dec} → ${gid.gid_out}) operates within your Phase ${phase} tempo and ${scalar} mode. This means you process information in ${phase}-beat cycles while ${scalar === 'Action' ? 'actively engaging' : scalar === 'Reflection' ? 'reflectively integrating' : 'receptively absorbing'}. Your thinking has rhythm.`;
}

function generateIntegration(profile) {
  const arch = profile.archetypeName;
  const phase = profile.thdPhase;
  const scalar = profile.scalarMod;
  const lp = profile.lifePath;
  
  let integration = `<div class="pep-int-title">How Your Components Interact</div>`;
  
  integration += `<div class="pep-int-block">
    <div class="pep-int-label">${arch} + Phase ${phase}</div>
    <p>${getArchetypePhaseIntegration(arch, phase)}</p>
  </div>`;
  
  integration += `<div class="pep-int-block">
    <div class="pep-int-label">Phase ${phase} + ${scalar} Mode</div>
    <p>${getPhaseScalarIntegration(phase, scalar)}</p>
  </div>`;
  
  if (lp === 11 || lp === 22 || lp === 33) {
    integration += `<div class="pep-int-block">
      <div class="pep-int-label">Master Number ${lp} Influence</div>
      <p>${getMasterNumberIntegration(lp, arch)}</p>
    </div>`;
  }
  
  integration += `<div class="pep-int-block">
    <div class="pep-int-label">Cognitive Flow Pattern</div>
    <p>${getCognitiveFlowIntegration(profile)}</p>
  </div>`;
  
  return integration;
}

/***************************************************************
   MOTION ANALYSIS GENERATOR (SECTION XIV)
****************************************************************/
function getSignatureDescription(arch, phase, scalar) {
  if (arch === 'Builder' && phase === 3 && scalar === 'Restoration') {
    return 'Your operational pattern is defined by a specific tension: you\'re wired for rapid iteration (Phase 3) but require regeneration cycles (Restoration) while building enduring systems (Builder archetype). You don\'t build continuously—your construction happens in 3-beat cycles separated by necessary rest.';
  }
  
  return `Your ${arch} archetype operates in Phase ${phase} (${phase === 3 ? 'rapid' : phase === 6 ? 'balanced' : 'deep'} cycles) with ${scalar} energetic mode. This creates a unique operational signature that differs from both pure ${arch} types and other Phase ${phase} individuals.`;
}

function getOperationalPattern(phase, scalar) {
  if (phase === 3 && scalar === 'Restoration') {
    return '<strong>1. Initiate</strong> → Structural insight arrives quickly<br><strong>2. Stabilize</strong> → Test and refine the foundation<br><strong>3. Release</strong> → Rest and integrate before the next cycle<br><br>The Restoration constraint: Unlike Action types who can push through, you deplete. Quality output requires honoring this rhythm: sprint → rest → sprint.';
  }
  
  return `Your ${phase}-beat cycle combined with ${scalar} mode creates a ${phase === 3 ? 'rapid' : phase === 6 ? 'sustained' : 'deep'} ${scalar === 'Action' ? 'active engagement' : scalar === 'Reflection' ? 'reflective processing' : 'regenerative integration'} pattern.`;
}

function getTimingFrameworks(phase, turtleDay) {
  const daily = phase === 3 ? '3rd day' : phase === 6 ? '6th day' : '9th day';
  const weekly = phase === 3 ? 'Week 1 = initiate, Week 2 = stabilize, Week 3 = release/rest' : 
                 phase === 6 ? 'Weeks alternate: build → peak → rest → rebuild' :
                 'Extended 9-week cycles with deep integration phases';
  
  return `
    <ul class="pep-timing-list">
      <li><strong>Daily:</strong> Every ${daily} should be lower-output, higher-integration</li>
      <li><strong>Weekly:</strong> ${weekly}</li>
      <li><strong>Monthly:</strong> Day ${turtleDay} markers = return to baseline rhythm</li>
      <li><strong>Quarterly:</strong> Every 121 days = natural recalibration window</li>
    </ul>
  `;
}

function getArchetypePhaseTension(arch, phase) {
  if (arch === 'Builder' && phase === 3) {
    return 'Your archetype wants methodical construction, but your rhythm is iterative. This isn\'t a flaw—it\'s your signature. Your best systems emerge through successive refinement cycles, not linear progression. Trust the bursts.';
  }
  
  return `The ${arch} archetype typically operates in a certain way, but your Phase ${phase} rhythm modifies this. Understanding this tension is key to mastery.`;
}

function getPerformanceRisks(scalar, phase) {
  const risks = [];
  
  if (scalar === 'Restoration') {
    risks.push('<li><strong>Over-restoration</strong> without re-engagement → withdrawal, analysis paralysis</li>');
    risks.push('<li><strong>Over-initiation</strong> without rest → depletion, rigidity, diminished output quality</li>');
  }
  
  if (phase === 3) {
    risks.push('<li><strong>Ignoring the 3-beat cycle</strong> → working against your natural tempo, chronic fatigue</li>');
    risks.push('<li><strong>Forcing continuous output</strong> → quality degradation and burnout</li>');
  }
  
  if (risks.length === 0) {
    risks.push('<li><strong>Misalignment with natural rhythm</strong> → reduced efficiency and satisfaction</li>');
  }
  
  return `<ul class="pep-risk-list">${risks.join('')}</ul>`;
}

function getOptimizationStrategy(arch, phase, scalar) {
  if (arch === 'Builder' && phase === 3 && scalar === 'Restoration') {
    return 'Trust the bursts. Your architecture doesn\'t come from grinding—it comes from rapid insight → deep integration → refined iteration. When you honor this pattern, your output is both fast AND structurally sound. Your cognitive model (Structural Scanning → Linear Logic → Pragmatic Utility → Blueprinting) operates within your 3-beat tempo: scan rapidly, build in sprints, decide quickly then verify during rest, blueprints emerge through iterative refinement.';
  }
  
  return `Align your work with your natural ${phase}-beat rhythm and ${scalar} energetic mode. Your best results come from honoring your design, not fighting it.`;
}

function generateMotionAnalysis(profile) {
  const arch = profile.archetypeName;
  const phase = profile.thdPhase;
  const scalar = profile.scalarMod;
  
  let html = `
    <div class="pep-motion-title">Phase ${phase} + ${scalar} + ${arch} = Your Harmonic Signature</div>
    
    <div class="pep-motion-block">
      <p>${getSignatureDescription(arch, phase, scalar)}</p>
    </div>
    
    <div class="pep-motion-section">
      <div class="pep-motion-label">Operational Pattern</div>
      <p>${getOperationalPattern(phase, scalar)}</p>
    </div>
    
    <div class="pep-motion-section">
      <div class="pep-motion-label">Timing Frameworks</div>
      ${getTimingFrameworks(phase, profile.turtleDay)}
    </div>
    
    <div class="pep-motion-section">
      <div class="pep-motion-label">The ${arch}-Phase ${phase} Tension</div>
      <p>${getArchetypePhaseTension(arch, phase)}</p>
    </div>
    
    <div class="pep-motion-section">
      <div class="pep-motion-label">Performance Risks</div>
      ${getPerformanceRisks(scalar, phase)}
    </div>
    
    <div class="pep-motion-section">
      <div class="pep-motion-label">Optimization Strategy</div>
      <p>${getOptimizationStrategy(arch, phase, scalar)}</p>
    </div>
    
    <div class="pep-motion-footer">You're not inconsistent. You're cyclical. The difference matters.</div>
  `;
  
  return html;
}

console.log('PEP Integration & Motion Analysis Functions Loaded');
