/***************************************************************
   ARCHETYPE COMPATIBILITY & SHADOW WORK
****************************************************************/
const ARCHETYPE_COMPATIBILITY = {
  'Visionary': {
    high: ['Builder', 'Explorer', 'Alchemist'],
    med: ['Sage', 'Leader', 'Mystic'],
    low: ['Guardian', 'Nurturer'],
    high_desc: 'Builder grounds your vision. Explorer expands it. Alchemist transforms it into reality.',
    med_desc: 'Sage adds wisdom. Leader provides direction. Mystic deepens spiritual context.',
    low_desc: 'Guardian resists change you need. Nurturer wants present focus vs your future orientation.'
  },
  'Builder': {
    high: ['Visionary', 'Explorer', 'Artist'],
    med: ['Sage', 'Leader', 'Alchemist'],
    low: ['Rebel', 'Mystic'],
    high_desc: 'Visionary provides the vision you ground. Explorer expands what you stabilize. Artist brings beauty to your structures.',
    med_desc: 'Sage offers wisdom for your plans. Leader shares your drive for results. Alchemist transforms your materials.',
    low_desc: 'Rebel disrupts your order. Mystic resists concrete thinking. Both challenge your core system.'
  },
  'Explorer': {
    high: ['Visionary', 'Sage', 'Seeker'],
    med: ['Artist', 'Alchemist', 'Healer'],
    low: ['Guardian', 'Builder'],
    high_desc: 'Visionary gives direction to your wandering. Sage helps you synthesize discoveries. Seeker shares the quest.',
    med_desc: 'Artist documents your journey. Alchemist transforms what you find. Healer supports your process.',
    low_desc: 'Guardian wants you to stay. Builder wants structure. Both limit your movement.'
  },
  'Sage': {
    high: ['Explorer', 'Seeker', 'Mystic'],
    med: ['Builder', 'Leader', 'Healer'],
    low: ['Rebel', 'Artist'],
    high_desc: 'Explorer brings you data. Seeker asks the questions. Mystic shares your depth.',
    med_desc: 'Builder applies your wisdom. Leader implements it. Healer transmits it compassionately.',
    low_desc: 'Rebel disrupts your contemplation. Artist values feeling over thinking. Both resist pure analysis.'
  },
  'Nurturer': {
    high: ['Healer', 'Guardian', 'Artist'],
    med: ['Builder', 'Sage', 'Seeker'],
    low: ['Rebel', 'Leader'],
    high_desc: 'Healer shares your restorative mission. Guardian protects what you tend. Artist values emotional depth.',
    med_desc: 'Builder provides structure for care. Sage adds understanding. Seeker needs your support.',
    low_desc: 'Rebel disrupts your container. Leader prioritizes goals over feelings. Both resist your pace.'
  },
  'Rebel': {
    high: ['Alchemist', 'Artist', 'Explorer'],
    med: ['Visionary', 'Leader', 'Mystic'],
    low: ['Builder', 'Guardian'],
    high_desc: 'Alchemist transforms what you break. Artist channels your disruption. Explorer needs your courage.',
    med_desc: 'Visionary directs your rebellion. Leader harnesses your energy. Mystic dissolves what you fight.',
    low_desc: 'Builder wants order you destroy. Guardian protects what you challenge. Direct opposition.'
  },
  'Leader': {
    high: ['Builder', 'Visionary', 'Alchemist'],
    med: ['Sage', 'Explorer', 'Rebel'],
    low: ['Mystic', 'Seeker'],
    high_desc: 'Builder executes your vision. Visionary provides direction. Alchemist transforms your strategy.',
    med_desc: 'Sage advises you. Explorer scouts. Rebel pushes boundaries you set.',
    low_desc: 'Mystic resists your authority. Seeker questions your certainty. Both undermine command.'
  },
  'Artist': {
    high: ['Nurturer', 'Rebel', 'Mystic'],
    med: ['Visionary', 'Explorer', 'Healer'],
    low: ['Builder', 'Leader'],
    high_desc: 'Nurturer supports your process. Rebel shares your wild expression. Mystic understands your depths.',
    med_desc: 'Visionary inspires you. Explorer expands your palette. Healer helps you transmit beauty.',
    low_desc: 'Builder wants function over beauty. Leader demands results. Both limit creative chaos.'
  },
  'Alchemist': {
    high: ['Rebel', 'Mystic', 'Healer'],
    med: ['Builder', 'Leader', 'Visionary'],
    low: ['Guardian', 'Sage'],
    high_desc: 'Rebel breaks what you transmute. Mystic shares your depth. Healer applies your transformation.',
    med_desc: 'Builder structures your process. Leader directs your power. Visionary sees your potential.',
    low_desc: 'Guardian resists change you create. Sage overthinks your intuitive process. Friction points.'
  },
  'Guardian': {
    high: ['Nurturer', 'Builder', 'Healer'],
    med: ['Sage', 'Leader', 'Artist'],
    low: ['Rebel', 'Explorer'],
    high_desc: 'Nurturer shares your protective mission. Builder creates what you guard. Healer tends what you hold.',
    med_desc: 'Sage archives what you preserve. Leader respects your boundaries. Artist needs your containment.',
    low_desc: 'Rebel disrupts your protection. Explorer resists your limits. Both threaten security.'
  },
  'Seeker': {
    high: ['Sage', 'Explorer', 'Mystic'],
    med: ['Visionary', 'Alchemist', 'Healer'],
    low: ['Guardian', 'Leader'],
    high_desc: 'Sage has answers. Explorer shares the journey. Mystic points to the center.',
    med_desc: 'Visionary shows possibilities. Alchemist transforms your search. Healer supports the process.',
    low_desc: 'Guardian wants you to settle. Leader demands direction. Both resist your wandering.'
  },
  'Healer': {
    high: ['Nurturer', 'Alchemist', 'Guardian'],
    med: ['Sage', 'Artist', 'Seeker'],
    low: ['Rebel', 'Leader'],
    high_desc: 'Nurturer tends alongside you. Alchemist transforms wounds. Guardian protects your work.',
    med_desc: 'Sage provides understanding. Artist expresses healing. Seeker needs your restoration.',
    low_desc: 'Rebel rejects healing care. Leader pushes through pain. Both resist your medicine.'
  },
  'Mystic': {
    high: ['Sage', 'Alchemist', 'Artist'],
    med: ['Visionary', 'Seeker', 'Healer'],
    low: ['Builder', 'Leader'],
    high_desc: 'Sage intellectually validates your knowing. Alchemist transforms with you. Artist expresses the ineffable.',
    med_desc: 'Visionary sees your visions. Seeker asks your questions. Healer applies your wisdom.',
    low_desc: 'Builder demands concrete proof. Leader wants actionable plans. Both reject formless wisdom.'
  }
};

