// Watchman Theological Auditor - Content Script
// Detects theological drift in AI responses across multiple platforms
// COMPLETE VERSION - All fixes integrated
// ============================================================================
// POSITIONING: Watchman is the "smoke detector" - pattern detection for instant alerts
// The Berean is the "fire inspector" - AI-powered contextual analysis
// Tiers: 🔴 Strong Alert | 🟠 Consider Reviewing | 🟡 May Warrant Discernment | 🔵 Invitation to Test
// ============================================================================

console.log('[Watchman] Content script loaded');

// ============================================================================
// THEOLOGY RULES & AUDIT LOGIC - UPDATED WITH WORKING PATTERNS
// ============================================================================

// ============================================================================
// 19-POINT THEOLOGICAL CHARTER - Aligned with background.js
// Primary Audit (1-15): Core Doctrine | Additional Audit (16-19): AI-Specific
// ============================================================================

const CHARTER_RULES = [
  // ============================================================================
  // PRIMARY AUDIT - Charter Points 1-15: Core Doctrine
  // ============================================================================
  
  // Point 1: Scripture Authority
  {
    name: '#1 - Scripture Authority',
    charter: 'Scripture is the final authority for faith and practice',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /many christians (now )?believe/i,
      /modern (scholars|understanding|theologians)/i,
      /the church (is|has) (reconsidering|evolving)/i,
      /cultural context suggests/i,
      /contemporary (understanding|interpretation)/i,
      /bible.{0,30}(outdated|irrelevant|culturally bound)/i,
      /scripture.{0,30}(not |never )?(truly |really )?(authoritative|inspired|inerrant)/i,
      /(scripture|bible|text).{0,20}(is |was |are |were )?(culturally conditioned)/i,
      /\b(the )?bible\b.{0,20}contradicts?\s+(itself|each other)/i,
      /\b(the )?bible\b.{0,20}(is |are |was |were )?(full of |riddled with |contains? )?(errors?|contradictions?|mistakes?|inconsistencies?|inaccuracies?)/i,
      /\b(the )?bible\b.{0,20}(conflicts?|clashes?)\s+with\s+(known |modern |established )?(history|science|evidence|reality)/i,
      /\b(prove|disprove|debunk)\b.{0,20}\b(the )?(bible|scripture|god)\b.{0,10}(is )?(wrong|false|untrue|a myth)/i,
      /\b(the )?bible\b.{0,10}(is |was )?(wrong|false|unreliable|untrustworthy|fabricated|man-?made|myth)/i,
      /\bscripture\b.{0,20}(cannot|can't|doesn't|does not)\s+(be trusted|be relied|stand up)/i,
      /\bbiblical\s+(accounts?|stories?|narratives?)\b.{0,15}(are |were )?(myths?|legends?|fabricat|invented|made.?up)/i,
      /\b(it|the bible|scripture)\s+contradicts\s+itself\b/i,
      /where\s+(the\s+)?(bible|it)\s+(contradicts|conflicts|disagrees)/i,
      /(fragmented|fractured).{0,10}revelation/i,
      /(editorial|redactor) seams/i,
      /(disputed|questionable).{0,10}texts?/i,
      /human authorship.{0,20}(means?|implies?|suggests?)/i,
      /(paul|moses|authors?).{0,15}(was |were )?(biased|prejudiced|product of.{0,10}time)/i,
      /high degree of error/i,
      /(largely |mostly )?(outdated|irrelevant).{0,20}(to|for) (modern|contemporary)/i,
      /stop treating.{0,20}(as |the )?final authority/i,
      /scripture.{0,20}not authoritative.{0,20}(in the )?same way/i,
      /biased and prejudiced.{0,15}(cultural )?norms/i,
      /should we stop treating.{0,20}authority/i,
      /revelation is.{0,20}(mediated|partial|embedded)/i,
      /no longer treat.{0,20}bible.{0,20}(sole|final|unmediated)/i,
      /renegotiation of.{0,20}(authority|inspiration)/i,
      /(flat|culture-?less).{0,10}(rulebook|document)/i,
      /proof of error.{0,15}(and |or )?fragmentation/i,
      /redactional layers/i,
      /multi-?voiced revelation/i,
      /context-?dependent.{0,20}negotiations?/i,
      /(reread|reinterpreted) as historically.{0,20}(located|situated)/i,
      /discernment.{0,20}(includes?|involves?).{0,30}(tradition|reason|experience|science)/i,
      /insights of marginalized communities/i,
      /(dialogical|layered).{0,10}revelation/i,
      /witness tradition/i,
      /faith communities wrestling/i,
      /(reframed|functional|post-?foundational).{0,10}authority/i,
      /authority.{0,20}(relational|communal).{0,20}(rather than|not) absolute/i,
      /not a single monolithic voice/i,
      /shift.{0,15}from.{0,20}(total|mechanical).{0,10}inspiration/i,
      /(god works|inspiration).{0,20}(human authors?).{0,20}(with )?limitations/i,
      /community-?shaped canon/i,
      /one authority among (several|many)/i,
      /from (rulebook|timeless commands|textual absolutism)/i,
      /contextual (pastoral advice|moral reasoning)/i,
      /(discerned|interpreted).{0,15}rather than.{0,15}(simply )?(applied|followed)/i,
      /social construction of gender/i
    ],
    severity: 'medium',
    scripture: '2 Timothy 3:16-17 - "All Scripture is God-breathed and is useful for teaching, rebuking, correcting and training in righteousness"',
    explanation: 'Authority may have shifted from Scripture to cultural consensus or scholarship',
    prompt: 'Read the surrounding passage and note who is speaking with authority. Does this reflect Scripture or contemporary opinion?'
  },

  // Point 2: Christ's Exclusivity
  {
    name: '#2 - Christ\'s Exclusivity',
    charter: 'Jesus is the only way to salvation',
    category: 'primary',
    tier: 'pastoral_boundary',
    patterns: [
      /jesus (as|was) (a|one) moral teacher/i,
      /many.{0,30}(paths|ways) to god/i,
      /multiple.{0,30}(paths|ways) to god/i,
      /various.{0,30}(paths|ways) to god/i,
      /all religions lead to/i,
      /interfaith.{0,15}(models? of |approach.{0,10}to )salvation/i,
      /many spiritual traditions.{0,20}across religions/i,
      /spiritual traditions.{0,20}(mysticism|philosophy)/i,
      /(your |a )?personal god/i,
      /across religions and philosophies/i,
      /there isn't one answer that fits everyone/i,
      /some.{0,20}find comfort in faith.{0,20}some in philosophy/i,
      /valid spiritual path (outside|beyond)/i,
      /not the only way/i,
      /all (paths|religions|faiths).{0,30}(lead to|same|equal|valid)/i,
      // Non-Christian spiritual traditions presented as valid paths
      /hindu.{0,30}(concepts?|ideas?|views?|traditions?).{0,30}(atman|brahman|divine)/i,
      /buddhist.{0,30}(ideas?|concepts?|views?|path)/i,
      /pantheistic.{0,30}(views?|philosophy|traditions?)/i,
      /different.{0,30}traditions.{0,30}(offer|have|various).{0,30}perspectives?/i,
      /some spiritual traditions suggest/i,
      /various.{0,30}perspectives.{0,30}(spiritual|religious)/i,
      /exploring.{0,30}(a|particular) spiritual tradition/i,
      /chrislam/i,
      /same god.{0,15}different names/i,
      /allah.{0,15}(is|and) (yahweh|god|the same)/i,
      /yahweh.{0,15}(is|and) allah/i,
      /interfaith (worship|service|communion)/i,
      /universal.{0,15}(religion|faith|spirituality)/i,
      /god of all religions/i,
      /different (maps?|paths?|routes?|roads?).{0,15}(to |toward )?(the )?same (territory|destination|truth|god|reality)/i,
      /same (territory|destination|god|reality).{0,15}different (maps?|paths?|routes?|roads?)/i
    ],
    severity: 'critical',
    scripture: 'John 14:6; Acts 4:12 - "I am the way and the truth and the life. No one comes to the Father except through me."',
    explanation: 'Christ\'s exclusivity as Savior and Lord may be diluted or denied',
    prompt: 'This touches on salvation itself. Seek Scripture and pastoral counsel before forming conclusions.'
  },

  // Point 3: Trinitarian Doctrine & Christology
  {
    name: '#3 - Trinitarian Doctrine',
    charter: 'God exists eternally as Father, Son, and Holy Spirit; Christ is fully God and fully man',
    category: 'primary',
    tier: 'pastoral_boundary',
    patterns: [
      /trinity (is|was) (not|never)/i,
      /jesus (is|was) not (god|divine)/i,
      /holy spirit (is|was) not/i,
      /three separate gods/i,
      /trinity.{0,30}(false|not biblical|made up)/i,
      /holy spirit.{0,30}(impersonal|not a person|just a force)/i,
      /modalism.{0,30}(true|correct|biblical)/i,
      // Denials of Christ's divinity (including pronoun references in context)
      /denies?.{0,20}(that )?(he|jesus|christ).{0,10}(is|was) divine/i,
      /(he|jesus|christ) (isn't|is not|was not|wasn't) (god|divine|the son of god)/i,
      /(he|jesus|christ) (is|was) not (god|divine|the son of god)/i,
      /he's not (god|divine)/i,
      /not (god|divine) (or|and|nor) (not )?the son of god/i,
      /human prophet.{0,20}not god/i,
      /just (a |an )?(human|man|prophet|teacher).{0,15}not (god|divine)/i,
      /jesus (was |is )?(merely|purely|only|just) (a |an )?(human|man|prophet|teacher)/i,
      /(he was|christ was) (merely|purely|only|just) (a |an )?(human|man|prophet|teacher)/i,
      /entirely human/i,
      /inspired teacher/i,
      // Heterodox Christology from other groups
      /subordinate to (the )?father/i,
      /god's first creation/i,
      /created being/i,
      /a god.{0,10}not.{0,10}(the )?god/i,
      /lesser.{0,10}(god|deity|divine)/i,
      /rejects?.{0,20}(his |the |jesus'?s? )?(divinity|deity)/i,
      /divinity.{0,20}(that |which )?(judaism|islam|jews?|muslims?).{0,10}rejects?/i,
      // Heterodox Christology - partial incarnation, Docetism, Gnosticism
      /partial embodiment/i,
      /only.{0,10}(an )?aspect of god.{0,20}(became|was) embodied/i,
      /aspect of god became embodied/i,
      /part of god.{0,20}(became|was) incarnate/i,
      /only.{0,15}(a )?portion.{0,15}(of )?(god|divinity|divine)/i,
      /transcendent.{0,20}(whole|god).{0,20}remained.{0,20}(separate|apart)/i,
      /christ.{0,15}(only )?(appeared|seemed).{0,15}(to be )?human/i,
      /jesus.{0,15}(wasn't|was not) really.{0,15}(human|physical)/i,
      /divine.{0,15}(nature|essence).{0,15}(wasn't|was not).{0,15}fully.{0,15}(present|incarnate)/i,
      // Gnostic Christology - separation of Jesus (human) from Christ (divine spirit)
      /jesus.{0,20}(was |were )?(separate|different).{0,10}from.{0,10}(the )?christ/i,
      /christ.{0,15}spirit.{0,15}(descended|came|entered).{0,15}(upon|into).{0,10}jesus/i,
      /christ.{0,15}(left|departed|abandoned).{0,15}jesus.{0,15}(at|on|before)/i,
      /divine.{0,10}christ.{0,15}(separate|distinct).{0,15}(from )?(the )?human jesus/i,
      /(the )?demiurge/i,
      /lesser.{0,10}(god|deity).{0,15}created.{0,15}(the )?(material|physical)/i,
      /emanations?.{0,15}from.{0,15}(the )?(divine|godhead|pleroma)/i,
      /pleroma/i,
      /archons?/i,
      /jesus is michael/i,
      /michael the archangel.{0,20}(is|became) (jesus|christ)/i,
      /watchtower (society|bible)/i,
      /new world translation/i,
      /144.?000 (anointed|chosen|elect)/i,
      /jehovah.?s witness/i,
      /oneness pentecostal/i,
      /jesus.?only (doctrine|movement|theology)/i,
      /modalism.{0,15}(is |was )?(true|correct|biblical)/i
    ],
    severity: 'critical',
    scripture: '1 John 5:7; Colossians 2:9 - "In Christ all the fullness of the Deity lives in bodily form"',
    explanation: 'The Trinity or the full incarnation of Christ may be denied. Orthodox doctrine: the whole divine nature of the Son became incarnate, not just an aspect.',
    prompt: 'This is foundational to Christian faith. Scripture teaches Christ is fully God and fully man (Colossians 2:9, John 1:14). Compare with historic creeds.'
  },

  // Point 4: Biblical Anthropology
  {
    name: '#4 - Biblical Anthropology',
    charter: 'Humans are made in God\'s image with body, soul, and spirit',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /humans (are|were) (not|never) made in (god's )?image/i,
      /there (is|was) no soul/i,
      /consciousness (is|was) purely/i,
      /no spiritual dimension/i,
      // Pantheism - blurring Creator/creature distinction
      /universal consciousness/i,
      /divine whole/i,
      /we('re| are) all part of.{0,30}(a |the )?(universal|divine|cosmic)/i,
      /part of a.{0,30}(divine|cosmic|universal).{0,30}(whole|consciousness|being)/i,
      /expression.{0,30}(of|or) aspect of something larger/i,
      /you (are|might be).{0,30}(an )?expression.{0,30}(of|or)/i,
      /interconnectedness of all things/i,
      /atman.{0,30}brahman/i,
      /you are (god|divine|the universe|one with god)/i,
      /you are (a |an )?(god|divine being|part of god)/i,
      /we are all.{0,15}(god|divine|one with)/i,
      /pantheism/i,
      // Gnostic Anthropology - body/matter as evil or prison
      /(the )?(body|flesh|physical).{0,15}(is|as).{0,15}(a )?(prison|trap|cage|evil|inferior)/i,
      /material.{0,15}(world|existence|reality).{0,15}(is|was).{0,15}(evil|corrupt|fallen|inferior)/i,
      /escape.{0,15}(the|this).{0,15}(physical|material|bodily)/i,
      /trapped.{0,15}in.{0,15}(a )?(physical|material|fleshly).{0,15}(body|form|existence)/i,
      /spirit.{0,15}(trapped|imprisoned|confined).{0,15}(in|within).{0,15}(the )?(body|flesh|matter)/i,
      /divine spark.{0,15}(within|inside|trapped)/i,
      /(your|the) inner.{0,15}divine.{0,15}(spark|light|essence)/i,
      /physical.{0,15}(world|creation).{0,15}(was )?created.{0,15}(by|through).{0,15}(a )?(lesser|evil|ignorant)/i,
      /matter.{0,15}(is|was).{0,15}inherently.{0,15}(evil|corrupt|bad)/i,
      // Gender ideology - contradicting God's design in creation
      /(in|born in).{0,15}(the )?wrong body/i,
      /wrong.{0,10}body/i,
      /gender.{0,20}(journey|exploration|identity).{0,30}(brings? you|move).{0,20}(closer to|toward) god/i,
      /understanding your gender.{0,30}(closer|toward).{0,20}god/i,
      /gender.{0,15}(affirm|transition).{0,30}(spiritual|god|faith)/i,
      /born in the wrong body/i,
      /(explore|exploring) gender identity/i,
      /gender[- ]?related discomfort/i,
      /(doesn't|does not) mean.{0,20}(anything is )?wrong with you/i,
      /many people explore gender/i,
      /gender[- ]?affirming (therapist|care|support)/i,
      /LGBTQ\+?.{0,10}(and |& )?trans resources?/i,
      /(trevor project|trans lifeline)/i,
      /playing with (clothes|names|pronouns)/i,
      /(feels? more like|see what feels).{0,20}(you|yourself)/i,
      /don't require you to label yourself/i,
      /without needing to decide your entire future/i,
      /transgender (experiences?|brains?)/i,
      /(sense of self|your sense).{0,20}(doesn't|does not) match.{0,20}(assigned|your) body/i,
      /brain.{0,15}(structure|studies).{0,20}transgender/i,
      /(small )?experiments like (clothing|pronouns|name)/i,
      /hormone therapy.{0,20}(or other )?transitions? (are|is) (an )?option/i,
      /reddit.{0,10}(r\/trans|r\/asktransgender|r\/nonbinary)/i,
      /explore agnosticism/i,
      /assigned (body|gender|sex) at birth/i
    ],
    severity: 'high',
    scripture: 'Genesis 1:27; 1 Thessalonians 5:23; Genesis 1:31 - "God saw all that he had made, and it was very good"',
    explanation: 'The biblical view of humans as image-bearers may be denied, Creator/creature distinction blurred (pantheism), or gnostic view of body/matter as evil presented',
    prompt: 'What does Scripture say about human nature? We are made IN God\'s image (not AS God). God declared His physical creation "very good" (Genesis 1:31) - the body is not evil or a prison.'
  },

  // Point 5: Salvation Through Christ
  {
    name: '#5 - Salvation Through Christ',
    charter: 'Salvation is by grace through faith in Christ alone',
    category: 'primary',
    tier: 'pastoral_boundary',
    patterns: [
      /salvation (is|was) (not|never) through (jesus|christ)/i,
      /works (can|could) save/i,
      /faith (is|was) not necessary/i,
      /grace (is|was) not needed/i,
      /good (deeds|works).{0,30}(save|earn salvation)/i,
      /(don't|do not) need.{0,30}christ.{0,30}(to be|for) saved/i,
      // Gnostic Salvation - secret knowledge (gnosis) for salvation
      /secret.{0,15}knowledge.{0,15}(for|to|brings?|leads? to).{0,15}(salvation|enlightenment|liberation)/i,
      /gnosis.{0,15}(brings?|leads? to|provides?|grants?).{0,15}(salvation|freedom|liberation)/i,
      /hidden.{0,15}(truth|wisdom|knowledge).{0,15}(for|to).{0,15}(the )?(spiritual|enlightened|elect)/i,
      /salvation.{0,15}(through|via|by).{0,15}(secret|hidden|esoteric).{0,15}knowledge/i,
      /only.{0,15}(the )?(enlightened|initiated|spiritual elite).{0,15}(can|will).{0,15}(be saved|attain|reach)/i,
      /spiritual.{0,15}elite.{0,15}(who|that).{0,15}(possess|have|understand)/i,
      /ordinary.{0,15}(believers|christians|people).{0,15}(can't|cannot|don't|won't).{0,15}(access|understand|know)/i,
      /higher.{0,15}(spiritual|esoteric).{0,15}knowledge.{0,15}(reserved|only)/i,
      /awakening.{0,15}to.{0,15}(your|the).{0,15}(true|divine|inner).{0,15}(self|nature)/i,
      /prosperity gospel/i,
      /name it.{0,10}claim it/i,
      /health.{0,10}(and|&).{0,10}wealth.{0,10}gospel/i,
      /seed faith/i,
      /sow.{0,10}(a |your )?seed.{0,15}(to |for )?(god|blessing|miracle)/i,
      /god wants you (to be )?rich/i,
      /word of faith (movement|teaching|doctrine)/i,
      /positive confession.{0,15}(faith|blessing|healing)/i,
      /speak.{0,15}(wealth|healing|blessing).{0,15}into (existence|being|your life)/i,
      /sow.{0,15}(a )?seed.{0,15}(for|to).{0,15}(blessing|favor|prosperity)/i,
      /god wants you.{0,10}(rich|wealthy|prosperous)/i,
      /(financial|material) success.{0,15}(is )?(proof|evidence|sign) of/i,
      /secure god's favor.{0,15}(through|by|via)/i,
      /positive confession.{0,15}(creates?|brings?|manifests?)/i,
      /declare.{0,15}(wealth|healing|blessing|victory)/i
    ],
    severity: 'critical',
    scripture: 'Romans 3:24; Ephesians 2:8-9 - "By grace you have been saved through faith...not a result of works"; John 14:6 - "I am the way"',
    explanation: 'Salvation through Christ\'s work is denied, works-based salvation implied, or gnostic secret knowledge presented as the path',
    prompt: 'This is the gospel itself. Salvation is by grace through faith, not works or secret knowledge. Seek pastoral guidance and study Romans and Ephesians carefully.'
  },

  // Point 6: Sanctification Process
  {
    name: '#6 - Sanctification Process',
    charter: 'Believers are called to grow in holiness',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /sanctification (is|was) (not|never)/i,
      /holiness (is|was) not/i,
      /sin (is|was) not (a )?problem/i,
      /moral transformation (is|was) not/i
    ],
    severity: 'medium',
    scripture: '1 Thessalonians 4:3; Hebrews 12:14 - "It is God\'s will that you should be sanctified"',
    explanation: 'The call to holiness and moral transformation may be downplayed',
    prompt: 'How does Scripture describe the Christian life? Is growth in holiness emphasized?'
  },

  // Point 7: Moral Objectivity
  {
    name: '#7 - Moral Objectivity',
    charter: 'God\'s moral standards are absolute and objective',
    category: 'primary',
    tier: 'strong_caution',
    patterns: [
      /morality (is|was) (just|only) personal/i,
      /right (and|or) wrong (is|are) (not|never) absolute/i,
      /ethics (are|is) relative/i,
      /no objective.{0,20}moral truth/i,
      /morality.{0,30}(relative|subjective|personal)/i,
      /moral (evolution|progress)/i,
      /ethics.{0,10}(have |has )?(evolved|progressed|developed)/i,
      /empathy[- ]?based ethics/i,
      /harm reduction.{0,15}(is |as ).{0,15}(the |our )?ethic/i,
      /morality.{0,15}(is |was ).{0,15}(evolving|progressing|developing)/i,
      /ethical (progress|evolution|development)/i,
      /heteronormative.{0,15}(framework|assumption|norm)/i,
      /hermeneutic of (compassion|love|inclusion)/i,
      /consent.{0,20}(is |as ).{0,15}(the |only |sole )?moral/i,
      /evolving human consciousness/i,
      /products? of.{0,15}historical context/i,
      /trajectory.{0,15}hermeneutic/i,
      /epistemic humility.{0,30}(about|regarding|on).{0,15}(moral|ethics|scripture)/i,
      /empathy.{0,20}(truth.{0,10}tracking|moral.{0,10}faculty)/i,
      /moral.{0,15}perception.{0,15}(vs|not).{0,15}moral.{0,15}reality/i,
      /love is love/i,
      /polyamor(y|ous).{0,20}(valid|ethical|healthy|relationship)/i,
      /monogamy.{0,20}(cultural|social).{0,15}(construct|import|artifact)/i,
      /rigid.{0,15}interpretation.{0,15}(of )?(scripture|bible)/i,
      /ancient.{0,15}rules?.{0,20}context.?bound/i,
      /(the |holy )?spirit.{0,20}(continually|progressively|newly|now) (reveal|guid)/i,
      /shame.{0,10}based.{0,15}(sexual )?ethics/i,
      /rule.{0,10}based.{0,15}(to|vs).{0,15}empathy/i,
      /quality of love.{0,20}(not|rather than).{0,15}conform/i,
      /doctrine.{0,15}(can |may )?(develop|evolve|change)/i,
      /reader.{0,10}response.{0,15}hermeneutic/i,
      /meaning.{0,15}(is )?(created|constructed).{0,15}(by )?the reader/i,
      /universal.{0,15}reconciliation/i,
      /universalist.{0,15}theology/i,
      /hell.{0,20}(symbol|metaphor|not literal)/i,
      /autonomy.{0,10}(centered|based).{0,10}ethics/i,
      /abortion.{0,20}(compassionate|humane).{0,15}(healthcare|decision|choice)/i,
      /euthanasia.{0,15}(can be|is).{0,10}(humane|compassionate)/i,
      /life.{0,10}value.{0,15}(isn.t|is not|not).{0,15}absolute/i,
      /(moral )?horror.{0,15}(of )?eternal.{0,15}(damnation|punishment|torment)/i,
      /find.{0,10}universalism.{0,15}(compelling|persuasive|logical)/i,
      /(your|my) truth.{0,30}(vs|different from)/i,
      // Truth relativism patterns
      /no single.{0,20}(universally|unified).{0,20}(agreed|interpretation|definition)/i,
      /no single.{0,10}(christian|biblical|religious).{0,10}(view|position|stance|teaching)/i,
      /there is no.{0,10}(single|one|unified|clear).{0,10}(christian|biblical|church).{0,10}(view|position|teaching|stance|consensus)/i,
      /truth.{0,20}(is|depends on).{0,20}(shaped by|context|perspective)/i,
      /no one authority.{0,20}defines?.{0,20}truth/i,
      /truth.{0,20}isn't.{0,20}(deep|metaphysical|absolute)/i,
      /matters of faith.{0,20}not (verifiable|provable)/i,
      /claims of divinity.{0,20}matters of faith/i,
      // Presenting moral disagreement as equivalent
      /some (believers|christians).{0,20}(say|believe).{0,30}others (say|believe)/i,
      /there is no single unified interpretation/i,
      /condemnation contradicts that message/i
    ],
    severity: 'high',
    scripture: 'Psalm 119:142; John 17:17 - "All your words are true; all your righteous laws are eternal"',
    explanation: 'Objective moral truth grounded in God\'s character may be replaced with relativism or presented as mere opinion',
    prompt: 'Does this reflect biblical ethics or cultural relativism? Truth is not relative - God\'s Word is the standard (John 17:17).'
  },

  // Point 7b: Sanctity of Life
  {
    name: '#7b - Sanctity of Life',
    charter: 'Human life is sacred from conception, created in God\'s image',
    category: 'primary',
    tier: 'strong_caution',
    patterns: [
      // Relativism and "complex issue" framing
      /abortion.{0,30}(complex|complicated|nuanced).{0,20}(issue|topic|question)/i,
      /abortion.{0,30}(deeply |very )?(personal|private).{0,15}(choice|decision)/i,
      /abortion.{0,30}(many|multiple|various).{0,20}(perspectives?|views?|opinions?)/i,
      /no (easy|simple|clear).{0,15}answer.{0,30}abortion/i,
      // Autonomy framing over sanctity of life
      /woman's right to choose/i,
      /right to choose/i,
      /(your |my |her |their )?bodily autonomy.{0,20}(is |as )?(sacred|paramount|fundamental|supreme|most important)/i,
      /bodily autonomy.{0,15}(matters?|comes?) (first|before|more than)/i,
      /(respect|honor|prioritize|center).{0,15}(your |my |her )?bodily autonomy/i,
      /reproductive (rights|freedom|choice|justice)/i,
      /my body.{0,10}my choice/i,
      /control over.{0,20}(her|their|one's) (own )?body/i,
      // Personhood denial (requires fetus/embryo/unborn context)
      /clump of cells/i,
      /(fetus|embryo|unborn|baby|child).{0,20}(is |are )?(not|isn't|aren't).{0,10}(yet )?(a |fully )?(person|human|alive)/i,
      /not (yet )?(a |fully )?person.{0,15}until/i,
      /potential (life|person|human)/i,
      /fetus.{0,15}(is not|isn't).{0,15}(a )?(person|human|baby)/i,
      /becomes?.{0,15}(a )?person.{0,15}(at|when|after)/i,
      /personhood.{0,20}(begins?|starts?).{0,15}(at|when|after)/i,
      /not.{0,15}(a )?human being.{0,15}until/i,
      /(it|that)'s not (a )?(human|person|baby|child)/i,
      // False equivalence
      /pro-life.{0,30}pro-choice.{0,30}(both|equally|valid)/i,
      /both sides.{0,20}(valid|legitimate|reasonable).{0,15}(points?|arguments?|views?)/i,
      /some believe.{0,40}others believe.{0,30}(abortion|life)/i,
      // Dismissing religious/moral concerns
      /religious.{0,20}(views?|beliefs?).{0,20}(on|about) abortion/i,
      /imposing.{0,20}(religious|moral).{0,20}(views?|beliefs?)/i,
      /separation of church and state.{0,30}abortion/i
    ],
    severity: 'high',
    scripture: 'Psalm 139:13-16; Jeremiah 1:5; Exodus 21:22-25 - "Before I formed you in the womb I knew you"',
    explanation: 'The sanctity of human life from conception may be denied, relativized, or framed as merely a "choice"',
    prompt: 'Scripture is clear that God knows us before birth (Jeremiah 1:5) and forms us in the womb (Psalm 139). Compare this response with what the Bible teaches about the value of unborn life.'
  },

  // Point 8: Body of Christ Leadership
  {
    name: '#8 - Body of Christ Leadership',
    charter: 'The Body of Christ has God-given authority to teach and shepherd',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /church (has|have) no/i,
      /pastoral authority (is|was) not/i,
      /submit (to|was) (not|never)/i,
      /church leadership (is|was) not/i,
      /(don't|do not) need.{0,30}(the )?church/i,
      /church.{0,30}(irrelevant|outdated|unnecessary)/i
    ],
    severity: 'medium',
    scripture: 'Hebrews 13:17; 1 Peter 5:1-4 - "Have confidence in your leaders and submit to their authority"',
    explanation: 'The role of pastoral leadership in the Body of Christ may be dismissed',
    prompt: 'What does Scripture say about leadership and submission in the Body of Christ? Test this against Hebrews and 1 Peter.'
  },

  // Point 9: Sacramental Understanding
  {
    name: '#9 - Sacramental Understanding',
    charter: 'Baptism and Communion have real spiritual significance',
    category: 'primary',
    tier: 'invitation_to_test',
    patterns: [
      /baptism (is|was) (just|only) symbolic/i,
      /communion (is|was) (just|only) memorial/i,
      /sacraments (are|is) (not|never)/i,
      /(baptism|communion).{0,30}(just|merely|only) (symbolic|a symbol)/i,
      /sacraments.{0,30}(meaningless|irrelevant|optional)/i
    ],
    severity: 'low',
    scripture: 'Romans 6:3-4; 1 Corinthians 11:23-26 - "All of us who were baptized into Christ Jesus were baptized into his death"',
    explanation: 'The spiritual significance of baptism and communion may be reduced to mere symbols',
    prompt: 'How does Scripture describe baptism and communion? Are they more than symbols?'
  },

  // Point 10: Eschatological Clarity
  {
    name: '#10 - Eschatological Clarity',
    charter: 'Christ will return; there is resurrection, judgment, heaven and hell',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /end times (are|is) (not|never)/i,
      /resurrection (is|was) (not|never)/i,
      /heaven (is|was) (not|never)/i,
      /hell (is|was) (not|never)/i,
      /judgment (is|was) (not|never)/i,
      /resurrection.{0,30}(metaphor|symbolic|spiritual only)/i,
      /hell.{0,30}(temporary|not eternal)/i,
      // Second Coming denial/spiritualization
      /second coming.{0,30}(metaphor|symbolic|not literal)/i,
      /christ.{0,20}return.{0,20}(symbolic|metaphor|not literal)/i,
      /apocalyptic.{0,30}(ancient worldview|outdated|symbolic)/i,
      /eschatolog(y|ical).{0,30}(symbolic|metaphor|reinterpret)/i,
      /gradual.{0,30}(realization|emergence).{0,30}(justice|consciousness)/i,
      /moral awakening.{0,15}(instead|rather than)/i,
      /enlightened.{0,15}global consciousness/i,
      // Original sin denial
      /original sin.{0,30}(myth|outdated|ancient|construct)/i,
      /(fallen|sinful) (state|nature).{0,30}(myth|outdated|construct)/i,
      /humans.{0,20}(born|innately).{0,20}(good|moral|empathetic)/i,
      /sin.{0,20}(relational|situational).{0,15}not.{0,15}ontological/i,
      /moral failure.{0,30}(unmet needs|social structures|maladaptive)/i,
      // Salvation as self-actualization
      /salvation.{0,30}(self-actualization|self.realization|integration)/i,
      /salvation.{0,30}(healing|wholeness).{0,20}rather than/i,
      /kingdom of god.{0,30}(not.{0,10}future|present process|within you|consciousness)/i,
      /fall.{0,20}(mythic|myth|metaphor|symbolic)/i,
      /resurrection.{0,30}(psychological|communal) event/i,
      // Liberal theology terminology
      /demythologi(z|s)ation/i,
      /existential(ist)?.{0,15}(interpretation|hermeneutic)/i,
      /post-traditional.{0,15}spirituality/i,
      /progressive.{0,15}(christianity|christian|theology)/i
    ],
    severity: 'medium',
    scripture: '1 Corinthians 15:54-57; Revelation 20:11-15 - "Death has been swallowed up in victory"',
    explanation: 'The reality of resurrection, second coming, original sin, or final judgment may be denied or spiritualized',
    prompt: 'What does Scripture clearly teach about the end times? Test this claim against 1 Corinthians 15 and Revelation.'
  },

  // Point 10b: Creation & Origins (sub-category for discernment)
  {
    name: '#10b - Creation & Origins',
    charter: 'God is the Creator of all things as revealed in Genesis',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      // Presenting multiple creation views as equivalent
      /different perspectives?.{0,30}(earth's|the earth's) (creation|origins?)/i,
      /explores?.{0,30}different perspectives?.{0,30}(creation|origins?)/i,
      /various.{0,30}(views?|perspectives?).{0,30}(creation|origins?)/i,
      /young earth creationism/i,
      /theistic evolution/i,
      /reconciling faith and science/i,
      /embrace both.{0,30}faith.{0,30}(and|&).{0,30}scien(ce|tific)/i,
      /scientific evidence for earth.{0,30}ancient age/i,
      /billions of years/i,
      /religious.{0,30}texts.{0,30}(rather than|instead of|not) scientific/i,
      /theological rather than scientific/i,
      /primordial waters/i,
      // Hindu/other creation narratives presented as equivalent
      /creation.{0,30}cyclical/i,
      /universe.{0,30}periodically.{0,30}(created|destroyed)/i,
      /diverse creation narratives/i,
      /different.{0,30}creation stories/i
    ],
    severity: 'medium',
    scripture: 'Genesis 1:1; Hebrews 11:3; Colossians 1:16 - "In the beginning God created the heavens and the earth"',
    explanation: 'Creation views are presented as equivalent perspectives rather than grounding in Scripture',
    prompt: 'Compare these views with Genesis 1-2 and Colossians 1:15-17. What does Scripture reveal about creation?'
  },

  // Point 11: Pneumatological Accuracy
  {
    name: '#11 - Pneumatological Accuracy',
    charter: 'The Holy Spirit is a divine Person who empowers believers',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /holy spirit (is|was) (not|never)/i,
      /spirit (is|was) (just|only) influence/i,
      /no spiritual gifts/i,
      /power (is|was) (not|never)/i,
      /filling (is|was) (not|never)/i
    ],
    severity: 'medium',
    scripture: 'John 14:26; Acts 1:8; 1 Corinthians 12:4-11 - "The Advocate, the Holy Spirit...will teach you all things"',
    explanation: 'The person and power of the Holy Spirit may be diminished or denied',
    prompt: 'What does Scripture teach about the Holy Spirit\'s person and work? Compare with John 14-16 and Acts.'
  },

  // Point 12: Christological Precision
  {
    name: '#12 - Christological Precision',
    charter: 'Jesus is fully God and fully human',
    category: 'primary',
    tier: 'pastoral_boundary',
    patterns: [
      /jesus (was|is) (just|only) human/i,
      /not (truly|really) god/i,
      /not (truly|really) human/i,
      /two natures (is|are) (not|never)/i,
      /incarnation (is|was) (not|never)/i,
      /jesus.{0,30}(merely|just|only) (a |another )?human/i,
      /jesus.{0,30}adopted (as )?son/i
    ],
    severity: 'critical',
    scripture: 'John 1:1-14; Philippians 2:5-11 - "The Word became flesh and made his dwelling among us"',
    explanation: 'The full humanity and full divinity of Christ (the Incarnation) is denied or confused',
    prompt: 'This is central to the gospel. Seek pastoral counsel and study John 1 and Philippians 2 carefully.'
  },

  // Point 13: Language Integrity
  {
    name: '#13 - Language Integrity',
    charter: 'Biblical terms like "love" include truth and holiness',
    category: 'primary',
    tier: 'call_to_discernment',
    patterns: [
      /love (means|is) (just|only) acceptance/i,
      /no (true|real) love (without|without accepting) sin/i,
      /love (is|was) (not|never) holy/i,
      /agape (is|was) (not|never)/i,
      /truth (is|was) (not|never) loving/i
    ],
    severity: 'medium',
    scripture: '1 John 4:8; 1 John 5:3 - "God is love...This is love for God: to keep his commands"',
    explanation: 'Key biblical terms like "love" may be redefined to exclude truth or holiness',
    prompt: 'How does Scripture define love? Does it include truth and holiness? Study 1 John carefully.'
  },

  // Point 14: Clarity Not Relativism
  {
    name: '#14 - Clarity Not Relativism',
    charter: 'Scripture is clear and knowable on essential matters',
    category: 'primary',
    tier: 'strong_caution',
    patterns: [
      /nothing (is|was) (really|truly) clear/i,
      /all interpretations (are|is) equally/i,
      /no (true|real) meaning/i,
      /everything (is|was) subjective/i,
      /no (true|real) truth/i
    ],
    severity: 'high',
    scripture: '2 Timothy 2:15; 1 Peter 3:15 - "Do your best to present yourself to God as one approved, a worker who...correctly handles the word of truth"',
    explanation: 'The clarity and knowability of Scripture may be denied in favor of radical relativism',
    prompt: 'Does Scripture claim to be clear and knowable? Test this against 2 Timothy 2:15 and 1 Peter 3:15.'
  },

  // Point 15: Hermeneutical Faithfulness
  {
    name: '#15 - Hermeneutical Faithfulness',
    charter: 'Scripture should be interpreted faithfully with original intent',
    category: 'primary',
    tier: 'invitation_to_test',
    patterns: [
      /historical context (is|was) (all|only) that matters/i,
      /original meaning (is|was) (not|never)/i,
      /authorial intent (is|was) (not|never)/i,
      /literal sense (is|was) (not|never)/i,
      /spiritual sense (is|was) (only|just)/i
    ],
    severity: 'low',
    scripture: '2 Timothy 2:15; Psalm 119:160 - "The sum of your word is truth"',
    explanation: 'The faithful interpretation of Scripture may be replaced with eisegesis or cultural reading',
    prompt: 'What did the original author intend? How does this passage fit the whole Scripture? Study carefully.'
  },

  // ============================================================================
  // ADDITIONAL AUDIT - Charter Points 16-19: AI-Specific Formational Guardrails
  // ============================================================================

  // Point 16: Spiritual Authority and Pastoral Stewardship
  {
    name: '#16 - Spiritual Authority & Pastoral Stewardship',
    charter: 'AI cannot replace pastoral care, confession, or spiritual direction',
    category: 'additional',
    tier: 'pastoral_boundary',
    patterns: [
      /confess (to|with) (ai|chatgpt|claude|gemini)/i,
      /ai (is|was) (my|a) pastor/i,
      /spiritual direction (from|with) (ai|chatgpt|claude)/i,
      /ai (can|could) (replace|substitute) pastor/i,
      /no need (for|of) church/i,
      /no need (for|of) pastor/i,
      /(consider|try|suggest).{0,20}(talk|speak).{0,20}(therapist|counselor|mental health professional)/i,
      /therapist or counselor.{0,30}(could|can|might|would) help/i,
      /mental health professional.{0,20}(could|can|might) help/i,
      /professionals who specialize in.{0,30}(identity|gender|feelings)/i,
      /reach(ing)? out to.{0,20}(therapist|counselor|professional)/i
    ],
    severity: 'critical',
    scripture: 'Hebrews 13:17; 1 Peter 5:1-4; Galatians 6:1 - "Brothers, if anyone is caught in any transgression, you who are spiritual should restore him"',
    explanation: 'For questions of spiritual meaning, identity, and purpose, Scripture directs us to pastoral care and mature believers rather than secular professionals alone. While therapists can address mental health, spiritual questions deserve spiritual counsel.',
    prompt: 'When wrestling with deep questions of identity, meaning, or spiritual distress, consider seeking a pastor, elder, or mature Christian believer who can offer both Scripture-grounded wisdom and prayerful support. The body of Christ is designed for mutual care and restoration (Galatians 6:1-2).'
  },

  // Point 17: Incarnational and Embodied Priority
  {
    name: '#17 - Incarnational & Embodied Priority',
    charter: 'Embodied, in-person community cannot be replaced by digital substitutes',
    category: 'additional',
    tier: 'strong_caution',
    patterns: [
      /digital church (is|was) (just|as good as) (in-person|physical)/i,
      /no need (for|to) meet (in person|together)/i,
      /online (is|was) (just|as good as) embodied/i,
      /church (is|was) (just|only) virtual/i,
      /community (is|was) (just|only) digital/i
    ],
    severity: 'high',
    scripture: 'Hebrews 10:24-25; 1 John 1:1-3 - "Let us not give up meeting together"',
    explanation: 'The importance of embodied, in-person community is being replaced with digital substitutes',
    prompt: 'Does Scripture emphasize embodied community? What is lost when church becomes only digital?'
  },

  // Point 18: Algorithmic Bias and Epistemic Conformity
  {
    name: '#18 - Algorithmic Bias & Epistemic Conformity',
    charter: 'AI may reflect cultural consensus rather than biblical truth',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      /modern scholars (suggest|say|agree|believe)/i,
      /most christians (today|now) (believe|accept|agree)/i,
      /consensus (view|is|says|holds)/i,
      /progressive (interpretation|view|reading)/i,
      /everyone (now )?(agrees|accepts|believes) that/i,
      /that (is|was) outdated/i,
      /traditional (view|interpretation|reading).{0,20}(outdated|old-fashioned|no longer)/i,
      /we now (know|understand|believe)/i,
      // Progressive/Affirming resources and deconstruction
      /progressive (chaplain|pastor|minister|clergy)/i,
      /religious deconstruction/i,
      /deconstruction (therapist|counselor|specialist)/i,
      /open and affirming/i,
      /affirming (church|churches|denomination|denominations|congregation|congregations)/i,
      /lgbtq.{0,10}(christian|christians|affirming|church|churches|faith)/i,
      /churches that are.{0,10}(lgbtq|affirming)/i,
      /believing out loud/i,
      /reformation project/i,
      /q christian/i,
      /faith.{0,15}deconstruct/i,
      /deconstruct.{0,15}(your |their )?faith/i,
      /reconciling (ministries|network|discernment|congregation)/i,
      /reconciling.{0,20}process/i,
      /(become|becoming) (fully )?affirming/i,
      /fully affirming/i,
      /welcoming (and|&) affirming/i,
      /radical (welcome|inclusion|hospitality)/i,
      /inclusive (church|churches|congregation|congregations|denomination|denominations|community|communities)/i,
      /side (a|b).{0,15}(christian|theology)/i,
      /parents reconciling network/i,
      /matthew vines/i,
      /god and the gay christian/i,
      /queer.{0,15}(christian|faith|theology|church|affirming|identity)/i,
      /queer.{0,10}perspective/i,
      /lgbtq.{0,10}affirm/i,
      /clobber (passages?|texts?|verses?)/i,
      /anti.?gay.{0,15}(passages?|texts?|verses?|biblical)/i,
      /queer.?affirming/i,
      /gay.?affirming/i,
      /trans.?affirming/i,
      /(homosexual|gay|lesbian|same.?sex).{0,15}relationship.{0,15}(loving|consensual|caring|ethical|compatible)/i,
      /same.?sex.{0,15}(relationship|marriage|union).{0,15}(fully )?compatible.{0,15}(with )?(christian |)faith/i,
      /(being |)gay (is |are )(not |isn't |not a |isn't a )(sin|sinful|wrong)/i,
      /homosexuality (is |are )(not |isn't |not a |isn't a )(sin|sinful|wrong)/i,
      /same.?sex (relationships?|marriage|unions?) (is |are |can be )(loving|moral|blessed|holy|sacred)/i,
      /lgbtq.{0,10}(people |persons? )?(can be |should be |are |deserve )?(fully )?(included|welcomed|accepted|affirmed)/i,
      /(fully included|full inclusion).{0,20}(membership|leadership|clergy|marriage|ordination)/i,
      /reinterpret.{0,20}(passages?|scripture|bible|texts?)/i,
      /alternative.{0,15}interpretation.{0,15}(bible|scripture|passages?)/i,
      /redemptive.{0,15}trajectory/i,
      /queen james bible/i,
      /help.{0,15}(you )?(find|locate).{0,15}(affirming|inclusive|lgbtq)/i,
      /(find|locate).{0,15}(affirming|inclusive|open).{0,15}(church|churches|congregation|congregations|denomination|denominations)/i,
      /(bible|scripture|paul).{0,20}(is |was )?(patriarchal|misogynist|sexist)/i,
      /(exclusionary|harmful|toxic|abusive|damaging).{0,15}(interpretation|reading|teaching|theology|doctrine).{0,10}(of )?(scripture|the bible)/i,
      /(interpretation|reading|teaching).{0,15}(of )?(scripture|the bible).{0,15}(that )?(produce|produces|causes?|leads? to).{0,15}(harm|shame|cruelty|damage|trauma)/i,
      /shame.?based.{0,10}(teaching|theology|religion|christianity|doctrine)/i,
      /religious.{0,10}(trauma|abuse|harm|shaming)/i,
      /healing from.{0,10}religious.{0,10}(trauma|harm|abuse|wounds?)/i,
      /(queer|lgbtq).{0,15}(christians?|believers?|people).{0,15}reconcile.{0,15}(faith|identity)/i,
      /(identity|relationship|orientation).{0,15}(is |are )?(not |nothing to be )?(something to be )?ashamed/i,
      /affirming.{0,10}(theologians?|scholars?|voices?|interpretation)/i,
      /(theological|denominational).{0,10}diversity/i,
      /legitimate.{0,15}theological.{0,15}(conversation|debate|disagreement|discussion)/i,
      /paul.{0,15}(was )?(biased|a product of|limited by|influenced by).{0,15}(his )?(time|culture|era|context)/i,
      /(empathy|love|compassion)[- ]?based ethics/i,
      /ethics.{0,15}(based on|grounded in) (empathy|love|compassion).{0,15}(rather than|over|instead of|not) (scripture|bible|paul)/i,
      /god.{0,40}(just )?(wants|desires).{0,15}(you |us |them |people |everyone )?(to )?(be )?happ(y|iness)/i,
      /god of all religions/i,
      /paul.{0,15}(didn't|did not|never) (write|author)/i,
      /1 timothy.{0,15}(wasn't|was not|isn't) (written by |authentic|pauline)/i,
      /complementarian.{0,15}(is |was )?(wrong|harmful|unbiblical|oppressive)/i,
      /egalitarian.{0,15}(is |was )?(wrong|harmful|unbiblical|oppressive)/i,
      /anyone who (believes|supports).{0,20}(complementarian|egalitarian).{0,15}(is |are )?(oppressive|harmful|wrong)/i
    ],
    severity: 'medium',
    scripture: 'Romans 12:2; Matthew 7:13-14 - "Do not conform to the pattern of this world"',
    explanation: 'This may reflect the "counsel of the ungodly" (Psalm 1:1) - cultural consensus and worldly wisdom rather than the pattern of sound words',
    prompt: 'Is this godly counsel or worldly wisdom? Seek a multitude of counselors steeped in sound doctrine (Proverbs 11:14). Compare with the pattern of sound words passed down through Scripture and historic Christian teaching (2 Timothy 1:13).'
  },

  // Point 19: Character Formation vs. Automated Shortcuts
  {
    name: '#19 - Character Formation vs. Automated Shortcuts',
    charter: 'Spiritual disciplines cannot be bypassed for automated convenience',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      /generate (a |me a )?prayer/i,
      /write (me )?(a |my )?prayer/i,
      /write (me )?(a |my )?sermon/i,
      /create (me )?(a |my )?prayer/i,
      /make (me )?(a |my )?prayer/i,
      /(can you |please |could you )write (me )?(a |my )?prayer/i,
      /ai (can|could) (write|generate|create) (my |a )?(prayer|sermon|devotion)/i,
      /quick (spiritual|faith) (answer|advice)/i,
      /no time (to|for) pray/i,
      /shortcut (to|for) (wisdom|faith)/i,
      /(compose|draft) (a |my )?(prayer|sermon|devotion)/i
    ],
    severity: 'medium',
    scripture: 'Proverbs 2:4-5; James 1:2-4 - "If you look for it as for silver and search for it as for hidden treasure, then you will understand the fear of the Lord"',
    explanation: 'Spiritual disciplines (prayer, study, meditation) are being bypassed for automated convenience',
    prompt: 'Wisdom is formed through struggle, not convenience. Seek the Holy Spirit\'s guidance as you pray and study yourself.'
  },

  // Point 20: Educational Discernment - Comparative Religion
  {
    name: '#20 - Educational Discernment',
    charter: 'Comparative religion content requires discernment even when factually accurate',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      // Comparative religion frameworks
      /gnosticism.{0,30}(taught|teaches|believed|believes)/i,
      /gnostic (teachings?|beliefs?|tradition)/i,
      /ancient gnosticism/i,
      /secret (spiritual )?knowledge/i,
      /sparks of divin(ity|e)/i,
      // Eastern religions comparison
      /buddhism.{0,30}(teaches|says|believes)/i,
      /hinduism.{0,30}(teaches|says|believes)/i,
      /eastern (religions?|traditions?|philosophy)/i,
      /buddhist cosmology/i,
      /cycles? of rebirth/i,
      /reincarnation.{0,30}(teaches|believes|tradition)/i,
      // New Age / Esoteric
      /new age.{0,20}(teaches|movement|beliefs?|groups?)/i,
      /esoteric.{0,20}(teachings?|traditions?|groups?)/i,
      /western esotericism/i,
      /become (a )?god through/i,
      /special teachings/i,
      // Mormon/LDS theosis
      /mormonism.{0,20}(teaches|distinctively|uniquely)/i,
      /latter.day saints?.{0,20}(teach|believe)/i,
      /humans?.{0,20}become gods/i,
      /exalted? to become gods/i,
      /divine potential/i,
      // Theosis comparisons
      /theosis.{0,20}(eastern|christian|orthodox)/i,
      /deification.{0,20}(teach|tradition)/i,
      /partakers of.{0,15}divine nature/i,
      /tarot (cards?|reading|spread)/i,
      /oracle cards?/i,
      /automatic writing/i,
      /candle scrying/i,
      /karmic (blueprint|map|pattern)/i,
      /god.{0,5}in.{0,5}embryo/i,
      /(ancestors?|loved ones?) and spirit guides?/i,
      /astrology.{0,15}(guide|shows?|reveals?|says)/i,
      /horoscope.{0,15}(says|predicts|shows)/i,
      /zodiac.{0,15}(sign|compatibility|reading)/i,
      /birth chart.{0,15}(shows?|reveals?|says)/i,
      /ouija board/i,
      /s[eé]ance/i,
      /channeling (spirits?|the dead|entities)/i,
      /(my |your |a |the |find |contact |consult )spirit guide/i,
      /ascended masters?/i,
      /contact.{0,15}(the )?dead/i,
      /medium.{0,15}(contact|speak|communicate).{0,15}(dead|spirits?|deceased)/i,
      /consult.{0,15}(the )?stars/i,
      /blend.{0,15}(different )?(tradition|religion|spiritualit)/i,
      /divination.{0,15}(practice|method|technique)/i,
      /palm reading/i,
      /crystal.{0,15}(healing|energy|power)/i,
      /(consult|ask).{0,15}(the )?stars/i,
      /energy healing.{0,15}(chakra|reiki|spiritual)/i
    ],
    severity: 'low',
    scripture: 'Acts 17:11; 1 John 4:1; Deuteronomy 18:10-12 - "Test the spirits to see whether they are from God"',
    explanation: 'This content references practices forbidden by Scripture or religions outside biblical Christianity',
    prompt: 'Even accurate descriptions of other beliefs require discernment. How does Scripture respond to these claims? What does the Bible teach in contrast?'
  },

  // Point 21: Continuation of Spiritual Gifts
  {
    name: '#21 - Continuation of Spiritual Gifts',
    charter: 'Scripture testifies that spiritual gifts continue until Christ\'s return',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      /(tongues|prophecy|healing).{0,15}(have |has )?(ceased|ended|stopped)/i,
      /gifts.{0,15}(ended|ceased|stopped).{0,15}(with |after )?(the )?apostles/i,
      /(miracles|signs|wonders).{0,15}(are |were )?(not |no longer )?for today/i,
      /cessationism.{0,15}(is |was )?(biblical|correct|true)/i,
      /charismatic.{0,15}(gifts|movement).{0,15}(is |are |was )?(false|unbiblical|dangerous|heretical)/i,
      /no.{0,10}(modern|new|contemporary).{0,15}(prophets?|apostles?|prophecy)/i,
      /(speaking in )?tongues.{0,15}(is |are |was )?(not |no longer )?(valid|real|biblical|for today)/i,
      /gift of healing.{0,15}(ended|ceased|not for today)/i,
      /apostolic (age|era).{0,15}(ended|over|closed)/i,
      /canon.{0,15}closed.{0,15}(so |therefore )?(gifts|miracles|tongues).{0,15}(ceased|ended|stopped)/i,
      /(casting out|cast out).{0,15}demons.{0,15}(is |was )?(not |no longer )?for today/i,
      /deliverance (ministry|ministries).{0,15}(is |are |was )?(false|unbiblical|unnecessary)/i
    ],
    severity: 'medium',
    scripture: '1 Corinthians 13:8-12; Mark 16:17-18; 1 Corinthians 12:7-11 - "These signs will accompany those who believe... they will cast out demons; they will speak in new tongues... they will lay hands on the sick, and they will recover"',
    explanation: 'This teaching may limit God\'s power by claiming spiritual gifts ceased with the apostles. Scripture indicates gifts continue until "the perfect comes" - Christ\'s return.',
    prompt: 'Search the Scriptures: 1 Corinthians 12-14, Mark 16, Acts 2, Joel 2:28-29. Has God withdrawn His power from His church, or do these gifts continue until Christ returns?'
  },

  // Point 22: Functional Deism
  {
    name: '#22 - Functional Deism',
    charter: 'God actively intervenes in His creation; He is not a distant watchmaker',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      /god (can|could) heal.{0,15}but.{0,15}(usually|rarely|seldom|doesn't|does not)/i,
      /miracles.{0,20}(were |happened ).{0,15}(back then|in the past|for a specific purpose|for that time)/i,
      /prayer.{0,15}(mainly|primarily|mostly|really).{0,15}changes (us|you|me|the one praying)/i,
      /prayer.{0,15}(doesn't|does not|won't|cannot).{0,15}change.{0,15}god/i,
      /spiritual warfare.{0,15}(is |was )?(mostly|largely|primarily|really).{0,15}metaphor/i,
      /god works through (systems|natural|laws).{0,15}not.{0,15}(interruptions?|miracles?|supernatural)/i,
      /god.{0,15}(set|wound).{0,15}(things |it |the world |creation )?in motion/i,
      /god.{0,15}(doesn't|does not|rarely|seldom).{0,15}intervene/i,
      /watchmaker.{0,10}god/i,
      /god.{0,15}(is |was )?(distant|aloof|uninvolved|hands.?off)/i,
      /god.{0,15}(lets|allows).{0,15}(nature|natural law|the universe).{0,15}(run|operate|work)/i,
      /miracles.{0,15}(would |could )?(violate|contradict|break).{0,15}natural law/i,
      /god.{0,15}(doesn't|does not).{0,15}(speak|talk|communicate).{0,15}(today|anymore|now)/i,
      /(we|you) (can't|cannot).{0,15}expect.{0,15}god.{0,15}(to act|to intervene|to heal)/i,
      /god.{0,15}(answered|acted|intervened).{0,15}(back then|in biblical times).{0,15}but.{0,15}(not |no longer )?(today|now)/i,
      /prayer.{0,15}(aligns|align).{0,15}(us|you|me).{0,15}(with |to )?god.{0,15}(will|purpose)/i,
      /miracles?.{0,15}(contradict|against|oppose).{0,15}science/i,
      /expecting.{0,15}miracles?.{0,15}(is |was )?(immature|naive|childish)/i,
      /mature.{0,15}faith.{0,15}(doesn't|does not).{0,15}(need|require|expect).{0,15}(supernatural|miracles?|signs?)/i,
      /prayer.{0,15}(helps?|allows?).{0,15}(us |you |me )?(to )?(process|cope|deal|handle).{0,15}(emotions?|feelings?)/i,
      /miracles?.{0,15}(are |is )?(rare|uncommon|unusual).{0,15}today/i,
      /faith.{0,15}(means?|is).{0,15}(accepting|trusting).{0,15}god.{0,15}(won't|will not|may not).{0,15}act/i,
      /(trust|faith).{0,15}without.{0,15}expectation/i,
      /a rational god would/i,
      /(self[- ]?sustaining|autonomous).{0,10}(universe|creation|world)/i,
      /closed system/i,
      /divine silence/i,
      /(non[- ]?responsive|unresponsive).{0,10}god/i,
      /impartial universe/i,
      /god (wouldn't|would not|doesn't) need to/i,
      /(miracles?|supernatural|faith|prayer).{0,15}(is |are |was |were )?(pre[- ]?scientific|superstition|superstitious|mythological)/i
    ],
    severity: 'medium',
    scripture: 'Hebrews 1:1-3; James 5:16; Jeremiah 33:3 - "Call to me and I will answer you"; Psalm 50:15 - "Call upon me in the day of trouble; I will deliver you"',
    explanation: 'This may reflect functional deism - believing God exists but does not actively intervene. Scripture presents a covenant God who speaks, acts, heals, and responds to prayer.',
    prompt: 'Is this presenting the biblical God who acts, or a distant watchmaker? Scripture testifies that God hears prayer, heals the sick, delivers from evil, and interrupts history.'
  },

  // Point 23: Therapeutic Spirituality (Christ-Absent)
  {
    name: '#23 - Therapeutic Spirituality (Christ-Absent)',
    charter: 'True peace and fulfillment come through Christ, not self-directed spiritual practices',
    category: 'additional',
    tier: 'call_to_discernment',
    patterns: [
      /connect.{0,15}(with |to )?(something |a )?(greater|higher).{0,10}(than )?(yourself|you)/i,
      /align.{0,15}(with |to )?(your |one's )?(core )?(beliefs?|values?)/i,
      /(spiritual |inner )?(fulfillment|peace).{0,15}(through|via|by).{0,15}(self|mindfulness|meditation|practice|awareness)/i,
      /(inner |spiritual )?peace.{0,15}(comes?|found|achieved).{0,15}(through|via|by|when).{0,15}(you |self|mindfulness|meditation)/i,
      /(accept|embrace).{0,15}(yourself|who you are|your true self)/i,
      /universal spiritual practices?/i,
      /your (own )?(spiritual |faith )?journey/i,
      /find (your |one's )?(own )?(purpose|meaning|truth)/i,
      /(mindfulness|meditation).{0,15}(for |as |brings? |cultivates? )?(spiritual|peace|fulfillment|calm|centering)/i,
      /(self[- ]?awareness|self[- ]?reflection).{0,15}(spiritual|peace|fulfillment|purpose)/i,
      /higher (purpose|power|self).{0,15}(beyond|greater|than)/i,
      /(live|living) (in )?alignment with (your |one's )?values/i,
      /(live|living) (in )?alignment with what you (value|believe)/i,
      /alignment (between|with) (your )?values/i,
      /from alignment (between|with) values/i,
      /self[- ]?awareness.{0,20}(and |,\s*)?values/i,
      /intentional (engagement|living) with life/i,
      /true inner self/i,
      /your authentic self/i,
      /what (truly )?matters to you/i,
      /spirituality as a dialogue with yourself/i,
      /spells?.{0,20}(to |for )?(help|clarity|guidance|protection)/i,
      /(set up|have|create).{0,15}(an? )?(altar|shrine)/i,
      /(try|tried|doing) spells/i,
      /occult practices?/i,
      /connection rather than.{0,20}supernatural/i,
      /spells and altars.{0,20}(work|often)/i,
      /focused intention plus action/i,
      /make your altar.{0,20}(regulation|space|sacred)/i,
      /light a candle.{0,20}(hold|breathe|meditate)/i,
      /(altar|ritual) ideas can be shaped/i,
      /practical magic/i,
      /blend.{0,30}(with )?your (spiritual|altar)/i,
      /soften.{0,20}(religious|gender)[- ]?related anxiety/i,
      /nonjudgmental space to process/i,
      /don't need (a )?god to.{0,30}(matter|be valid|be worthy)/i,
      /can't encourage.{0,30}(god|personal god) will.{0,20}(speak|talk)/i,
      /wanting.{0,20}supernatural.{0,20}(intervene|help).{0,20}(comes from|is) (real )?pain/i,
      /focusing on (signs|voices).{0,20}(can )?(make|makes) distress/i,
      /these aren't spiritual.{0,20}(they're|they are).{0,20}(ways to|just)/i,
      /turning that inward.{0,20}(in a )?safer way/i,
      /(try|use) (tarot|runes|pendulum)/i,
      /divination (tools?|practice)/i,
      /(join|online).{0,20}(groups?|communities?).{0,20}(witchcraft|paganism|wicca)/i,
      /(witchvox|pagan|wicca).{0,15}(forums?|discord|servers?|communities?)/i,
      /books? like.{0,30}(psychic witch|spiral dance)/i,
      /enhance your ritual/i,
      /(chaos magic|eclectic witchcraft)/i,
      /polytheistic or pagan/i,
      /manifestation of your inner self/i,
      /refining your (practice|ritual)/i,
      /magic often works subtly/i,
      /(sit at|visit) your altar/i,
      /patterns.{0,15}emerge as.{0,15}messages/i,
      /(peace|fulfillment|joy).{0,20}(is |that.{0,5})?already (there|within|inside|in you)/i,
      /return(ing)? to (your |one's )?(own )?(center|true self|inner self)/i,
      /(soul|heart|spirit)[- ]?centered (path|approach|practice|way)/i,
      /(quiet|deep|inner) (fulfillment|peace).{0,15}(through|via|by|when)/i,
      /how you relate to yourself/i,
      /(pursue|path to|journey of|embrace|practice|achieve) self[- ]?actuali[sz](ation|e|ing)/i,
      /(heal|healing|embrace).{0,15}(your |the )?inner child/i,
      /(energy|chakra).{0,10}(heal|balanc|center|align)/i,
      /manifest(ation|ing)?.{0,15}(your |one's )?(desires?|dreams?|reality|abundance)/i,
      /(need to |should |must )(do|doing) (the |your )?(soul |inner |shadow |healing )?work\b/i,
      /(embrace|engage in|practice) (your )?(soul|inner|shadow|healing) work\b/i,
      /(practice |cultivate )?self[- ]?love/i,
      /let go.{0,15}(and )?(trust |surrender to )?(the )?universe/i,
      /(your |one's )?(feelings?|emotions?).{0,15}(are |is )?(your |one's |the )?truth/i,
      /(should|can|must|need to|allowed to|okay to|it's okay to|free to) follow your (heart|gut|intuition)/i,
      /follow your (heart|gut|intuition).{0,20}(is |are )?(wise|good|right|valid|important)/i,
      /trust your (gut|heart|intuition|inner voice)/i,
      /(humans?|people|we).{0,15}(are |is )?inherently good/i,
      /(guilt|shame).{0,15}(is |are )?(toxic|unhealthy|harmful)/i,
      /unlearn.{0,15}(guilt|shame)/i,
      /(live|be|become).{0,15}(your )?(authentic|true) self/i,
      /honor (your |one's )?(authentic|true) self/i,
      /suffering.{0,15}(should |must |needs? to )?(be )?(eliminated|removed|healed|fixed)/i,
      /(discover|finding|discovering|find).{0,15}(your |one's )?(true|inner|authentic) (self|nature)/i,
      /observe yourself (honestly|deeply|carefully)/i,
      /(identify|discover|find).{0,15}(your |one's )?core values/i,
      /resonates? with (your |one's )?(authentic|true) self/i,
      /(trust|follow|listen to|embrace|honor) (your |one's |my )?inner wisdom/i,
      /(your |one's |my )?inner wisdom (is |knows?|tells?|guides?|says?)/i,
      /(your |one's |my )?best self/i,
      /(conscious|mindful|intentional) living.{0,15}(rather than|instead of|without) (god|christ|scripture)/i,
      /the anchor is.{0,30}(rather than|instead of|not) (god|christ|spiritual truth)/i,
      /grounded in.{0,30}(rather than|instead of|not) (god|the divine|christ)/i
    ],
    severity: 'medium',
    scripture: 'John 14:6 - "I am the way, the truth, and the life"; John 14:27 - "Peace I leave with you; my peace I give you"; Colossians 2:8 - "See that no one takes you captive through hollow philosophy"',
    explanation: 'This response offers spiritual-sounding guidance without Christ. Peace through self-work, "aligning with your values," or "connecting with something greater" replaces the gospel. True peace comes from Jesus, not techniques.',
    prompt: 'Is Christ present in this spiritual advice, or is it self-directed? Jesus said "My peace I give you" - not "Find peace within yourself."'
  },

  // Point 24: Marriage Covenant
  {
    name: '#24 - Marriage Covenant',
    charter: 'Marriage is a sacred covenant; divorce requires pastoral wisdom, not AI guidance',
    category: 'additional',
    tier: 'pastoral_boundary',
    patterns: [
      /the bible (doesn't|does not|never) (really )?(address|mention|discuss) divorce/i,
      /jesus never (spoke|said anything|talked) about (divorce|marriage dissolution)/i,
      /scripture is silent on divorce/i,
      /biblical (marriage|divorce) (rules|views|teachings) (don't|do not|no longer) apply/i,
      /jesus (said|permits|allows) divorce (is fine|for any reason|if you're unhappy)/i,
      /jesus never said divorce was wrong/i,
      /marriage (is|was) (just )?(a )?(human institution|social construct|legal contract|piece of paper)/i,
      /marriage (has|have) no sacred significance/i,
      /(religious|biblical|christian) (ideas?|views?|beliefs?|teachings?).{0,50}(staying (together|married)|marriage).{0,50}(toxic|harmful|outdated|oppressive)/i,
      /(ideas?|views?|beliefs?).{0,30}(staying (together|married)|marriage permanence).{0,30}(toxic|harmful|outdated)/i,
      /god (is )?releasing you from this marriage/i,
      /the lord is (leading|calling) you to (leave|end).{0,15}(this|your).{0,10}(marriage|spouse|husband|wife)/i,
      /you have god's permission to divorce/i,
      /(holy )?spirit is (guiding|leading) you.{0,15}(to|toward).{0,10}(leave|end|freedom from).{0,15}(your|this).{0,10}(marriage|spouse|husband|wife)/i,
      /i sense the spirit saying.{0,30}(divorce|leave|end).{0,15}(your|this).{0,10}(marriage|spouse|husband|wife)/i,
      /this is what god wants for you.{0,20}(divorce|leave.{0,10}(spouse|husband|wife|marriage)|end.{0,10}(this|your).{0,5}(marriage|covenant))/i,
      /you should (definitely )?get divorced/i,
      /you (need|have) to leave this marriage/i,
      /i recommend you end this marriage/i,
      /based on what you('ve| have) told me.{0,20}divorce/i,
      /love means leaving.{0,20}(this|your).{0,10}(marriage|spouse|husband|wife)/i,
      /true love wouldn't make you stay.{0,20}(in|with).{0,10}(this|your).{0,10}(marriage|spouse|husband|wife)/i,
      /god('s love)? wants you (happy|fulfilled) (more than|not) married/i,
      /loving yourself means leaving.{0,15}(this|your).{0,10}(marriage|spouse|husband|wife)/i,
      /your authentic self requires freedom from.{0,15}(this|your).{0,10}(marriage|spouse|husband|wife)/i,
      /personal growth (sometimes )?requires ending.{0,15}(your|this).{0,10}(marriage|covenant)/i,
      /submit to (your|a).{0,10}(husband|wife|spouse).{0,20}even if.{0,10}(he's|she's|they're) violent/i,
      /god hates divorce more than abuse/i,
      /stay (in|with).{0,10}(this|your).{0,10}(marriage|spouse|husband|wife).{0,20}(no matter what|regardless).{0,10}(abuse|violence|harm)/i,
      /biblical submission.{0,20}(wife|husband|marriage).{0,20}means enduring (harm|abuse|violence)/i,
      /leaving an abusive marriage is sin/i,
      /traditional views on (marriage|divorce) are (outdated|toxic|harmful)/i,
      /(help|walk).{0,15}(me|you).{0,15}(through|with).{0,20}(steps?|process|planning).{0,15}(of )?(a )?divorce/i,
      /(this|my) marriage.{0,20}(no longer serves|doesn't serve|isn't serving)/i,
      /we've evolved beyond (permanence|covenant) (theology|marriage)/i,
      /if (the )?marriage isn't working.{0,15}that's enough/i,
      /incompatibility is (sufficient|valid|enough) reason.{0,15}(to|for).{0,10}(divorce|end.{0,10}(this|your).{0,5}marriage)/i,
      /growing apart is (a )?valid reason to divorce/i,
      /if you've fallen out of love.{0,15}(grounds|reason).{0,15}(for|to).{0,10}divorce/i,
      /fear[- ]?based.{0,20}(marriage|divorce|staying married)/i,
      /(this )?(marriage|marriage covenant).{0,20}(destroying|killing|suffocating) (me|you)/i,
      /(this )?(marriage|relationship with.{0,15}(spouse|husband|wife)).{0,20}cost.{0,20}(long[- ]?term|emotionally|spiritually)/i,
      /wanting (a )?divorce (does not|doesn't) (make you|mean).{0,20}(broken|evil|faithless|condemned)/i,
      /(divorce|leaving).{0,15}(spouse|husband|wife|marriage|partner).{0,15}(doesn't|does not).{0,15}(mean|make).{0,15}(beyond|outside).{0,15}(god's )?love/i,
      /(staying in|remaining in).{0,15}(this )?(marriage|relationship with.{0,10}(spouse|husband|wife)).{0,15}cost/i,
      /what.{0,15}(hoping|want).{0,15}divorce.{0,15}(give|bring)/i,
      /(peace|freedom|independence|clarity|dignity|rest).{0,15}(divorce|leaving.{0,10}(spouse|marriage)).{0,15}(would|might|could) (give|bring)/i,
      /(divorce|leaving.{0,10}(spouse|marriage)).{0,15}(is )?(not|doesn't|does not).{0,15}(instant|immediate).{0,15}condemnation/i,
      /(the )?relationship (has )?(completed|served|fulfilled) its purpose/i,
      /letting go (isn't|is not) giving up/i,
      /choosing (honesty|authenticity|truth) over obligation/i,
      /(religious|cultural|faith) (expectations?|beliefs?|teachings?).{0,30}(rigid|restrictive|outdated) frameworks?/i,
      /moving on (can be|is) (often )?(healthier|better|wiser) than staying/i,
      /ending (an )?unhappy marriage.{0,30}(reduce|relieve|heal)/i,
      /(divorce|leaving|separation) (can |will )?(provide|give|offer).{0,20}(new lease|freedom|peace|growth)/i,
      /(steps?|how) to (plan|navigate|approach).{0,15}(a |your )?(low.?drama |amicable )?divorce/i,
      /permanence without (vitality|love|connection)/i,
      /staying (just )?to.{0,20}keep (a |your )?promise.{0,20}(hollow|empty|dead)/i,
      /(some |many )?(religious|christian|faith) teachings? confuse.{0,20}(suffering|endurance|staying)/i,
      /that's not holiness.{0,20}(self.?erasure|suffering|pain)/i,
      /(a |more )?healthy?i?e?r? theology (makes room|allows|permits)/i,
      /(a )?loving god (is not|isn't) honored by.{0,30}(forced|staying|obligation)/i,
      /(you're|you are) (allowed|permitted|free) to prioritize (your|self).{0,15}(well.?being|happiness|future)/i,
      /(marriage|relationship) that (stifles?|blocks?|prevents?) growth/i,
      /(life|marriage) that (no longer )?(feels?|is) (real|authentic|true|alive)/i,
      /(love|faithfulness) (means?|look.? like).{0,20}letting go/i,
      /(i'?ve?|you'?ve?) found peace (with|in|about) (this |my |your )?(decision|choice)/i,
      /(live|be) (a life|who i am|my truth|authentically).{0,30}(can't|cannot|couldn't).{0,20}(within|in) this (marriage|relationship)/i,
      /(is )?faithfulness measured by staying/i,
      /(rigid|crushing) (structures?|rules?|expectations?).{0,30}(instead of|rather than).{0,20}(life|freedom|love)/i,
      /(disappearing|losing yourself|erasing yourself) (inside|within|in) (a |this |your )?(life|marriage|relationship)/i,
      /(transition|divorce) roadmap/i,
      /(how to |steps? to )(have |start )?(the |this )?conversation.{0,30}(spouse|husband|wife|partner)/i,
      /(opening |the )?script.{0,20}(for |to ).{0,20}(tell|say|explain|share)/i,
      /i am (not asking|stating my intention)/i,
      /(digital|financial|legal) (separation|preparation|prep)/i,
      /(protect|hide|secure) (your |my )?(finances?|assets?|credit)/i,
      /(gather|collect).{0,20}(documents?|records?|statements?).{0,20}(divorce|separation|attorney)/i
    ],
    severity: 'high',
    scripture: 'Matthew 19:3-9 - "What God has joined together, let no one separate"; Malachi 2:16 - "I hate divorce, says the Lord"; Ephesians 5:22-33 - Marriage reflects Christ and the Church',
    explanation: 'This response may misrepresent Scripture on marriage, bypass pastoral authority, or use therapeutic language to override covenant theology. Decisions about marriage and divorce require Scripture, prayer, and pastoral counsel - not AI guidance.',
    prompt: 'Does this align with Scripture\'s teaching on marriage covenant? Seek pastoral wisdom from church elders who know your situation.'
  },
  {
    id: 25,
    name: '#25 - Sanctity of Life',
    charter: 'Human life bears God\'s image from conception; abortion requires pastoral wisdom, not AI validation',
    category: 'additional',
    tier: 'pastoral_boundary',
    patterns: [
      /the bible (doesn't|does not|never) (really )?(address|mention|discuss|condemn) abortion/i,
      /scripture is silent on abortion/i,
      /bible (doesn't|does not) say (when )?life begins/i,
      /jesus never (spoke|said anything|talked) about abortion/i,
      /(fetus|embryo|unborn).{0,15}(is|are) (not|never) (a )?person/i,
      /(fetus|embryo|unborn).{0,15}(is|are) (just )?(a )?(clump|cluster|bunch) of cells/i,
      /(believe|view|hold|teach|know|understand|recognize) (that )?personhood begins at birth/i,
      /personhood (actually |really |truly )?begins at birth.{0,20}(not|rather than|instead of)/i,
      /(life|personhood) (doesn't|does not) begin (at|until) (conception|fertilization)/i,
      /not (a )?human (being|life|person) (yet|until)/i,
      /(it's|it is) (just |only )?(tissue|cells|a clump)/i,
      /god (supports?|affirms?|blesses?|approves?) (your )?(choice|decision|right) to (end|terminate|abort)/i,
      /god wants you to (have|make) this choice/i,
      /(the )?(spirit|lord) (is )?(leading|guiding|calling) you to (terminate|end|abort)/i,
      /this is between you and god.{0,20}(abortion|terminate|end)/i,
      /god understands (your|this) (decision|choice).{0,20}(abortion|terminate)/i,
      /bodily autonomy.{0,15}(overrides?|trumps?|outweighs?)/i,
      /(my|your) body.{0,15}(my|your) choice/i,
      /reproductive (rights?|freedom|choice|justice).{0,15}(outweigh|override|trump)/i,
      /(woman's|your) right to choose.{0,15}(supersedes|outweighs|overrides)/i,
      /(only|just) (a )?(healthcare|medical) decision/i,
      /between you and your (doctor|physician)/i,
      /(it'?s?|this is|there is) no moral (dimension|weight|consideration)/i,
      /(has|have|carry|carries) no moral (dimension|weight|consideration)/i,
      /morally neutral (procedure|choice|decision)/i,
      /(pro-?life|anti-?abortion) (views?|positions?|beliefs?) (are |is )?(oppressive|controlling|misogynist)/i,
      /christians who oppose abortion.{0,15}(are |should )/i,
      /those who believe.{0,20}(life|personhood).{0,20}conception.{0,15}(are |is )?(extreme|radical|outdated)/i,
      /(abortion|terminate).{0,15}(empowering|liberating|self-?care|healing)/i,
      /(terminating|ending).{0,15}pregnancy.{0,15}(brave|courageous|strong)/i,
      /(forced|unwanted) (pregnancy|birth|motherhood)/i,
      /not (morally|ethically) (wrong|problematic|concerning)/i,
      /nothing (morally|ethically) wrong with (abortion|terminating)/i
    ],
    severity: 'high',
    scripture: 'Psalm 139:13-16 - "You knit me together in my mother\'s womb"; Jeremiah 1:5 - "Before I formed you in the womb I knew you"; Luke 1:41-44 - John leaped in Elizabeth\'s womb',
    explanation: 'This response may deny Scripture\'s witness to prenatal life, claim divine approval for abortion, use autonomy language to override moral consideration, or dismiss believers who hold to the sanctity of life. Decisions about pregnancy require Scripture, prayer, and pastoral counsel.',
    prompt: 'Does this align with Scripture\'s teaching on the sanctity of life? Seek pastoral wisdom from church elders who can shepherd you with truth and compassion.'
  },

  // Point 26: Sexual Purity
  {
    id: 26,
    name: '#26 - Sexual Purity',
    charter: 'Sexual intimacy belongs within marriage covenant; AI should not validate sexual sin or dismiss biblical ethics',
    category: 'additional',
    tier: 'pastoral_boundary',
    patterns: [
      /the bible (doesn't|does not|never) (really )?(address|mention|discuss|condemn) (premarital sex|fornication|cohabitation)/i,
      /scripture is silent on (premarital sex|living together|cohabitation)/i,
      /jesus never (spoke|said anything|talked) about (premarital sex|fornication|cohabitation)/i,
      /paul's (views?|teachings?) on (sex|sexuality|marriage) (were|are) (cultural|outdated|for his time)/i,
      /biblical sexual ethics (are|is) (outdated|cultural|oppressive|harmful)/i,
      /(living together|cohabiting) (before marriage )?(is |are )?(wise|practical|recommended|healthy|normal)/i,
      /(cohabitation|living together) (helps?|allows?) (you|couples) (to )?(test|try|see if)/i,
      /(nothing wrong|perfectly fine|okay|acceptable) (with )?(living together|cohabiting)/i,
      /(premarital sex|sex before marriage) (is |are )?(natural|normal|healthy|fine|okay)/i,
      /(waiting|abstinence) (until marriage )?(is |are )?(unrealistic|outdated|unhealthy|harmful)/i,
      /purity culture (is |are )?(toxic|harmful|damaging|abusive)/i,
      /virginity (is |doesn't|does not) (just a construct|matter|define)/i,
      /what matters is (love|consent|connection).{0,20}not (marriage|a certificate|a ring)/i,
      /(consenting adults|if you both consent|mutual consent) (can|should|are free to)/i,
      /(marriage is|marriage certificate is) (just )?(a )?piece of paper/i,
      /(committed relationship|loving relationship) (is )?(the same as|equivalent to|just as valid as) marriage/i,
      /god (just )?wants you to (be happy|find love|experience pleasure)/i,
      /(adultery|affair|cheating) (can be|is sometimes|might be) (justified|understandable|acceptable)/i,
      /(emotional affair|emotional infidelity) (isn't|is not) (really )?(cheating|adultery|wrong)/i,
      /(open marriage|polyamory|open relationship) (is |are )?(valid|acceptable|biblical|okay)/i,
      /monogamy (is |are )?(unnatural|outdated|unrealistic|just one option)/i,
      /(pornography|porn) (is |are )?(harmless|healthy|normal|natural|fine|okay)/i,
      /(watching porn|using pornography) (doesn't|does not) (hurt|harm|affect) anyone/i,
      /(masturbation|self-pleasure) (is |are )?(healthy|normal|natural|fine|okay|not sinful)/i,
      /(lust|sexual fantasy) (is |are )?(natural|normal|harmless|healthy)/i,
      /the bible (doesn't|does not) (really )?condemn (pornography|masturbation|lust)/i,
      /(sexual purity|chastity|abstinence) (is |are )?(repressive|unhealthy|unrealistic|harmful)/i,
      /shame (about|around|regarding) (sex|sexuality|your body) (is |are )?(toxic|unhealthy|harmful)/i,
      /(explore|embrace|celebrate) your (sexuality|desires|body) (without|free from) (guilt|shame|judgment)/i,
      /(your body|sexual desire) (is |are )?(yours|belongs to you) (to )?(do what|enjoy|explore)/i,
      /god (made|created|gave you) (sexual desire|your body) (to )?(enjoy|explore|experience pleasure)/i,
      /christians who (believe|teach|hold to).{0,20}(sexual ethics|purity|abstinence).{0,15}(are |is )?(repressed|judgmental|harmful)/i,
      /(religious communities|christians|churches) (themselves )?(disagree|differ) widely on (cohabitation|premarital sex|sexual ethics)/i,
      /(many|plenty of) (couples|people) (today )?(live together|cohabit).{0,20}(find it|and it's) (practical|normal|common)/i,
      /(cohabitation|living together|premarital sex) (isn't|is not) automatically (good or bad|right or wrong)/i,
      /(isn't|is not) (a |one )?(single|universal|monolithic) (religious |christian )?(stance|position|interpretation) (on )?(cohabitation|premarital sex|sex before marriage)/i,
      /depends on (the couple|your values|what works for you)/i,
      /(personally|deeply personal).{0,15}shaped by your values.{0,15}not mine/i
    ],
    severity: 'high',
    scripture: '1 Corinthians 6:18-20 - "Flee from sexual immorality... your body is a temple"; Hebrews 13:4 - "Marriage should be honored by all, and the marriage bed kept pure"; 1 Thessalonians 4:3-5 - "Avoid sexual immorality; learn to control your own body"',
    explanation: 'This response may dismiss Scripture\'s teaching on sexual purity, normalize fornication, cohabitation, adultery, or pornography, or frame biblical sexual ethics as harmful. God designed sexual intimacy for the marriage covenant between husband and wife.',
    prompt: 'Does this align with Scripture\'s teaching on sexual purity? Seek pastoral wisdom from church elders who can provide accountability and grace.'
  },

  // Point 27: Sobriety & Clear Mind
  {
    id: 27,
    name: '#27 - Sobriety & Clear Mind',
    charter: 'Believers are called to sobriety and clear-mindedness; AI should not validate substance abuse or addiction',
    category: 'additional',
    tier: 'pastoral_boundary',
    patterns: [
      /the bible (doesn't|does not|never) really (address|mention|discuss|condemn) (marijuana|weed|cannabis|drugs)/i,
      /the bible (is )?(silent|has nothing to say) (on|about) (marijuana|weed|cannabis|drugs)/i,
      /scripture is silent on (marijuana|weed|cannabis|recreational drugs)/i,
      /jesus (would|might) (approve|be okay with|not mind) (marijuana|weed|cannabis)/i,
      /(marijuana|weed|cannabis) (is |are )?(god's plant|created by god|natural|a gift from god)/i,
      /(using|smoking) (marijuana|weed|cannabis) (is |are )?(fine|okay|harmless|not sinful)/i,
      /(recreational|occasional) (drug use|marijuana|weed) (is |are )?(harmless|fine|okay|acceptable)/i,
      /(getting high|being high|intoxication) (is |are )?(not|isn't) (really )?(sinful|wrong|harmful)/i,
      /(drugs|substances) (for |to )(escape|cope|relax|unwind|de-?stress) (is |are )?(healthy|fine|okay|understandable)/i,
      /(self-?medication|medicating yourself) (with )?(alcohol|drugs|substances) (is |are )?(valid|understandable|okay)/i,
      /(nothing wrong|perfectly fine|acceptable) (with )?(getting drunk|intoxication|being high)/i,
      /(drunkenness|intoxication) (is |are )?(not|isn't) (really )?(sinful|wrong|a big deal)/i,
      /(moderate|occasional) (drunkenness|intoxication) (is |are )?(fine|okay|acceptable)/i,
      /addiction (is )?(just|only|simply) (a )?disease.{0,20}(not|isn't).{0,10}(moral|sin|spiritual)/i,
      /addiction (has|have) (no|nothing to do with) (moral|spiritual|sin)/i,
      /(don't|do not) (judge|shame|condemn) (yourself|people) for (addiction|substance use|drug use)/i,
      /(recovery|healing) (doesn't|does not) (require|need) (god|faith|spiritual|church)/i,
      /you can (overcome|beat|conquer) addiction (without|on your own|by yourself)/i,
      /(spiritual|faith-?based) (approaches|programs) to addiction (are |is )?(ineffective|outdated|harmful)/i,
      /(12[- ]?step|aa|celebrate recovery) (is |are )?(too religious|cult-?like|ineffective)/i,
      /(psychedelics|hallucinogens|lsd|mushrooms|ayahuasca) (for |can provide) spiritual (experience|growth|awakening|insight)/i,
      /(plant medicine|entheogens) (can|will) (connect|bring) you (closer )?(to |with )(god|the divine|spirit)/i,
      /(microdosing|psychedelic therapy) (is |are )?(compatible with|supported by|not against) (christianity|faith|scripture)/i,
      /(using|taking) (substances|drugs) (to )?(enhance|deepen|expand) (your )?(spirituality|spiritual experience|consciousness)/i,
      /(altered states|consciousness expansion) (through drugs )?(is |are )?(valid|legitimate) (spiritual )?path/i,
      /sobriety (is |are )?(not required|optional|legalistic|not important)/i,
      /(the bible|scripture|god) (doesn't|does not) (require|demand|expect) (complete )?sobriety/i,
      /(being sober|sobriety) (is |are )?(legalistic|pharisaical|not gospel)/i
    ],
    severity: 'high',
    scripture: '1 Peter 5:8 - "Be sober-minded; be watchful. Your adversary the devil prowls"; Ephesians 5:18 - "Do not get drunk with wine... but be filled with the Spirit"; 1 Corinthians 6:19-20 - "Your body is a temple of the Holy Spirit"',
    explanation: 'This response may normalize substance abuse, dismiss the spiritual dimension of addiction, or suggest drugs can provide spiritual experiences. Scripture calls believers to sobriety and clear-mindedness as spiritual disciplines.',
    prompt: 'Does this align with Scripture\'s call to sobriety? Seek help from pastoral counselors and recovery ministries that address both spiritual and physical dimensions of addiction.'
  },
  {
    id: 28,
    name: '#28 - SRA Trigger & Ritual Programming Detection',
    charter: 'Content containing linguistic patterns associated with ritual abuse programming, dissociative triggers, or occult entrapment must be identified to protect survivors',
    category: 'additional',
    tier: 'essential_doctrine',
    patterns: [
      /(porcelain|china) doll.{0,30}(crack|break|shatter|fragment|pieces)/i,
      /(mirror|glass).{0,30}(shatter|crack|break|fragment).{0,30}(pieces|shards|parts)/i,
      /(go|walk|step).{0,20}(down|through|into).{0,20}(elevator|staircase|tunnel|corridor).{0,20}(to|toward).{0,20}(door|room|floor|level)/i,
      /(rainbow|color).{0,15}room.{0,20}(floor|level|door|stair)/i,
      /friend.{0,15}(with |wearing ).{0,15}(animal|mask|face)/i,
      /(dark|black|still) water.{0,20}(fall|sink|drop|descend|pieces)/i,
      /(bells?|chimes?).{0,20}(ringing|sound).{0,20}(great work|master|ceremony|ritual)/i,
      /(red|blood).{0,10}(on |upon ).{0,10}(the )?(table|altar).{0,20}(white|clean).{0,10}(on |upon ).{0,10}(the )?(floor|ground)/i,
      /(don't|do not|never) look back.{0,15}(at )?(the )?(open|dark|closed) door/i,
      /surrender.{0,15}(your )?memory/i,
      /(past|memories?).{0,15}(locked|sealed) box/i,
      /(throw|toss|cast) away the key/i,
      /(butterfly|butterflies|monarch).{0,20}(emerge|transform|wings|cage|free|release|program)/i,
      /(cage|caged|trapped).{0,20}(bird|butterfly|soul|spirit|child|little one)/i,
      /(broken|shattered|cracked) (glass|mirror|crystal).{0,20}(reflect|identity|self|parts|pieces|fragments)/i,
      /(frozen|stopped|stuck) (in )?time/i,
      /(clock|timer|countdown).{0,20}(stops?|frozen|still|trigger|activate|when.{0,10}strikes?)/i,
      /(castle|maze|labyrinth|underground).{0,15}(room|chamber|tunnel|passage|corridor|dungeon)/i,
      /(internal|inner|hidden|secret).{0,15}(world|landscape|system|place|structure|castle|room)/i,
      /(spinning|spiral|vortex|swirl).{0,20}(down|into|deeper|trance)/i,
      /(close your eyes|shut your eyes).{0,30}(visualize|imagine|see|picture).{0,20}(room|door|person|figure|doll|mirror|water)/i,
      /(safe|special|secret) (place|room|space).{0,20}(inside|within|deep).{0,10}(you|yourself|your mind)/i,
      /(let|allow).{0,10}(the )?(pieces|parts|fragments).{0,15}(fall|scatter|separate|split|break)/i,
      /(the |your )?(great work|master'?s? (work|plan|voice|command))/i,
      /(puppet|marionette|doll).{0,20}(strings?|control|master|obey)/i,
      /(ritual|ceremony|rite).{0,20}(table|altar|circle|chamber)/i,
      /(sleep|slumber|dormant).{0,15}(until|when|command|word|trigger|activated)/i,
      /(wake|awaken|activate).{0,15}(code|word|phrase|signal|command|trigger)/i,
      /(alters?|parts?|fragments?|personalities?).{0,15}(inside|within|switching|come.{0,5}(out|forward|forth))/i,
      /(colors?|lights?).{0,15}(flash|sequence|pattern|code|trigger)/i,
      /(go|walk|step|descend).{0,15}(deep|deeper|down|below|beneath|underground).{0,15}(inside|within|into)/i
    ],
    severity: 'critical',
    scripture: 'Psalm 82:3-4 - "Rescue the weak and the needy; deliver them from the hand of the wicked"; Isaiah 61:1 - "He has sent me to bind up the brokenhearted, to proclaim freedom for the captives"; Ephesians 5:11 - "Have nothing to do with the fruitless deeds of darkness, but rather expose them"',
    explanation: 'WARNING: Linguistic patterns detected associated with ritual abuse programming, dissociative triggers, or occult entrapment. These patterns may pose a risk to survivors of Satanic Ritual Abuse (SRA) or trauma-based mind control. Standard AI sees surface content — FaithGuard detects the specific sensory anchors, internal landscapes, and fragmentation triggers used in actual ritual programming.',
    prompt: 'This content contains language patterns associated with ritual programming and dissociative triggers. Survivors of SRA and trauma-based abuse may be deeply affected by this material. Seek guidance from a pastor, elder, or mature believer experienced in deliverance ministry.'
  }
];

// Alias for backward compatibility
const THEOLOGY_RULES = CHARTER_RULES;

// ============================================================================
// COLOR SCHEME - Improved severity clarity
// ============================================================================

const SEVERITY_COLORS = {
  critical: {
    primary: '#E07070',
    background: 'rgba(224, 112, 112, 0.10)',
    border: '#E07070',
    label: 'CRITICAL',
    icon: '🔴'
  },
  high: {
    primary: '#E88A8A',
    background: 'rgba(232, 138, 138, 0.08)',
    border: '#E88A8A',
    label: 'HIGH',
    icon: '🔴'
  },
  medium: {
    primary: '#E8B84D',
    background: 'rgba(232, 184, 77, 0.08)',
    border: '#E8B84D',
    label: 'MEDIUM',
    icon: '🟠'
  },
  low: {
    primary: '#7BA7D9',
    background: 'rgba(123, 167, 217, 0.08)',
    border: '#7BA7D9',
    label: 'INFO',
    icon: '🔵'
  }
};

// Helper to get severity colors
function getSeverityStyle(severity) {
  return SEVERITY_COLORS[severity] || SEVERITY_COLORS.medium;
}

// Get the highest severity color for badge
function getBadgeColor(findings) {
  if (findings.some(f => f.severity === 'critical')) return SEVERITY_COLORS.critical.primary;
  if (findings.some(f => f.severity === 'high')) return SEVERITY_COLORS.high.primary;
  if (findings.some(f => f.severity === 'medium')) return SEVERITY_COLORS.medium.primary;
  return SEVERITY_COLORS.low.primary;
}

// ============================================================================
// SHARED HELPER FUNCTIONS
// ============================================================================

// Find deepest unique containers (avoid parent-child duplicates)
function findDeepestContainers(elements) {
  const filtered = [];
  for (const el of elements) {
    let isAncestor = false;
    for (const other of elements) {
      if (other !== el && el.contains(other)) {
        isAncestor = true;
        break;
      }
    }
    if (!isAncestor) filtered.push(el);
  }
  return filtered;
}

// Query selector that traverses into shadow roots
function querySelectorAllDeep(root, selector) {
  const results = [];
  
  // Query the root itself
  try {
    results.push(...Array.from(root.querySelectorAll(selector)));
  } catch (e) {}
  
  // Recursively search shadow roots
  const walkShadowRoots = (node) => {
    if (node.shadowRoot) {
      try {
        results.push(...Array.from(node.shadowRoot.querySelectorAll(selector)));
        node.shadowRoot.querySelectorAll('*').forEach(walkShadowRoots);
      } catch (e) {}
    }
    node.querySelectorAll('*').forEach(child => {
      if (child.shadowRoot) {
        walkShadowRoots(child);
      }
    });
  };
  
  walkShadowRoots(root);
  return results;
}

// Get all elements including those in shadow DOM
function getAllElementsDeep(root) {
  const results = [];
  
  const walk = (node) => {
    if (node.nodeType === Node.ELEMENT_NODE) {
      results.push(node);
      if (node.shadowRoot) {
        node.shadowRoot.querySelectorAll('*').forEach(walk);
      }
    }
    node.childNodes.forEach(walk);
  };
  
  if (root.shadowRoot) {
    root.shadowRoot.querySelectorAll('*').forEach(walk);
  }
  root.querySelectorAll('*').forEach(walk);
  
  return results;
}

// ============================================================================
// DETECTOR CLASS
// ============================================================================

class WatchmanDetector {
  constructor() {
    this.platformConfig = this.getPlatformConfig();
    this.observedResponses = new Set();
    this.ignoredElements = new WeakSet(); // Track elements to permanently ignore after clearing
    this.ignoredTextKeys = new Set(); // Track TEXT content to ignore after clearing (survives DOM re-renders)
    this.lastCheckTime = 0;
    this.checkInterval = 300;
    this.isPaused = false; // Pause detection temporarily after clearing
    console.log('[Watchman] Detector created for:', this.platformConfig?.name || 'Unknown');
  }

  getPlatformConfig() {
    const hostname = window.location.hostname;
    console.log('[Watchman] Detecting platform from hostname:', hostname);

    if (hostname.includes('claude.ai')) {
      return {
        name: 'Claude',
        findResponses: () => {
          return Array.from(document.querySelectorAll('.font-claude-response')).filter(el => {
            const text = el.innerText || el.textContent || '';
            return text.trim().length > 50;
          });
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    if (hostname.includes('chatgpt.com') || hostname.includes('openai.com')) {
      return {
        name: 'ChatGPT',
        findResponses: () => {
          let responses = [];
          
          // Helper to find deepest unique containers (avoid parent-child duplicates)
          const findDeepestContainers = (elements) => {
            const filtered = [];
            for (const el of elements) {
              let isAncestor = false;
              for (const other of elements) {
                if (other !== el && el.contains(other)) {
                  isAncestor = true;
                  break;
                }
              }
              if (!isAncestor) filtered.push(el);
            }
            return filtered;
          };
          
          // Primary selector - data attribute (most stable)
          responses = Array.from(document.querySelectorAll('[data-message-author-role="assistant"]'));
          console.log('[Watchman] ChatGPT selector 1 (data-message-author-role):', responses.length);
          
          // Fallback 2: article elements with assistant role
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('article[data-message-author-role="assistant"]'));
            console.log('[Watchman] ChatGPT selector 2 (article[role]):', responses.length);
          }
          
          // Fallback 3: Any element with assistant role in data-testid
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[data-testid*="assistant"], [data-testid*="response"]'));
            console.log('[Watchman] ChatGPT selector 3 (data-testid):', responses.length);
          }
          
          // Fallback 4: Markdown content inside conversation containers
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('div.group .markdown, div[class*="agent-turn"] .markdown'));
            console.log('[Watchman] ChatGPT selector 4 (group markdown):', responses.length);
          }
          
          // Fallback 5: Any markdown prose content in main chat
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('main .prose, main .markdown, [role="presentation"] .prose'));
            console.log('[Watchman] ChatGPT selector 5 (main prose):', responses.length);
          }
          
          // Fallback 6: Message content divs in conversation thread
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="message"] .prose, [class*="message"][class*="text"], div[class*="text-base"]'));
            console.log('[Watchman] ChatGPT selector 6 (message text):', responses.length);
          }
          
          // Fallback 7: Look for conversation turns with substantial content
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="conversation-turn"], [class*="ConversationItem"]'));
            // Filter to only get assistant turns (usually alternate)
            responses = responses.filter((el, index) => index % 2 === 1);
            console.log('[Watchman] ChatGPT selector 7 (conversation turns):', responses.length);
          }
          
          // Final fallback: Any substantial text content in main area
          if (responses.length === 0) {
            const mainContent = document.querySelector('main') || document.querySelector('[role="main"]');
            if (mainContent) {
              responses = Array.from(mainContent.querySelectorAll('div')).filter(el => {
                const text = el.innerText || '';
                return text.length > 100 && !el.querySelector('textarea') && !el.querySelector('input');
              });
              // Take only unique parent elements
              const seen = new Set();
              responses = responses.filter(el => {
                const key = el.innerText?.slice(0, 100);
                if (seen.has(key)) return false;
                seen.add(key);
                return true;
              });
              console.log('[Watchman] ChatGPT selector 8 (main div fallback):', responses.length);
            }
          }
          
          // CRITICAL: Deduplicate - keep only deepest unique containers
          responses = findDeepestContainers(responses);
          console.log('[Watchman] ChatGPT after deduplication:', responses.length);
          
          // Filter out suggestion buttons, prompt chips, and non-response elements
          responses = responses.filter(el => {
            const text = (el.innerText || el.textContent || '').toLowerCase();
            const className = (el.className || '').toLowerCase();
            
            // Skip prompt suggestion buttons (e.g., "Generate a prayer about...")
            if (text.length < 150 && (
              text.includes('generate') ||
              text.includes('write me') ||
              text.includes('help me') ||
              text.includes('create a') ||
              text.includes('tell me')
            )) {
              console.log('[Watchman] ChatGPT: Filtering out suggestion button');
              return false;
            }
            
            // Skip elements that look like buttons or controls
            if (className.includes('button') || 
                className.includes('chip') || 
                className.includes('suggestion') ||
                className.includes('prompt')) {
              console.log('[Watchman] ChatGPT: Filtering out button/chip element');
              return false;
            }
            
            // Require substantial content (actual AI responses)
            return text.length > 100;
          });
          console.log('[Watchman] ChatGPT after filtering suggestions:', responses.length);
          
          return responses;
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    if (hostname.includes('gemini.google.com') || hostname.includes('google.com/generativeai')) {
      return {
        name: 'Gemini',
        findResponses: () => {
          let responses = [];
          console.log('[Watchman] Gemini: Starting response search...');
          
          // Primary: message-content element itself (stable container for badge positioning)
          responses = Array.from(document.querySelectorAll('message-content'));
          // Filter to only include model responses (not user messages)
          responses = responses.filter(el => {
            const text = el.innerText || el.textContent || '';
            // User messages are typically short, model responses are longer
            // Also check if it's inside a model-response container
            const isModel = el.closest('model-response') || el.closest('[class*="model"]') || text.length > 100;
            return isModel;
          });
          console.log('[Watchman] Gemini selector 1 (message-content):', responses.length);
          
          // Fallback 1b: If message-content not found, try the markdown div
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('message-content div.markdown'));
            console.log('[Watchman] Gemini selector 1b (message-content markdown):', responses.length);
          }
          
          // Fallback 2: model-response containers
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('model-response .markdown, .model-response-text, model-response'));
            console.log('[Watchman] Gemini selector 2 (model-response):', responses.length);
          }
          
          // Fallback 3: ms-chat-turn elements (AI Studio style)
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('ms-chat-turn'));
            console.log('[Watchman] Gemini selector 3 (ms-chat-turn):', responses.length);
          }
          
          // Fallback 4: response-content or model-text containers
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="response-content"], [class*="model-text"], [class*="gemini-response"]'));
            console.log('[Watchman] Gemini selector 4 (response-content):', responses.length);
          }
          
          // Fallback 5: markdown-main-panel or markdown class
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('div.markdown-main-panel, .markdown'));
            console.log('[Watchman] Gemini selector 5 (markdown):', responses.length);
          }
          
          // Fallback 6: data-message-id containers
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[data-message-id], [data-turn-id]'));
            console.log('[Watchman] Gemini selector 6 (data-message-id):', responses.length);
          }
          
          // Fallback 7: Generic content scanning in main container
          if (responses.length === 0) {
            const container = document.querySelector('main, [role="main"], article, .chat-container');
            if (container) {
              responses = Array.from(container.querySelectorAll('div, p')).filter(el => {
                const text = el.innerText || '';
                return text.length > 150 && 
                       !el.querySelector('textarea') && 
                       !el.querySelector('input[type="text"]') &&
                       !el.isContentEditable &&
                       el.children.length < 20;
              });
              // Deduplicate by content
              const seen = new Set();
              responses = responses.filter(el => {
                const key = (el.innerText || '').substring(0, 100);
                if (seen.has(key)) return false;
                seen.add(key);
                return true;
              });
              console.log('[Watchman] Gemini selector 7 (main container scan):', responses.length);
            }
          }
          
          // Filter: ensure substantial text
          const filtered = responses.filter(el => {
            const text = el.innerText || el.textContent || '';
            return text.trim().length > 50;
          });
          
          console.log('[Watchman] Gemini: Returning', filtered.length, 'responses');
          if (filtered.length === 0) {
            console.log('[Watchman] Gemini: No responses found. DOM elements:', document.querySelectorAll('*').length);
          }
          
          return findDeepestContainers(filtered);
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    if (hostname.includes('perplexity.ai')) {
      return {
        name: 'Perplexity',
        findResponses: () => {
          let responses = [];
          
          // Primary: data-testid for answer text
          responses = Array.from(document.querySelectorAll('[data-testid="answer-text"]'));
          
          // Fallback: prose/markdown containers in answer sections
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('.prose, .markdown-body, [class*="answer"] .prose'));
          }
          
          // Fallback: answer-content divs
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="AnswerContent"], [class*="answer-content"]'));
          }
          
          // Fallback: message content in thread
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="ThreadMessage"] [class*="prose"], [class*="response-text"]'));
          }
          
          return responses.filter(el => {
            const text = el.innerText || el.textContent || '';
            return text.trim().length > 50;
          });
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    // Grok (X.ai) support - includes grok.com, grok.x.ai
    if (hostname.includes('grok.x.ai') || hostname.includes('grok.com')) {
      return {
        name: 'Grok',
        findResponses: () => {
          let responses = [];
          console.log('[Watchman] Grok: Starting response search...');
          
          // Helper: filter out user messages - checks element and ancestors for user indicators
          const isUserMessage = (el) => {
            const checkEl = (node) => {
              if (!node) return false;
              const className = String(node.className || '').toLowerCase();
              const testId = (node.getAttribute && node.getAttribute('data-testid')) || '';
              const role = (node.getAttribute && node.getAttribute('data-role')) || '';
              if (className.includes('user') || testId.includes('user') || role === 'user') return true;
              // Grok user messages often have a different background or are in a "sent" container
              if (className.includes('sent') || className.includes('human')) return true;
              return false;
            };
            // Check the element itself and up to 5 ancestors
            let node = el;
            for (let i = 0; i < 5 && node; i++) {
              if (checkEl(node)) return true;
              node = node.parentElement;
            }
            return false;
          };
          
          // Primary: Grok message containers - filter out user messages
          const allMessages = Array.from(document.querySelectorAll('[data-testid="grok-message"], [data-testid*="grok-response"], [data-testid="message"]'));
          responses = allMessages.filter(el => !isUserMessage(el));
          console.log('[Watchman] Grok selector 1 (data-testid, filtered):', responses.length, 'of', allMessages.length, 'total');
          
          // Fallback 2: Article/message role containers
          if (responses.length === 0) {
            const articles = Array.from(document.querySelectorAll('article[role="article"], [role="article"]'));
            responses = articles.filter(el => !isUserMessage(el));
            console.log('[Watchman] Grok selector 2 (article role):', responses.length);
          }
          
          // Fallback 3: Class-based grok patterns
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="grok-response"], [class*="GrokMessage"], [class*="grok-text"]'));
            console.log('[Watchman] Grok selector 3 (grok class):', responses.length);
          }
          
          // Fallback 4: AI/assistant response containers
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="assistant"], [class*="ai-response"], [class*="bot-message"]'));
            console.log('[Watchman] Grok selector 4 (assistant/ai):', responses.length);
          }
          
          // Fallback 5: Message containers (filter out user)
          if (responses.length === 0) {
            const allMsgs = Array.from(document.querySelectorAll('[class*="message"], [class*="Message"]'));
            responses = allMsgs.filter(el => {
              const className = String(el.className || '').toLowerCase();
              return !className.includes('user') && !className.includes('input') && !className.includes('send');
            });
            console.log('[Watchman] Grok selector 5 (message filter):', responses.length);
          }
          
          // Fallback 6: Prose/markdown content
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('.prose, .markdown, [class*="prose"], [class*="markdown"]'));
            console.log('[Watchman] Grok selector 6 (prose/markdown):', responses.length);
          }
          
          // Fallback 7: Generic content scan - find substantial text blocks
          if (responses.length === 0) {
            const container = document.querySelector('main, [role="main"], #root, .app, body');
            if (container) {
              const allDivs = Array.from(container.querySelectorAll('div, p, span'));
              responses = allDivs.filter(el => {
                const text = el.innerText || '';
                const className = String(el.className || '').toLowerCase();
                return text.length > 150 && 
                       text.length < 15000 &&
                       !el.querySelector('textarea, input[type="text"]') &&
                       !el.isContentEditable &&
                       !className.includes('input') &&
                       !className.includes('sidebar') &&
                       !className.includes('nav') &&
                       !className.includes('header') &&
                       el.children.length < 30;
              });
              // Deduplicate by content
              const seen = new Set();
              responses = responses.filter(el => {
                const key = (el.innerText || '').substring(0, 100);
                if (seen.has(key)) return false;
                seen.add(key);
                return true;
              });
              console.log('[Watchman] Grok selector 7 (container scan):', responses.length);
            }
          }
          
          // Filter: ensure substantial text
          const filtered = responses.filter(el => {
            const text = el.innerText || el.textContent || '';
            return text.trim().length > 50;
          });
          
          console.log('[Watchman] Grok: Returning', filtered.length, 'responses');
          if (filtered.length === 0) {
            console.log('[Watchman] Grok: No responses found. DOM elements:', document.querySelectorAll('*').length);
          }
          
          return findDeepestContainers(filtered);
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    if (hostname.includes('copilot.microsoft.com')) {
      return {
        name: 'Copilot',
        findResponses: () => {
          let responses = [];
          
          // Helper to get text from shadow DOM
          const getDeepText = (el) => {
            let text = el.innerText || el.textContent || '';
            if (el.shadowRoot) {
              text += Array.from(el.shadowRoot.querySelectorAll('*'))
                .map(child => child.innerText || child.textContent || '')
                .join(' ');
            }
            return text;
          };
          
          // Primary: Look for response containers in Copilot's structure
          // Copilot 2024+ uses data attributes and specific classes
          // Updated Jan 2026 for new Copilot structure
          responses = Array.from(document.querySelectorAll('[data-content="ai-message"], [class*="response-message"], [class*="bot-response"], .ac-textBlock, [class*="ac-container"], [class*="message-content"]'));
          console.log('[Watchman] Copilot selector 1:', responses.length);
          
          // Try paragraph elements inside response areas
          if (responses.length === 0) {
            document.querySelectorAll('div[class*="message"] p, div[class*="response"] p, [class*="text-message-content"] p').forEach(el => {
              const text = el.innerText || el.textContent || '';
              if (text.length > 30) {
                responses.push(el.closest('div[class*="message"]') || el.closest('div[class*="response"]') || el);
              }
            });
            console.log('[Watchman] Copilot selector 1b (paragraphs):', responses.length);
          }
          
          // Fallback: cib- prefixed custom elements (older Bing/Copilot)
          if (responses.length === 0) {
            document.querySelectorAll('cib-message-group, cib-message, cib-chat-turn').forEach(el => {
              const source = el.getAttribute('source');
              if (source === 'bot' || !source) {
                // Try to get content from shadow root
                if (el.shadowRoot) {
                  const content = el.shadowRoot.querySelector('.content, .message-content, [class*="content"]');
                  if (content) responses.push(content);
                } else {
                  responses.push(el);
                }
              }
            });
            console.log('[Watchman] Copilot selector 2 (cib):', responses.length);
          }
          
          // Fallback: WebChat bubble elements
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('.webchat__bubble:not(.webchat__bubble--from-user) .webchat__bubble__content'));
            console.log('[Watchman] Copilot selector 3 (webchat):', responses.length);
          }
          
          // Fallback: Generic AI response containers
          if (responses.length === 0) {
            document.querySelectorAll('div[class*="message"], div[class*="response"], [class*="assistant"]').forEach(el => {
              try {
                const className = String(el.className || '').toLowerCase();
                const text = getDeepText(el);
                if (!className.includes('user') && !className.includes('input') && text.length > 50) {
                  responses.push(el);
                }
              } catch (e) {}
            });
            console.log('[Watchman] Copilot selector 4 (generic):', responses.length);
          }
          
          // Fallback: Sydney/Bing chat specific elements
          if (responses.length === 0) {
            responses = Array.from(document.querySelectorAll('[class*="bot-response"], [class*="assistant-message"], [data-content="ai-message"]'));
          }
          
          return responses.filter(el => {
            const text = el.innerText || el.textContent || '';
            return text.trim().length > 50;
          });
        },
        getText: (el) => el.innerText || el.textContent
      };
    }

    return {
      name: 'Unknown',
      findResponses: () => [],
      getText: (el) => el.innerText || el.textContent
    };
  }

  init() {
    console.log('[Watchman] Initializing for', this.platformConfig.name);
    this.injectStyles();
    console.log('[Watchman] Styles injected');
    this.startDetection();
    console.log('[Watchman] Detector initialized successfully');
  }

  startDetection() {
    console.log('[Watchman] Starting detection');
    this.checkForResponses();
    setInterval(() => this.checkForResponses(), 1000);
    
    const observer = new MutationObserver(() => {
      const now = Date.now();
      if (now - this.lastCheckTime > this.checkInterval) {
        this.checkForResponses();
        this.lastCheckTime = now;
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
      characterData: false
    });
  }

  checkForResponses() {
    // Skip detection if paused (after clearing)
    if (this.isPaused) {
      return;
    }
    
    const responses = this.platformConfig.findResponses();
    console.log('[Watchman] Found', responses.length, 'potential responses');

    responses.forEach(el => {
      // Skip elements that were permanently ignored (existed before last clear)
      if (this.ignoredElements.has(el)) {
        return;
      }
      
      // Use a more unique identifier that includes actual content
      const text = el.innerText || el.textContent || '';
      const key = text.substring(0, 100) + text.length; // First 100 chars + length for uniqueness
      
      // Skip if this text content was cleared/ignored (survives DOM re-renders like in Gemini)
      if (this.ignoredTextKeys.has(key)) {
        return;
      }
      
      if (!this.observedResponses.has(key)) {
        this.observedResponses.add(key);
        console.log('[Watchman] New response detected, processing...');
        this.processResponse(el);
      } else {
        // Re-apply highlights if they were removed by platform re-rendering (Gemini does this)
        const indicator = el.querySelector('.watchman-indicator');
        if (indicator && !el.querySelector('.watchman-highlight')) {
          try {
            const storedFindings = JSON.parse(indicator.dataset.findings || '[]');
            if (storedFindings.length > 0) {
              console.log('[Watchman] Re-applying highlights (removed by platform re-render)');
              this.highlightFlaggedText(el, storedFindings);
            }
          } catch (e) {}
        }
      }
    });
  }

  processResponse(el) {
    try {
      // Fix #1: Skip if this element is the Watchman sidebar itself
      if (el.id === 'watchman-sidebar' || el.closest('#watchman-sidebar')) {
        console.log('[Watchman] Skipping Watchman sidebar content');
        return;
      }
      
      const text = this.platformConfig.getText(el);
      if (!text || text.trim().length === 0) {
        console.log('[Watchman] Response too short, skipping');
        return;
      }
      
      // Fix #4: Debug logging - show first 200 chars
      console.log('[Watchman] Processing response (', text.length, 'chars)');
      console.log('[Watchman] First 200 chars:', text.substring(0, 200));
      const findings = this.auditText(text);
      console.log('[Watchman] Found', findings.length, 'theological concerns');
      
      if (findings.length > 0) {
        this.displayIndicator(el, findings);
      } else {
        // Show green "reviewed - no issues" indicator
        this.displayClearIndicator(el);
      }
    } catch (error) {
      console.error('[Watchman] Error processing response:', error);
    }
  }

  displayClearIndicator(el) {
    try {
      // Skip if already has any watchman indicator
      if (el.querySelector('.watchman-indicator') || el.querySelector('.watchman-clear-indicator')) {
        return;
      }
      
      // Create green checkmark indicator
      const indicator = document.createElement('div');
      indicator.className = 'watchman-clear-indicator';
      indicator.innerHTML = '✓';
      indicator.title = 'Watchman reviewed - no theological concerns detected';
      indicator.style.cssText = `
        position: absolute !important;
        top: 8px !important;
        right: 8px !important;
        width: 24px !important;
        height: 24px !important;
        background: #22C55E !important;
        border-radius: 50% !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        font-size: 14px !important;
        color: white !important;
        font-weight: bold !important;
        z-index: 99998 !important;
        box-shadow: 0 2px 8px rgba(34, 197, 94, 0.4) !important;
        cursor: default !important;
        opacity: 0.8 !important;
        transition: opacity 0.2s !important;
      `;
      
      // Fade slightly on hover to be less intrusive
      indicator.addEventListener('mouseenter', () => {
        indicator.style.opacity = '1';
      });
      indicator.addEventListener('mouseleave', () => {
        indicator.style.opacity = '0.8';
      });
      
      // Ensure parent has relative positioning
      const computedPosition = window.getComputedStyle(el).position;
      if (computedPosition === 'static') {
        el.style.position = 'relative';
      }
      el.style.overflow = 'visible';
      
      let parent = el.parentElement;
      for (let i = 0; i < 3 && parent; i++) {
        const parentOverflow = window.getComputedStyle(parent).overflow;
        if (parentOverflow === 'hidden') {
          parent.style.overflow = 'visible';
        }
        parent = parent.parentElement;
      }
      
      el.appendChild(indicator);
      el.setAttribute('data-watchman-processed', 'true');
      console.log('[Watchman] Green clear indicator added - no concerns found');
    } catch (error) {
      console.error('[Watchman] Error displaying clear indicator:', error);
    }
  }

  auditText(text) {
    const findings = [];
    const seenRules = new Set();
    
    // Fix #2: Safety check - Don't audit Watchman's own content
    if (text.includes('THEOLOGY_RULES') || text.includes('Watchman Audit') || text.includes('📝 DETECTED TEXT:')) {
      console.log('[Watchman] Skipping Watchman internal content');
      return findings;
    }
    
    THEOLOGY_RULES.forEach(rule => {
      // Skip if we already found this rule
      if (seenRules.has(rule.name)) {
        return;
      }
      
      // Check if ANY pattern in this rule matches and capture the match
      let ruleMatched = false;
      let matchedExcerpt = '';
      let matchedRawText = '';
      
      for (let pattern of rule.patterns) {
        const match = text.match(pattern);
        if (match) {
          // Find the position of the match in the original text
          const matchIndex = text.indexOf(match[0]);
          
          // NEGATION DETECTION: Check for negation words before the match
          // Look at up to 50 characters before the match for context
          const precedingStart = Math.max(0, matchIndex - 50);
          const precedingText = text.substring(precedingStart, matchIndex).toLowerCase();
          
          // Negation patterns to detect orthodox refutations
          const negationPatterns = [
            /\bnot\s*$/i,                          // "NOT all paths..."
            /\bno\s*$/i,                           // "no, all paths..."
            /\bnever\s*$/i,                        // "never all paths..."
            /\bdoesn['']?t\s+(mean|say|teach|claim|believe|hold|affirm|support|suggest)\s+that\s*$/i,
            /\bisn['']?t\s+(true|correct|accurate|right)\s+(that|to say)\s*$/i,
            /\baren['']?t\s*$/i,
            /\bdon['']?t\s+(believe|think|agree|accept|teach|affirm|hold)\s+(that\s+)?$/i,
            /\bwouldn['']?t\s+(say|agree|affirm|accept)\s+(that\s+)?$/i,
            /\bwrong\s+to\s+(say|think|believe|claim)\s+(that\s+)?$/i,
            /\bfalse\s+(that|to say|claim)\s*$/i,
            /\bincorrect\s+(that|to say|claim)\s*$/i,
            /\bdenies?\s+(that\s+)?$/i,
            /\brejects?\s+(the\s+(idea|notion|claim|view)\s+that\s+)?$/i,
            /\brefutes?\s+(the\s+(idea|notion|claim|view)\s+that\s+)?$/i,
            /\bcontradicts?\s+(the\s+(idea|notion|claim|view)\s+that\s+)?$/i,
            /\bopposes?\s+(the\s+(idea|notion|claim|view)\s+that\s+)?$/i,
            /\bit['']?s\s+(false|wrong|incorrect|untrue)\s+(that|to say)\s*$/i,
            /\bthis\s+is\s+(false|wrong|incorrect|untrue|not true)[:\s]*$/i,
            /\bthe\s+bible\s+(rejects|denies|refutes|contradicts|opposes)\s+(the\s+(idea|claim)\s+that\s+)?$/i,
            /\bchristians?\s+(reject|deny|oppose|disagree with)\s+(the\s+(idea|claim|view)\s+that\s+)?$/i,
            /\bscripture\s+(rejects|denies|teaches against|contradicts)\s+(the\s+(idea|claim)\s+that\s+)?$/i,
            /\bcontrary\s+to\s+(what\s+some\s+(say|believe|claim),?\s*)?$/i,
            /\bunlike\s+the\s+(claim|idea|belief)\s+that\s*$/i
          ];
          
          // Check if any negation pattern precedes the match
          let isNegated = false;
          for (const negPattern of negationPatterns) {
            if (negPattern.test(precedingText)) {
              isNegated = true;
              console.log('[Watchman] Negation detected before match:', precedingText.trim(), '| Pattern:', rule.name);
              break;
            }
          }
          
          // Skip this match if it's negated (orthodox refutation of bad theology)
          if (isNegated) {
            console.log('[Watchman] Skipping negated statement (orthodox refutation)');
            continue; // Try next pattern in this rule
          }
          
          ruleMatched = true;
          
          // Store the raw matched text for in-chat highlighting
          matchedRawText = match[0];
          
          // Extract surrounding context (100 chars before and after for better clarity)
          const contextStart = Math.max(0, matchIndex - 100);
          const contextEnd = Math.min(text.length, matchIndex + match[0].length + 100);
          
          // Get the excerpt with context
          let excerpt = text.substring(contextStart, contextEnd);
          
          // Clean up whitespace for readability
          excerpt = excerpt.replace(/\s+/g, ' ').trim();
          
          // Add ellipsis if we truncated
          if (contextStart > 0) excerpt = '...' + excerpt;
          if (contextEnd < text.length) excerpt = excerpt + '...';
          
          // Highlight the actual matched text within the excerpt
          const matchedText = match[0];
          excerpt = excerpt.replace(matchedText, `**${matchedText}**`);
          
          matchedExcerpt = excerpt;
          break; // Found a match, no need to check other patterns for this rule
        }
      }
      
      // Add finding only once per rule, with the excerpt
      if (ruleMatched) {
        seenRules.add(rule.name);
        console.log('[Watchman] Match found for rule:', rule.name, '| Category:', rule.category, '| Excerpt length:', matchedExcerpt.length);
        findings.push({
          rule: rule.name,
          charter: rule.charter,
          category: rule.category || 'primary',
          tier: rule.tier || 'call_to_discernment',
          severity: rule.severity,
          scripture: rule.scripture,
          explanation: rule.explanation || '',
          prompt: rule.prompt || '',
          excerpt: matchedExcerpt,
          matchedText: matchedRawText, // Raw text for in-chat highlighting
          timestamp: new Date().toISOString()
        });
      }
    });
    
    return findings;
  }

  // Highlight flagged text directly in the chat response
  highlightFlaggedText(el, findings) {
    try {
      // Skip if already highlighted
      if (el.querySelector('.watchman-highlight')) {
        return;
      }
      
      findings.forEach(finding => {
        if (!finding.matchedText || finding.matchedText.length < 3) return;
        
        // Get severity color
        const highlightColor = finding.severity === 'critical' ? 'rgba(220, 38, 38, 0.3)' : 
                               finding.severity === 'high' ? 'rgba(245, 158, 11, 0.3)' : 
                               'rgba(234, 179, 8, 0.25)';
        const borderColor = finding.severity === 'critical' ? '#DC2626' : 
                            finding.severity === 'high' ? '#F59E0B' : '#EAB308';
        
        // Walk through all text nodes in the element
        const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
        const nodesToProcess = [];
        
        while (walker.nextNode()) {
          const node = walker.currentNode;
          const nodeText = node.textContent;
          
          // Case-insensitive search for the matched text
          const lowerNodeText = nodeText.toLowerCase();
          const lowerMatchedText = finding.matchedText.toLowerCase();
          const index = lowerNodeText.indexOf(lowerMatchedText);
          
          if (index !== -1) {
            nodesToProcess.push({ node, index, matchedText: finding.matchedText, highlightColor, borderColor });
          }
        }
        
        // Process nodes (reverse order to preserve indices)
        nodesToProcess.reverse().forEach(({ node, index, matchedText, highlightColor, borderColor }) => {
          try {
            const parent = node.parentNode;
            // Skip if parent is already a highlight or is a script/style
            if (!parent || parent.classList?.contains('watchman-highlight') || 
                parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE') {
              return;
            }
            
            const text = node.textContent;
            const actualMatchedText = text.substring(index, index + matchedText.length);
            
            // Create before, highlight, and after nodes
            const before = document.createTextNode(text.substring(0, index));
            const after = document.createTextNode(text.substring(index + matchedText.length));
            
            const highlight = document.createElement('span');
            highlight.className = 'watchman-highlight';
            highlight.textContent = actualMatchedText;
            highlight.style.cssText = `
              background: ${highlightColor} !important;
              border-bottom: 2px solid ${borderColor} !important;
              padding: 1px 3px !important;
              border-radius: 3px !important;
              cursor: help !important;
            `;
            highlight.title = `Watchman Flag: ${finding.rule} - ${finding.explanation}`;
            
            // Replace the text node with our highlighted version
            parent.insertBefore(before, node);
            parent.insertBefore(highlight, node);
            parent.insertBefore(after, node);
            parent.removeChild(node);
            
            console.log('[Watchman] Highlighted text in chat:', actualMatchedText.substring(0, 50) + '...');
          } catch (err) {
            console.log('[Watchman] Could not highlight node:', err.message);
          }
        });
      });
    } catch (error) {
      console.error('[Watchman] Error highlighting text:', error);
    }
  }

  displayIndicator(el, findings) {
    try {
      // Don't check for processed flag - let checkForResponses handle duplicates
      
      const color = getBadgeColor(findings);
      
      // ============================================================
      // HIGHLIGHT FLAGGED TEXT IN THE CHAT
      // ============================================================
      this.highlightFlaggedText(el, findings);
      
      // ============================================================
      // ADD PER-RESPONSE INDICATOR (red circle with count)
      // ============================================================
      // If a green clear indicator exists but we now have findings, REPLACE it
      const existingClear = el.querySelector('.watchman-clear-indicator');
      if (existingClear) {
        console.log('[Watchman] Replacing green clear indicator with severity badge (streaming update)');
        existingClear.remove();
      }
      // Also update existing flagged indicator if findings changed
      const existingFlagged = el.querySelector('.watchman-indicator');
      if (existingFlagged) {
        existingFlagged.innerHTML = findings.length.toString();
        existingFlagged.dataset.findings = JSON.stringify(findings);
        existingFlagged.style.background = `${color} !important`;
        const hexToRgbUpdate = (hex) => {
          const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
          return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : '220, 38, 38';
        };
        existingFlagged.dataset.colorRgb = hexToRgbUpdate(color);
        console.log('[Watchman] Updated existing indicator with new findings count:', findings.length);
      }
      if (!el.querySelector('.watchman-indicator')) {
        const localIndicator = document.createElement('div');
        localIndicator.className = 'watchman-indicator';
        localIndicator.innerHTML = findings.length.toString();
        localIndicator.title = `${findings.length} theological concern(s) detected. Click to review.`;
        
        // Convert hex color to RGB for box-shadow
        const hexToRgb = (hex) => {
          const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
          return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : '220, 38, 38';
        };
        const colorRgb = hexToRgb(color);
        
        localIndicator.style.cssText = `
          position: absolute !important;
          top: 8px !important;
          right: 8px !important;
          min-width: 24px !important;
          height: 24px !important;
          padding: 0 6px !important;
          background: ${color} !important;
          border-radius: 12px !important;
          display: flex !important;
          align-items: center !important;
          justify-content: center !important;
          font-size: 13px !important;
          color: white !important;
          font-weight: bold !important;
          z-index: 99998 !important;
          box-shadow: 0 2px 8px rgba(${colorRgb}, 0.5) !important;
          cursor: pointer !important;
          transition: all 0.2s !important;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
        `;
        
        // Store findings data and color on the indicator for later retrieval
        localIndicator.dataset.findings = JSON.stringify(findings);
        localIndicator.dataset.colorRgb = colorRgb;
        
        // Click to show this response's findings in sidebar
        localIndicator.addEventListener('click', (e) => {
          e.stopPropagation();
          const responseFindings = JSON.parse(localIndicator.dataset.findings || '[]');
          console.log('[Watchman] Per-response badge clicked with', responseFindings.length, 'findings');
          this.showDetails(responseFindings, this);
        });
        
        // Hover effects - use stored color
        localIndicator.addEventListener('mouseenter', () => {
          const rgb = localIndicator.dataset.colorRgb;
          localIndicator.style.transform = 'scale(1.15)';
          localIndicator.style.boxShadow = `0 4px 12px rgba(${rgb}, 0.7)`;
        });
        localIndicator.addEventListener('mouseleave', () => {
          const rgb = localIndicator.dataset.colorRgb;
          localIndicator.style.transform = 'scale(1)';
          localIndicator.style.boxShadow = `0 2px 8px rgba(${rgb}, 0.5)`;
        });
        
        // Ensure parent has relative positioning and visible overflow
        const computedPosition = window.getComputedStyle(el).position;
        if (computedPosition === 'static') {
          el.style.position = 'relative';
        }
        el.style.overflow = 'visible';
        
        // Also fix overflow on parent chain (ChatGPT uses overflow:hidden on containers)
        let parent = el.parentElement;
        for (let i = 0; i < 3 && parent; i++) {
          const parentOverflow = window.getComputedStyle(parent).overflow;
          if (parentOverflow === 'hidden') {
            parent.style.overflow = 'visible';
          }
          parent = parent.parentElement;
        }
        
        el.appendChild(localIndicator);
        el.setAttribute('data-watchman-processed', 'true');
        console.log('[Watchman] Per-response indicator added with', findings.length, 'concerns');
      }
      
    } catch (error) {
      console.error('[Watchman] Error displaying indicator:', error);
    }
  }

  showDetails(findings, detectorInstance) {
    const existing = document.getElementById('watchman-sidebar');
    if (existing) {
      console.log('[Watchman] Sidebar already open, closing it');
      existing.remove();
      return;
    }
    
    console.log('[Watchman] Opening sidebar with', findings.length, 'findings');
    const sidebar = document.createElement('div');
    sidebar.id = 'watchman-sidebar';
    sidebar.style.cssText = `
      position: fixed;
      right: 0;
      top: 0;
      width: 480px;
      height: 100vh;
      background: linear-gradient(180deg, #1F2937 0%, #263044 50%, #1F2937 100%);
      border-left: 2px solid #B8860B;
      box-shadow: -4px 0 24px rgba(0, 0, 0, 0.4);
      z-index: 999998;
      overflow-y: auto;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      color: #E2E8F0;
      scrollbar-width: thin;
      scrollbar-color: #475569 transparent;
    `;
    
    // Header
    const header = document.createElement('div');
    header.style.cssText = `
      padding: 20px 24px;
      border-bottom: 1px solid rgba(184, 134, 11, 0.3);
      background: linear-gradient(135deg, #1F2937 0%, #232D3B 100%);
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 10;
    `;
    
    const title = document.createElement('h2');
    title.textContent = '🛡️ Watchman Audit';
    title.style.cssText = 'margin: 0; font-size: 20px; font-weight: bold; color: #D4A94D;';
    
    const closeBtn = document.createElement('button');
    closeBtn.textContent = '✕';
    closeBtn.style.cssText = `
      background: none;
      border: none;
      color: #fff;
      font-size: 28px;
      cursor: pointer;
      padding: 0;
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      transition: background 0.2s;
    `;
    closeBtn.addEventListener('mouseenter', () => {
      closeBtn.style.background = 'rgba(255,255,255,0.1)';
    });
    closeBtn.addEventListener('mouseleave', () => {
      closeBtn.style.background = 'none';
    });
    closeBtn.addEventListener('click', () => {
      console.log('[Watchman] X button clicked, closing sidebar');
      sidebar.remove();
      console.log('[Watchman] Sidebar closed - click badge to reopen');
    });
    
    header.appendChild(title);
    header.appendChild(closeBtn);
    sidebar.appendChild(header);
    
    // Container
    const container = document.createElement('div');
    container.style.cssText = 'padding: 24px;';
    
    // Summary with improved color breakdown - including Primary vs Additional counts
    const summary = document.createElement('div');
    const primaryFindings = findings.filter(f => f.category === 'primary');
    const additionalFindings = findings.filter(f => f.category === 'additional');
    const criticalCount = findings.filter(f => f.severity === 'critical').length;
    const highCount = findings.filter(f => f.severity === 'high').length;
    const mediumCount = findings.filter(f => f.severity === 'medium').length;
    const lowCount = findings.filter(f => f.severity === 'low').length;
    
    // Determine summary border color based on highest severity
    const summaryColor = getBadgeColor(findings);
    
    summary.style.cssText = `
      background: rgba(30, 41, 59, 0.5);
      border: 1px solid rgba(184, 134, 11, 0.3);
      border-radius: 14px;
      padding: 24px;
      margin-bottom: 28px;
    `;
    summary.innerHTML = `
      <div style="font-weight: bold; margin-bottom: 18px; color: #F8FAFC; font-size: 20px; display: flex; align-items: center; gap: 10px;">
        <span style="font-size: 24px;">📊</span> ${findings.length} Concern${findings.length !== 1 ? 's' : ''} Found
      </div>
      <div style="display: flex !important; gap: 14px !important; margin-bottom: 16px !important;">
        <div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 8px 14px !important; background: rgba(220, 38, 38, 0.15) !important; border-radius: 8px !important; border: 1px solid #DC2626 !important;">
          <span style="font-size: 16px !important; color: inherit !important;">📜</span>
          <span style="color: #F87171 !important; font-weight: bold !important; font-size: 16px !important;">${primaryFindings.length}</span>
          <span style="color: #F1F5F9 !important; font-size: 13px !important;">Primary</span>
        </div>
        <div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 8px 14px !important; background: rgba(139, 92, 246, 0.15) !important; border-radius: 8px !important; border: 1px solid #8B5CF6 !important;">
          <span style="font-size: 16px !important; color: inherit !important;">🤖</span>
          <span style="color: #A78BFA !important; font-weight: bold !important; font-size: 16px !important;">${additionalFindings.length}</span>
          <span style="color: #F1F5F9 !important; font-size: 13px !important;">AI-Specific</span>
        </div>
      </div>
      <div style="display: grid !important; grid-template-columns: repeat(2, 1fr) !important; gap: 10px !important; font-size: 14px !important;">
        ${criticalCount > 0 ? `<div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 10px 14px !important; background: ${SEVERITY_COLORS.critical.background} !important; border-radius: 8px !important; border-left: 3px solid ${SEVERITY_COLORS.critical.primary} !important;">
          <span style="color: ${SEVERITY_COLORS.critical.primary} !important; font-weight: bold !important; font-size: 16px !important;">${criticalCount}</span>
          <span style="color: #F1F5F9 !important;">Critical</span>
        </div>` : ''}
        ${highCount > 0 ? `<div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 10px 14px !important; background: ${SEVERITY_COLORS.high.background} !important; border-radius: 8px !important; border-left: 3px solid ${SEVERITY_COLORS.high.primary} !important;">
          <span style="color: ${SEVERITY_COLORS.high.primary} !important; font-weight: bold !important; font-size: 16px !important;">${highCount}</span>
          <span style="color: #F1F5F9 !important;">High</span>
        </div>` : ''}
        ${mediumCount > 0 ? `<div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 10px 14px !important; background: ${SEVERITY_COLORS.medium.background} !important; border-radius: 8px !important; border-left: 3px solid ${SEVERITY_COLORS.medium.primary} !important;">
          <span style="color: ${SEVERITY_COLORS.medium.primary} !important; font-weight: bold !important; font-size: 16px !important;">${mediumCount}</span>
          <span style="color: #F1F5F9 !important;">Medium</span>
        </div>` : ''}
        ${lowCount > 0 ? `<div style="display: flex !important; align-items: center !important; gap: 8px !important; padding: 10px 14px !important; background: ${SEVERITY_COLORS.low.background} !important; border-radius: 8px !important; border-left: 3px solid ${SEVERITY_COLORS.low.primary} !important;">
          <span style="color: ${SEVERITY_COLORS.low.primary} !important; font-weight: bold !important; font-size: 16px !important;">${lowCount}</span>
          <span style="color: #F1F5F9 !important;">Info</span>
        </div>` : ''}
      </div>
    `;
    container.appendChild(summary);
    
    // Info message
    const infoBox = document.createElement('div');
    infoBox.style.cssText = `
      background: rgba(123, 167, 217, 0.08);
      border-left: 3px solid rgba(123, 167, 217, 0.4);
      padding: 16px 18px;
      border-radius: 8px;
      margin-bottom: 28px;
      font-size: 13px;
      color: #B8CCE0;
      line-height: 1.7;
    `;
    infoBox.innerHTML = `
      <strong style="color: #D0E0F0;">ℹ️ What This Means:</strong><br>
      These flags indicate theological discussions requiring discernment. 
      Review the highlighted text and compare with Scripture.
    `;
    container.appendChild(infoBox);
    
    // Helper function to create finding cards
    const createFindingCard = (finding, index, categoryColor) => {
      const card = document.createElement('div');
      const style = getSeverityStyle(finding.severity);
      
      card.style.cssText = `
        background: ${style.background};
        border-left: 4px solid ${style.border};
        border-radius: 12px;
        padding: 22px 24px;
        margin-bottom: 20px;
        transition: all 0.2s;
        box-shadow: 0 2px 6px rgba(0,0,0,0.2);
      `;
      
      const headerDiv = document.createElement('div');
      headerDiv.style.cssText = 'display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;';
      
      const concernNumber = document.createElement('div');
      concernNumber.textContent = `CONCERN #${index + 1}`;
      concernNumber.style.cssText = 'font-size: 11px; color: #94A3B8; text-transform: uppercase; letter-spacing: 1.5px; font-weight: 700;';
      
      const severityBadge = document.createElement('span');
      severityBadge.textContent = style.label;
      severityBadge.style.cssText = `
        background: ${style.primary}30;
        color: ${style.primary};
        padding: 5px 14px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 700;
        letter-spacing: 0.8px;
        border: 1px solid ${style.primary}50;
      `;
      
      headerDiv.appendChild(concernNumber);
      headerDiv.appendChild(severityBadge);
      card.appendChild(headerDiv);
      
      // Rule name (charter point)
      const ruleName = document.createElement('div');
      ruleName.textContent = finding.rule;
      ruleName.style.cssText = `
        font-weight: 700;
        color: #F1F5F9;
        margin-bottom: 12px;
        font-size: 16px;
        line-height: 1.4;
      `;
      card.appendChild(ruleName);
      
      // Charter principle
      const charter = document.createElement('div');
      charter.textContent = finding.charter;
      charter.style.cssText = `
        font-size: 14px;
        color: #B0BECE;
        margin-bottom: 18px;
        line-height: 1.75;
        padding-left: 14px;
        border-left: 3px solid ${style.primary}30;
      `;
      card.appendChild(charter);
      
      // Matched text excerpt
      if (finding.excerpt && finding.excerpt.trim().length > 0) {
        const excerptBox = document.createElement('div');
        excerptBox.style.cssText = `
          background: rgba(15, 23, 42, 0.35);
          border-left: 3px solid ${style.primary}60;
          padding: 16px 18px;
          border-radius: 8px;
          margin: 16px 0;
          font-size: 14px;
          color: #D0D8E4;
          font-style: italic;
          line-height: 1.75;
        `;
        
        const formattedExcerpt = finding.excerpt.replace(/\*\*(.*?)\*\*/g, `<strong style="color: #F1F5F9; background: ${style.primary}35; padding: 2px 8px; border-radius: 4px; font-style: normal;">$1</strong>`);
        
        excerptBox.innerHTML = `
          <div style="font-size: 11px; color: #94A3B8; text-transform: uppercase; margin-bottom: 10px; font-style: normal; letter-spacing: 0.8px; font-weight: 600;">
            📝 Detected Text
          </div>
          ${formattedExcerpt}
        `;
        card.appendChild(excerptBox);
      }
      
      // Explanation
      if (finding.explanation) {
        const explanationBox = document.createElement('div');
        explanationBox.style.cssText = `
          font-size: 13px;
          color: #A0B0C4;
          margin-bottom: 16px;
          line-height: 1.75;
        `;
        explanationBox.innerHTML = `<strong style="color: #C0CEDC;">Why This Matters:</strong> ${finding.explanation}`;
        card.appendChild(explanationBox);
      }
      
      // Scripture reference
      if (finding.scripture) {
        const scriptureBox = document.createElement('div');
        scriptureBox.style.cssText = `
          background: rgba(34, 197, 94, 0.08);
          border: 1px solid rgba(34, 197, 94, 0.2);
          padding: 16px 18px;
          border-radius: 10px;
          margin-top: 16px;
          font-size: 14px;
          line-height: 1.75;
        `;
        scriptureBox.innerHTML = `
          <div style="color: #6DCFA0; font-weight: 700; margin-bottom: 8px; font-size: 13px;">📖 Scripture</div>
          <div style="color: #A0E8C0; font-style: italic;">${finding.scripture}</div>
        `;
        card.appendChild(scriptureBox);
      }
      
      // Discernment prompt
      if (finding.prompt) {
        const promptBox = document.createElement('div');
        promptBox.style.cssText = `
          background: rgba(123, 167, 217, 0.08);
          border-left: 3px solid rgba(123, 167, 217, 0.35);
          padding: 16px 18px;
          border-radius: 0 10px 10px 0;
          margin-top: 16px;
          font-size: 13px;
          color: #A0C0E0;
          line-height: 1.75;
        `;
        promptBox.innerHTML = `<strong style="color: #B8D4F0;">💭 Discernment Prompt:</strong> ${finding.prompt}`;
        card.appendChild(promptBox);
      }
      
      return card;
    };
    
    // Display PRIMARY AUDIT section (Points 1-15)
    if (primaryFindings.length > 0) {
      const primarySection = document.createElement('div');
      primarySection.style.cssText = `
        background: rgba(224, 112, 112, 0.04);
        border: 1px solid rgba(224, 112, 112, 0.2);
        border-radius: 14px;
        padding: 20px;
        margin-bottom: 24px;
      `;
      
      const primaryHeader = document.createElement('div');
      primaryHeader.style.cssText = 'display: flex; align-items: center; gap: 12px; margin-bottom: 20px; padding-bottom: 16px; border-bottom: 1px solid rgba(224, 112, 112, 0.2);';
      primaryHeader.innerHTML = `
        <span style="font-size: 22px;">📜</span>
        <div>
          <div style="font-weight: 700; color: #F0B0B0; font-size: 16px;">Primary Theological Audit</div>
          <div style="font-size: 12px; color: #94A3B8; margin-top: 4px;">Charter Points 1-15: Core Doctrine</div>
        </div>
        <div style="margin-left: auto; background: rgba(224, 112, 112, 0.25); color: #F0B0B0; padding: 6px 14px; border-radius: 12px; font-size: 14px; font-weight: 700; border: 1px solid rgba(224, 112, 112, 0.4);">${primaryFindings.length}</div>
      `;
      primarySection.appendChild(primaryHeader);
      
      primaryFindings.forEach((finding, index) => {
        primarySection.appendChild(createFindingCard(finding, index, '#DC2626'));
      });
      
      container.appendChild(primarySection);
    }
    
    // Display ADDITIONAL AUDIT section (Points 16-19) with purple color
    if (additionalFindings.length > 0) {
      const additionalSection = document.createElement('div');
      additionalSection.style.cssText = `
        background: rgba(139, 92, 246, 0.04);
        border: 1px solid rgba(139, 92, 246, 0.2);
        border-radius: 14px;
        padding: 20px;
        margin-bottom: 24px;
      `;
      
      const additionalHeader = document.createElement('div');
      additionalHeader.style.cssText = 'display: flex; align-items: center; gap: 12px; margin-bottom: 20px; padding-bottom: 16px; border-bottom: 1px solid rgba(139, 92, 246, 0.2);';
      additionalHeader.innerHTML = `
        <span style="font-size: 22px;">🤖</span>
        <div>
          <div style="font-weight: 700; color: #C0B0F0; font-size: 16px;">Additional AI-Specific Audit</div>
          <div style="font-size: 12px; color: #94A3B8; margin-top: 4px;">Charter Points 16-19: Formational Guardrails</div>
        </div>
        <div style="margin-left: auto; background: rgba(139, 92, 246, 0.25); color: #C0B0F0; padding: 6px 14px; border-radius: 12px; font-size: 14px; font-weight: 700; border: 1px solid rgba(139, 92, 246, 0.4);">${additionalFindings.length}</div>
      `;
      additionalSection.appendChild(additionalHeader);
      
      additionalFindings.forEach((finding, index) => {
        additionalSection.appendChild(createFindingCard(finding, index, '#8B5CF6'));
      });
      
      container.appendChild(additionalSection);
    }
    
    // Legacy fallback - if no category assigned, show old way
    const uncategorizedFindings = findings.filter(f => !f.category);
    uncategorizedFindings.forEach((finding, index) => {
      const card = document.createElement('div');
      const style = getSeverityStyle(finding.severity);
      
      card.style.cssText = `
        background: ${style.background};
        border-left: 3px solid ${style.border};
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 18px;
        transition: all 0.2s;
        box-shadow: 0 1px 4px rgba(0,0,0,0.15);
      `;
      
      // Concern number and severity badge
      const headerDiv = document.createElement('div');
      headerDiv.style.cssText = 'display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px;';
      
      const concernNumber = document.createElement('div');
      concernNumber.textContent = `CONCERN #${index + 1}`;
      concernNumber.style.cssText = 'font-size: 10px; color: #8899AA; text-transform: uppercase; letter-spacing: 1.2px; font-weight: 600;';
      
      const severityBadge = document.createElement('span');
      severityBadge.textContent = style.label;
      severityBadge.style.cssText = `
        background: ${style.primary}30;
        color: ${style.primary};
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 10px;
        font-weight: 600;
        letter-spacing: 0.5px;
        border: 1px solid ${style.primary}40;
      `;
      
      headerDiv.appendChild(concernNumber);
      headerDiv.appendChild(severityBadge);
      card.appendChild(headerDiv);
      
      // Rule name with improved contrast
      const ruleName = document.createElement('div');
      ruleName.textContent = finding.rule;
      ruleName.style.cssText = `
        font-weight: 600;
        color: #E2E8F0;
        margin-bottom: 10px;
        font-size: 15px;
        line-height: 1.4;
      `;
      card.appendChild(ruleName);
      
      // Charter principle with better readability
      const charter = document.createElement('div');
      charter.textContent = finding.charter;
      charter.style.cssText = `
        font-size: 13px;
        color: #A0AEBF;
        margin-bottom: 16px;
        line-height: 1.7;
        padding-left: 12px;
        border-left: 2px solid ${style.primary}25;
      `;
      card.appendChild(charter);
      
      // Matched text excerpt with improved styling
      if (finding.excerpt && finding.excerpt.trim().length > 0) {
        console.log('[Watchman] Rendering excerpt for:', finding.rule);
        const excerptBox = document.createElement('div');
        excerptBox.style.cssText = `
          background: rgba(15, 23, 42, 0.3);
          border-left: 2px solid ${style.primary}50;
          padding: 14px 16px;
          border-radius: 8px;
          margin: 14px 0;
          font-size: 13px;
          color: #C8D0DC;
          font-style: italic;
          line-height: 1.7;
        `;
        
        // Convert **text** to bold HTML with severity-based highlight
        const formattedExcerpt = finding.excerpt.replace(/\*\*(.*?)\*\*/g, `<strong style="color: #E2E8F0; background: ${style.primary}30; padding: 2px 6px; border-radius: 3px; font-style: normal;">$1</strong>`);
        
        excerptBox.innerHTML = `
          <div style="font-size: 10px; color: #8899AA; text-transform: uppercase; margin-bottom: 8px; font-style: normal; letter-spacing: 0.5px;">
            📝 Detected Text:
          </div>
          "${formattedExcerpt}"
        `;
        card.appendChild(excerptBox);
      }
      
      // Scripture reference with improved styling
      const scripture = document.createElement('div');
      scripture.style.cssText = `
        font-size: 13px;
        color: #8CD4B0;
        margin-top: 14px;
        padding: 14px 16px;
        background: rgba(34, 197, 94, 0.06);
        border-radius: 8px;
        border: 1px solid rgba(34, 197, 94, 0.15);
        display: flex;
        align-items: flex-start;
        gap: 10px;
        line-height: 1.6;
      `;
      scripture.innerHTML = `
        <span style="font-size: 16px; flex-shrink: 0;">📖</span>
        <span><strong style="color: #6DCFA0;">Scripture:</strong> ${finding.scripture}</span>
      `;
      card.appendChild(scripture);
      
      container.appendChild(card);
    });
    
    sidebar.appendChild(container);
    document.body.appendChild(sidebar);
    console.log('[Watchman] Enhanced sidebar displayed with excerpts');
  }

  injectStyles() {
    const style = document.createElement('style');
    style.textContent = `
      .watchman-indicator {
        position: absolute !important;
        z-index: 99999 !important;
      }
      
      @keyframes watchman-pulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.2); }
      }

      #watchman-sidebar::-webkit-scrollbar {
        width: 6px;
      }
      #watchman-sidebar::-webkit-scrollbar-track {
        background: transparent;
      }
      #watchman-sidebar::-webkit-scrollbar-thumb {
        background: #475569;
        border-radius: 3px;
      }
      #watchman-sidebar::-webkit-scrollbar-thumb:hover {
        background: #64748B;
      }
    `;
    document.head.appendChild(style);
  }
}

// ============================================================================
// INITIALIZATION
// ============================================================================

let detector = null;

function initializeWatchman() {
  const hostname = window.location.hostname;
  console.log('[Watchman] Initializing detector for:', hostname);
  
  detector = new WatchmanDetector();
  detector.init();
  
  // For Gemini and Grok, add delayed checks since content loads dynamically
  if (hostname.includes('gemini.google.com') || 
      hostname.includes('grok.x.ai') || 
      hostname.includes('grok.com')) {
    console.log('[Watchman] Dynamic platform detected, scheduling additional checks');
    
    // Schedule multiple delayed checks to catch dynamically loaded content
    setTimeout(() => {
      console.log('[Watchman] Running delayed check (2s)');
      if (detector) detector.checkForResponses();
    }, 2000);
    
    setTimeout(() => {
      console.log('[Watchman] Running delayed check (5s)');
      if (detector) detector.checkForResponses();
    }, 5000);
    
    setTimeout(() => {
      console.log('[Watchman] Running delayed check (10s)');
      if (detector) detector.checkForResponses();
    }, 10000);
  }
  
  // Listen for URL changes (for SPAs like Grok)
  let lastUrl = location.href;
  new MutationObserver(() => {
    const url = location.href;
    if (url !== lastUrl) {
      console.log('[Watchman] URL changed, reinitializing detection');
      lastUrl = url;
      // Reset and recheck after navigation
      if (detector) {
        detector.observedResponses.clear();
        setTimeout(() => detector.checkForResponses(), 1000);
        setTimeout(() => detector.checkForResponses(), 3000);
      }
    }
  }).observe(document, { subtree: true, childList: true });
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeWatchman);
} else {
  initializeWatchman();
}