const SHADOW_WORK = {
  'Visionary': {
    deep: 'The Visionary shadow emerges as spiritual bypassing—using future focus to avoid present pain. You may become ungrounded, abandoning practical responsibilities for "higher purpose," or manipulate others with visions they can\'t verify. The deeper pattern: using foresight as escapism. You see tomorrow to avoid today.',
    integration: 'True mastery comes when you ground your visions in present action. Your gift isn\'t escaping reality—it\'s seeing potential within it. Integration: bring your visions down. Test them. Let them change. The future you see must serve the present you occupy.'
  },
  'Builder': {
    deep: 'The Builder shadow emerges when structure becomes prison. You may control others through "stability," refuse emotional complexity because it doesn\'t fit your blueprint, or mistake rigidity for strength. The deeper pattern: using construction as armor against vulnerability. You build walls when you need bridges.',
    integration: 'True mastery comes when you recognize that the strongest foundations flex. Your gift isn\'t control—it\'s creating containers strong enough to hold change. Integration: build systems that breathe, structures that evolve, foundations that support growth rather than restrict it.'
  },
  'Explorer': {
    deep: 'The Explorer shadow is perpetual flight disguised as adventure. You may abandon commitments when they deepen, use "discovery" to avoid intimacy, or mistake restlessness for purpose. The deeper pattern: running from yourself under the banner of expansion. Every horizon is another escape.',
    integration: 'True mastery comes when you realize the deepest territory is internal. Your gift isn\'t avoiding stillness—it\'s bringing discoveries home. Integration: pause to integrate. Let some journeys complete. Your greatest exploration is learning to arrive.'
  },
  'Sage': {
    deep: 'The Sage shadow is analysis paralysis disguised as wisdom. You may intellectualize emotions to avoid feeling them, use knowledge as superiority, or retreat into abstraction when reality demands engagement. The deeper pattern: thinking about life instead of living it. Your library becomes your prison.',
    integration: 'True mastery comes when wisdom becomes embodied. Your gift isn\'t accumulating knowing—it\'s transmitting it through action. Integration: move before you\'re certain. Feel before you analyze. Let wisdom be messy, incomplete, and lived.'
  },
  'Nurturer': {
    deep: 'The Nurturer shadow is self-abandonment disguised as service. You may enable dysfunction to feel needed, absorb others\' pain without boundaries, or use caretaking to control. The deeper pattern: giving to avoid receiving. You empty yourself to avoid being filled.',
    integration: 'True mastery comes when you nurture yourself with the same devotion you offer others. Your gift isn\'t martyrdom—it\'s creating space where all beings (including you) can grow. Integration: receive. Rest. Let others tend you without guilt.'
  },
  'Rebel': {
    deep: 'The Rebel shadow is destruction without creation. You may oppose for opposition\'s sake, use rebellion to avoid responsibility, or mistake chaos for freedom. The deeper pattern: fighting the old because building the new terrifies you. Your revolution has no blueprint.',
    integration: 'True mastery comes when disruption serves emergence. Your gift isn\'t destroying—it\'s clearing space for what wants to be born. Integration: after you break it, build something. Your rebellion must midwife the new world it fights for.'
  },
  'Leader': {
    deep: 'The Leader shadow is domination disguised as direction. You may control others to avoid your own vulnerability, mistake authority for worth, or demand loyalty while offering none. The deeper pattern: leading to avoid following anyone, including your own heart.',
    integration: 'True mastery comes when you lead from surrender, not control. Your gift isn\'t power over—it\'s power with. Integration: follow sometimes. Serve those you lead. Let authority be earned through presence, not position.'
  },
  'Artist': {
    deep: 'The Artist shadow is performance replacing authenticity. You may create for validation rather than expression, use beauty to hide pain, or mistake aesthetic for truth. The deeper pattern: performing your life instead of living it. Even your vulnerability is curated.',
    integration: 'True mastery comes when creation serves truth over applause. Your gift isn\'t making yourself palatable—it\'s revealing what\'s real. Integration: create ugly things. Make art no one wants. Let expression be medicine, not theater.'
  },
  'Alchemist': {
    deep: 'The Alchemist shadow is perpetual processing without completion. You may retraumatize yourself seeking transformation, mistake intensity for depth, or use "inner work" to avoid outer action. The deeper pattern: transmuting to avoid arriving. The process becomes the prison.',
    integration: 'True mastery comes when transformation serves life, not itself. Your gift isn\'t endless burning—it\'s completing the cycle. Integration: finish something. Let gold be gold. Not everything needs transmutation.'
  },
  'Guardian': {
    deep: 'The Guardian shadow is preservation of what should die. You may protect dysfunction because it\'s familiar, use safety to control, or mistake stagnation for stability. The deeper pattern: guarding the past while calling it the future. Your fortress becomes your tomb.',
    integration: 'True mastery comes when protection serves life, not fear. Your gift isn\'t keeping everything—it\'s discerning what deserves preservation. Integration: let some things end. Guard growth, not graves. Protect becoming, not being.'
  },
  'Seeker': {
    deep: 'The Seeker shadow is using the quest to avoid finding. You may chase meaning to evade responsibility, mistake searching for purpose, or use "not knowing yet" to avoid commitment. The deeper pattern: seeking as procrastination. The answer terrifies you.',
    integration: 'True mastery comes when you realize you\'ve always been home. Your gift isn\'t the search—it\'s recognizing what you find. Integration: stop sometimes. Declare an answer. Let seeking complete in arrival, even temporary.'
  },
  'Healer': {
    deep: 'The Healer shadow is fixing others to avoid your own wounds. You may enable suffering to stay needed, absorb trauma without clearing it, or use healing as superiority. The deeper pattern: treating others\' pain to numb your own. Your medicine becomes your disease.',
    integration: 'True mastery comes when you heal yourself first. Your gift isn\'t rescuing—it\'s witnessing transformation. Integration: let people hurt without fixing them. Heal your own wounds. Your clearest medicine flows from your own wholeness.'
  },
  'Mystic': {
    deep: 'The Mystic shadow is spiritual bypassing disguised as transcendence. You may use "oneness" to avoid boundaries, dismiss material reality as illusion, or escape responsibility through detachment. The deeper pattern: ascending to avoid descending. The formless becomes another escape.',
    integration: 'True mastery comes when transcendence serves embodiment. Your gift isn\'t leaving—it\'s bringing heaven down. Integration: get dirty. Handle money. Feel your body. The infinite must serve the finite or it\'s just avoidance.'
  }
};

/***************************************************************
   TURTLE CALENDAR FUNCTIONS
****************************************************************/
function getTurtleDay(dateObj) {
  const doy = Math.floor((dateObj - new Date(dateObj.getFullYear(), 0, 0)) / 86400000);
  return ((doy - 1) % 364) + 1;
}

function getTHDPhase(turtleDay) {
  if (turtleDay <= 121) return 3;
  if (turtleDay <= 242) return 6;
  return 9;
}

function getScalarModulator(turtleDay) {
  const mod = (turtleDay - 1) % 3;
  if (mod === 0) return 'Action';
  if (mod === 1) return 'Reflection';
  return 'Restoration';
}

function getArchetypeFromTurtleDay(turtleDay) {
  const idx = Math.floor((turtleDay - 1) / 28);
  const names = Object.keys(ARCHETYPES);
  return names[idx > 12 ? 12 : idx];
}

function calculateNumerology(fullName) {
  const name = clean(fullName).toUpperCase().replace(/\s/g, '');
  const vowels = 'AEIOU';
  let exprSum = 0, soulSum = 0;
  
  for (let char of name) {
    if (char >= 'A' && char <= 'Z') {
      const val = ((char.charCodeAt(0) - 64) % 9) || 9;
      exprSum += val;
      if (vowels.includes(char)) soulSum += val;
    }
  }
  
  function reduce(n) {
    while (n > 9 && ![11, 22, 33].includes(n)) {
      n = String(n).split('').reduce((a, b) => a + parseInt(b), 0);
    }
    return n;
  }
  
  return { expr: reduce(exprSum), soul: reduce(soulSum) };
}

function calculateLifePath(dateStr) {
  const digits = dateStr.replace(/\D/g, '');
  let sum = 0;
  for (let d of digits) sum += parseInt(d);
  
  while (sum > 9 && ![11, 22, 33].includes(sum)) {
    sum = String(sum).split('').reduce((a, b) => a + parseInt(b), 0);
  }
  return sum;
}

function calculateHarmonicId(turtleDay, thdPhase, scalarMod) {
  const modMap = { 'Action': 0, 'Reflection': 1, 'Restoration': 2 };
  const phaseMap = { 3: 0, 6: 1, 9: 2 };
  
  const modIdx = modMap[scalarMod] || 0;
  const phaseIdx = phaseMap[thdPhase] || 0;
  
  return ((turtleDay - 1) * 9) + (phaseIdx * 3) + modIdx + 1;
}

function generateSoulName(hashHex) {
  const cons = ['D','K','L','M','N','R','S','SH','T','TH','V','Z'];
  const vows = ['a','ay','e','ee','i','o','oh','u'];
  
  let syls = [];
  let breakdown = [];
  let meanings = [];
  
  for (let i = 0; i < 4; i++) {
    const cIdx = parseInt(hashHex.substring(i*2, i*2+2), 16) % 12;
    const vIdx = parseInt(hashHex.substring(i*2+2, i*2+4), 16) % 8;
    
    const c = cons[cIdx];
    const v = vows[vIdx];
    const syl = c + v;
    const sylCap = syl.charAt(0).toUpperCase() + syl.slice(1);
    
    syls.push(sylCap);
    
    const cMeaning = PHONEME_MAP[c] || 'Structure';
    const vMeaning = PHONEME_MAP[v] || 'Flow';
    
    breakdown.push(`<strong>${sylCap}</strong>: ${c} (${cMeaning}) + ${v} (${vMeaning})`);
    meanings.push(cMeaning);
  }
  
  return {
    name: syls.join(''),
    breakdown: breakdown,
    summary: `A vibrational signature defined by <strong>${meanings[0]}</strong> and <strong>${meanings[1]}</strong>, anchored by <strong>${meanings[2]}</strong> and expressing through <strong>${meanings[3]}</strong>.`
  };
}

/***************************************************************
   MAIN PROFILE GENERATOR
****************************************************************/
window.generatePEP = function(name, birthDate, place, country, time, zone) {
  try {
    if (!name || !birthDate || !place || !country) {
      return { error: 'Please complete all required fields: Name, Birth Date, Place, Country' };
    }
    
    const dt = new Date(birthDate);
    if (isNaN(dt.getTime())) {
      return { error: 'Invalid date format. Please use YYYY-MM-DD.' };
    }
    
    const cName = clean(name);
    const cPlace = clean(place);
    const cCountry = clean(country);
    const cDate = birthDate;
    const cTime = time ? time.trim() : '';  // Don't clean time - preserve colon for parsing
    const cZone = zone ? zone.trim().toUpperCase() : '';  // Just trim and uppercase zone
    
    // Canonical location format matching Turtle Calendar
    const canonical = [cPlace, cCountry].filter(x => x).join(', ');
    
    // Complete seed includes all birth data for uniqueness
    // Format: name | canonical location | date | time | zone
    const seed = `${cName} | ${canonical} | ${cDate} | ${cTime} | ${cZone}`;
    const hashHex = sha256(seed);
    const hashBigInt = BigInt('0x' + hashHex);
    const cnid = getBase58(Number(hashBigInt % BigInt(2**53)));
    
    const soulHash = sha256(hashHex + 'soul');
    const soulName = generateSoulName(soulHash);
    
    const turtleDay = getTurtleDay(dt);
    const thdPhase = getTHDPhase(turtleDay);
    const scalarMod = getScalarModulator(turtleDay);
    const archetypeName = getArchetypeFromTurtleDay(turtleDay);
    const archetype = ARCHETYPES[archetypeName];
    
    const lifePath = calculateLifePath(birthDate);
    const { expr, soul } = calculateNumerology(name);
    
    const lpData = NUMEROLOGY[lifePath] || { title: String(lifePath), desc: '' };
    const exData = NUMEROLOGY[expr] || { title: String(expr), desc: '' };
    const suData = NUMEROLOGY[soul] || { title: String(soul), desc: '' };
    
    const harmonicId = calculateHarmonicId(turtleDay, thdPhase, scalarMod);
    
    const thdData = THD_PHASES[thdPhase];
    const scalarData = SCALAR_MODULATORS[scalarMod];
    
    // Hour Quadrant - Birth Time Coherence Modulation
    const hourQuadrantKey = cTime ? window.getHourQuadrant(cTime) : null;
    const hourQuadrantData = hourQuadrantKey ? window.HOUR_QUADRANTS[hourQuadrantKey] : null;
    
    return {
      // Identity
      cnid: cnid,
      harmonicId: harmonicId,
      seedHash: hashHex,
      
      // Birth Data Echo (for verification)
      birthName: cName,
      birthDate: cDate,
      birthLocation: canonical,
      birthTime: cTime || null,
      birthZone: cZone || null,
      
      // Soul Name
      soulName: soulName.name,
      soulBreakdown: soulName.breakdown,
      soulSummary: soulName.summary,
      
      // Turtle Calendar
      turtleDay: turtleDay,
      
      // THD Phase
      thdPhase: thdPhase,
      thdData: thdData,
      
      // Scalar Modulator
      scalarMod: scalarMod,
      scalarData: scalarData,
      
      // Archetype
      archetypeName: archetypeName,
      archetype: archetype,
      
      // Hour Quadrant (Birth Time Modulation)
      hourQuadrant: hourQuadrantKey,
      hourQuadrantData: hourQuadrantData,
      
      // Numerology
      lifePath: lifePath,
      lpData: lpData,
      expr: expr,
      exData: exData,
      soul: soul,
      suData: suData
    };
    
  } catch (err) {
    console.error('PEP Generation Error:', err);
    return { error: 'An unexpected error occurred during profile generation.' };
  }
};

console.log('PEP Engine Core Functions Loaded');
